Running from Python#
The entry script (__main__.py) does this for you, but you can drive the pipeline directly if
you need finer control (e.g. from a notebook or a custom orchestration script):
import logging
from pathlib import Path
from kaxanuk.attribution_analysis.config_handlers.excel_configurator import ExcelConfigurator
from kaxanuk.attribution_analysis.performance_attribution import main
from kaxanuk.attribution_analysis.services.configuration_logger import configure_logger
from kaxanuk.attribution_analysis.services.env_loader import load_config_env
# Load Config/.env (the licence key KNAA_API_KEY_KAXANUK)
load_config_env()
configure_logger(
logger_name="kaxanuk.attribution_analysis",
logger_level=logging.INFO,
logger_format="[%(levelname)s] %(message)s",
logger_file=None,
)
# Load and validate the Excel configuration
configurator = ExcelConfigurator(Path("Config") / "attribution_analysis_parameters.xlsx")
configuration = configurator.get_configuration()
# Run the full attribution pipeline
main(
configuration,
launch_dashboard=True,
dashboard_port=configurator.get_dashboard_port(),
)
main() returns the same AttributionResult
that run_attribution() returns. It first passes the result to its output
handlers: by default the Excel report, written to configuration.output_directory (see
The Excel Report); output_handlers=[...] replaces them and output_handlers=() writes
nothing (see Output Handlers). With launch_dashboard=False it draws
static matplotlib plots instead of starting the dashboard. The dashboard binds to 127.0.0.1 with
Dash’s debug mode off; both can be changed from Python:
main(
configuration,
launch_dashboard=True,
dashboard_port=configurator.get_dashboard_port(),
dashboard_host="0.0.0.0", # listen on every interface (default "127.0.0.1")
dashboard_debug=False, # Dash debug mode (default False)
)
Dash’s debug mode serves the Werkzeug debugger. Whoever reaches the port sees tracebacks with your
source code when an error occurs, and the debugger’s console, which runs code on the machine, is
guarded only by the PIN printed in your terminal. Turn debug mode on only with the default host
127.0.0.1; debug mode with any other host logs a warning.
Getting results as data#
run_attribution(configuration) runs the same pipeline as main() but only returns the
numbers: it never draws a plot, never starts the dashboard and never writes a file (pass its result
to ExcelOutputHandler or write_excel_report() for the Excel report). It validates the licence first and
raises ConfigurationError if both brinson_fachler_method and factor_model_method are off.
from pathlib import Path
from kaxanuk.attribution_analysis import run_attribution
from kaxanuk.attribution_analysis.config_handlers.excel_configurator import ExcelConfigurator
configuration = ExcelConfigurator(
Path("Config") / "attribution_analysis_parameters.xlsx"
).get_configuration()
result = run_attribution(configuration)
print(result.start_date, result.end_date) # the common date window
print(result.summary_stats["Total Return"]) # compounded total return
print(result.brinson_fachler.cumulative) # pyarrow Table
print(result.factor_model.cumulative_shares) # {factor: share of the cumulative return}
for diagnostic in result.diagnostics: # the warnings the run logged
print(diagnostic.code, diagnostic.count, diagnostic.first_date)
The result is a frozen AttributionResult. Tables are PyArrow tables keyed by a date column;
mappings are read-only. A result can be pickled, deep-copied and passed to
dataclasses.asdict, and repr(result) is a one-line summary.
Field |
Contents |
|---|---|
|
The common date window all inputs were aligned to, as |
|
|
|
|
|
|
|
|
|
|
|
The warnings (and a few notes) the run logged, in order, as |
|
The |
|
The portfolio against that benchmark: |
brinson_fachler.by_year and factor_model.by_year hold one row per calendar year (column
year), linked within the year exactly as the cumulative tables link the whole window: a year’s
effects add up to its own return difference, and years compound into the window.
With linking_method set to carino or grap the cumulative tables are linked and
cumulative_totals reconciles to the compounded return and to cumulative_contributions. With
none, cumulative_totals is an arithmetic running sum over the dates that have a return, so
cumulative_totals["portfolio_returns"] differs from summary_stats["Total Return"].
cumulative_contributions is then a running sum over every attribution date, including dates
without a return such as the first price date, so cumulative_totals["factor_returns"] need not
equal the sum of the per-factor cumulative_contributions columns.
Options set from Python#
Two options have no row in the Excel parameters file. Set them on the configuration before running:
import dataclasses
configuration = dataclasses.replace(
configuration,
risk_free_rate=0.03, # annual, decimal: 3%
active_factor_model=True, # needs factor_model_method and benchmark weights
)
result = run_attribution(configuration)
active = result.factor_model.active
print(active.returns) # date, portfolio_returns, benchmark_returns, active_returns
print(active.cumulative_contributions) # active effect per factor and component, plus f_idio_returns
print(active.cumulative_totals) # portfolio, benchmark and active returns, factors, components, residual
risk_free_rate(default 0.0): annual risk-free rate as a decimal, used only by the Sharpe ratio insummary_stats(converted to a daily rate over 252 periods a year). It must be finite and above -1.active_factor_model(default False): also runs the factor model on the benchmark’s constituent weights and stores the portfolio-minus-benchmark decomposition inresult.factor_model.active(anActiveFactorResult). It requiresfactor_model_method. Every benchmark constituent with a non-zero weight needs a price file, and the factor files are read for the benchmark’s tickers too. Each date’s active contributions add up toactive_returns. The cumulative ones are linked withlinking_methodagainst the holdings benchmark return, so withcarinoorgrapthey add up to the compoundedR_p - R_b; withnonethey are running sums. The active window can be shorter than the portfolio’s: dates without a benchmark return or benchmark weights are dropped, with one warning, and withnonethe first price date (in the portfolio’s tables, without a return) is left out. A weighted constituent without a return on a kept date counts as 0, with one warning. Turning the option on never changes the portfolio’s own numbers, in file runs and in Backtest-Engine runs. The dashboard does not show the active results yet. See Factor Model for the formulas and requirements.
AttributionSettings takes the same two arguments for a Backtest-Engine run.
From a Backtest-Engine run#
run_attribution_from_backtest() attributes a finished KaxaNuk Backtest-Engine run straight from
its in-memory result. Nothing is read from disk for the portfolio, its prices or the benchmark
return: they come from the engine’s result dict and from the market data bundle it was priced from.
Only the factor-return CSVs (factor model) and, for Brinson-Fachler or the active factor model, the
benchmark’s constituent weights are supplied separately. The method options live in an AttributionSettings, the same
validated settings that the Excel configuration uses.
import pandas as pd
import pyarrow as pa
from kaxanuk.attribution_analysis import AttributionSettings, run_attribution_from_backtest
# A Backtest-Engine 0.67.0 backtester, created as usual (e.g. PyArrowBacktesterFast.create_from_configuration)
backtest_result = backtester.run_with_benchmark() # the BacktestResultDict
bundle = backtester.market_data_bundle # the prices the run was valued at
# Factor model only: needs a folder of per-factor return CSVs (date x ticker), no engine benchmark
result = run_attribution_from_backtest(
backtest_result,
bundle,
settings=AttributionSettings(brinson_fachler_method=False, factor_model_method=True),
factor_returns_directory="Input/Factor_Models",
)
# Brinson-Fachler: needs the benchmark's start-of-day constituent weights, one row per
# attribution date: every engine date but the first (day 0 has no start-of-day book)
dates = pd.DatetimeIndex(backtest_result["Daily_Weights"].index[1:]).normalize()
benchmark_weights = pa.table({
"date": pa.array(dates), # naive timestamps at midnight (date32 also works)
"AAA": [0.25] * len(dates),
"BBB": [0.25] * len(dates),
"CCC": [0.25] * len(dates),
"DDD": [0.25] * len(dates),
})
result = run_attribution_from_backtest(
backtest_result,
bundle,
settings=AttributionSettings(brinson_fachler_method=True, factor_model_method=False, cash_ticker="USD"),
benchmark_weights=benchmark_weights,
segment_map={"AAA": "Tech", "BBB": "Tech", "CCC": "Energy", "DDD": "Energy"}, # optional
)
result.summary_stats["Total Return"] # the holdings' compounded return
result.implementation # holdings vs engine NAV, per date
backtest_result can also be kaxanuk.backtest_engine.main(...).data. The function returns the
same AttributionResult as run_attribution(), with implementation set.
Holdings basis. The portfolio is the engine’s book at the start of each day: the end-of-day
Daily_Weights snapshot of the previous date (the engine snapshots after trading). It is priced at
the engine’s mark-to-market prices. summary_stats, portfolio_returns and each method’s
portfolio return are therefore the return of that book before commissions, slippage, financing and
trade execution. They match the engine’s NAV return on quiet days and differ on trading and financing
days. The implementation table holds the difference.
The dashboard shows the holdings return.
create_dashboard_from_result()(and therefore themain()flows) plots and reports the holdings-basis return as the portfolio return, not the engine’s NAV return; in the test fixture, 9.07% against 8.82%. Theimplementationtable is not shown in the dashboard yet.Day 0 is excluded. The first engine date (initial capital to the first end-of-day NAV) has no start-of-day book, and the engine excludes it too. Its initial-build costs and its return are excluded with it. So the cost columns do not sum to the engine’s
Total_commissions,Total_slippage_costsandTotal_financing_costs(in the test fixture, 708.35 of the 2,262.30 of commissions and 489.91 of the 1,193.57 of slippage fall on day 0). Compounded over the whole run,engine_returnsgives \(NAV_{last} / NAV_{day 0} - 1\) (8.82% in the fixture), not the return from the initial capital (8.67%).Cash. The engine’s
CASH_RESERVEcolumn is renamed tosettings.cash_tickerand earns 0. Interest on cash is booked in thefinancingcolumn ofimplementation(positive when it is a credit). Columns that are 0 on every start-of-day row are dropped, such as the benchmark ETF the engine prices but never holds.
The implementation table. One row per attribution date, columns date, engine_returns,
holdings_returns, commissions, slippage, financing and execution, such that on
every date
engine_returns is \(NAV_t / NAV_{t-1} - 1\) from the engine’s Total_Portfolio_Value.
holdings_returns is \(\sum_i w_{i,t}^{sod} r_{i,t}\). The three costs are the engine’s
currency amounts for the date as negative fractions of \(NAV_{t-1}\) (0 on a date the engine
booked nothing). execution is the remainder. It holds the trade-execution price versus the close
on traded shares, plus any other NAV movement that the holdings and the three cost columns do not
explain (forced exits, for example) and rounding. It is about 0 on dates without trades. On the
test fixture’s rebalance days, execution times \(NAV_{t-1}\) equals
\(\sum_i q_i (close_i - p_i)\) over the traded shares \(q_i\) at reference price
\(p_i\), to within the NAV’s cent rounding.
Slippage is already inside the engine’s fill price. execution is measured from the
trade-execution (reference) price before slippage, and slippage has its own column, so slippage is
never counted twice.
A worked example. \(NAV_{t-1} = 106\), of which 66 is in A and 40 in cash. On day t, A rises 10% (66 to 72.6), and one share of B is bought at a fill of 21 (reference price 20.7 plus slippage 0.3) while B closes at 20. Commission is 0.5 and financing 0.2. Cash ends at \(40 - 21 - 0.5 - 0.2 = 18.3\) and \(NAV_t = 72.6 + 20 + 18.3 = 110.9\).
Column |
Value |
Why |
|---|---|---|
|
\(4.9 / 106\) |
\(110.9 / 106 - 1\) |
|
\(6.6 / 106\) |
\((66/106) \times 10\%\); B was not in the start-of-day book |
|
\(-0.5 / 106\) |
|
|
\(-0.3 / 106\) |
inside the fill price |
|
\(-0.2 / 106\) |
|
|
\(-0.7 / 106\) |
\(1 \times (20 - 20.7)\): reference price vs close |
The rows add up: \(6.6 - 0.5 - 0.3 - 0.2 - 0.7 = 4.9\).
implementation keeps exactly the dates of portfolio_returns (the KPI dates), including when a
date inside the window drops out of the attribution (for example a date the benchmark weights skip).
Compounding its holdings_returns therefore gives summary_stats["Total Return"]. For the whole
run (for example when the benchmark weights cover a shorter period), call implementation_breakdown()
on start_of_day_weights() and asset_returns_from_bundle().
Contract checks. Returns are taken over consecutive rows, so the adapter raises
DataValidationError when Register_df or Daily_Weights has repeated or unsorted dates, when
the two frames’ dates differ, or when the bundle’s dates between the first and last engine date are not
exactly the engine’s (a date the bundle prices but the engine never valued would otherwise fold two
days’ moves into one return). A Financing_df with rows but no Financing_Cost column also
raises; an empty one means financing was off. Prices convert to float64 exactly as the file pipeline
converts its price files, and decimal benchmark_weights exactly as it converts weight files
(float(Decimal)).
Benchmarks. The engine’s benchmark is a single ticker without constituents. Its return, recomputed from its mark-to-market price, is the reported benchmark return.
The factor model alone uses no benchmark, so it also runs on a backtest without one (
backtest_result["benchmark"]isNone). When there is one, its dates still bound the attribution window, as every input’s do; in the test fixture they cover the whole run, so the numbers are the same with or without it.benchmark_weightsis ignored (logged at INFO) when both Brinson-Fachler andactive_factor_modelare off.Brinson-Fachler and
active_factor_modelneed the engine benchmark: theirbenchmark_weightsstand for it, and its return is the one they are cross-checked against. On a backtest without a benchmark they raiseDataValidationErrorbefore any factor file is read.Brinson-Fachler requires
benchmark_weightsand raisesConfigurationErrorwithout them; it is never switched off silently. The table has adatecolumn (date32, or naive timestamps at midnight, without nulls) and one numeric column per constituent, with start-of-day weights. With the textbook formula the remainder to 1 is cash. Dates the weights do not cover shorten the attribution window.With the textbook formula or
active_factor_modelevery constituent with a non-zero weight must be priced in the engine run, and the benchmark return is those weights times the engine’s prices. Legacy Brinson-Fachler alone, as in the file pipeline, uses the portfolio’s tickers only and prices no benchmark-only constituent. With the textbook formula the benchmark return is compared with the engine benchmark’s return, and a warning is logged when the two differ by more than 1 bp on any date. The warning is the intended signal that the weights do not reproduce the engine benchmark. The legacy formula skips this check.active_factor_modelalso requiresbenchmark_weightsand raisesConfigurationErrorwithout them. The factor files are then read for the constituents too. The active decomposition’s holdings benchmark is compared once with the engine benchmark’s return (textbook Brinson-Fachler, when on, already runs that check). Without textbook Brinson-Fachler the weights are not topped up with cash: cash earns 0 and has no factor exposure, so topping up would change no number. They are used as given, and one warning gives the number of active dates whose net weights differ from 1 by more than 1e-6, the first such date and its sum. With Brinson-Fachler off the weights do not bound the attribution window: the dates they do not cover are left out of the active results only, with one warning, so turning the option on never changes the portfolio’s own numbers. Weights without a date inside the run’s window raiseDataValidationError.segment_mapgroups tickers into segments for textbook Brinson-Fachler only, as in the file pipeline.The factor model reads
factor_returns_directoryin the file pipeline’s format. The cash ticker has no factor exposure, so the factor-coverage log counts it as uncovered.
Known limitation. With textbook Brinson-Fachler or active_factor_model, benchmark
constituents must be in the engine’s universe, that is, priced in the bundle’s mark-to-market table.
A weighted constituent the run did not price raises DataValidationError naming it. The adapter
does not read prices from any other source.
Engine version. The adapter reads Backtest-Engine 0.67.0’s result layout
(ENGINE_CONTRACT_VERSION). The contract is pinned by a fixture generated from the real engine
and committed with the tests. A live test re-runs the engine where it is installed and fails if the
engine version or result layout changes. The attribution package never imports
kaxanuk.backtest_engine. It reads the result dict, the pandas frames and the Arrow tables by
duck typing, so the engine is not a dependency.
See API Reference for the full reference on main(), run_attribution(),
ExcelConfigurator, and the other public entry points used above.