Performance Attribution#
The top-level orchestration module. run_attribution() loads market and portfolio data, aligns
date ranges, executes Brinson-Fachler and/or factor-model attribution, and returns an
AttributionResult without plotting or writing a file. main() does the same, passes the result
to its output handlers (by default the Excel report), and then plots or launches the interactive dashboard, returning the same result.
attribute() is the attribution core both share with in-memory runs such as
run_attribution_from_backtest(): it aligns already-loaded AttributionInputs to their common
date window and runs the enabled methods. require_a_method() and weighted_columns() are the
helpers those callers share with it.
Performance Attribution Pipeline#
Main orchestration module for running multi-method portfolio performance attribution analysis.
run_attribution runs the full attribution workflow – loading market and
portfolio data, aligning date ranges, executing Brinson-Fachler and/or
factor-model attribution, computing summary statistics – and returns an
AttributionResult (PyArrow tables and read-only mappings); it never plots,
never starts a dashboard and never writes a file. main runs the same
workflow, passes the result to its output handlers (by default the Excel report,
written to Configuration.output_directory), then shows static plots or
serves the interactive dashboard, and returns the same result.
attribute is the attribution core they share with in-memory runs: it
aligns already-loaded inputs (an AttributionInputs) to their common date
window and runs the enabled methods. File-based runs read the configured files
into those inputs (_load_inputs) and call it; in-memory runs, such as the
Backtest-Engine adapter (run_attribution_from_backtest), build the inputs
themselves and call it, with require_a_method and weighted_columns, so
both compute the same way. The three are public because callers in other
modules rely on them: renaming or changing them is an API change. Being public,
attribute validates the licence itself, like every other entry point (once
per process, so the entry points that call it pay nothing more).
Notes
The pipeline supports two attribution methodologies that can be enabled
independently via the Configuration object (at least one must be):
Brinson-Fachler – decomposes active return into allocation, selection and interaction per segment (ticker by default, or a segment map), textbook formula by default.
Factor Model – decomposes portfolio return into portfolio-weighted factor contributions plus an idiosyncratic residual.
Cumulative outputs (Brinson-Fachler indexes, factor contributions and shares)
are linked across periods per Configuration.linking_method (carino by
default, grap or none) so they reconcile to the compounded return. The
legacy Brinson-Fachler formula is never linked.
All intermediate computations use PyArrow columnar tables for memory efficiency and vectorized operations.
Examples
>>> from kaxanuk.attribution_analysis.entities.configuration import Configuration
>>> from kaxanuk.attribution_analysis.performance_attribution import main, run_attribution
>>>
>>> config = Configuration(
... input_directory="data/input",
... weights_portfolio_directory="weights/portfolio",
... weights_benchmark_directory="weights/benchmark",
... benchmark_returns_directory="returns/benchmark",
... investable_assets_directory="data/prices",
... factor_returns_by_factor_directory="data/factors",
... portfolio_file_name="portfolio_weights.csv",
... benchmark_file_name="benchmark_weights.csv",
... benchmark_return_file_name="benchmark_returns.csv",
... user_column_date="date",
... user_column_price="close",
... market_data_input_format="csv",
... portfolio_input_format="csv",
... start_date="auto",
... end_date="auto",
... brinson_fachler_method=True,
... factor_model_method=True,
... )
>>> result = run_attribution(config) # data only
>>> result.summary_stats["Total Return"]
>>> main(config, launch_dashboard=True, dashboard_port=8050) # same result, plus the dashboard
- attribute(inputs: AttributionInputs, settings: AttributionSettings) tuple[AttributionResult, BrinsonFachlerArrowAttribution | None, FactorModelArrowAttribution | None][source]#
Align the inputs to their common date window and run the enabled methods.
The shared attribution core: file-based runs (
run_attribution()andmain(), through_run()) and in-memory runs, such as the Backtest-Engine adapter (run_attribution_from_backtest()), call it on loaded inputs, so both compute the same way. Being public, it validates the licence before anything else, like those entry points (the validation runs once per process, so calling it from them costs nothing).- Parameters:
inputs (AttributionInputs) – Loaded inputs (see
AttributionInputs).settings (AttributionSettings) – Which methods run, and how.
- Returns:
(result, brinson_fachler, factor_model): theAttributionResult, and the attribution objects that produced it (Nonefor a disabled method).- Return type:
tuple
- Raises:
LicenseError – Raised before the inputs are read when the licence does not validate.
ConfigurationError – If neither method is enabled, Brinson-Fachler is enabled without benchmark weights, or the active factor model is enabled without benchmark weights.
DataValidationError – If the benchmark weights do not bound the window (see
AttributionInputs.benchmark_weights_bound_window) and none of their dates is inside it.
Notes
The window is the dates every bounding table covers: asset returns, portfolio weights, every factor table and, when given, the benchmark returns, plus the benchmark weights when Brinson-Fachler runs or
inputs.benchmark_weights_bound_windowis True. When they do not bound it, the active factor model still gets only their dates inside the window and drops the window dates they do not cover, with one warning.The benchmark returns are only a cross-check: textbook Brinson-Fachler, or else the active factor model, compares its holdings benchmark return with them. Without them (
inputs.benchmark_returnsisNone) that check is skipped, with an INFO log when a method would have run it, and the factor model getsNone(it stores them but never uses them).Every warning (and those INFO notes) logged while it runs is also kept on
result.diagnostics. Inside a caller’scollect_diagnostics()block, as inrun_attribution(), they follow the caller’s own, such as those logged while the inputs were loaded.
- main(configuration: Configuration, *, launch_dashboard: bool = True, dashboard_port: int, dashboard_host: str = '127.0.0.1', dashboard_debug: bool = False, output_handlers: Sequence[OutputHandlerInterface] | None = None) AttributionResult[source]#
Run the full performance attribution pipeline, write its outputs, then plot or serve the dashboard.
Computes everything as
run_attribution()does (data loading, date-range alignment, attribution, summary statistics), passes the result to each of output_handlers (by default the Excel report, written toconfiguration.output_directoryand named afterportfolio_file_name), then either draws the static matplotlib plots or serves the interactive Dash dashboard.- Parameters:
configuration (Configuration) –
Frozen dataclass holding all runtime settings including:
Directory paths –
input_directory,weights_portfolio_directory,weights_benchmark_directory,benchmark_returns_directory,investable_assets_directory,factor_returns_by_factor_directory.File names –
portfolio_file_name,benchmark_file_name,benchmark_return_file_name.Column mappings –
user_column_date,user_column_price.Input formats –
market_data_input_format("csv"|"parquet"),portfolio_input_format("csv"|"excel").Date range –
start_date,end_date(datetime.date|"auto").Method flags –
brinson_fachler_method,factor_model_method(bothbool; at least one must beTrue).Linking –
linking_method("carino"|"grap"|"none"): how cumulative effects are linked across periods. Applies to textbook Brinson-Fachler and the factor model; the legacy formula is never linked.Report –
output_directory("Output"by default): where the Excel report is written.
launch_dashboard (bool, default True) – If
True, serve a Dash web application with interactive attribution charts and summary statistics (blocks until the server stops). WhenFalse, static matplotlib plots of the enabled methods are shown instead.dashboard_port (int) – TCP port on which the Dash server listens when
launch_dashboard=True. Required (no default); typically read from the configuration viaExcelConfigurator.get_dashboard_port().dashboard_host (str, default "127.0.0.1") – Interface the Dash server binds to.
dashboard_debug (bool, default False) – Run the Dash server in debug mode. It serves the Werkzeug debugger, which shows tracebacks with source code to anyone and guards its code-running console only with a PIN, so a warning is logged when it is combined with a dashboard_host that is not a loopback address.
output_handlers (Sequence[OutputHandlerInterface] or None, default None) – Where the result is written, in order, before any plot or dashboard (see
output_handlers).Nonewrites the Excel report:[ExcelOutputHandler.from_configuration(configuration)]. An empty sequence writes nothing.
- Returns:
The same result
run_attribution()returns.- Return type:
- Raises:
LicenseError – Raised before anything is read when the license does not validate (
services.license_validator.validate_license()): one ofLicenseNotFoundError,LicenseValidationError,LicenseServerErrororLicenseConfigurationError.FileNotFoundError – If any configured data directory or file does not exist.
ConfigurationError – If neither attribution method is enabled, or
configurationcontains invalid field values (raised duringConfiguration.__post_init__).OSError – If an output handler cannot write (the Excel report, by default), raised before any plot or dashboard.
Notes
All input tables (asset returns, portfolio weights, benchmark weights, benchmark returns, and factor returns) are aligned to the intersection of their date ranges before any attribution calculation. This prevents shape mismatches and ensures consistent time-series indexing across methods.
The pipeline proceeds in five stages:
Data loading – market prices, portfolio/benchmark weights, benchmark returns, and per-factor return series are read from disk using the appropriate input handlers.
Date alignment – the common start/end dates across all tables are computed and each table is filtered accordingly.
Attribution – enabled methods (Brinson-Fachler, Factor Model) are executed sequentially, then the summary statistics are computed.
Outputs – the output handlers write the result (by default the Excel report, to
output_directory).Visualisation – results are either plotted (matplotlib) or served via an interactive Dash dashboard.
Examples
Run attribution without the dashboard (static plots):
>>> result = main(config, launch_dashboard=False, dashboard_port=8050)
Run only the Brinson-Fachler method with the dashboard disabled:
>>> config = Configuration(..., brinson_fachler_method=True, ... factor_model_method=False) >>> result = main(config, launch_dashboard=False, dashboard_port=8050)
- require_a_method(settings: AttributionSettings) None[source]#
Raise unless at least one attribution method is enabled.
Part of the shared attribution core: every entry point, file-based (
run_attribution(),main()) or in-memory (such as the Backtest-Engine adapter), calls it before reading any input, andattribute()calls it again.- Parameters:
settings (AttributionSettings) – Supplies the method flags.
- Raises:
ConfigurationError – If neither method is enabled.
- run_attribution(configuration: Configuration) AttributionResult[source]#
Run the attribution and return the results as data.
Validates the licence, loads and aligns the inputs, runs the enabled methods, and returns an
AttributionResult. It never plots, never starts a dashboard and never writes a file: to write the result, pass it to an output handler, e.g.ExcelOutputHandler("Output").output_result(result=result)(seeoutput_handlers).- Parameters:
configuration (Configuration) – Runtime settings (see
main()).- Returns:
Per-method results (
Nonefor a disabled method), the aligned date window, the KPI return series and its summary statistics, and the warnings logged while loading and attributing (diagnostics).- Return type:
- Raises:
LicenseError – Raised before anything is read when the license does not validate.
ConfigurationError – If neither method is enabled.
FileNotFoundError – If any configured data directory or file does not exist.
- weighted_columns(weights: Table, date_column: str) list[str][source]#
Ticker columns with a non-zero weight on at least one date.
Part of the shared attribution core: file-based runs and in-memory runs (such as the Backtest-Engine adapter) use it to choose the benchmark constituents to price, and
attribute()to drop zero-weight columns before textbook Brinson-Fachler.NaN weights count as non-zero, so they reach the validation downstream instead of being dropped silently.
- Parameters:
weights (pa.Table) – Weights with date_column plus one column per ticker.
date_column (str) – Date column name.
- Returns:
Ticker columns, in table order.
- Return type:
list[str]