Source code for kaxanuk.attribution_analysis.adapters.backtest_engine

"""
Attribution inputs and the implementation table from a KaxaNuk Backtest-Engine run.

Engine contract (Backtest-Engine ``ENGINE_CONTRACT_VERSION``)
-------------------------------------------------------------
The adapter reads a finished run in memory:

- the ``BacktestResultDict`` (a plain dict) returned by the backtester's
  ``run()`` / ``run_with_benchmark()`` or by ``kaxanuk.backtest_engine.main(...).data``;
- the ``MarketDataBundlePyarrow`` the run was priced from.

Keys read from the result dict:

- ``Register_df``: date-indexed; ``Total_Portfolio_Value`` is the end-of-day NAV
  (rounded to cents). Its ``Returns`` column is rounded to 4 dp and is not used.
- ``Daily_Weights``: date-indexed end-of-day, post-trade weights at mark-to-market
  prices, one column per ticker of the engine universe (the benchmark ETF
  included, always 0) plus ``CASH_RESERVE``.
- ``Commission_df`` / ``Slippage_df``: event-date-indexed currency costs per
  ticker; may be empty. Slippage is already inside the engine's fill price
  (fill = trade-execution reference price adjusted by slippage); the adapter
  reports it in its own column and measures execution against the reference
  price before slippage, so it is never counted twice.
- ``Financing_df``: date-indexed; ``Financing_Cost`` is the net financing charge
  (borrow + margin - cash interest) in currency. Empty, without a date index,
  when financing is off.
- ``benchmark``: an Arrow table with ``date_column`` and
  ``mark_to_market_price_column``; its ``daily_return`` pads the first day with
  0 and is not used. ``None`` when the run has no benchmark, which only a
  factor-model-only attribution accepts.

From the bundle: ``price_tables["mark_to_market_price_column"]``, a wide Arrow
table (``date_column`` plus one price column per ticker, interior gaps carried
forward), and ``date_column_name``. Inside the run window its dates must be the
engine's dates. Engine prices are decimals and dates are ``date32``; prices
convert to float64 exactly as the file pipeline converts its price files, and
dates to ``timestamp[ns]``.

Timing: trades execute the same day at the trade-execution price and the
end-of-day snapshot is taken after trading and financing, so the start-of-day
book of date t is the snapshot of t-1. The implementation table's ``execution``
column is therefore the trade-execution (reference, before slippage) price vs
close on traded shares, plus any other NAV movement the holdings and the three
cost columns do not explain (e.g. forced exits) and rounding; slippage is
excluded. Day 0 (initial capital to the first end-of-day NAV) has no
start-of-day book and is excluded, as the engine excludes it: so are its
initial-build costs and its return.

The engine package is never imported: it is distributed from a private index,
validates a licence at import time and pulls in Dash. Everything here works on
plain dicts, pandas frames and Arrow tables by duck typing.
"""

import dataclasses
import logging
from collections.abc import Mapping, Sequence
from typing import Any

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

from kaxanuk.attribution_analysis.entities.attribution_inputs import AttributionInputs
from kaxanuk.attribution_analysis.entities.attribution_options import AttributionSettings, BrinsonFachlerFormula
from kaxanuk.attribution_analysis.entities.attribution_result import AttributionResult, DiagnosticCode, DiagnosticLevel
from kaxanuk.attribution_analysis.entities.portfolio_weights_arrow import PortfolioWeights
from kaxanuk.attribution_analysis.entities.returns_table import ReturnsTable
from kaxanuk.attribution_analysis.exceptions import ConfigurationError, DataValidationError
from kaxanuk.attribution_analysis.modules.data_wrangling import list_factor_return_files, load_by_factor_returns_arrow
from kaxanuk.attribution_analysis.modules.diagnostics import collect_diagnostics, log_diagnostic
from kaxanuk.attribution_analysis.modules.table_conversion_arrow import (
    column_to_float64,
    compute_returns_from_prices_arrow,
    pyarrow_prices_to_attribution_format,
)
from kaxanuk.attribution_analysis.modules.weights_normalization import append_zero_return_column, fill_implied_cash
from kaxanuk.attribution_analysis.performance_attribution import attribute, require_a_method, weighted_columns
from kaxanuk.attribution_analysis.services.license_validator import validate_license

logger = logging.getLogger("kaxanuk.attribution_analysis")

ENGINE_CONTRACT_VERSION = "0.67.0"
ENGINE_CASH_COLUMN = "CASH_RESERVE"
ENGINE_DATE_COLUMN = "date_column"
ENGINE_MARK_TO_MARKET_COLUMN = "mark_to_market_price_column"
REQUIRED_RESULT_KEYS = ("Register_df", "Daily_Weights", "Commission_df", "Slippage_df", "Financing_df", "benchmark")
IMPLEMENTATION_COLUMNS = (
    "date", "engine_returns", "holdings_returns", "commissions", "slippage", "financing", "execution",
)
_MIN_WEIGHT_DATES = 2
"""Day 0 plus at least one date with a start-of-day book."""


[docs] def check_result_keys(backtest_result: Mapping[str, Any]) -> None: """ Check that a Backtest-Engine result carries every key the adapter reads. Parameters ---------- backtest_result : Mapping[str, Any] The engine's ``BacktestResultDict``. Raises ------ DataValidationError If any key of ``REQUIRED_RESULT_KEYS`` is missing; the message lists every missing key. """ missing = [key for key in REQUIRED_RESULT_KEYS if key not in backtest_result] if missing: raise DataValidationError( f"Backtest result is missing {missing}; expected a Backtest-Engine " f"{ENGINE_CONTRACT_VERSION} BacktestResultDict." )
def _date_index(frame: pd.DataFrame) -> pd.DatetimeIndex: """ Naive, day-floored, nanosecond date index of an engine frame. The engine's index unit varies (seconds in memory, milliseconds after a parquet round trip), so every reindex or join goes through this. Parameters ---------- frame : pandas.DataFrame Date-indexed engine frame. Returns ------- pandas.DatetimeIndex The index normalized to midnight, in nanoseconds. """ return pd.DatetimeIndex(frame.index).normalize().as_unit("ns") def _check_ordered_dates(dates: pd.DatetimeIndex, name: str) -> None: """ Require strictly increasing dates: the adapter pairs rows by position. Parameters ---------- dates : pandas.DatetimeIndex Normalized dates of an engine frame. name : str The frame's name, for the message. Raises ------ DataValidationError If a date repeats or the dates are not sorted (the message names the first offending date). """ duplicated = dates.duplicated() if duplicated.any(): first = dates[int(np.argmax(duplicated))].date().isoformat() raise DataValidationError(f"{name} has a duplicate date ({first}).") if not dates.is_monotonic_increasing: backwards = np.diff(dates.to_numpy()) < np.timedelta64(0, "ns") first = dates[int(np.argmax(backwards)) + 1].date().isoformat() raise DataValidationError(f"{name} dates are not sorted (first out of order: {first}).") def _frame_to_table(frame: pd.DataFrame) -> pa.Table: """ Convert a date-indexed float frame into an independent Arrow table. Parameters ---------- frame : pandas.DataFrame Date-indexed frame of float columns. Returns ------- pyarrow.Table A ``date`` column (``timestamp[ns]``) followed by one float64 column per frame column, each built from a copy of the frame's data. """ columns = {"date": pa.array(_date_index(frame).to_numpy(), type=pa.timestamp("ns"))} for name in frame.columns: columns[str(name)] = pa.array(frame[name].to_numpy(dtype=np.float64, copy=True), type=pa.float64()) return pa.table(columns)
[docs] def start_of_day_weights(daily_weights: pd.DataFrame, cash_ticker: str) -> pa.Table: """ Start-of-day weights from the engine's end-of-day ``Daily_Weights``. The engine snapshots after trading, so the book held going into date t is the snapshot of t-1: every row moves one date later and the first date (day 0, from initial capital) has none. ``CASH_RESERVE`` becomes `cash_ticker`. Columns that are 0 on every start-of-day row (e.g. the benchmark ETF the engine prices but never holds) are dropped. Parameters ---------- daily_weights : pandas.DataFrame The engine's ``Daily_Weights``: date index, one column per ticker plus ``CASH_RESERVE``. cash_ticker : str Name given to the cash column in the output; ``"CASH_RESERVE"`` keeps the engine's name. Returns ------- pyarrow.Table ``date`` (``timestamp[ns]``, every engine date but the first) followed by the float64 weight of each ticker held on at least one start-of-day row, in the engine's column order. Raises ------ DataValidationError If ``CASH_RESERVE`` is missing, if `cash_ticker` already names a ticker column, if there are fewer than two dates, if the dates repeat or are not sorted, or if any weight is NaN or infinite (the message names the first bad date). """ _check_ordered_dates(_date_index(daily_weights), "Daily_Weights") if ENGINE_CASH_COLUMN not in daily_weights.columns: raise DataValidationError(f"Daily_Weights has no {ENGINE_CASH_COLUMN} column.") if cash_ticker != ENGINE_CASH_COLUMN and cash_ticker in daily_weights.columns: raise DataValidationError( f"cash_ticker {cash_ticker!r} is also a ticker column of Daily_Weights; choose another cash_ticker." ) if len(daily_weights.index) < _MIN_WEIGHT_DATES: raise DataValidationError("Daily_Weights needs at least two dates to form start-of-day weights.") weights = daily_weights.astype(np.float64).rename(columns={ENGINE_CASH_COLUMN: cash_ticker}) bad_rows = ~np.isfinite(weights.to_numpy()).all(axis=1) if bad_rows.any(): first = _date_index(weights)[int(bad_rows.argmax())].date().isoformat() raise DataValidationError(f"Daily_Weights has NaN or infinite weights (first: {first}).") start_of_day = pd.DataFrame(weights.to_numpy()[:-1], index=weights.index[1:], columns=weights.columns) held = [name for name in start_of_day.columns if (start_of_day[name] != 0.0).any()] return _frame_to_table(start_of_day[held])
[docs] def asset_returns_from_bundle( market_data_bundle: Any, *, tickers: Sequence[str], start: pd.Timestamp, end: pd.Timestamp, ) -> pa.Table: """ Simple returns of `tickers` from the bundle's mark-to-market prices, `start` to `end`. The first row (`start`) has no return (null), as in the file pipeline; prices are the engine's valuation prices (interior gaps already carried forward), converted to float64 by the file pipeline's own price conversion (``pyarrow_prices_to_attribution_format``), so the returns are bit for bit those of the same prices read from files. Parameters ---------- market_data_bundle : Any The engine's market data bundle, read by duck typing: ``price_tables`` keyed by ``"mark_to_market_price_column"`` and, optionally, ``date_column_name`` (default ``"date_column"``). tickers : Sequence[str] Tickers whose returns are wanted, in output column order. start : pandas.Timestamp First date kept (inclusive); its row has null returns. end : pandas.Timestamp Last date kept (inclusive). Returns ------- pyarrow.Table ``date`` (``timestamp[ns]``) followed by one float64 return column per ticker; the first row is null. Raises ------ DataValidationError If the bundle has no mark-to-market price table, or if a ticker has no price column (the message names them). """ try: prices = market_data_bundle.price_tables[ENGINE_MARK_TO_MARKET_COLUMN] except (AttributeError, KeyError, TypeError): raise DataValidationError( f"market_data_bundle has no {ENGINE_MARK_TO_MARKET_COLUMN!r} price table " f"(expected a Backtest-Engine {ENGINE_CONTRACT_VERSION} MarketDataBundlePyarrow)." ) from None date_name = getattr(market_data_bundle, "date_column_name", ENGINE_DATE_COLUMN) missing = sorted(set(tickers) - set(prices.column_names)) if missing: raise DataValidationError(f"No mark-to-market prices in the backtest for {missing}.") dates = pc.cast(prices.column(date_name), pa.timestamp("ns")) table = pyarrow_prices_to_attribution_format( pa.table({"date": dates, **{t: prices.column(t) for t in tickers}}), "date" ) in_window = pc.and_( pc.greater_equal(table.column("date"), pa.scalar(start.as_unit("ns"), type=pa.timestamp("ns"))), pc.less_equal(table.column("date"), pa.scalar(end.as_unit("ns"), type=pa.timestamp("ns"))), ) return compute_returns_from_prices_arrow(table.filter(in_window), "date").table
[docs] def benchmark_returns_from_backtest(benchmark: pa.Table | None) -> pa.Table: """ Benchmark simple returns recomputed from its mark-to-market price. The engine's ``daily_return`` pads the first day with 0 (a fabricated flat day), so it is not used; the first date is dropped instead. The price converts as in :func:`asset_returns_from_bundle`. Parameters ---------- benchmark : pyarrow.Table or None The result dict's ``benchmark`` table, with ``date_column`` and ``mark_to_market_price_column``. Returns ------- pyarrow.Table ``date`` (``timestamp[ns]``) and ``benchmark_returns`` (float64), one row per benchmark date but the first. Raises ------ DataValidationError If `benchmark` is None (the backtest has no benchmark) or lacks the date or mark-to-market price column. """ if benchmark is None: raise DataValidationError("The backtest has no benchmark; configure one in the Backtest-Engine run.") missing = [c for c in (ENGINE_DATE_COLUMN, ENGINE_MARK_TO_MARKET_COLUMN) if c not in benchmark.column_names] if missing: raise DataValidationError(f"Backtest benchmark table is missing columns {missing}.") prices = pyarrow_prices_to_attribution_format( pa.table({ "date": pc.cast(benchmark.column(ENGINE_DATE_COLUMN), pa.timestamp("ns")), "benchmark_returns": benchmark.column(ENGINE_MARK_TO_MARKET_COLUMN), }), "date", ) returns = compute_returns_from_prices_arrow(prices, "date").table return pa.table({name: returns.column(name).slice(1).combine_chunks() for name in returns.column_names})
def _event_totals( frame: pd.DataFrame, dates: pd.DatetimeIndex, name: str, column: str | None = None ) -> np.ndarray: """ Per-date currency totals of an engine cost frame on `dates`. Parameters ---------- frame : pandas.DataFrame Engine cost frame (``Commission_df``, ``Slippage_df`` or ``Financing_df``); may be empty and then has no date index. dates : pandas.DatetimeIndex Dates to report on (nanosecond, day-floored). name : str The frame's name, for the message. column : str or None, default None Column to total; None sums every column of the row. Returns ------- numpy.ndarray Float64 totals aligned with `dates`; 0 where the engine booked nothing (a cost that did not happen is a true zero, not missing data). Rows on other dates, such as day 0, are dropped. Raises ------ DataValidationError If `frame` has rows but not `column`. """ if frame.empty: return np.zeros(len(dates)) if column is not None and column not in frame.columns: raise DataValidationError(f"{name} has rows but no {column} column.") values = frame[column] if column is not None else frame.sum(axis=1) totals = pd.Series(values.to_numpy(dtype=np.float64), index=_date_index(frame)).groupby(level=0).sum() return totals.reindex(dates, fill_value=0.0).to_numpy(dtype=np.float64) def _check_same_dates(dates: pd.DatetimeIndex, name: str, weight_dates: pd.DatetimeIndex) -> None: """ Require `dates` to be the ``Daily_Weights`` dates, in the same order. Rows are paired by position: the previous NAV is ``shift(1)`` of ``Register_df``, and each asset return is taken over consecutive price rows. A date in one table and not the other would pair a return with the wrong NAV or the wrong start-of-day book (e.g. fold two days' moves into one return). Parameters ---------- dates : pandas.DatetimeIndex Normalized dates of the table checked. name : str That table's name, for the message. weight_dates : pandas.DatetimeIndex Normalized dates of ``Daily_Weights``. Raises ------ DataValidationError If the dates differ; the message names the first position where they do. """ if dates.equals(weight_dates): return common = min(len(dates), len(weight_dates)) differ = np.flatnonzero(dates[:common] != weight_dates[:common]) position = int(differ[0]) if differ.size else common def _at(values: pd.DatetimeIndex) -> str: return values[position].date().isoformat() if position < len(values) else "no date" raise DataValidationError( f"{name} and Daily_Weights dates differ at row {position}: " f"{name} has {_at(dates)}, Daily_Weights has {_at(weight_dates)}." )
[docs] def implementation_breakdown( backtest_result: Mapping[str, Any], start_of_day: pa.Table, asset_returns: pa.Table, cash_ticker: str, ) -> pa.Table: """ Reconcile the holdings return to the engine's NAV return, per date. For each start-of-day date t, with ``NAV`` the engine's ``Total_Portfolio_Value``:: engine_returns = NAV_t / NAV_{t-1} - 1 holdings_returns = sum_i w_sod[i, t] * r[i, t] (cash earns 0) commissions = -sum(Commission_df row t) / NAV_{t-1} slippage = -sum(Slippage_df row t) / NAV_{t-1} financing = -Financing_df.Financing_Cost[t] / NAV_{t-1} execution = engine_returns - holdings_returns - commissions - slippage - financing Costs are negative fractions of the previous NAV (0 on dates without an engine row; a financing credit is positive). ``execution`` is the residual: the trade-execution (reference, before slippage) price vs close on traded shares, plus any other NAV movement the holdings and the three cost columns do not explain (e.g. forced exits), and rounding. Slippage is inside the engine's fill price and reported in its own ``slippage`` column, so ``execution`` excludes it (no double count): with the reference price p, slippage s per share and close c, a purchase of q shares contributes ``-q * s`` to ``slippage`` and ``q * (c - p)`` to ``execution``. It is about 0 on dates without trades or financing. Day 0 has no row, so its initial-build costs and return are not in the table. Parameters ---------- backtest_result : Mapping[str, Any] The engine's ``BacktestResultDict`` (``Register_df``, ``Daily_Weights``, ``Commission_df``, ``Slippage_df``, ``Financing_df`` are read). start_of_day : pyarrow.Table Output of :func:`start_of_day_weights`. asset_returns : pyarrow.Table ``date`` plus one return column per non-cash ticker of `start_of_day`, e.g. from :func:`asset_returns_from_bundle`. Between the first and last ``Daily_Weights`` date its dates must be exactly the engine's. A missing return is allowed only where the start-of-day weight is 0. cash_ticker : str The cash column of `start_of_day`; it earns 0 (cash interest is in ``financing``). Returns ------- pyarrow.Table Columns ``IMPLEMENTATION_COLUMNS``, one row per date of `start_of_day`. Raises ------ DataValidationError If ``Register_df`` dates repeat or are not sorted, if they differ from the ``Daily_Weights`` dates, or if the `asset_returns` dates inside the run window differ from those (the message names the first difference), if ``Financing_df`` has rows but no ``Financing_Cost`` column, if ``Register_df`` lacks the NAV of a start-of-day date or of the date before it, if a held ticker has no return column, or if a held ticker has no return on a date (the message names the first such date and the tickers without a return on it). """ dates = pd.DatetimeIndex(start_of_day.column("date").to_pandas()).as_unit("ns") register = backtest_result["Register_df"] _check_ordered_dates(_date_index(register), "Register_df") weight_dates = _date_index(backtest_result["Daily_Weights"]) _check_same_dates(_date_index(register), "Register_df", weight_dates) return_dates = pd.DatetimeIndex(asset_returns.column("date").to_pandas()).as_unit("ns") in_window = (return_dates >= weight_dates[0]) & (return_dates <= weight_dates[-1]) _check_same_dates(return_dates[in_window], "Market data inside the run window", weight_dates) nav = pd.Series(register["Total_Portfolio_Value"].to_numpy(dtype=np.float64), index=_date_index(register)) nav_now = nav.reindex(dates).to_numpy() nav_prev = nav.shift(1).reindex(dates).to_numpy() if not (np.isfinite(nav_now).all() and np.isfinite(nav_prev).all()): raise DataValidationError("Register_df lacks Total_Portfolio_Value on a start-of-day weights date.") tickers = [c for c in start_of_day.column_names if c != "date"] missing = [t for t in tickers if t != cash_ticker and t not in asset_returns.column_names] if missing: raise DataValidationError(f"No returns for held tickers {missing}.") weights = np.column_stack([start_of_day.column(t).to_numpy() for t in tickers]) returns_frame = asset_returns.to_pandas().set_index("date") returns_frame.index = pd.DatetimeIndex(returns_frame.index).as_unit("ns") returns_frame = returns_frame.reindex(dates) returns = np.column_stack([ np.zeros(len(dates)) if t == cash_ticker else returns_frame[t].to_numpy(dtype=np.float64) for t in tickers ]) returns = np.where(weights == 0.0, np.nan_to_num(returns), returns) if not np.isfinite(returns).all(): row = int((~np.isfinite(returns)).any(axis=1).argmax()) names = [t for t, ok in zip(tickers, np.isfinite(returns[row]), strict=True) if not ok] raise DataValidationError(f"Held tickers {names} have no return on {dates[row].date().isoformat()}.") engine = nav_now / nav_prev - 1.0 holdings = (weights * returns).sum(axis=1) # 0.0 - x rather than -x: a date without a cost reports 0.0, not -0.0. commissions = (0.0 - _event_totals(backtest_result["Commission_df"], dates, "Commission_df")) / nav_prev slippage = (0.0 - _event_totals(backtest_result["Slippage_df"], dates, "Slippage_df")) / nav_prev financing = ( 0.0 - _event_totals(backtest_result["Financing_df"], dates, "Financing_df", "Financing_Cost") ) / nav_prev execution = engine - holdings - commissions - slippage - financing return pa.table({ "date": start_of_day.column("date").combine_chunks(), "engine_returns": engine, "holdings_returns": holdings, "commissions": commissions, "slippage": slippage, "financing": financing, "execution": execution, })
def _benchmark_weights_table(weights: pa.Table) -> pa.Table: """ Caller benchmark weights as an independent ``timestamp[ns]`` / float64 table. Parameters ---------- weights : pyarrow.Table ``date`` (``date32`` or naive timestamp at midnight) plus one numeric weight column per ticker. Returns ------- pyarrow.Table ``date`` (``timestamp[ns]``) followed by every other column cast to float64, each in its own buffers. Decimal weights convert exactly as the file pipeline's weight loader converts them (``float(Decimal)``). Raises ------ DataValidationError If `weights` has no ``date`` column, if that column is not a date or naive timestamp, is timezone-aware, has null values, or carries a time of day (the message names the first such value), or if a weight column is not numeric (the message names it). """ if "date" not in weights.column_names: raise DataValidationError("benchmark_weights needs a 'date' column.") date_type = weights.schema.field("date").type if pa.types.is_timestamp(date_type) and date_type.tz is not None: raise DataValidationError( f"benchmark_weights 'date' is timezone-aware ({date_type.tz}); pass naive dates." ) if not (pa.types.is_date(date_type) or pa.types.is_timestamp(date_type)): raise DataValidationError(f"benchmark_weights 'date' must be a date or timestamp column, got {date_type}.") if weights.column("date").null_count: raise DataValidationError( f"benchmark_weights 'date' has {weights.column('date').null_count} null value(s); every row needs a date." ) dates = pc.cast(weights.column("date"), pa.timestamp("ns")).combine_chunks() intraday = pc.fill_null(pc.not_equal(pc.floor_temporal(dates, unit="day"), dates), fill_value=False) if pc.any(intraday).as_py(): first = pc.filter(dates, intraday)[0].as_py() raise DataValidationError(f"benchmark_weights 'date' carries a time of day (first: {first}); pass dates.") columns = {"date": dates} for name in weights.column_names: if name == "date": continue try: columns[name] = column_to_float64(weights.column(name)).combine_chunks() except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as error: raise DataValidationError( f"benchmark_weights column {name!r} is not numeric ({weights.schema.field(name).type})." ) from error return pa.table(columns) def _keep_dates(table: pa.Table, dates: pa.ChunkedArray | pa.Array) -> pa.Table: """ Rows of `table` whose ``date`` is in `dates`, as an independent table. Parameters ---------- table : pyarrow.Table Table with a ``timestamp[ns]`` ``date`` column. dates : pyarrow.ChunkedArray or pyarrow.Array Dates to keep (a timestamp column). Returns ------- pyarrow.Table The kept rows in `table` order, each column in its own contiguous buffers. """ wanted = pc.cast(dates, pa.timestamp("ns")) if isinstance(wanted, pa.ChunkedArray): wanted = wanted.combine_chunks() kept = table.filter(pc.is_in(table.column("date"), value_set=wanted)) return pa.table({name: kept.column(name).combine_chunks() for name in kept.column_names})
[docs] def run_attribution_from_backtest( backtest_result: Mapping[str, Any], market_data_bundle: Any, *, settings: AttributionSettings, factor_returns_directory: str | None = None, benchmark_weights: pa.Table | None = None, segment_map: Mapping[str, str] | None = None, ) -> AttributionResult: """ Attribute a finished Backtest-Engine run, without reading files for it. The portfolio is the engine's book: start-of-day weights (the end-of-day snapshot of the previous date, ``CASH_RESERVE`` renamed to ``settings.cash_ticker`` and earning 0) priced at the engine's mark-to-market prices. Brinson-Fachler and the active factor model build their benchmark from `benchmark_weights` x the engine's prices, and need the engine benchmark: its return (recomputed from its price) is the reported benchmark return. Textbook Brinson-Fachler cross-checks the holdings benchmark against it; without textbook, the active factor model does (legacy Brinson-Fachler alone does not). The factor model alone uses no benchmark, so it also runs on a backtest without one; when there is one, its dates bound the window, as every input's do. The attribution then runs exactly as for a file-based run (both call the shared attribution core, :func:`~kaxanuk.attribution_analysis.performance_attribution.attribute`), and the result carries an ``implementation`` table that reconciles the holdings return to the engine's NAV return. Parameters ---------- backtest_result : Mapping[str, Any] The engine's ``BacktestResultDict``, from ``backtester.run_with_benchmark()`` or ``kaxanuk.backtest_engine.main(...).data``. Must hold the keys of ``REQUIRED_RESULT_KEYS``. Its ``benchmark`` may be None (a run without a benchmark) only when Brinson-Fachler and the active factor model are off. market_data_bundle : Any The bundle the run was priced from (``backtester.market_data_bundle``), read by duck typing: ``price_tables["mark_to_market_price_column"]`` and ``date_column_name``. settings : AttributionSettings Which methods run and how; ``cash_ticker`` names the engine's cash. factor_returns_directory : str or None, default None Required with the factor model: a directory of per-factor return CSVs (``date`` x ticker), the file pipeline's format. A ticker absent from a factor file (the cash ticker, typically) has no exposure to that factor, so the factor-coverage log counts cash as uncovered. benchmark_weights : pyarrow.Table or None, default None Required with Brinson-Fachler or the active factor model, ignored (logged at INFO) otherwise: start-of-day constituent weights, a naive ``date`` column (``date32`` or timestamp at midnight) plus one numeric column per ticker. Every ticker with a non-zero weight must be priced in the backtest's mark-to-market table; as in the file pipeline, only textbook Brinson-Fachler and the active factor model price the benchmark's own constituents (legacy Brinson-Fachler alone uses the portfolio's tickers). With the textbook formula the remainder to 1 is cash. The weights should reproduce the engine benchmark: textbook Brinson-Fachler compares the return they imply with the engine benchmark's and logs a warning when they differ by more than 1 bp on any date (legacy skips the check). With Brinson-Fachler, dates they do not cover shorten the attribution window. With ``active_factor_model`` the factor files are also read for these tickers, and ``FactorModelResult.active`` holds the portfolio-minus-benchmark decomposition; its holdings benchmark is compared with the engine benchmark's return (once, unless textbook Brinson-Fachler already did). For the active factor model alone the weights do not bound the window: dates they do not cover are left out of ``FactorModelResult.active`` only, with one warning, so the portfolio's own numbers are the same with the option on or off. Without the textbook formula the weights are used as given, not topped up: one warning gives the number of active dates whose net weights differ from 1 by more than ``WEIGHT_SUM_TOLERANCE``, the first such date and its sum (below 1 the remainder is cash earning 0). segment_map : Mapping[str, str] or None, default None Ticker-to-segment map for textbook Brinson-Fachler (the cash ticker is its own segment unless mapped); None makes every ticker its own segment. Ignored by the legacy formula and the factor model, as in the file pipeline. Returns ------- AttributionResult The attribution of the holdings, with ``implementation`` set: columns ``IMPLEMENTATION_COLUMNS`` (see :func:`implementation_breakdown`), one row per date of ``portfolio_returns`` (the KPI dates). Its ``diagnostics`` hold the warnings and notes logged once the inputs were checked, as for a file-based run. Raises ------ LicenseError If the attribution licence is missing or invalid. ConfigurationError If no method is enabled, if Brinson-Fachler is enabled without `benchmark_weights`, if the factor model is enabled without `factor_returns_directory`, or if the active factor model is enabled without `benchmark_weights`. DataValidationError If the result has no benchmark while Brinson-Fachler or the active factor model is on (raised before any factor file is read), if the result or bundle breaks the engine contract (a missing key or column; repeated or unsorted dates; engine frames, or bundle dates inside the run window, that disagree; bad weights), if a weighted ticker has no price in the backtest, or if `benchmark_weights` is malformed (no ``date`` column, null, timezone-aware or intraday dates, non-numeric weights) or has no date inside the run's window. FileNotFoundError If `factor_returns_directory` does not exist. Notes ----- Holdings basis: ``summary_stats``, ``portfolio_returns`` and each method's portfolio return are the return of the start-of-day book at mark-to-market prices, before commissions, slippage, financing and execution. They differ from the engine's NAV return on trading and financing days; the ``implementation`` table holds that difference per date. The dashboard (``create_dashboard_from_result``) therefore shows the holdings return as the portfolio return; it does not show the ``implementation`` table. Day 0 (initial capital to the first end-of-day NAV) has no start-of-day book and is excluded, as the engine excludes it. Its initial-build costs and its return are excluded with it: the cost columns do not sum to the engine's ``Total_commissions`` / ``Total_slippage_costs`` / ``Total_financing_costs``, and ``engine_returns`` compounded over the whole run give ``NAV_last / NAV_day0 - 1``, not the return from the initial capital. The ``implementation`` table keeps exactly the dates of ``portfolio_returns`` (the KPI series), so its ``holdings_returns`` compound to the reported KPIs even when a date inside the window drops out of the attribution (e.g. one that `benchmark_weights` skip); for the whole run, call :func:`implementation_breakdown` on :func:`start_of_day_weights` and :func:`asset_returns_from_bundle`. """ validate_license() require_a_method(settings) if settings.brinson_fachler_method and benchmark_weights is None: raise ConfigurationError( "Brinson-Fachler needs benchmark_weights: the Backtest-Engine benchmark is a single ticker " "without constituents. Pass start-of-day constituent weights or set brinson_fachler_method=False." ) if settings.active_factor_model and benchmark_weights is None: raise ConfigurationError( "The active factor model needs benchmark_weights: the Backtest-Engine benchmark is a single ticker " "without constituents. Pass start-of-day constituent weights or set active_factor_model=False." ) if settings.factor_model_method and factor_returns_directory is None: raise ConfigurationError("The factor model needs factor_returns_directory (per-factor return CSVs).") check_result_keys(backtest_result) uses_benchmark_weights = settings.brinson_fachler_method or settings.active_factor_model engine_benchmark = backtest_result["benchmark"] if engine_benchmark is None and uses_benchmark_weights: raise DataValidationError( "The backtest has no benchmark. Brinson-Fachler and the active factor model attribute against one: " "their benchmark_weights stand for the engine benchmark, whose return is the reported benchmark return " "they are checked against (legacy Brinson-Fachler skips the check). Configure a benchmark in the " "Backtest-Engine run, or set brinson_fachler_method=False and active_factor_model=False: the factor " "model alone needs none." ) # The factor model alone never uses the benchmark return, so a run without a benchmark is attributed without it. benchmark_returns = ( None if engine_benchmark is None else ReturnsTable(table=benchmark_returns_from_backtest(engine_benchmark)) ) # Everything logged from here on is also kept on the result's diagnostics. with collect_diagnostics() as diagnostics: cash = settings.cash_ticker textbook = ( settings.brinson_fachler_method and settings.brinson_fachler_formula is BrinsonFachlerFormula.TEXTBOOK ) daily_weights = backtest_result["Daily_Weights"] portfolio = PortfolioWeights(table=start_of_day_weights(daily_weights, cash)) benchmark = None if benchmark_weights is not None and not uses_benchmark_weights: log_diagnostic( logger, DiagnosticCode.BENCHMARK_WEIGHTS_IGNORED, "benchmark_weights ignored: Brinson-Fachler and the active factor model are off " "(the factor model alone uses no benchmark).", level=DiagnosticLevel.INFO, ) elif benchmark_weights is not None: benchmark = PortfolioWeights(table=_benchmark_weights_table(benchmark_weights)) if textbook: portfolio = fill_implied_cash(portfolio, cash) if benchmark is not None: # always set here: textbook Brinson-Fachler required benchmark_weights above benchmark = fill_implied_cash(benchmark, cash) # As in the file pipeline, only textbook Brinson-Fachler and the active factor model price the benchmark's # constituents, and a constituent with weight 0 on every date needs no price. The bundle is one table on the # engine's dates, so they are priced with the portfolio's tickers. tickers = set(portfolio.asset_names) if benchmark is not None and (textbook or settings.active_factor_model): tickers |= set(weighted_columns(benchmark.table, "date")) tickers.discard(cash) window = _date_index(daily_weights) asset_returns = append_zero_return_column( ReturnsTable(table=asset_returns_from_bundle( market_data_bundle, tickers=sorted(tickers), start=window[0], end=window[-1] )), cash, ) # Before the attribution, so a contract breach (e.g. bundle dates unlike the engine's) fails fast. implementation = implementation_breakdown(backtest_result, portfolio.table, asset_returns.table, cash) factor_returns = {} # factor_returns_directory is never None here: the factor model without it was rejected above. if settings.factor_model_method and factor_returns_directory is not None: factor_returns = load_by_factor_returns_arrow( path=factor_returns_directory, available_factors=list_factor_return_files(factor_returns_directory), portfolio_weights=portfolio, benchmark_weights=benchmark if settings.active_factor_model else None, ) inputs = AttributionInputs( asset_returns=asset_returns, portfolio_weights=portfolio, benchmark_returns=benchmark_returns, benchmark_weights=benchmark, # The file pipeline's benchmark weights file bounds every run's window; here they bound it only when # Brinson-Fachler needs them, so the active factor model alone never changes the portfolio's window. benchmark_weights_bound_window=settings.brinson_fachler_method, factor_returns=factor_returns, segment_map=segment_map, ) result, _, _ = attribute(inputs, settings) return dataclasses.replace( result, implementation=_keep_dates(implementation, result.portfolio_returns.column("date")), diagnostics=tuple(diagnostics), )