Source code for kaxanuk.attribution_analysis.modules.factor_totals

"""
Cumulative portfolio / factor / component / idiosyncratic totals of the factor model.

Derived from the cumulative factor contributions the model already produced
(``FactorModelArrowAttribution.simulated_rets``), so the contributions are not
linked a second time, and shared by the model and by the dashboard (which gets
only the result tables).
"""

import numpy as np
import pyarrow as pa
import pyarrow.compute as pc

from kaxanuk.attribution_analysis.entities.attribution_options import (
    AGGREGATE_FACTOR_COLUMNS,
    COMPONENT_COLUMNS,
    LinkingMethod,
)


[docs] def cumulative_totals_from_contributions( cumulative_contributions: pa.Table, portfolio_returns: pa.Table, linking: LinkingMethod | str, date_column: str = "date", ) -> pa.Table: """ Cumulative portfolio, factor, component and idiosyncratic return over the attribution window. The window is the dates of `cumulative_contributions` that have a non-null portfolio return. ``factor_returns`` is the sum of the cumulative contributions of every factor: columns in ``AGGREGATE_FACTOR_COLUMNS`` and the return components in ``COMPONENT_COLUMNS`` are excluded. Each component present (``f_carry``, ``f_dividends``) gets its own column (``carry_returns``, ``dividends_returns``); an absent component gets no column, rather than zeros that would claim a measured zero. ``portfolio_returns`` is the running portfolio return and ``idiosyncratic_returns`` what the factors and components leave of it. Parameters ---------- cumulative_contributions : pa.Table Cumulative contribution per factor, as ``simulated_rets``: `date_column` plus one float column per factor. With linking (``carino``/``grap``) the linked values on the window dates; with ``none`` plain running sums, which may also cover dates without a portfolio return. portfolio_returns : pa.Table `date_column` and ``portfolio_returns`` (nulls are not periods; on a repeated date the last row wins). linking : LinkingMethod or str The linking method `cumulative_contributions` was built with. With linking, ``portfolio_returns`` is compounded; with ``none`` every column is an arithmetic running sum over the window, so the contributions of dates without a portfolio return are taken out of each total. date_column : str, default ``"date"`` Name of the date column in both tables. Returns ------- pa.Table Columns `date_column` (same type as in `cumulative_contributions`), ``portfolio_returns``, ``factor_returns``, then ``carry_returns`` and ``dividends_returns`` when those components are present, then ``idiosyncratic_returns``. Empty (with those columns) when the window has no dates. Raises ------ ValueError If `linking` is not a known linking method. """ linking = LinkingMethod(linking) returns_by_date = { d: v for d, v in zip( portfolio_returns.column(date_column).to_pylist(), portfolio_returns.column("portfolio_returns").to_pylist(), strict=True, ) if v is not None } dates = cumulative_contributions.column(date_column).to_pylist() keep = np.array([d in returns_by_date for d in dates], dtype=bool) returns = np.array([returns_by_date[d] for d, k in zip(dates, keep, strict=True) if k], dtype=np.float64) def window_total(columns: list[str]) -> np.ndarray: """Sum of `columns` on the window dates (running sums corrected for dates without a return).""" running = sum( (np.asarray(pc.fill_null(cumulative_contributions.column(c), 0.0).to_numpy(), dtype=np.float64) for c in columns), np.zeros(len(dates)), ) if linking is LinkingMethod.NONE: # The running sums also accumulate dates without a portfolio return: remove what those dates added. added = np.diff(running, prepend=0.0) running = running - np.cumsum(np.where(keep, 0.0, added)) return running[keep] names = cumulative_contributions.column_names factor_columns = [ c for c in names if c != date_column and c not in AGGREGATE_FACTOR_COLUMNS and c not in COMPONENT_COLUMNS ] factors = window_total(factor_columns) components = {total: window_total([c]) for c, total in COMPONENT_COLUMNS.items() if c in names} portfolio = np.cumsum(returns) if linking is LinkingMethod.NONE else np.cumprod(1.0 + returns) - 1.0 idiosyncratic = portfolio - factors for values in components.values(): idiosyncratic = idiosyncratic - values return pa.table({ date_column: cumulative_contributions.column(date_column).filter(pa.array(keep)), "portfolio_returns": pa.array(portfolio, type=pa.float64()), "factor_returns": pa.array(factors, type=pa.float64()), **{name: pa.array(values, type=pa.float64()) for name, values in components.items()}, "idiosyncratic_returns": pa.array(idiosyncratic, type=pa.float64()), })