Backtest-Engine Adapter#

Attribution straight from a finished KaxaNuk Backtest-Engine run (result layout of engine ENGINE_CONTRACT_VERSION = 0.67.0), and the per-date implementation table that reconciles the holdings return to the engine’s NAV return. The engine package is never imported. See From a Backtest-Engine run for a walkthrough and a worked example.

run_attribution_from_backtest and AttributionSettings are also exported from the package root (from kaxanuk.attribution_analysis import AttributionSettings, run_attribution_from_backtest).

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.

asset_returns_from_bundle(market_data_bundle: Any, *, tickers: Sequence[str], start: Timestamp, end: Timestamp) → Table[source]#

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:

date (timestamp[ns]) followed by one float64 return column per ticker; the first row is null.

Return type:

pyarrow.Table

Raises:

DataValidationError – If the bundle has no mark-to-market price table, or if a ticker has no price column (the message names them).

benchmark_returns_from_backtest(benchmark: Table | None) → Table[source]#

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 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:

date (timestamp[ns]) and benchmark_returns (float64), one row per benchmark date but the first.

Return type:

pyarrow.Table

Raises:

DataValidationError – If benchmark is None (the backtest has no benchmark) or lacks the date or mark-to-market price column.

check_result_keys(backtest_result: Mapping[str, Any]) → None[source]#

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.

implementation_breakdown(backtest_result: Mapping[str, Any], start_of_day: Table, asset_returns: Table, cash_ticker: str) → Table[source]#

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 start_of_day_weights().

  • asset_returns (pyarrow.Table) – date plus one return column per non-cash ticker of start_of_day, e.g. from 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:

Columns IMPLEMENTATION_COLUMNS, one row per date of start_of_day.

Return type:

pyarrow.Table

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).

run_attribution_from_backtest(backtest_result: Mapping[str, Any], market_data_bundle: Any, *, settings: AttributionSettings, factor_returns_directory: str | None = None, benchmark_weights: Table | None = None, segment_map: Mapping[str, str] | None = None) → AttributionResult[source]#

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, 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:

The attribution of the holdings, with implementation set: columns IMPLEMENTATION_COLUMNS (see 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.

Return type:

AttributionResult

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 implementation_breakdown() on start_of_day_weights() and asset_returns_from_bundle().

start_of_day_weights(daily_weights: DataFrame, cash_ticker: str) → Table[source]#

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:

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.

Return type:

pyarrow.Table

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).

Settings#

class AttributionSettings(*, brinson_fachler_method: bool, factor_model_method: bool, brinson_fachler_formula: BrinsonFachlerFormula | str = BrinsonFachlerFormula.TEXTBOOK, factor_return_type: FactorReturnType | str = FactorReturnType.SIMPLE, linking_method: LinkingMethod | str = LinkingMethod.CARINO, cash_ticker: str = 'CASH', risk_free_rate: float = 0.0, active_factor_model: bool = False)[source]#

Bases: object

Which attribution methods run, and how.

Shared by Configuration (file-based runs) and in-memory runs such as a Backtest-Engine result. Strings are coerced to the enums; invalid values raise.

Variables:
  • factor_model_method (brinson_fachler_method,) – Enable each method; at least one must be True when a run starts.

  • brinson_fachler_formula (BrinsonFachlerFormula, default TEXTBOOK) – Brinson-Fachler variant (see BrinsonFachlerFormula).

  • factor_return_type (FactorReturnType, default SIMPLE) – Compounding convention of the factor returns (see FactorReturnType).

  • linking_method (LinkingMethod, default CARINO) – How per-period effects are combined over time (see LinkingMethod).

  • cash_ticker (str, default "CASH") – Column name of the zero-return cash segment (stripped).

  • risk_free_rate (float, default 0.0) – Annual risk-free rate as a decimal (0.03 = 3%) for the Sharpe ratio of summary_stats, converted to a per-period rate over 252 periods a year. Finite and above -1; an int is accepted and stored as float.

  • active_factor_model (bool, default False) – Also run the factor model on the benchmark’s constituent weights and report the portfolio-minus-benchmark decomposition (FactorModelResult.active). Needs factor_model_method and benchmark weights.

Raises:

ConfigurationError – If a flag is not a bool, an option is not a valid enum value, cash_ticker is not a non-empty string, risk_free_rate is not a finite real number above -1, or active_factor_model is not a bool or is on without factor_model_method.