Results and Inputs#

AttributionResult and the per-method results it holds, returned by run_attribution(), main() and run_attribution_from_backtest() (see Getting results as data), its Diagnostic entries, and AttributionInputs, the loaded inputs the computation runs on. AttributionResult is also exported from the package root as kaxanuk.attribution_analysis.AttributionResult.

Results of an attribution run, as data.

Returned by kaxanuk.attribution_analysis.run_attribution() (and by main). Tables are PyArrow tables keyed by a date column; mappings are read-only. Results pickle, copy.deepcopy and dataclasses.asdict cleanly.

class ActiveFactorResult(returns: Table, contributions: Table, cumulative_contributions: Table, cumulative_totals: Table, linking: LinkingMethod)[source]#

Bases: object

Active factor attribution: the portfolio’s factor decomposition minus the benchmark’s.

The same factor model runs on the benchmark’s constituent weights (holdings basis). Every table covers the dates on which both sides have a return and factor data. That window can be shorter than the portfolio’s own tables: dates without a benchmark return or benchmark weights (gaps in the weights file) are dropped with one warning, and with linking="none" it leaves out the first price date, which FactorModelResult.cumulative_contributions keeps.

Variables:
  • returns (pa.Table) – date, portfolio_returns, benchmark_returns (holdings benchmark: benchmark weights x asset returns) and active_returns (portfolio_returns - benchmark_returns).

  • contributions (pa.Table) – date, one column per factor (portfolio contribution minus benchmark contribution), then the return components present (f_carry, f_dividends), then f_idio_returns, the active residual. On each date the columns add up to active_returns.

  • cumulative_contributions (pa.Table) – The same columns, cumulative. With linking (carino/grap) they are linked with the portfolio return as r and the holdings benchmark return as b, so on every date they add up to the compounded R_p - R_b; with none they are running sums.

  • cumulative_totals (pa.Table) – date, portfolio_returns, benchmark_returns, active_returns (compounded with linking, running sums with none; active_returns = portfolio_returns - benchmark_returns), factor_returns (the cumulative active factor columns summed), carry_returns / dividends_returns when those components are present, and idiosyncratic_returns (active_returns minus the factors and components).

  • linking (LinkingMethod)

contributions: Table#
cumulative_contributions: Table#
cumulative_totals: Table#
linking: LinkingMethod#
returns: Table#
class AttributionResult(start_date: ~datetime.date, end_date: ~datetime.date, brinson_fachler: ~kaxanuk.attribution_analysis.entities.attribution_result.BrinsonFachlerResult | None, factor_model: ~kaxanuk.attribution_analysis.entities.attribution_result.FactorModelResult | None, portfolio_returns: ~pyarrow.lib.Table, summary_stats: ~collections.abc.Mapping[str, float], implementation: ~pyarrow.lib.Table | None = None, diagnostics: tuple[~kaxanuk.attribution_analysis.entities.attribution_result.Diagnostic, ...] = (), benchmark_stats: ~collections.abc.Mapping[str, float] = <factory>, relative_stats: ~collections.abc.Mapping[str, float] = <factory>)[source]#

Bases: object

Everything an attribution run produced.

Variables:
  • end_date (start_date,) – The common date window all inputs were aligned to. They are datetime.date while the tables’ date columns are timestamps: convert before comparing (e.g. ts.date() >= result.start_date).

  • brinson_fachler (BrinsonFachlerResult or None) – None when the method is disabled.

  • factor_model (FactorModelResult or None) – None when the method is disabled.

  • portfolio_returns (pa.Table) – date, portfolio_returns: the series behind summary_stats (dates with a return only).

  • summary_stats (Mapping[str, float]) – Total Return (compounded), Annualized Return, Annualized Vol, Sharpe Ratio, Max Drawdown, Skewness, Kurtosis, Cornish-Fisher VaR (5%), Historic CVaR (5%). Empty when portfolio_returns has no rows (the statistics are undefined).

  • implementation (pa.Table or None) – Only for runs from a Backtest-Engine result (None otherwise): date, engine_returns, holdings_returns, commissions, slippage, financing, execution. Per date, the engine’s NAV return equals the holdings return plus the four components (costs are negative returns, as fractions of the previous NAV).

  • diagnostics (tuple[Diagnostic, ...]) – The warnings (and notes) the run logged about its inputs and checks, in the order they were logged: dates or rows left out, returns substituted, the holdings benchmark differing from the reported one, a cross-check skipped. Empty when there were none. File-based and in-memory runs fill it alike; the log lines themselves are unchanged.

  • benchmark_stats (Mapping[str, float]) – The keys of summary_stats for the benchmark the attribution compared the portfolio with (Brinson-Fachler’s, else the active factor model’s holdings benchmark), on the dates both have a return. Empty when neither ran.

  • relative_stats (Mapping[str, float]) – The portfolio against that benchmark, on the same dates: Active Return (compounded difference), Annualized Active Return, Tracking Error, Information Ratio, Beta, Hit Rate (see relative_statistics(); the Backtest Engine’s definitions). Empty when neither ran.

benchmark_stats: Mapping[str, float]#
brinson_fachler: BrinsonFachlerResult | None#
diagnostics: tuple[Diagnostic, ...]#
end_date: date#
factor_model: FactorModelResult | None#
implementation: Table | None#
portfolio_returns: Table#
relative_stats: Mapping[str, float]#
start_date: date#
summary_stats: Mapping[str, float]#
class BrinsonFachlerResult(per_period: Table, cumulative: Table, details: Mapping[object, Table], formula: BrinsonFachlerFormula, linking: LinkingMethod, by_year: Table | None = None)[source]#

Bases: object

Brinson-Fachler output.

Variables:
  • per_period (pa.Table) – One row per date: portfolio_returns, benchmark_returns, alpha, allocation, selection, interaction.

  • cumulative (pa.Table) – Cumulative indexes (linked per linking).

  • details (Mapping[object, pa.Table]) – Per-date, per-segment detail tables. Keys are the weights’ date values as Python objects: pandas.Timestamp for the timestamp date columns the pipeline produces, so look them up with details[pandas.Timestamp("2024-01-02")] or iterate the keys.

  • formula (BrinsonFachlerFormula)

  • linking (LinkingMethod)

  • by_year (pa.Table or None) – One row per calendar year: year and the per_period columns, linked within the year exactly as cumulative links the whole window (returns compounded, effects linked; sums with none), so a year’s allocation, selection and interaction add up to its alpha. Years compound into the window; they do not add up to its linked effects. None for a result built without it.

by_year: Table | None#
cumulative: Table#
details: Mapping[object, Table]#
formula: BrinsonFachlerFormula#
linking: LinkingMethod#
per_period: Table#
class Diagnostic(code: DiagnosticCode, level: DiagnosticLevel, message: str, count: int | None = None, total: int | None = None, first_date: date | None = None, details: Mapping[str, object]=<factory>)[source]#

Bases: object

One warning or note an attribution run logged, kept as data.

Recorded where the line is logged, from the values the line is built from: nothing is parsed from log text, and recording changes no number.

Variables:
  • code (DiagnosticCode) – What it reports.

  • level (DiagnosticLevel) – The level the line was logged at.

  • message (str) – The log line, exactly as logged.

  • count (int or None) – How many dates, rows, group-dates or ticker-dates it concerns, when the line counts them.

  • total (int or None) – Out of how many, when the line says.

  • first_date (datetime.date or None) – The first date concerned, when the line names one.

  • details (Mapping[str, object]) – The line’s other values by name, e.g. side ("portfolio" or "benchmark"), ticker, largest_difference. Read-only.

code: DiagnosticCode#
count: int | None#
details: Mapping[str, object]#
first_date: date | None#
level: DiagnosticLevel#
message: str#
total: int | None#
class DiagnosticCode(*values)[source]#

Bases: StrEnum

What a diagnostic reports: one code per kind of log line a run keeps as data.

The values are stable identifiers, safe to compare with plain strings (diagnostic.code == "benchmark_returns_differ").

ACTIVE_DATES_EXCLUDED = 'active_dates_excluded'#
ACTIVE_UNPRICED_HOLDINGS = 'active_unpriced_holdings'#
ACTIVE_WEIGHT_SUMS = 'active_weight_sums'#
BENCHMARK_CHECK_BAD_RETURN_COLUMNS = 'benchmark_check_bad_return_columns'#
BENCHMARK_CHECK_NO_COMMON_DATES = 'benchmark_check_no_common_dates'#
BENCHMARK_CHECK_WITHOUT_RETURNS = 'benchmark_check_without_returns'#
BENCHMARK_RETURNS_DIFFER = 'benchmark_returns_differ'#
BENCHMARK_WEIGHTS_IGNORED = 'benchmark_weights_ignored'#
BRINSON_FACHLER_LEGACY_FORMULA = 'brinson_fachler_legacy_formula'#
BRINSON_FACHLER_LEGACY_NOT_LINKED = 'brinson_fachler_legacy_not_linked'#
BRINSON_FACHLER_SUBSTITUTED_GROUP_DATES = 'brinson_fachler_substituted_group_dates'#
BRINSON_FACHLER_UNPRICED_GROUP_DATES = 'brinson_fachler_unpriced_group_dates'#
BRINSON_FACHLER_WEIGHT_DATES_WITHOUT_PRICES = 'brinson_fachler_weight_dates_without_prices'#
CASH_PRICE_FILE_IGNORED = 'cash_price_file_ignored'#
END_DATE_AFTER_DATA = 'end_date_after_data'#
FACTOR_DATES_WITHOUT_FACTOR_ATTRIBUTION = 'factor_dates_without_factor_attribution'#
FACTOR_DATES_WITHOUT_PORTFOLIO_RETURN = 'factor_dates_without_portfolio_return'#
FACTOR_WEIGHT_ROWS_WITHOUT_DATE = 'factor_weight_rows_without_date'#
SEGMENT_UNPRICED_HOLDINGS = 'segment_unpriced_holdings'#
SUMMARY_STATISTICS_SKIPPED = 'summary_statistics_skipped'#
class DiagnosticLevel(*values)[source]#

Bases: StrEnum

How a diagnostic was logged.

Variables:
  • WARNING – Logged as a warning: something in the inputs changed what was attributed, or a check failed.

  • INFO – Logged as information: a note on how the run was done (e.g. a cross-check skipped for want of an input).

INFO = 'info'#
WARNING = 'warning'#
class FactorModelResult(portfolio_returns: Table, contributions: Table, cumulative_contributions: Table, cumulative_totals: Table, daily_shares: Table, cumulative_shares: Mapping[str, float], linking: LinkingMethod, active: ActiveFactorResult | None = None, by_year: Table | None = None)[source]#

Bases: object

Factor-model output.

Variables:
  • portfolio_returns (pa.Table) – date, portfolio_returns (null where no held asset had a return).

  • contributions (pa.Table) – Daily portfolio-weighted contribution per factor file (each file’s cells are asset contributions: exposure x factor return). The aggregate vendor files (AGGREGATE_FACTOR_COLUMNS) are not loaded, so they never appear here. The return components f_carry / f_dividends (COMPONENT_COLUMNS), when supplied, are columns here too: they are not factors.

  • cumulative_contributions (pa.Table) – Cumulative contribution per factor file, with the same columns as contributions. With linking (carino/grap): linked, on the dates with a portfolio return. With none: plain running sums over every attribution date, including dates without a portfolio return (e.g. the first price date).

  • cumulative_totals (pa.Table) – date, portfolio_returns, factor_returns, carry_returns and dividends_returns (only when those components were supplied), idiosyncratic_returns: cumulative series from the model, on the dates with a portfolio return. factor_returns excludes the components. With linking, portfolio_returns is compounded and factor_returns is the sum of the cumulative_contributions factor columns. With none every column is an arithmetic running sum: portfolio_returns differs from the compounded Total Return in summary_stats, and since the window differs from cumulative_contributions, factor_returns need not equal the sum of its columns.

  • daily_shares (pa.Table) – Each factor’s share of each day’s portfolio return; the residual column is f_idio_returns. Aggregate files are excluded. Components have their own share column and are taken out of the residual.

  • cumulative_shares (Mapping[str, float]) – Each factor’s share of the cumulative portfolio return; the residual key is idio_returns (not f_idio_returns as in daily_shares). Aggregate files are excluded; the shares sum to 1. Components are keys of their own.

  • linking (LinkingMethod)

  • active (ActiveFactorResult or None) – The portfolio-minus-benchmark decomposition; None unless active_factor_model is on.

  • by_year (pa.Table or None) – One row per calendar year over the window of cumulative_totals: year, portfolio_returns, factor_returns, each factor, the components present (carry_returns, dividends_returns) and idiosyncratic_returns, linked within the year (b = 0; sums with none). None for a result built without it.

active: ActiveFactorResult | None#
by_year: Table | None#
contributions: Table#
cumulative_contributions: Table#
cumulative_shares: Mapping[str, float]#
cumulative_totals: Table#
daily_shares: Table#
linking: LinkingMethod#
portfolio_returns: Table#
class ReadOnlyMapping(data: Mapping | None = None)[source]#

Bases: Mapping, Generic

Read-only mapping over a private copy of a dict.

Unlike types.MappingProxyType it survives pickle, copy.deepcopy and dataclasses.asdict. Item assignment and deletion raise TypeError.

Parameters:

data (Mapping[K, V], optional) – Items to hold; copied, so later changes to the source do not show.

Diagnostics#

How the warnings a run logs are also kept on AttributionResult.diagnostics.

Run diagnostics: the warnings an attribution run logs, kept as data as well.

Each warning site calls log_diagnostic() instead of logging directly. It writes the same log line, from the same logger and at the same level, and, while a run collects (collect_diagnostics()), records the line as a Diagnostic built from the values the line is made of. The run’s entry points put what was collected on AttributionResult.diagnostics.

Collection is per context (contextvars): runs in different threads or tasks never see each other’s diagnostics, and outside a run (a method class used on its own) only the log line is written. Recording reads the values the warning already computed, so it changes no number.

collect_diagnostics() → Iterator[list[Diagnostic]][source]#

Record the diagnostics logged inside the block, in order.

Nested blocks share the outermost block’s list, so an entry point that loads inputs and then calls the attribution core collects both stages in one list.

Yields:

list[Diagnostic] – The list the block records into; read it after the block (or at its end) for everything logged so far.

log_diagnostic(logger: Logger, code: DiagnosticCode, message: str, *args: object, level: DiagnosticLevel = DiagnosticLevel.WARNING, count: int | None = None, total: int | None = None, first_date: object = None, details: Mapping[str, object] | None = None) → None[source]#

Log a line as before and, inside collect_diagnostics(), record it.

Parameters:
  • logger (logging.Logger) – The logger the line has always been logged with.

  • code (DiagnosticCode) – What the line reports.

  • message (str) – %-style format of the line, as passed to logger.warning.

  • *args (object) – Its arguments.

  • level (DiagnosticLevel, default WARNING) – The level the line is logged at.

  • count (int or None) – How many items the line concerns and out of how many (see Diagnostic).

  • total (int or None) – How many items the line concerns and out of how many (see Diagnostic).

  • first_date (object) – The first date concerned: a datetime.date, datetime.datetime, pandas.Timestamp or ISO-8601 string, stored as a datetime.date; anything else is stored as None.

  • details (Mapping[str, object] or None) – The line’s other values by name.

Inputs#

Attribution inputs#

AttributionInputs holds everything the attribution stage needs, already loaded and in attribution format, so that file-based runs and in-memory runs (e.g. a Backtest-Engine result) share one computation, attribute().

class AttributionInputs(*, asset_returns: ReturnsTable, portfolio_weights: PortfolioWeights, benchmark_returns: ReturnsTable | None = None, benchmark_weights: PortfolioWeights | None = None, benchmark_weights_bound_window: bool = True, factor_returns: Mapping[str, ~kaxanuk.attribution_analysis.entities.factor_returns.FactorReturns]=<factory>, segment_map: Mapping[str, str] | None=None)[source]#

Bases: object

Loaded inputs of one attribution run, before date alignment.

Every table has a date column of type timestamp(ns).

Variables:
  • asset_returns (ReturnsTable) – Simple per-ticker returns. The first row is the first price date and has no return (null), as pct_change leaves it; it is never a period. When the weights hold the cash ticker, a zero-return cash column is present.

  • portfolio_weights (PortfolioWeights) – Start-of-day portfolio weights (the book held going into each date).

  • benchmark_returns (ReturnsTable or None, default None) – Reported benchmark return: date plus one return column. None when there is none (e.g. a Backtest-Engine run without a benchmark). When given, it bounds the aligned date window, and textbook Brinson-Fachler and the active factor model compare their holdings benchmark return with it (a warning when they differ); without it they skip that check. The factor model stores it but never uses it, so its numbers do not depend on it beyond the window.

  • benchmark_weights (PortfolioWeights or None) – Start-of-day benchmark weights; required by Brinson-Fachler and by the active factor model.

  • benchmark_weights_bound_window (bool, default True) – Whether the dates of benchmark_weights bound the aligned date window. True is the file pipeline’s behaviour: the benchmark weights file bounds the window of every run. With False they bound it only when Brinson-Fachler runs (it needs them on every date); the active factor model alone then leaves the portfolio’s window as it is and drops the dates without benchmark weights from the active results only.

  • factor_returns (Mapping[str, FactorReturns]) – Per-factor tables (date x ticker), simple or log as loaded. May be empty when the factor model does not run. Every table given bounds the aligned date window, whether or not the factor model runs.

  • segment_map (Mapping[str, str] or None) – Ticker-to-segment map for textbook Brinson-Fachler; None makes every ticker its own segment.

asset_returns: ReturnsTable#
benchmark_returns: ReturnsTable | None#
benchmark_weights: PortfolioWeights | None#
benchmark_weights_bound_window: bool#
factor_returns: Mapping[str, FactorReturns]#
portfolio_weights: PortfolioWeights#
segment_map: Mapping[str, str] | None#