Source code for kaxanuk.attribution_analysis.entities.attribution_result

"""
Results of an attribution run, as data.

Returned by :func:`kaxanuk.attribution_analysis.run_attribution` (and by
``main``). Tables are PyArrow tables keyed by a ``date`` column; mappings are
read-only. Results pickle, ``copy.deepcopy`` and ``dataclasses.asdict`` cleanly.
"""

import dataclasses
import datetime
import enum
from collections.abc import Iterator, Mapping

import pyarrow as pa

from kaxanuk.attribution_analysis.entities.attribution_options import BrinsonFachlerFormula, LinkingMethod


[docs] class ReadOnlyMapping[K, V](Mapping[K, V]): """ Read-only mapping over a private copy of a dict. Unlike ``types.MappingProxyType`` it survives ``pickle``, ``copy.deepcopy`` and ``dataclasses.asdict``. Item assignment and deletion raise ``TypeError``. Parameters ---------- data : Mapping[K, V], optional Items to hold; copied, so later changes to the source do not show. """ __slots__ = ("_data",) def __init__(self, data: Mapping[K, V] | None = None) -> None: self._data: dict[K, V] = dict(data) if data is not None else {} def __getitem__(self, key: K) -> V: return self._data[key] def __iter__(self) -> Iterator[K]: return iter(self._data) def __len__(self) -> int: return len(self._data) def __repr__(self) -> str: return f"{type(self).__name__}({self._data!r})" def __reduce__(self) -> tuple[type, tuple[dict[K, V]]]: return type(self), (self._data,)
[docs] class DiagnosticLevel(enum.StrEnum): """ How a diagnostic was logged. Attributes ---------- WARNING Logged as a warning: something in the inputs changed what was attributed, or a check failed. INFO Logged as information: a note on how the run was done (e.g. a cross-check skipped for want of an input). """ WARNING = "warning" INFO = "info"
[docs] class DiagnosticCode(enum.StrEnum): """ What a diagnostic reports: one code per kind of log line a run keeps as data. The values are stable identifiers, safe to compare with plain strings (``diagnostic.code == "benchmark_returns_differ"``). """ # Inputs BENCHMARK_WEIGHTS_IGNORED = "benchmark_weights_ignored" CASH_PRICE_FILE_IGNORED = "cash_price_file_ignored" END_DATE_AFTER_DATA = "end_date_after_data" # Brinson-Fachler BRINSON_FACHLER_LEGACY_FORMULA = "brinson_fachler_legacy_formula" BRINSON_FACHLER_LEGACY_NOT_LINKED = "brinson_fachler_legacy_not_linked" BRINSON_FACHLER_SUBSTITUTED_GROUP_DATES = "brinson_fachler_substituted_group_dates" BRINSON_FACHLER_UNPRICED_GROUP_DATES = "brinson_fachler_unpriced_group_dates" BRINSON_FACHLER_WEIGHT_DATES_WITHOUT_PRICES = "brinson_fachler_weight_dates_without_prices" SEGMENT_UNPRICED_HOLDINGS = "segment_unpriced_holdings" # Benchmark cross-check BENCHMARK_CHECK_BAD_RETURN_COLUMNS = "benchmark_check_bad_return_columns" BENCHMARK_CHECK_NO_COMMON_DATES = "benchmark_check_no_common_dates" BENCHMARK_CHECK_WITHOUT_RETURNS = "benchmark_check_without_returns" BENCHMARK_RETURNS_DIFFER = "benchmark_returns_differ" # Factor model FACTOR_DATES_WITHOUT_FACTOR_ATTRIBUTION = "factor_dates_without_factor_attribution" FACTOR_DATES_WITHOUT_PORTFOLIO_RETURN = "factor_dates_without_portfolio_return" FACTOR_WEIGHT_ROWS_WITHOUT_DATE = "factor_weight_rows_without_date" # Active factor model ACTIVE_DATES_EXCLUDED = "active_dates_excluded" ACTIVE_UNPRICED_HOLDINGS = "active_unpriced_holdings" ACTIVE_WEIGHT_SUMS = "active_weight_sums" # Summary statistics SUMMARY_STATISTICS_SKIPPED = "summary_statistics_skipped"
[docs] @dataclasses.dataclass(frozen=True, slots=True) class Diagnostic: """ One warning or note an attribution run logged, kept as data. Recorded where the line is logged, from the values the line is built from: nothing is parsed from log text, and recording changes no number. Attributes ---------- code : DiagnosticCode What it reports. level : DiagnosticLevel The level the line was logged at. message : str The log line, exactly as logged. count : int or None How many dates, rows, group-dates or ticker-dates it concerns, when the line counts them. total : int or None Out of how many, when the line says. first_date : datetime.date or None The first date concerned, when the line names one. details : Mapping[str, object] The line's other values by name, e.g. ``side`` (``"portfolio"`` or ``"benchmark"``), ``ticker``, ``largest_difference``. Read-only. """ code: DiagnosticCode level: DiagnosticLevel message: str count: int | None = None total: int | None = None first_date: datetime.date | None = None details: Mapping[str, object] = dataclasses.field(default_factory=ReadOnlyMapping)
[docs] @dataclasses.dataclass(frozen=True, slots=True) class BrinsonFachlerResult: """ Brinson-Fachler output. Attributes ---------- per_period : pa.Table One row per date: ``portfolio_returns``, ``benchmark_returns``, ``alpha``, ``allocation``, ``selection``, ``interaction``. cumulative : pa.Table Cumulative indexes (linked per ``linking``). details : Mapping[object, pa.Table] Per-date, per-segment detail tables. Keys are the weights' date values as Python objects: ``pandas.Timestamp`` for the timestamp date columns the pipeline produces, so look them up with ``details[pandas.Timestamp("2024-01-02")]`` or iterate the keys. formula : BrinsonFachlerFormula linking : LinkingMethod by_year : pa.Table or None One row per calendar year: ``year`` and the ``per_period`` columns, linked within the year exactly as ``cumulative`` links the whole window (returns compounded, effects linked; sums with ``none``), so a year's allocation, selection and interaction add up to its alpha. Years compound into the window; they do not add up to its linked effects. ``None`` for a result built without it. """ per_period: pa.Table = dataclasses.field(repr=False) cumulative: pa.Table = dataclasses.field(repr=False) details: Mapping[object, pa.Table] = dataclasses.field(repr=False) formula: BrinsonFachlerFormula linking: LinkingMethod by_year: pa.Table | None = dataclasses.field(default=None, repr=False)
[docs] @dataclasses.dataclass(frozen=True, slots=True) class ActiveFactorResult: """ Active factor attribution: the portfolio's factor decomposition minus the benchmark's. The same factor model runs on the benchmark's constituent weights (holdings basis). Every table covers the dates on which both sides have a return and factor data. That window can be shorter than the portfolio's own tables: dates without a benchmark return or benchmark weights (gaps in the weights file) are dropped with one warning, and with ``linking="none"`` it leaves out the first price date, which ``FactorModelResult.cumulative_contributions`` keeps. Attributes ---------- returns : pa.Table ``date``, ``portfolio_returns``, ``benchmark_returns`` (holdings benchmark: benchmark weights x asset returns) and ``active_returns`` (``portfolio_returns - benchmark_returns``). contributions : pa.Table ``date``, one column per factor (portfolio contribution minus benchmark contribution), then the return components present (``f_carry``, ``f_dividends``), then ``f_idio_returns``, the active residual. On each date the columns add up to ``active_returns``. cumulative_contributions : pa.Table The same columns, cumulative. With linking (``carino``/``grap``) they are linked with the portfolio return as ``r`` and the holdings benchmark return as ``b``, so on every date they add up to the compounded ``R_p - R_b``; with ``none`` they are running sums. cumulative_totals : pa.Table ``date``, ``portfolio_returns``, ``benchmark_returns``, ``active_returns`` (compounded with linking, running sums with ``none``; ``active_returns = portfolio_returns - benchmark_returns``), ``factor_returns`` (the cumulative active factor columns summed), ``carry_returns`` / ``dividends_returns`` when those components are present, and ``idiosyncratic_returns`` (``active_returns`` minus the factors and components). linking : LinkingMethod """ returns: pa.Table = dataclasses.field(repr=False) contributions: pa.Table = dataclasses.field(repr=False) cumulative_contributions: pa.Table = dataclasses.field(repr=False) cumulative_totals: pa.Table = dataclasses.field(repr=False) linking: LinkingMethod
[docs] @dataclasses.dataclass(frozen=True, slots=True) class FactorModelResult: """ Factor-model output. Attributes ---------- portfolio_returns : pa.Table ``date``, ``portfolio_returns`` (null where no held asset had a return). contributions : pa.Table Daily portfolio-weighted contribution per factor file (each file's cells are asset contributions: exposure x factor return). The aggregate vendor files (``AGGREGATE_FACTOR_COLUMNS``) are not loaded, so they never appear here. The return components ``f_carry`` / ``f_dividends`` (``COMPONENT_COLUMNS``), when supplied, are columns here too: they are not factors. cumulative_contributions : pa.Table Cumulative contribution per factor file, with the same columns as ``contributions``. With linking (``carino``/``grap``): linked, on the dates with a portfolio return. With ``none``: plain running sums over every attribution date, including dates without a portfolio return (e.g. the first price date). cumulative_totals : pa.Table ``date``, ``portfolio_returns``, ``factor_returns``, ``carry_returns`` and ``dividends_returns`` (only when those components were supplied), ``idiosyncratic_returns``: cumulative series from the model, on the dates with a portfolio return. ``factor_returns`` excludes the components. With linking, ``portfolio_returns`` is compounded and ``factor_returns`` is the sum of the ``cumulative_contributions`` factor columns. With ``none`` every column is an arithmetic running sum: ``portfolio_returns`` differs from the compounded ``Total Return`` in ``summary_stats``, and since the window differs from ``cumulative_contributions``, ``factor_returns`` need not equal the sum of its columns. daily_shares : pa.Table Each factor's share of each day's portfolio return; the residual column is ``f_idio_returns``. Aggregate files are excluded. Components have their own share column and are taken out of the residual. cumulative_shares : Mapping[str, float] Each factor's share of the cumulative portfolio return; the residual key is ``idio_returns`` (not ``f_idio_returns`` as in ``daily_shares``). Aggregate files are excluded; the shares sum to 1. Components are keys of their own. linking : LinkingMethod active : ActiveFactorResult or None The portfolio-minus-benchmark decomposition; ``None`` unless ``active_factor_model`` is on. by_year : pa.Table or None One row per calendar year over the window of ``cumulative_totals``: ``year``, ``portfolio_returns``, ``factor_returns``, each factor, the components present (``carry_returns``, ``dividends_returns``) and ``idiosyncratic_returns``, linked within the year (``b = 0``; sums with ``none``). ``None`` for a result built without it. """ portfolio_returns: pa.Table = dataclasses.field(repr=False) contributions: pa.Table = dataclasses.field(repr=False) cumulative_contributions: pa.Table = dataclasses.field(repr=False) cumulative_totals: pa.Table = dataclasses.field(repr=False) daily_shares: pa.Table = dataclasses.field(repr=False) cumulative_shares: Mapping[str, float] = dataclasses.field(repr=False) linking: LinkingMethod active: ActiveFactorResult | None = dataclasses.field(default=None, repr=False) by_year: pa.Table | None = dataclasses.field(default=None, repr=False)
[docs] @dataclasses.dataclass(frozen=True, slots=True) class AttributionResult: """ Everything an attribution run produced. Attributes ---------- start_date, end_date : datetime.date The common date window all inputs were aligned to. They are ``datetime.date`` while the tables' ``date`` columns are timestamps: convert before comparing (e.g. ``ts.date() >= result.start_date``). brinson_fachler : BrinsonFachlerResult or None ``None`` when the method is disabled. factor_model : FactorModelResult or None ``None`` when the method is disabled. portfolio_returns : pa.Table ``date``, ``portfolio_returns``: the series behind ``summary_stats`` (dates with a return only). summary_stats : Mapping[str, float] ``Total Return`` (compounded), ``Annualized Return``, ``Annualized Vol``, ``Sharpe Ratio``, ``Max Drawdown``, ``Skewness``, ``Kurtosis``, ``Cornish-Fisher VaR (5%)``, ``Historic CVaR (5%)``. Empty when ``portfolio_returns`` has no rows (the statistics are undefined). implementation : pa.Table or None Only for runs from a Backtest-Engine result (``None`` otherwise): ``date``, ``engine_returns``, ``holdings_returns``, ``commissions``, ``slippage``, ``financing``, ``execution``. Per date, the engine's NAV return equals the holdings return plus the four components (costs are negative returns, as fractions of the previous NAV). diagnostics : tuple[Diagnostic, ...] The warnings (and notes) the run logged about its inputs and checks, in the order they were logged: dates or rows left out, returns substituted, the holdings benchmark differing from the reported one, a cross-check skipped. Empty when there were none. File-based and in-memory runs fill it alike; the log lines themselves are unchanged. benchmark_stats : Mapping[str, float] The keys of ``summary_stats`` for the benchmark the attribution compared the portfolio with (Brinson-Fachler's, else the active factor model's holdings benchmark), on the dates both have a return. Empty when neither ran. relative_stats : Mapping[str, float] The portfolio against that benchmark, on the same dates: ``Active Return`` (compounded difference), ``Annualized Active Return``, ``Tracking Error``, ``Information Ratio``, ``Beta``, ``Hit Rate`` (see :func:`~kaxanuk.attribution_analysis.modules.relative_statistics.relative_statistics`; the Backtest Engine's definitions). Empty when neither ran. """ start_date: datetime.date end_date: datetime.date brinson_fachler: BrinsonFachlerResult | None factor_model: FactorModelResult | None portfolio_returns: pa.Table summary_stats: Mapping[str, float] implementation: pa.Table | None = dataclasses.field(default=None, repr=False) diagnostics: tuple[Diagnostic, ...] = dataclasses.field(default=(), repr=False) benchmark_stats: Mapping[str, float] = dataclasses.field(default_factory=ReadOnlyMapping, repr=False) relative_stats: Mapping[str, float] = dataclasses.field(default_factory=ReadOnlyMapping, repr=False) def __repr__(self) -> str: """Short summary: the window, which methods ran, row counts, the diagnostics count and a few statistics.""" methods = [ name for name, ran in ( ("brinson_fachler", self.brinson_fachler is not None), ("factor_model", self.factor_model is not None), ) if ran ] stats = ", ".join( f"{key!r}: {self.summary_stats[key]:.6g}" for key in ("Total Return", "Annualized Return", "Annualized Vol", "Sharpe Ratio") if key in self.summary_stats ) implementation = ( "" if self.implementation is None else f"implementation=<{self.implementation.num_rows} rows>, " ) diagnostics = "" if not self.diagnostics else f"diagnostics=<{len(self.diagnostics)} entries>, " return ( f"AttributionResult(start_date={self.start_date}, end_date={self.end_date}, " f"methods={methods}, portfolio_returns=<{self.portfolio_returns.num_rows} rows>, " f"{implementation}{diagnostics}summary_stats={{{stats}}})" )