"""
Active factor attribution: the portfolio's factor decomposition minus the benchmark's.
The factor model runs twice, on the portfolio's and on the benchmark's
constituent weights (holdings basis). Per date, each factor's and each return
component's active contribution is the portfolio's minus the benchmark's, and
the active idiosyncratic residual is the active return ``r_p - r_b`` minus all
of them, so a date's active effects add up to ``r_p - r_b`` exactly.
Cumulative effects are linked with the portfolio return as ``r`` and the
holdings benchmark return as ``b`` (see ``modules.linking``). With Carino or
GRAP they add up to the compounded ``R_p - R_b`` on every date; with ``none``
they are running sums that add up to the running sum of ``r_p - r_b``.
"""
import logging
from collections.abc import Iterable
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,
WEIGHT_SUM_TOLERANCE,
LinkingMethod,
)
from kaxanuk.attribution_analysis.entities.attribution_result import ActiveFactorResult, DiagnosticCode
from kaxanuk.attribution_analysis.exceptions import PerformanceAttributionError
from kaxanuk.attribution_analysis.modules.diagnostics import log_diagnostic
from kaxanuk.attribution_analysis.modules.linking import link_cumulative
logger = logging.getLogger(__name__)
RESIDUAL_COLUMN = "f_idio_returns"
"""Active residual column; named like the residual of ``FactorModelResult.daily_shares``."""
def _label(date: object) -> str:
"""A date as ``YYYY-MM-DD`` for messages."""
return date.strftime("%Y-%m-%d") if hasattr(date, "strftime") else str(date)
def _returns_by_date(returns: pa.Table, date_column: str) -> dict:
"""Non-null ``portfolio_returns`` keyed by date (on a repeated date the last row wins)."""
return {
d: v
for d, v in zip(
returns.column(date_column).to_pylist(),
returns.column("portfolio_returns").to_pylist(),
strict=True,
)
if v is not None
}
def _effect_columns(contributions: pa.Table, date_column: str) -> list[str]:
"""Contribution columns that are factors or return components (aggregate files never are)."""
return [c for c in contributions.column_names if c != date_column and c not in AGGREGATE_FACTOR_COLUMNS]
def _on_window(contributions: pa.Table, column: str, rows: list[int]) -> np.ndarray:
"""
`column` of `contributions` at `rows`; zeros when the column is absent.
An absent column means the factor model gave this side no exposure to that
factor (it writes 0.0 for a factor without data on a date), so 0 is the
contribution, not a fill for missing data. In the pipeline the columns have
no nulls: ``multifactor_attribution`` already counts a null factor cell as
no exposure. A null passed in directly becomes NaN and ``_validate``
rejects it, naming the date.
"""
if column not in contributions.column_names:
return np.zeros(len(rows))
values = np.asarray(contributions.column(column).to_numpy(), dtype=np.float64)
return values[rows]
def _validate(window: list, r_p: np.ndarray, r_b: np.ndarray, effects: dict[str, np.ndarray]) -> None:
"""
Reject returns that cannot be linked and non-finite contributions, naming the date.
Raises
------
PerformanceAttributionError
On the first portfolio or benchmark return that is not finite or is
<= -100%, or the first non-finite active contribution.
"""
for side, values in (("portfolio", r_p), ("benchmark", r_b)):
bad = np.flatnonzero(~np.isfinite(values) | (values <= -1.0))
if bad.size:
i = int(bad[0])
raise PerformanceAttributionError(
f"Active factor model: {side} return {float(values[i])!r} on {_label(window[i])} is not a "
"finite value above -100%; check the price series for zeros or gaps."
)
for name, values in effects.items():
bad = np.flatnonzero(~np.isfinite(values))
if bad.size:
raise PerformanceAttributionError(
f"Active factor model: active '{name}' contribution on {_label(window[int(bad[0])])} is not finite"
)
[docs]
def warn_unpriced_holdings(
weights: pa.Table,
asset_returns: pa.Table,
side: str,
date_column: str = "date",
) -> int:
"""
Warn once when weighted tickers have no return on a date the side has a return.
The factor model's return is ``sum w * r`` over the tickers with a
return, so a weighted ticker without one counts as 0 that day. Only dates
with a returns row on which at least one weighted ticker has a return are
checked; on the others the side has no return and the date is dropped.
Parameters
----------
weights : pa.Table
Start-of-day weights: `date_column` plus one column per ticker. Null
and 0.0 weights are not holdings.
asset_returns : pa.Table
`date_column` plus one return column per ticker (null = no return).
A weighted ticker without a column has no return on any date.
side : str
Named in the message (e.g. ``"benchmark"``).
date_column : str, default ``"date"``
Date column of both tables.
Returns
-------
int
Number of weighted ticker-dates without a return (0: nothing logged).
"""
return_rows = {d: i for i, d in enumerate(asset_returns.column(date_column).to_pylist())}
dates = weights.column(date_column).to_pylist()
rows = np.array([return_rows.get(d, -1) for d in dates], dtype=np.int64)
has_row = rows >= 0
tickers = [c for c in weights.column_names if c != date_column]
held = np.zeros((len(dates), len(tickers)), dtype=bool)
priced = np.zeros((len(dates), len(tickers)), dtype=bool)
for j, ticker in enumerate(tickers):
w = np.asarray(pc.cast(weights.column(ticker), pa.float64()).to_numpy(zero_copy_only=False), dtype=np.float64)
held[:, j] = ~np.isnan(w) & (w != 0.0)
if ticker in asset_returns.column_names:
r = np.asarray(
pc.cast(asset_returns.column(ticker), pa.float64()).to_numpy(zero_copy_only=False), dtype=np.float64
)
priced[has_row, j] = ~np.isnan(r[rows[has_row]])
checked = has_row & (held & priced).any(axis=1)
unpriced = held & ~priced & checked[:, None]
count = int(unpriced.sum())
if count:
date_index, ticker_index = np.argwhere(unpriced)[0]
log_diagnostic(
logger,
DiagnosticCode.ACTIVE_UNPRICED_HOLDINGS,
"Active factor model: %d weighted %s ticker-dates have no return and count as 0 (first: %s on %s).",
count,
side,
tickers[ticker_index],
_label(dates[date_index]),
count=count,
first_date=dates[date_index],
details={"side": side, "ticker": tickers[ticker_index]},
)
return count
[docs]
def warn_weight_sums(
weights: pa.Table,
side: str,
dates: Iterable | None = None,
date_column: str = "date",
) -> int:
"""
Warn once when the side's net weights do not sum to 1 on the checked dates.
The factor model's return is ``sum w * r`` over the weights as given, so a
sum below 1 leaves the remainder as cash that earns 0 and has no factor
exposure, and a sum above 1 is used as given. Adding an explicit
zero-return cash weight would change no number; the weights have to be
completed or rescaled by whoever knows the benchmark. Nothing is raised.
Parameters
----------
weights : pa.Table
Start-of-day weights: `date_column` plus one column per ticker. A
null weight is not a holding and counts as 0.
side : str
Named in the message (e.g. ``"benchmark"``).
dates : Iterable or None, default None
Dates to check, as `date_column` holds them (the dates the side is
attributed on). None checks every row.
date_column : str, default ``"date"``
Date column of `weights`.
Returns
-------
int
Number of checked dates whose net weights differ from 1 by more than
``WEIGHT_SUM_TOLERANCE`` (0: nothing logged).
"""
all_dates = weights.column(date_column).to_pylist()
wanted = None if dates is None else set(dates)
checked = np.array([wanted is None or d in wanted for d in all_dates], dtype=bool)
sums = np.zeros(len(all_dates))
for ticker in weights.column_names:
if ticker != date_column:
sums += np.asarray(
pc.fill_null(pc.cast(weights.column(ticker), pa.float64()), 0.0).to_numpy(), dtype=np.float64
)
off = np.flatnonzero(checked & (np.abs(sums - 1.0) > WEIGHT_SUM_TOLERANCE))
if off.size:
first = int(off[0])
log_diagnostic(
logger,
DiagnosticCode.ACTIVE_WEIGHT_SUMS,
"Active factor model: net %s weights differ from 1 on %d of %d dates (first: %s, sum %.6f). "
"A sum below 1 leaves the remainder as cash earning 0 with no factor exposure; a sum above 1 is "
"used as given. The holdings %s return is then not the fully invested %s's, and the difference "
"lands in the active effects.",
side,
off.size,
int(checked.sum()),
_label(all_dates[first]),
float(sums[first]),
side,
side,
count=off.size,
total=int(checked.sum()),
first_date=all_dates[first],
details={"side": side, "first_sum": float(sums[first])},
)
return int(off.size)
[docs]
def active_factor_attribution(
portfolio_contributions: pa.Table,
portfolio_returns: pa.Table,
benchmark_contributions: pa.Table,
benchmark_returns: pa.Table,
linking: LinkingMethod | str,
date_column: str = "date",
) -> ActiveFactorResult:
"""
Active (portfolio minus benchmark) factor attribution from two factor decompositions.
Parameters
----------
portfolio_contributions, benchmark_contributions : pa.Table
Each side's daily contributions, as
``FactorModelArrowAttribution.portfolio_attribution_ts``: `date_column`
(unique dates) plus one float column per factor or return component.
portfolio_returns, benchmark_returns : pa.Table
Each side's return, as ``FactorModelArrowAttribution.portfolio_returns``:
`date_column` and ``portfolio_returns`` (null where the side has none).
linking : LinkingMethod or str
``"carino"``, ``"grap"`` or ``"none"``.
date_column : str, default ``"date"``
Date column of every table.
Returns
-------
ActiveFactorResult
Tables over the window: the portfolio contribution dates with a
portfolio return that also have benchmark contributions and a benchmark
return. Portfolio return dates left out are counted in one warning.
Columns: factors (sorted), then components, then ``f_idio_returns``.
Raises
------
ValueError
If `linking` is not a known linking method.
PerformanceAttributionError
If a portfolio or benchmark return on the window is not finite or is
at or below -100%, or an active contribution is not finite (each naming
the date), or linking overflows.
"""
linking = LinkingMethod(linking)
portfolio_by_date = _returns_by_date(portfolio_returns, date_column)
benchmark_by_date = _returns_by_date(benchmark_returns, date_column)
portfolio_rows = {d: i for i, d in enumerate(portfolio_contributions.column(date_column).to_pylist())}
benchmark_rows = {d: i for i, d in enumerate(benchmark_contributions.column(date_column).to_pylist())}
candidates = [d for d in portfolio_rows if d in portfolio_by_date]
window = [d for d in candidates if d in benchmark_rows and d in benchmark_by_date]
if len(window) < len(candidates):
log_diagnostic(
logger,
DiagnosticCode.ACTIVE_DATES_EXCLUDED,
"Active factor model: %d of %d dates with a portfolio return have no benchmark return or "
"benchmark factor data and are excluded.",
len(candidates) - len(window),
len(candidates),
count=len(candidates) - len(window),
total=len(candidates),
)
names = sorted(
set(_effect_columns(portfolio_contributions, date_column))
| set(_effect_columns(benchmark_contributions, date_column))
)
factors = [c for c in names if c not in COMPONENT_COLUMNS]
components = [c for c in COMPONENT_COLUMNS if c in names]
p_rows = [portfolio_rows[d] for d in window]
b_rows = [benchmark_rows[d] for d in window]
r_p = np.array([portfolio_by_date[d] for d in window], dtype=np.float64)
r_b = np.array([benchmark_by_date[d] for d in window], dtype=np.float64)
active_returns = r_p - r_b
effects = {
c: _on_window(portfolio_contributions, c, p_rows) - _on_window(benchmark_contributions, c, b_rows)
for c in (*factors, *components)
}
residual = active_returns.copy()
for values in effects.values():
residual = residual - values
effects[RESIDUAL_COLUMN] = residual
_validate(window, r_p, r_b, effects)
linked = link_cumulative(effects, r_p, r_b, linking)
if linking is LinkingMethod.NONE:
portfolio_total, benchmark_total = np.cumsum(r_p), np.cumsum(r_b)
else:
portfolio_total, benchmark_total = np.cumprod(1.0 + r_p) - 1.0, np.cumprod(1.0 + r_b) - 1.0
active_total = portfolio_total - benchmark_total
factor_total = sum((linked[c] for c in factors), np.zeros(len(window)))
component_totals = {COMPONENT_COLUMNS[c]: linked[c] for c in components}
idiosyncratic_total = active_total - factor_total
for values in component_totals.values():
idiosyncratic_total = idiosyncratic_total - values
date_type = portfolio_contributions.schema.field(date_column).type
def table(columns: dict[str, np.ndarray]) -> pa.Table:
"""An independent table: the window dates plus fresh float64 columns."""
return pa.table({
date_column: pa.array(window, type=date_type),
**{name: pa.array(values, type=pa.float64()) for name, values in columns.items()},
})
return ActiveFactorResult(
returns=table({"portfolio_returns": r_p, "benchmark_returns": r_b, "active_returns": active_returns}),
contributions=table(effects),
cumulative_contributions=table(linked),
cumulative_totals=table({
"portfolio_returns": portfolio_total,
"benchmark_returns": benchmark_total,
"active_returns": active_total,
"factor_returns": factor_total,
**component_totals,
"idiosyncratic_returns": idiosyncratic_total,
}),
linking=linking,
)