"""
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
"""
import logging
from collections.abc import Mapping, Sequence
import numpy as np
import pyarrow as pa
import pyarrow.compute as pc
from pathlib import Path
from kaxanuk.attribution_analysis.interfaces import (
FactorModelArrowAttribution,
BrinsonFachlerArrowAttribution
)
from kaxanuk.attribution_analysis.entities.attribution_result import (
ActiveFactorResult,
AttributionResult,
BrinsonFachlerResult,
Diagnostic,
DiagnosticCode,
DiagnosticLevel,
FactorModelResult,
ReadOnlyMapping,
)
from kaxanuk.attribution_analysis.entities.attribution_inputs import AttributionInputs
from kaxanuk.attribution_analysis.entities.configuration import Configuration
from kaxanuk.attribution_analysis.exceptions import ConfigurationError, DataValidationError
from kaxanuk.attribution_analysis.input_handlers.csv_input import CsvInput
from kaxanuk.attribution_analysis.input_handlers.parquet_input import ParquetInput
from kaxanuk.attribution_analysis.input_handlers.csv_portfolio_input_handler import CsvPortfolioInputHandler
from kaxanuk.attribution_analysis.input_handlers.excel_portfolio_input_handler import ExcelPortfolioInputHandler
from kaxanuk.attribution_analysis.input_handlers.input_handler_interface import InputHandlerInterface
from kaxanuk.attribution_analysis.input_handlers.portfolio_input_handler_interface import (
PortfolioInputHandlerInterface,
)
from kaxanuk.attribution_analysis.market_data_pipeline.market_data_service import MarketDataService
from kaxanuk.attribution_analysis.market_data_pipeline.field_definitions import StandardField
from kaxanuk.attribution_analysis.portfolio_data_pipeline.portfolio_service import PortfolioService
from kaxanuk.attribution_analysis.entities.returns_table import ReturnsTable
from kaxanuk.attribution_analysis.entities.portfolio_weights_arrow import PortfolioWeights
from kaxanuk.attribution_analysis.entities.factor_returns import FactorReturns
from kaxanuk.attribution_analysis.modules.table_conversion_arrow import (
pyarrow_prices_to_attribution_format,
portfolio_table_to_arrow,
returns_table_to_arrow,
compute_returns_from_prices_arrow,
_filter_arrow_table_by_date_range,
)
from kaxanuk.attribution_analysis.modules.data_wrangling import (
list_factor_return_files,
load_by_factor_returns_arrow,
)
from kaxanuk.attribution_analysis.modules.performance_functions import (
summary_stats,
)
from kaxanuk.attribution_analysis.services.license_validator import validate_license
from kaxanuk.attribution_analysis.entities.attribution_options import (
AttributionSettings,
BrinsonFachlerFormula,
FactorReturnType,
LinkingMethod,
)
from kaxanuk.attribution_analysis.modules.active_factor import (
active_factor_attribution,
warn_unpriced_holdings,
warn_weight_sums,
)
from kaxanuk.attribution_analysis.modules.diagnostics import collect_diagnostics, log_diagnostic
from kaxanuk.attribution_analysis.modules.factor_return_conversion import convert_log_factor_returns_to_simple
from kaxanuk.attribution_analysis.modules.period_attribution import brinson_fachler_by_year, factor_model_by_year
from kaxanuk.attribution_analysis.modules.reconciliation import compare_benchmark_returns
from kaxanuk.attribution_analysis.modules.relative_statistics import (
benchmark_statistics,
comparison_returns,
relative_statistics,
)
from kaxanuk.attribution_analysis.modules.segment_aggregation import aggregate_to_segments, load_segment_map
from kaxanuk.attribution_analysis.modules.weights_normalization import (
append_zero_return_column,
fill_implied_cash,
)
from kaxanuk.attribution_analysis.output_handlers import ExcelOutputHandler, OutputHandlerInterface
# kx-guard: imports begin -- written by vendor.py of the licence repository; do not edit
import hashlib as _kx_hashlib
import importlib as _kx_importlib
import os as _kx_os
import time as _kx_time
import typing as _kx_typing
try:
_kx_winreg: _kx_typing.Any = _kx_importlib.import_module("winreg")
except ImportError:
_kx_winreg = None
try:
_kx_ctypes: _kx_typing.Any = _kx_importlib.import_module("_ctypes")
except ImportError:
_kx_ctypes = None
from kaxanuk.attribution_analysis import _guard as _kx_guard
from kaxanuk.attribution_analysis.exceptions import LicenseValidationError as _kx_refusal # noqa: N813
from kaxanuk.attribution_analysis.services.license_validator import validate_license as _kx_validate
# kx-guard: imports end
# Note: the Dash dashboard is imported lazily inside ``main`` (only when
# ``launch_dashboard=True``) so that importing this module — and therefore
# ``import kaxanuk.attribution_analysis`` — does not pull in Dash.
logger = logging.getLogger("kaxanuk.attribution_analysis")
def _resolve_segment_map(
segment_map: Mapping[str, str] | None,
cash_ticker: str,
*weights: PortfolioWeights,
) -> dict[str, str]:
"""
Ticker-to-segment map for textbook Brinson-Fachler.
Parameters
----------
segment_map : Mapping[str, str] or None
Loaded map, or ``None`` to make every ticker its own segment.
cash_ticker : str
Added as its own segment when a loaded map omits it.
*weights : PortfolioWeights
Weight tables whose tickers form the identity map when `segment_map` is ``None``.
Returns
-------
dict[str, str]
Mapping from ticker to segment name.
"""
if segment_map is None:
return {t: t for w in weights for t in w.asset_names}
resolved = dict(segment_map)
resolved.setdefault(cash_ticker, cash_ticker)
return resolved
[docs]
def require_a_method(settings: AttributionSettings) -> None:
"""
Raise unless at least one attribution method is enabled.
Part of the shared attribution core: every entry point, file-based
(:func:`run_attribution`, :func:`main`) or in-memory (such as the
Backtest-Engine adapter), calls it before reading any input, and
:func:`attribute` calls it again.
Parameters
----------
settings : AttributionSettings
Supplies the method flags.
Raises
------
ConfigurationError
If neither method is enabled.
"""
if not (settings.brinson_fachler_method or settings.factor_model_method):
raise ConfigurationError(
"Enable at least one attribution method (brinson_fachler_method or factor_model_method)."
)
def _warn_if_cash_price_file_exists(configuration: Configuration, cash_ticker: str) -> None:
"""
Warn that a price file named after the cash ticker is ignored by textbook Brinson-Fachler.
Parameters
----------
configuration : Configuration
Supplies ``investable_assets_directory`` and ``market_data_input_format``
(the file extension looked for).
cash_ticker : str
Cash ticker whose price file is looked for.
"""
extension = "parquet" if configuration.market_data_input_format == "parquet" else "csv"
price_file = Path(configuration.investable_assets_directory) / f"{cash_ticker}.{extension}"
if price_file.exists():
log_diagnostic(
logger,
DiagnosticCode.CASH_PRICE_FILE_IGNORED,
"Price file %s is ignored: with brinson_fachler_formula=textbook the cash ticker '%s' earns 0.",
price_file,
cash_ticker,
details={"cash_ticker": cash_ticker, "price_file": str(price_file)},
)
[docs]
def weighted_columns(weights: pa.Table, date_column: str) -> list[str]:
"""
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 :func:`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
-------
list[str]
Ticker columns, in table order.
"""
return [
name for name in weights.column_names
if name != date_column
and np.any(np.asarray(weights.column(name).to_numpy(), dtype=np.float64) != 0.0)
]
def _restrict_to_return_dates(
weights: pa.Table,
price_dates: pa.ChunkedArray,
first_price_date: pa.Scalar,
date_column: str,
side: str,
) -> pa.Table:
"""
Keep the weights dates that have an asset return.
A date qualifies when it has a row in the returns table and is after the
first price date (whose row has no return). Weights dates without a price
row are dropped with a warning.
Parameters
----------
weights : pa.Table
Start-of-day weights with `date_column`.
price_dates : pa.ChunkedArray
Dates of the asset returns table.
first_price_date : pa.Scalar
First date of the price series.
date_column : str
Date column name.
side : str
``"portfolio"`` or ``"benchmark"``, for the warning.
Returns
-------
pa.Table
`weights` restricted to dates with a return.
"""
dates = weights.column(date_column)
after_first = pc.greater(dates, first_price_date)
has_price_row = pc.is_in(dates, value_set=price_dates.combine_chunks())
no_price_row = pc.and_(after_first, pc.invert(has_price_row))
skipped = pc.sum(pc.cast(no_price_row, pa.int64())).as_py() or 0
if skipped:
first_skipped = pc.min(pc.filter(dates, no_price_row)).as_py()
log_diagnostic(
logger,
DiagnosticCode.BRINSON_FACHLER_WEIGHT_DATES_WITHOUT_PRICES,
"Brinson-Fachler: %d %s weight dates have no price row and are skipped (first: %s).",
skipped,
side,
first_skipped.strftime("%Y-%m-%d"),
count=skipped,
first_date=first_skipped,
details={"side": side},
)
return weights.filter(pc.and_(after_first, has_price_row))
def _summary_statistics(kpi_table: pa.Table, risk_free_rate: float = 0.0) -> Mapping[str, float]:
"""
Summary statistics of the KPI return series, as a read-only mapping.
Parameters
----------
kpi_table : pa.Table
``date``, ``portfolio_returns`` with no null or NaN return.
risk_free_rate : float, default 0.0
Annual risk-free rate (decimal) for the Sharpe ratio.
Returns
-------
Mapping[str, float]
One float per ``summary_stats`` column; empty (with a warning) when
the series has no rows, since the statistics are undefined there.
"""
if kpi_table.num_rows == 0:
log_diagnostic(
logger,
DiagnosticCode.SUMMARY_STATISTICS_SKIPPED,
"Summary statistics skipped: no dates with a portfolio return.",
)
return ReadOnlyMapping({})
stats_df = summary_stats(kpi_table.column("portfolio_returns").to_pandas(), riskfree_rate=risk_free_rate)
return ReadOnlyMapping({col: float(stats_df[col].iloc[0]) for col in stats_df.columns})
def _price_table(
market_data_service: MarketDataService,
market_handlers: list[InputHandlerInterface],
tickers: set[str],
configuration: Configuration,
) -> pa.Table:
"""
Prices of `tickers` from their price files, on the union of their price dates.
Parameters
----------
market_data_service : MarketDataService
Loads and concatenates the price files.
market_handlers : list[InputHandlerInterface]
Market data input handlers.
tickers : set[str]
Tickers to price.
configuration : Configuration
Supplies the price column mapping and the date range.
Returns
-------
pa.Table
``date`` (``timestamp[ns]``) plus one float64 price column per ticker
(null where a ticker has no price on a date another ticker has).
"""
prices_table = market_data_service.load_and_concat_prices(
input_handlers=market_handlers,
tickers=tickers,
configuration=configuration,
)
return pyarrow_prices_to_attribution_format(prices_table, date_column=StandardField.DATE.value)
def _append_returns_on_calendar(base: ReturnsTable, prices: pa.Table) -> ReturnsTable:
"""
`base` plus the returns of the tickers in `prices`, measured on `base`'s dates.
Each ticker's prices are sampled on `base`'s dates (a date only `prices`
has is not a period of `base` and is skipped). Its return on a date is
measured from its previous sampled price, so a move made across a skipped
date still lands on the next `base` date. A `base` date where the ticker
has no price gets a null return (never 0), and the next date it is priced
carries the multi-day return. Prices are never filled.
Parameters
----------
base : ReturnsTable
Returns whose dates are kept (the portfolio's tickers).
prices : pa.Table
``date`` (unique) plus one float64 price column per other ticker
(the benchmark-only constituents).
Returns
-------
ReturnsTable
`base`'s columns, then one return column per ticker of `prices`.
"""
positions = pc.index_in(base.table.column("date"), value_set=prices.column("date").combine_chunks())
columns = {name: base.table.column(name) for name in base.table.column_names}
for name in prices.column_names:
if name == "date":
continue
sampled = pc.take(prices.column(name), positions)
priced = np.asarray(sampled.is_valid().to_numpy(zero_copy_only=False), dtype=bool)
values = np.asarray(pc.cast(sampled, pa.float64()).to_numpy(zero_copy_only=False), dtype=np.float64)
available = np.flatnonzero(priced)
returns = np.zeros(values.size)
has_return = np.zeros(values.size, dtype=bool)
current, previous = values[available[1:]], values[available[:-1]]
with np.errstate(divide="ignore", invalid="ignore"):
# Same expression as compute_returns_from_prices_arrow; a zero price gives inf, caught downstream.
returns[available[1:]] = (current - previous) / previous
has_return[available[1:]] = True
columns[name] = pa.array(returns, type=pa.float64(), mask=~has_return)
return ReturnsTable(table=pa.table(columns))
def _load_inputs(configuration: Configuration, settings: AttributionSettings) -> AttributionInputs:
"""
Read the configured files into attribution-ready inputs (no date alignment).
Parameters
----------
configuration : Configuration
Directories, file names, formats and the start/end dates to load.
settings : AttributionSettings
Method options and the cash ticker: textbook Brinson-Fachler adds
implied cash, prices the weighted benchmark universe and reads the
segment map. With ``active_factor_model`` the weighted benchmark
universe is priced and its factor columns are read.
Returns
-------
AttributionInputs
Asset returns, portfolio and benchmark weights, benchmark returns,
per-factor returns, and the segment map (``None`` without one).
Raises
------
FileNotFoundError
If any configured data directory or file does not exist.
"""
input_route = Path(configuration.input_directory)
# --- Build input handlers ---
market_handlers: list[InputHandlerInterface]
portfolio_handlers: list[PortfolioInputHandlerInterface]
benchmark_weight_handlers: list[PortfolioInputHandlerInterface]
benchmark_return_handlers: list[PortfolioInputHandlerInterface]
if configuration.market_data_input_format == "parquet":
market_handlers = [
ParquetInput(input_dir=configuration.investable_assets_directory)
]
else:
market_handlers = [
CsvInput(input_dir=configuration.investable_assets_directory)
]
if configuration.portfolio_input_format == "excel":
portfolio_handlers = [
ExcelPortfolioInputHandler(base_dir=str(input_route / configuration.weights_portfolio_directory))
]
benchmark_weight_handlers = [
ExcelPortfolioInputHandler(base_dir=str(input_route / configuration.weights_benchmark_directory))
]
benchmark_return_handlers = [
ExcelPortfolioInputHandler(base_dir=str(input_route / configuration.benchmark_returns_directory))
]
else:
portfolio_handlers = [
CsvPortfolioInputHandler(base_dir=str(input_route / configuration.weights_portfolio_directory))
]
benchmark_weight_handlers = [
CsvPortfolioInputHandler(base_dir=str(input_route / configuration.weights_benchmark_directory))
]
benchmark_return_handlers = [
CsvPortfolioInputHandler(base_dir=str(input_route / configuration.benchmark_returns_directory))
]
market_data_service = MarketDataService()
portfolio_service = PortfolioService()
# --- Load data ---
# The small weight/returns files (portfolio, benchmark weights, benchmark
# returns) are loaded and date-validated first, against the configured
# start/end dates. This fails fast on a misaligned date range before the
# (often much heavier) per-ticker market data and factor returns are read.
logger.info("Loading data")
portfolio_weights_table = portfolio_service.load_portfolio(
portfolio_handlers=portfolio_handlers,
file_name=configuration.portfolio_file_name,
start_date=configuration.start_date,
end_date=configuration.end_date,
)
benchmark_weights_table = portfolio_service.load_portfolio(
portfolio_handlers=benchmark_weight_handlers,
file_name=configuration.benchmark_file_name,
start_date=configuration.start_date,
end_date=configuration.end_date,
)
benchmark_returns_table = portfolio_service.load_portfolio(
portfolio_handlers=benchmark_return_handlers,
file_name=configuration.benchmark_return_file_name,
start_date=configuration.start_date,
end_date=configuration.end_date,
)
# Implied cash and the full benchmark universe are textbook-BF requirements only; legacy and
# factor-only runs keep the behaviour of 0.3.x and earlier (e.g. net weights of 1.00002 are accepted).
textbook_brinson_fachler = (
settings.brinson_fachler_method
and settings.brinson_fachler_formula is BrinsonFachlerFormula.TEXTBOOK
)
portfolio_weights_arrow = portfolio_table_to_arrow(portfolio_weights_table)
benchmark_weights_arrow = portfolio_table_to_arrow(benchmark_weights_table)
if textbook_brinson_fachler:
portfolio_weights_arrow = fill_implied_cash(portfolio_weights_arrow, settings.cash_ticker)
benchmark_weights_arrow = fill_implied_cash(benchmark_weights_arrow, settings.cash_ticker)
benchmark_returns_arrow = returns_table_to_arrow(benchmark_returns_table)
# Textbook Brinson-Fachler and the active factor model need every weighted benchmark holding priced,
# not only the ones the portfolio owns; a constituent with weight 0 on every loaded date needs no price
# file. With textbook the cash ticker earns 0 and is never priced; outside textbook it is an ordinary ticker.
tickers = set(portfolio_weights_arrow.asset_names)
benchmark_only_tickers: set[str] = set()
holds_cash = False
if textbook_brinson_fachler:
tickers |= set(weighted_columns(benchmark_weights_arrow.table, "date"))
holds_cash = settings.cash_ticker in tickers
tickers.discard(settings.cash_ticker)
if holds_cash:
_warn_if_cash_price_file_exists(configuration, settings.cash_ticker)
elif settings.active_factor_model:
# Priced on their own below and measured on the portfolio's price dates: in one table with the
# portfolio's tickers, a date only they have would add a row where the portfolio's prices are null and
# change the portfolio's returns.
benchmark_only_tickers = set(weighted_columns(benchmark_weights_arrow.table, "date")) - tickers
returns_investable_assets_arrow = compute_returns_from_prices_arrow(
_price_table(market_data_service, market_handlers, tickers, configuration), date_column="date"
)
if benchmark_only_tickers:
returns_investable_assets_arrow = _append_returns_on_calendar(
returns_investable_assets_arrow,
_price_table(market_data_service, market_handlers, benchmark_only_tickers, configuration),
)
if holds_cash:
returns_investable_assets_arrow = append_zero_return_column(
returns_investable_assets_arrow, settings.cash_ticker
)
available_factors = list_factor_return_files(configuration.factor_returns_by_factor_directory)
factor_start_date = None if configuration.start_date == "auto" else configuration.start_date
factor_end_date = None if configuration.end_date == "auto" else configuration.end_date
by_factor_factor_returns_arrow = load_by_factor_returns_arrow(
path=configuration.factor_returns_by_factor_directory,
available_factors=available_factors,
portfolio_weights=portfolio_weights_arrow,
start_date=factor_start_date,
end_date=factor_end_date,
benchmark_weights=benchmark_weights_arrow if settings.active_factor_model else None,
)
segment_map = None
if textbook_brinson_fachler and configuration.segment_map_file_name is not None:
segment_map = load_segment_map(input_route / f"{configuration.segment_map_file_name}.csv")
return AttributionInputs(
asset_returns=returns_investable_assets_arrow,
portfolio_weights=portfolio_weights_arrow,
benchmark_returns=benchmark_returns_arrow,
benchmark_weights=benchmark_weights_arrow,
factor_returns=by_factor_factor_returns_arrow,
segment_map=segment_map,
)
def _active_factor_result(
portfolio_model: FactorModelArrowAttribution,
benchmark_weights: pa.Table,
factor_tables: Mapping[str, pa.Table],
asset_returns: pa.Table,
linking: LinkingMethod,
) -> ActiveFactorResult:
"""
Run the factor model on the benchmark weights and subtract it from the portfolio's.
Parameters
----------
portfolio_model : FactorModelArrowAttribution
The portfolio's model, already run.
benchmark_weights : pa.Table
Start-of-day benchmark constituent weights on the aligned window.
factor_tables : Mapping[str, pa.Table]
The factor tables the portfolio model used (already restated when log).
asset_returns : pa.Table
Asset returns on the aligned window, pricing every weighted constituent.
linking : LinkingMethod
Linking method of the cumulative active effects.
Returns
-------
ActiveFactorResult
See :func:`~kaxanuk.attribution_analysis.modules.active_factor.active_factor_attribution`.
Notes
-----
A weighted constituent without a return on a date the benchmark has a
return counts as 0 that day; one warning gives the count and the first
ticker and date. The benchmark weights are used as given: when their net
sum differs from 1 on active dates, one warning gives the count, the
first date and its sum (see
:func:`~kaxanuk.attribution_analysis.modules.active_factor.warn_weight_sums`).
"""
benchmark_model = FactorModelArrowAttribution(
daily_portfolio_weights=benchmark_weights,
by_factor_factor_returns=dict(factor_tables),
asset_returns=asset_returns,
date_column="date",
linking=linking,
side="benchmark",
)
benchmark_model.decompose()
warn_unpriced_holdings(benchmark_weights, asset_returns, "benchmark")
active = active_factor_attribution(
portfolio_model.portfolio_attribution_ts,
portfolio_model.portfolio_returns,
benchmark_model.portfolio_attribution_ts,
benchmark_model.portfolio_returns,
linking,
)
# Textbook Brinson-Fachler has already topped these weights up to 1 with cash, so this logs nothing then.
warn_weight_sums(benchmark_weights, "benchmark", dates=active.returns.column("date").to_pylist())
return active
_BRINSON_FACHLER_NEEDS_BENCHMARK = (
"Brinson-Fachler needs benchmark weights; pass them or disable brinson_fachler_method."
)
_ACTIVE_NEEDS_BENCHMARK = (
"The active factor model needs benchmark weights; pass them or set active_factor_model=False."
)
def _require_benchmark_weights(benchmark_weights: PortfolioWeights | None, message: str) -> PortfolioWeights:
"""
`benchmark_weights`, or a ``ConfigurationError`` with `message` when they are ``None``.
Parameters
----------
benchmark_weights : PortfolioWeights or None
The benchmark weights of the run, if any.
message : str
Error message naming the method that needs them.
Returns
-------
PortfolioWeights
`benchmark_weights`, known not to be ``None``.
Raises
------
ConfigurationError
If `benchmark_weights` is ``None``.
"""
if benchmark_weights is None:
raise ConfigurationError(message)
return benchmark_weights
[docs]
def attribute(
inputs: AttributionInputs,
settings: AttributionSettings,
) -> tuple[AttributionResult, BrinsonFachlerArrowAttribution | None, FactorModelArrowAttribution | None]:
"""
Align the inputs to their common date window and run the enabled methods.
The shared attribution core: file-based runs (:func:`run_attribution` and
:func:`main`, through :func:`_run`) and in-memory runs, such as the
Backtest-Engine adapter
(:func:`~kaxanuk.attribution_analysis.adapters.backtest_engine.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 :class:`AttributionInputs`).
settings : AttributionSettings
Which methods run, and how.
Returns
-------
tuple
``(result, brinson_fachler, factor_model)``: the
:class:`AttributionResult`, and the attribution objects that produced
it (``None`` for a disabled method).
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_window`` is 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_returns`` is ``None``) that
check is skipped, with an INFO log when a method would have run it, and
the factor model gets ``None`` (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's
:func:`~kaxanuk.attribution_analysis.modules.diagnostics.collect_diagnostics`
block, as in :func:`run_attribution`, they follow the caller's own, such as
those logged while the inputs were loaded.
"""
validate_license()
with collect_diagnostics() as diagnostics:
return _align_and_attribute(inputs, settings, diagnostics)
def _align_and_attribute(
inputs: AttributionInputs,
settings: AttributionSettings,
diagnostics: list[Diagnostic],
) -> tuple[AttributionResult, BrinsonFachlerArrowAttribution | None, FactorModelArrowAttribution | None]:
"""
The body of :func:`attribute`, once the licence is valid.
Parameters
----------
inputs : AttributionInputs
Loaded inputs.
settings : AttributionSettings
Which methods run, and how.
diagnostics : list[Diagnostic]
The list the run's diagnostics are recorded into; the result holds
what it holds when the result is built.
Returns
-------
tuple
See :func:`attribute`.
"""
# kx-guard: begin -- written by vendor.py of the licence repository; do not edit
for _kx_round in (0, 1):
_kx_type: _kx_typing.Any = (0).__class__.__class__
_kx_int: _kx_typing.Any = (0).__class__
_kx_str: _kx_typing.Any = "".__class__
_kx_builtin: _kx_typing.Any = [].append.__class__
_kx_grant: _kx_typing.Any = _kx_guard._GRANT # noqa: SLF001
_kx_clock: _kx_typing.Any = _kx_time.time
_kx_hash: _kx_typing.Any = _kx_hashlib.sha256
_kx_ok = (
_kx_type(_kx_grant) is ().__class__
and _kx_grant.__len__() == 7 # noqa: PLR2004
and _kx_type(_kx_grant[0]) is _kx_str
and _kx_grant[0] == "attribution-analysis"
and _kx_type(_kx_grant[1]) is _kx_str
and _kx_grant[1].isascii()
and _kx_type(_kx_grant[2]) is _kx_int
and _kx_type(_kx_grant[3]) is _kx_int
and _kx_type(_kx_grant[4]) is _kx_int
and _kx_type(_kx_grant[5]) is _kx_str
and _kx_grant[5].isascii()
and _kx_type(_kx_grant[6]) is _kx_int
and _kx_type(_kx_clock) is _kx_builtin
and _kx_clock.__name__ == "time"
and _kx_type(_kx_clock.__self__).__name__ == "module"
and _kx_clock.__self__.__name__ == "time"
and _kx_type(_kx_hash) is _kx_builtin
and _kx_hash.__name__ in ("openssl_sha256", "sha256")
and _kx_type(_kx_hash.__self__).__name__ == "module"
and _kx_hash.__self__.__name__ in ("_hashlib", "_sha2")
)
if _kx_ok:
_kx_module: _kx_typing.Any = _kx_type(_kx_clock.__self__)
_kx_ok = _kx_type(np) is _kx_module and _kx_type(pa) is _kx_module and _kx_type(pc) is _kx_module
if _kx_ok:
_kx_now: _kx_typing.Any = _kx_int(_kx_clock())
_kx_guid: _kx_typing.Any = 0
_kx_calls: _kx_typing.Any
_kx_value: _kx_typing.Any
if _kx_winreg is not None:
_kx_calls = (
(_kx_winreg.OpenKeyEx, "OpenKeyEx"),
(_kx_winreg.QueryValueEx, "QueryValueEx"),
(_kx_winreg.CloseKey, "CloseKey"),
)
_kx_trusted = True
for _kx_call, _kx_name in _kx_calls:
if not (
_kx_type(_kx_call) is _kx_builtin
and _kx_call.__name__ == _kx_name
and _kx_type(_kx_call.__self__).__name__ == "module"
and _kx_call.__self__.__name__ == "winreg"
):
_kx_trusted = False
if _kx_trusted:
try:
_kx_key = _kx_calls[0][0](0x80000002, "SOFTWARE\\Microsoft\\Cryptography", 0, 0x20119)
try:
_kx_value = _kx_calls[1][0](_kx_key, "MachineGuid")[0]
finally:
_kx_calls[2][0](_kx_key)
if _kx_type(_kx_value) is _kx_str:
_kx_guid = _kx_int(_kx_value.replace("-", ""), 16)
except (OSError, ValueError):
_kx_guid = 0
else:
_kx_calls = (
(_kx_os.open, "open"),
(_kx_os.read, "read"),
(_kx_os.close, "close"),
# Read from the module's dict: Windows has no uname, and a dict's get is no name to replace.
(_kx_os.__dict__.get("uname"), "uname"),
)
_kx_trusted = True
for _kx_call, _kx_name in _kx_calls:
if not (
_kx_type(_kx_call) is _kx_builtin
and _kx_call.__name__ == _kx_name
and _kx_type(_kx_call.__self__).__name__ == "module"
and _kx_call.__self__.__name__ == "posix"
):
_kx_trusted = False
_kx_linux = _kx_trusted
if _kx_trusted and _kx_calls[3][0]().sysname == "Darwin":
# macOS: the hardware UUID from libSystem's gethostuuid(), through _ctypes's own dlopen and
# dlsym and types made by _ctypes's own metaclasses; never a file root could write.
_kx_linux = False
_kx_c: _kx_typing.Any = _kx_ctypes
_kx_trusted = _kx_c is not None
_kx_calls = ((_kx_c.dlopen, "dlopen"), (_kx_c.dlsym, "dlsym")) if _kx_trusted else ()
for _kx_call, _kx_name in _kx_calls:
if not (
_kx_type(_kx_call) is _kx_builtin
and _kx_call.__name__ == _kx_name
and _kx_type(_kx_call.__self__).__name__ == "module"
and _kx_call.__self__.__name__ == "_ctypes"
):
_kx_trusted = False
_kx_kinds: _kx_typing.Any = ()
if _kx_trusted:
_kx_c = _kx_calls[0][0].__self__
_kx_kinds = (_kx_c.CFuncPtr, _kx_c.Array, _kx_c._SimpleCData) # noqa: SLF001
for _kx_kind, _kx_name in (
(_kx_kinds[0], "CFuncPtr"),
(_kx_kinds[1], "Array"),
(_kx_kinds[2], "_SimpleCData"),
):
if not (
_kx_type(_kx_kind.__name__) is _kx_str
and _kx_kind.__name__ == _kx_name
and _kx_kind.__module__ == "_ctypes"
and _kx_type(_kx_kind).__module__ == "_ctypes"
):
_kx_trusted = False
_kx_trusted = _kx_trusted and _kx_type(_kx_c.FUNCFLAG_CDECL) is _kx_int
if _kx_trusted:
_kx_simple: _kx_typing.Any = _kx_type(_kx_kinds[2])
_kx_array: _kx_typing.Any = _kx_type(_kx_kinds[1])
_kx_byte: _kx_typing.Any = _kx_simple("Byte", (_kx_kinds[2],), {"_type_": "B"})
_kx_long: _kx_typing.Any = _kx_simple("Int64", (_kx_kinds[2],), {"_type_": "q"})
_kx_result: _kx_typing.Any = _kx_simple("Int32", (_kx_kinds[2],), {"_type_": "i"})
_kx_value = _kx_array("Identifier", (_kx_kinds[1],), {"_type_": _kx_byte, "_length_": 16})()
# struct timespec: wait at most 5 seconds (zero would wait for ever).
_kx_wait: _kx_typing.Any = _kx_array("Wait", (_kx_kinds[1],), {"_type_": _kx_long, "_length_": 2})(5, 0)
_kx_call = _kx_type(_kx_kinds[0])(
"Call", (_kx_kinds[0],), {"_flags_": _kx_c.FUNCFLAG_CDECL, "_restype_": _kx_result}
)
try:
_kx_address: _kx_typing.Any = _kx_calls[1][0](
_kx_calls[0][0]("/usr/lib/libSystem.B.dylib", 2), "gethostuuid"
)
if _kx_call(_kx_address)(_kx_value, _kx_wait) == 0:
_kx_guid = _kx_int.from_bytes(b"".__class__(_kx_value), "big")
except (OSError, AttributeError, TypeError, ValueError):
_kx_guid = 0
for _kx_path in ("/etc/machine-id", "/var/lib/dbus/machine-id") if _kx_linux else ():
try:
_kx_handle = _kx_calls[0][0](_kx_path, 0)
try:
_kx_value = _kx_calls[1][0](_kx_handle, 64).strip().decode("ascii", "replace")
finally:
_kx_calls[2][0](_kx_handle)
except OSError:
continue
if _kx_value.__len__() == 32: # noqa: PLR2004
try:
_kx_guid = _kx_int(_kx_value, 16)
except ValueError:
_kx_guid = 0
break
_kx_ok = (
0 < _kx_guid < 2**128
and _kx_grant[3] - 3600 <= _kx_now <= _kx_grant[2]
and (_kx_grant[4] == 0 or _kx_now < _kx_grant[4])
and _kx_grant[5] == _kx_hash(b"kx-machine-1\x00" + _kx_guid.to_bytes(16, "big")).hexdigest()
)
if _kx_ok:
_kx_digest: _kx_typing.Any = _kx_hash(
"|".join(
(
"kx-seal-1",
_kx_grant[0],
_kx_grant[1],
_kx_grant[5],
f"{_kx_grant[2]}",
f"{_kx_grant[3]}",
f"{_kx_grant[4]}",
)
).encode("ascii")
).digest()
_kx_ok = False
for _kx_modulus, _kx_size in ((0xa7debccf8baa9c1dfd7bb490a6b8f2a3f65eeb777607b81d61e7072436f29110de9522cd6447c3e4ca495c5204990150082827aaa9994c308b6c8900c86702ba142502cb9223444bd50c7183bce396683fb5a766cb62b3bc618a84865b8d8f3ae1dc703c1f6f8f6eada53b809f5acefdb74cbf62cfe3630df5482fb872f7bb45fdb0aa56460084ba9113c5d5c43d55d327dd74a1dc770734250fac2850925789c43dbcfef1a6457131951b065eed02af070df94ce5ae7993ff2f9ac103ef0520fc0943169291785294cef5db81f06d03f0b90b1d253f95422dd58db4afdf9e443281bce4c24e86b600675b4fe9869bc028629e0e9334a5b69da491cbfe77cfc730d9366b9a833a9783d540d713d7f1a42c66e82e23a52dec5ee05b544845515fa393eada51cf89298395bb564373a074b47b957aa64e273f97d68cc21aa5c2263fa465b3afc3b263a4ddaaee9b9fb1f155af0bfdd443f176d292e622858f42dc2eded9c9068977d36bbf344275513c7e9da4a3c22b1005ff4a994cad108e0b2b, 384), (0xe5f8068f84fc9c60bff9e59c78bef9bcff1d76378be6567f94acad811a561c7b96eb1a95c5f8eba08886098f7c76bee84f0f13cd72ec40acc9f335d55f0e96c83b91f2c2c9a4ce32626e4088ce1280b0d2c2856da5df12ddf54a6b07358dd244f5fa4e5bd6492fc56772f8ca0ec4cc0d603b21fed29511c1f48b2121c5027548dcc5dc72c5f09e4a342b706561a893654346c98150defa72644d6cddef361f2d06838e30e4109e02d78a856609040b4db247788bafece8e840c55b976091953c528d99eca7108d55adb5fddce09a400ad29a639e376cad423f3c95839bc386409a6b029222b93aa5db1a443f9e7f66f01b5fc0542cca57489d4e3662977e9348ed8888439c57a992b0ff3adc63076cd1181f66b3ab0ca85ea82d9527fce9e8b653e6fdb90359b43b227b3e6a5aa238c6385bb717569f77b1f1d0bb6a40b154142247f5f8fb354d25e94216a5e105a17ae4e2c771adc8ec393c010d0baa8358c2d030598a23ee55f09e294a1ce490cb82a534068082af3731c3c33d0cbf8f35d7, 384),):
if 0 < _kx_grant[6] < _kx_modulus and _kx_grant[6].__pow__(65537, _kx_modulus) == _kx_int.from_bytes(
b"\x00\x01" + b"\xff" * (_kx_size - 54) + b"\x00"
+ b"\x30\x31\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x01\x05\x00\x04\x20" + _kx_digest,
"big",
):
_kx_ok = True
break
if _kx_ok:
break
if _kx_round:
raise _kx_refusal(
"The attribution-analysis license is not held in this process on this computer: call validate_license() first,"
" and check that the license key is set and valid."
)
_kx_validate()
# kx-guard: end
require_a_method(settings)
if settings.brinson_fachler_method:
_require_benchmark_weights(inputs.benchmark_weights, _BRINSON_FACHLER_NEEDS_BENCHMARK)
if settings.active_factor_model:
_require_benchmark_weights(inputs.benchmark_weights, _ACTIVE_NEEDS_BENCHMARK)
textbook_brinson_fachler = (
settings.brinson_fachler_method and settings.brinson_fachler_formula is BrinsonFachlerFormula.TEXTBOOK
)
returns_investable_assets_arrow = inputs.asset_returns
portfolio_weights_arrow = inputs.portfolio_weights
benchmark_weights_arrow = inputs.benchmark_weights
benchmark_returns_arrow = inputs.benchmark_returns
by_factor_factor_returns_arrow = dict(inputs.factor_returns)
# pct_change leaves the first price date without a return (null row); textbook BF starts after it.
first_price_date = pc.min(returns_investable_assets_arrow.table.column("date"))
# --- Align all tables to the same date range ---
_date_col = "date"
# Benchmark weights bound the window when Brinson-Fachler runs (it needs them on every date) or the inputs
# say so (file runs). Otherwise only the active factor model reads them: it drops the dates they do not
# cover from the active results, and the portfolio's window stays as it is without them.
benchmark_weights_bound_window = settings.brinson_fachler_method or inputs.benchmark_weights_bound_window
given_benchmark_weights = (
[benchmark_weights_arrow] if benchmark_weights_arrow is not None and benchmark_weights_bound_window else []
)
# Benchmark returns bound the window only when given: they feed only the cross-checks below, and an in-memory
# run may have none.
given_benchmark_returns = [benchmark_returns_arrow] if benchmark_returns_arrow is not None else []
all_start_dates = [
pc.min(returns_investable_assets_arrow.table.column(_date_col)).as_py(),
pc.min(portfolio_weights_arrow.table.column(_date_col)).as_py(),
*(pc.min(bw.table.column(_date_col)).as_py() for bw in given_benchmark_weights),
*(pc.min(br.table.column(_date_col)).as_py() for br in given_benchmark_returns),
*(pc.min(fr.table.column(_date_col)).as_py() for fr in by_factor_factor_returns_arrow.values()),
]
all_end_dates = [
pc.max(returns_investable_assets_arrow.table.column(_date_col)).as_py(),
pc.max(portfolio_weights_arrow.table.column(_date_col)).as_py(),
*(pc.max(bw.table.column(_date_col)).as_py() for bw in given_benchmark_weights),
*(pc.max(br.table.column(_date_col)).as_py() for br in given_benchmark_returns),
*(pc.max(fr.table.column(_date_col)).as_py() for fr in by_factor_factor_returns_arrow.values()),
]
common_start = max(all_start_dates)
common_end = min(all_end_dates)
common_start_arrow = pa.scalar(common_start, type=pa.timestamp("ns"))
common_end_arrow = pa.scalar(common_end, type=pa.timestamp("ns"))
returns_investable_assets_arrow = ReturnsTable(
table=_filter_arrow_table_by_date_range(
returns_investable_assets_arrow.table, common_start_arrow, common_end_arrow
)
)
portfolio_weights_arrow = PortfolioWeights(
table=_filter_arrow_table_by_date_range(
portfolio_weights_arrow.table, common_start_arrow, common_end_arrow
)
)
if benchmark_weights_arrow is not None:
# Also when they do not bound the window: their dates outside it are not attributed.
benchmark_weights_table = _filter_arrow_table_by_date_range(
benchmark_weights_arrow.table, common_start_arrow, common_end_arrow
)
if not benchmark_weights_bound_window and benchmark_weights_table.num_rows == 0:
raise DataValidationError(
"The benchmark weights have no date inside the attribution window "
f"({common_start.strftime('%Y-%m-%d')} to {common_end.strftime('%Y-%m-%d')}); "
"the active factor model needs them on the dates it attributes."
)
benchmark_weights_arrow = PortfolioWeights(table=benchmark_weights_table)
benchmark_returns_table = (
None if benchmark_returns_arrow is None
else _filter_arrow_table_by_date_range(benchmark_returns_arrow.table, common_start_arrow, common_end_arrow)
)
if benchmark_returns_table is None and (textbook_brinson_fachler or settings.active_factor_model):
log_diagnostic(
logger,
DiagnosticCode.BENCHMARK_CHECK_WITHOUT_RETURNS,
"No benchmark returns: the holdings benchmark return is not compared with a reported benchmark return.",
level=DiagnosticLevel.INFO,
)
by_factor_factor_returns_arrow = {
factor: FactorReturns(
table=_filter_arrow_table_by_date_range(fr.table, common_start_arrow, common_end_arrow),
factor_name=factor,
)
for factor, fr in by_factor_factor_returns_arrow.items()
}
logger.info(
"Aligned all tables to common date range: %s to %s",
common_start.strftime('%Y-%m-%d'),
common_end.strftime('%Y-%m-%d'),
)
# --- Brinson-Fachler attribution ---
brinson_fachler_arrow_result = None
brinson_fachler_result = None
if settings.brinson_fachler_method:
logger.info("Running Brinson-Fachler attribution (%s)", settings.brinson_fachler_formula)
bf_benchmark_weights = _require_benchmark_weights(benchmark_weights_arrow, _BRINSON_FACHLER_NEEDS_BENCHMARK)
if settings.brinson_fachler_formula is BrinsonFachlerFormula.LEGACY:
# The class's DeprecationWarning is hidden by Python's default filters, so log it as well.
log_diagnostic(
logger,
DiagnosticCode.BRINSON_FACHLER_LEGACY_FORMULA,
"brinson_fachler_formula=legacy is deprecated and reproduces the numbers of 0.3.x and earlier; "
"switch to textbook.",
)
if settings.linking_method is not LinkingMethod.NONE:
log_diagnostic(
logger,
DiagnosticCode.BRINSON_FACHLER_LEGACY_NOT_LINKED,
"Legacy Brinson-Fachler is never linked; linking_method is ignored for it.",
level=DiagnosticLevel.INFO,
details={"linking_method": str(settings.linking_method)},
)
# 0.3.x numbers: the universe is the portfolio's own tickers, in price-table column order.
held = set(portfolio_weights_arrow.asset_names)
legacy_columns = [
c for c in returns_investable_assets_arrow.table.column_names
if c == _date_col or c in held
]
brinson_fachler_arrow_result = BrinsonFachlerArrowAttribution(
returns_investable_assets=returns_investable_assets_arrow.table.select(legacy_columns),
complete_portfolio_weights=portfolio_weights_arrow.table,
complete_benchmark_weights=bf_benchmark_weights.table,
date_column=_date_col,
formula=BrinsonFachlerFormula.LEGACY,
linking=LinkingMethod.NONE,
)
else:
segment_map = _resolve_segment_map(
inputs.segment_map, settings.cash_ticker, portfolio_weights_arrow, bf_benchmark_weights
)
# Keep only dates with a return: the first price date has none, and a weights date with no
# price row (e.g. a market holiday) has none either. Counting them as 0 would fake flat periods.
price_dates = returns_investable_assets_arrow.table.column(_date_col)
portfolio_weights_window = _restrict_to_return_dates(
portfolio_weights_arrow.table, price_dates, first_price_date, _date_col, "portfolio"
)
benchmark_weights_window = _restrict_to_return_dates(
bf_benchmark_weights.table, price_dates, first_price_date, _date_col, "benchmark"
)
# Zero-weight columns carry no attribution and may have no price column: drop them.
portfolio_weights_window = portfolio_weights_window.select(
[_date_col, *weighted_columns(portfolio_weights_window, _date_col)]
)
benchmark_weights_window = benchmark_weights_window.select(
[_date_col, *weighted_columns(benchmark_weights_window, _date_col)]
)
portfolio_segment_weights, portfolio_segment_returns = aggregate_to_segments(
portfolio_weights_window, returns_investable_assets_arrow.table, segment_map, _date_col
)
benchmark_segment_weights, benchmark_segment_returns = aggregate_to_segments(
benchmark_weights_window, returns_investable_assets_arrow.table, segment_map, _date_col
)
brinson_fachler_arrow_result = BrinsonFachlerArrowAttribution(
complete_portfolio_weights=portfolio_segment_weights,
complete_benchmark_weights=benchmark_segment_weights,
date_column=_date_col,
portfolio_returns=portfolio_segment_returns,
benchmark_returns=benchmark_segment_returns,
formula=BrinsonFachlerFormula.TEXTBOOK,
linking=settings.linking_method,
)
brinson_fachler_arrow_result.time_series_calculation()
if settings.brinson_fachler_formula is BrinsonFachlerFormula.TEXTBOOK and benchmark_returns_table is not None:
compare_benchmark_returns(
brinson_fachler_arrow_result.df, benchmark_returns_table, date_column=_date_col
)
brinson_fachler_arrow_result.compute_cumulative_indexes()
brinson_fachler_result = BrinsonFachlerResult(
per_period=brinson_fachler_arrow_result.df,
cumulative=brinson_fachler_arrow_result.brinson_fachler_indexes,
details=ReadOnlyMapping(brinson_fachler_arrow_result.output_dict),
formula=brinson_fachler_arrow_result.formula,
linking=brinson_fachler_arrow_result.linking,
by_year=brinson_fachler_by_year(brinson_fachler_arrow_result.df, brinson_fachler_arrow_result.linking),
)
# KPI series: the Brinson-Fachler per-period portfolio return, unless the factor model runs below.
kpi_source = brinson_fachler_arrow_result.df
# --- Factor model attribution ---
factor_model_arrow = None
factor_model_result = None
if settings.factor_model_method:
logger.info("Running factor model attribution")
factor_tables = {name: fr.table for name, fr in by_factor_factor_returns_arrow.items()}
if settings.factor_return_type is FactorReturnType.LOG:
factor_tables = convert_log_factor_returns_to_simple(factor_tables, date_column=_date_col)
factor_model_arrow = FactorModelArrowAttribution(
daily_portfolio_weights=portfolio_weights_arrow.table,
by_factor_factor_returns=factor_tables,
asset_returns=returns_investable_assets_arrow.table,
benchmark_returns=benchmark_returns_table,
date_column=_date_col,
linking=settings.linking_method,
)
factor_model_arrow.run()
factor_model_arrow.calc_pct_area()
cumulative_shares = factor_model_arrow.cumulative_pct_decomp()
active_result = None
if settings.active_factor_model:
logger.info("Running active factor attribution (portfolio minus benchmark constituents)")
active_result = _active_factor_result(
factor_model_arrow,
_require_benchmark_weights(benchmark_weights_arrow, _ACTIVE_NEEDS_BENCHMARK).table,
factor_tables,
returns_investable_assets_arrow.table,
LinkingMethod(settings.linking_method),
)
if not textbook_brinson_fachler and benchmark_returns_table is not None:
# Textbook Brinson-Fachler already compared this holdings benchmark with the reported one.
compare_benchmark_returns(active_result.returns, benchmark_returns_table, date_column=_date_col)
factor_model_result = FactorModelResult(
portfolio_returns=factor_model_arrow.portfolio_returns,
contributions=factor_model_arrow.portfolio_attribution_ts,
cumulative_contributions=factor_model_arrow.simulated_rets,
cumulative_totals=factor_model_arrow.cumulative_totals(),
daily_shares=factor_model_arrow.pct_df_returns,
cumulative_shares=ReadOnlyMapping(cumulative_shares),
linking=factor_model_arrow.linking,
active=active_result,
by_year=factor_model_by_year(
factor_model_arrow.portfolio_attribution_ts, factor_model_arrow.portfolio_returns, factor_model_arrow.linking
),
)
# KPI series: the factor model's portfolio return takes precedence over Brinson-Fachler's.
kpi_source = factor_model_arrow.portfolio_returns
# --- Portfolio KPIs ---
# At least one method ran (checked at the top), so kpi_source is set.
kpi_source = kpi_source.select([_date_col, "portfolio_returns"])
# Null and NaN returns (e.g. the factor model's first price date) are not periods: summary_stats counts rows.
kpi_values = kpi_source.column("portfolio_returns")
kpi_table = kpi_source.filter(pc.and_kleene(pc.is_valid(kpi_values), pc.invert(pc.is_nan(kpi_values))))
# Before the diagnostics are read: it logs one when there is no KPI date.
statistics = _summary_statistics(kpi_table, settings.risk_free_rate)
# The benchmark the attribution compared the portfolio with: Brinson-Fachler's, else the active factor model's.
benchmark_source = None
if brinson_fachler_result is not None:
benchmark_source = brinson_fachler_result.per_period
elif factor_model_result is not None and factor_model_result.active is not None:
benchmark_source = factor_model_result.active.returns
comparison = (
None if benchmark_source is None
else comparison_returns(kpi_table, benchmark_source.select([_date_col, "benchmark_returns"]), _date_col)
)
result = AttributionResult(
start_date=common_start.date(),
end_date=common_end.date(),
brinson_fachler=brinson_fachler_result,
factor_model=factor_model_result,
portfolio_returns=kpi_table,
summary_stats=statistics,
diagnostics=tuple(diagnostics),
benchmark_stats=(
ReadOnlyMapping({}) if comparison is None else benchmark_statistics(comparison, settings.risk_free_rate)
),
relative_stats=ReadOnlyMapping({}) if comparison is None else relative_statistics(comparison),
)
return result, brinson_fachler_arrow_result, factor_model_arrow
def _run(
configuration: Configuration,
) -> tuple[AttributionResult, BrinsonFachlerArrowAttribution | None, FactorModelArrowAttribution | None]:
"""
Load, align and attribute; shared by :func:`run_attribution` and :func:`main`.
Parameters
----------
configuration : Configuration
Runtime settings (see :func:`main`).
Returns
-------
tuple
``(result, brinson_fachler, factor_model)``: the
:class:`AttributionResult`, and the attribution objects that produced
it (``None`` for a disabled method), which ``main`` uses to plot.
Raises
------
ConfigurationError
If neither attribution method is enabled.
"""
validate_license()
settings = configuration.attribution_settings()
require_a_method(settings)
# One collection for both stages: the result's diagnostics start with those logged while loading.
with collect_diagnostics():
inputs = _load_inputs(configuration, settings)
return attribute(inputs, settings)
[docs]
def run_attribution(configuration: Configuration) -> AttributionResult:
"""
Run the attribution and return the results as data.
Validates the licence, loads and aligns the inputs, runs the enabled
methods, and returns an :class:`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)`` (see
:mod:`~kaxanuk.attribution_analysis.output_handlers`).
Parameters
----------
configuration : Configuration
Runtime settings (see :func:`main`).
Returns
-------
AttributionResult
Per-method results (``None`` for a disabled method), the aligned date
window, the KPI return series and its summary statistics, and the
warnings logged while loading and attributing (``diagnostics``).
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.
"""
result, _, _ = _run(configuration)
return result
[docs]
def 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:
"""
Run the full performance attribution pipeline, write its outputs, then plot or serve the dashboard.
Computes everything as :func:`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 to
``configuration.output_directory`` and named after
``portfolio_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`` (both ``bool``; at least one must be
``True``).
* **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). When ``False``, 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 via ``ExcelConfigurator.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 :mod:`~kaxanuk.attribution_analysis.output_handlers`). ``None``
writes the Excel report:
``[ExcelOutputHandler.from_configuration(configuration)]``. An empty
sequence writes nothing.
Returns
-------
AttributionResult
The same result :func:`run_attribution` returns.
Raises
------
LicenseError
Raised before anything is read when the license does not validate
(``services.license_validator.validate_license()``): one of
``LicenseNotFoundError``, ``LicenseValidationError``,
``LicenseServerError`` or ``LicenseConfigurationError``.
FileNotFoundError
If any configured data directory or file does not exist.
ConfigurationError
If neither attribution method is enabled, or ``configuration``
contains invalid field values (raised during
``Configuration.__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:
1. **Data loading** -- market prices, portfolio/benchmark weights,
benchmark returns, and per-factor return series are read from disk
using the appropriate input handlers.
2. **Date alignment** -- the common start/end dates across all tables
are computed and each table is filtered accordingly.
3. **Attribution** -- enabled methods (Brinson-Fachler, Factor Model) are
executed sequentially, then the summary statistics are computed.
4. **Outputs** -- the output handlers write the result (by default the
Excel report, to ``output_directory``).
5. **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)
"""
result, brinson_fachler, factor_model = _run(configuration)
handlers = (
[ExcelOutputHandler.from_configuration(configuration)] if output_handlers is None else output_handlers
)
# Before the plots and the dashboard, which block until they are closed or stopped.
for handler in handlers:
handler.output_result(result=result)
if not launch_dashboard:
if brinson_fachler is not None:
brinson_fachler.attribution_plots()
if factor_model is not None:
logger.info("Plotting factor model results")
factor_model.attribution_plots(title='Factor Model Attribution')
return result
from kaxanuk.attribution_analysis.dashboard.attribution_dashboard import ( # noqa: PLC0415
create_dashboard_from_result,
)
logger.info("Preparing dashboard data")
dashboard = create_dashboard_from_result(
result,
portfolio_name=getattr(configuration, 'portfolio_file_name', 'Portfolio'),
benchmark_name=getattr(configuration, 'benchmark_file_name', None),
days_of_smoothing=45,
)
logger.info("Launching dashboard on %s:%s", dashboard_host, dashboard_port)
dashboard.run_server(port=dashboard_port, host=dashboard_host, debug=dashboard_debug)
return result