Source code for kaxanuk.attribution_analysis.entities.attribution_options

"""
Shared option types for the attribution methods.

Kept in their own module so entities, interfaces, modules and config handlers
can import them without cycles.
"""

import dataclasses
import enum
import math
import types

from kaxanuk.attribution_analysis.exceptions import ConfigurationError


class BrinsonFachlerFormula(enum.StrEnum):
    """
    Brinson-Fachler decomposition variant.

    Attributes
    ----------
    TEXTBOOK
        Standard single-period Brinson-Fachler (1985): allocation
        ``(w_p - w_b)(R_b,i - R_b)``, selection ``w_b (R_p,i - R_b,i)``,
        interaction ``(w_p - w_b)(R_p,i - R_b,i)``.
    LEGACY
        The previous asset-level variant (0.3.x and earlier), kept only to
        reproduce published results. Deprecated.
    """

    TEXTBOOK = "textbook"
    LEGACY = "legacy"


class FactorReturnType(enum.StrEnum):
    """
    Compounding convention of the values in the per-factor return files.

    Attributes
    ----------
    SIMPLE
        Values are simple (arithmetic) returns and are used as-is.
    LOG
        Values are log returns; they are restated as simple returns before
        attribution (see ``modules.factor_return_conversion``).
    """

    SIMPLE = "simple"
    LOG = "log"


class LinkingMethod(enum.StrEnum):
    """
    How single-period effects are combined over many periods.

    Attributes
    ----------
    CARINO
        Carino (1999) logarithmic smoothing: residual-free and order-independent.
        Linked effects add up to the compounded return difference.
    GRAP
        GRAP (1997): earlier periods grow at the portfolio return, later ones at
        the benchmark return. Also residual-free; depends on period order.
    NONE
        Plain running sums of the per-period effects (no linking, the behaviour before this release).
        They add up to the sum of period returns, not the compounded return.
    """

    CARINO = "carino"
    GRAP = "grap"
    NONE = "none"


AGGREGATE_FACTOR_COLUMNS = frozenset({
    "f_total_factor_returns",
    "f_total_excess_returns",
    "f_idyo_returns",
})
"""Factor-file names that hold totals, never counted as a factor."""

COMPONENT_COLUMNS = types.MappingProxyType({
    "f_carry": "carry_returns",
    "f_dividends": "dividends_returns",
})
"""
Reserved factor-file names for return components that are not factors, mapped to their column in
the cumulative totals. Their cells are simple returns (never restated from log returns); each is
reported on its own and taken out of the idiosyncratic residual like a factor.
"""

FACTOR_DISPLAY_NAMES = types.MappingProxyType({
    "f_idio_returns": "Idiosyncratic",
    "idio_returns": "Idiosyncratic",
    "f_carry": "Carry",
    "f_dividends": "Dividends",
})
"""
Chart labels for the data keys that are not shown under their own name: the idiosyncratic residual
(``f_idio_returns`` in daily tables, ``idio_returns`` in ``cumulative_shares``) and the return components.
"""

STYLE_FACTORS = ("f_market", "f_size", "f_momentum", "f_beta", "f_residual volatility", "f_value")
"""Known style-factor names, in the order the charts draw them (other non-industry factors follow alphabetically)."""

INDUSTRY_FACTORS = (
    "f_Communication Services", "f_Consumer Discretionary", "f_Consumer Staples",
    "f_Energy", "f_Financials", "f_Health Care", "f_Industrials",
    "f_Information Technology", "f_Materials", "f_Real Estate", "f_Utilities",
)
"""GICS sector factor names, drawn in the industry panel when any value is non-zero."""

WEIGHT_SUM_TOLERANCE = 1e-6
"""Max |sum(weights) - 1| per date: below it no implied cash is added, and textbook Brinson-Fachler accepts the sum."""


[docs] @dataclasses.dataclass(frozen=True, slots=True, kw_only=True) class AttributionSettings: """ Which attribution methods run, and how. Shared by :class:`~kaxanuk.attribution_analysis.entities.configuration.Configuration` (file-based runs) and in-memory runs such as a Backtest-Engine result. Strings are coerced to the enums; invalid values raise. Attributes ---------- brinson_fachler_method, factor_model_method : bool Enable each method; at least one must be ``True`` when a run starts. brinson_fachler_formula : BrinsonFachlerFormula, default TEXTBOOK Brinson-Fachler variant (see :class:`BrinsonFachlerFormula`). factor_return_type : FactorReturnType, default SIMPLE Compounding convention of the factor returns (see :class:`FactorReturnType`). linking_method : LinkingMethod, default CARINO How per-period effects are combined over time (see :class:`LinkingMethod`). cash_ticker : str, default "CASH" Column name of the zero-return cash segment (stripped). risk_free_rate : float, default 0.0 Annual risk-free rate as a decimal (``0.03`` = 3%) for the Sharpe ratio of ``summary_stats``, converted to a per-period rate over 252 periods a year. Finite and above -1; an int is accepted and stored as float. active_factor_model : bool, default False Also run the factor model on the benchmark's constituent weights and report the portfolio-minus-benchmark decomposition (``FactorModelResult.active``). Needs `factor_model_method` and benchmark weights. Raises ------ ConfigurationError If a flag is not a bool, an option is not a valid enum value, `cash_ticker` is not a non-empty string, `risk_free_rate` is not a finite real number above -1, or `active_factor_model` is not a bool or is on without `factor_model_method`. """ brinson_fachler_method: bool factor_model_method: bool brinson_fachler_formula: BrinsonFachlerFormula | str = BrinsonFachlerFormula.TEXTBOOK factor_return_type: FactorReturnType | str = FactorReturnType.SIMPLE linking_method: LinkingMethod | str = LinkingMethod.CARINO cash_ticker: str = "CASH" risk_free_rate: float = 0.0 active_factor_model: bool = False def __post_init__(self) -> None: """Validate the flags and coerce the options to their enums.""" if not isinstance(self.brinson_fachler_method, bool): raise ConfigurationError("Incorrect format for brinson_fachler_method, expecting a bool") if not isinstance(self.factor_model_method, bool): raise ConfigurationError("Incorrect format for factor_model_method, expecting a bool") try: object.__setattr__(self, "brinson_fachler_formula", BrinsonFachlerFormula(self.brinson_fachler_formula)) except (ValueError, TypeError): raise ConfigurationError( "Incorrect value for brinson_fachler_formula, expecting 'textbook' or 'legacy'" ) from None try: object.__setattr__(self, "factor_return_type", FactorReturnType(self.factor_return_type)) except (ValueError, TypeError): raise ConfigurationError("Incorrect value for factor_return_type, expecting 'simple' or 'log'") from None try: object.__setattr__(self, "linking_method", LinkingMethod(self.linking_method)) except (ValueError, TypeError): raise ConfigurationError( "Incorrect value for linking_method, expecting 'carino', 'grap' or 'none'" ) from None if not isinstance(self.cash_ticker, str) or not self.cash_ticker.strip(): raise ConfigurationError("Incorrect format for cash_ticker, expecting a non-empty str") object.__setattr__(self, "cash_ticker", self.cash_ticker.strip()) if isinstance(self.risk_free_rate, bool) or not isinstance(self.risk_free_rate, (int, float)): raise ConfigurationError( "Incorrect format for risk_free_rate, expecting a float (annual rate as a decimal, e.g. 0.03)" ) if not (math.isfinite(self.risk_free_rate) and self.risk_free_rate > -1.0): raise ConfigurationError( "Incorrect value for risk_free_rate, expecting a finite annual rate above -1 (e.g. 0.03 for 3%)" ) object.__setattr__(self, "risk_free_rate", float(self.risk_free_rate)) if not isinstance(self.active_factor_model, bool): raise ConfigurationError("Incorrect format for active_factor_model, expecting a bool") if self.active_factor_model and not self.factor_model_method: raise ConfigurationError("active_factor_model needs factor_model_method=True")