Source code for kaxanuk.attribution_analysis.modules.linking

"""
Multi-period linking of single-period attribution effects.

Single-period effects (Brinson-Fachler allocation/selection/interaction, or
factor contributions) add up to that period's return difference. Summed over
time they do not add up to the compounded return difference, because value
added early compounds later. Linking rescales them so they do.

Notes
-----
Carino: ``k(x, y) = (ln(1+x) - ln(1+y)) / (x - y)`` (``1/(1+x)`` when x == y),
evaluated as ``log1p(d) / d / (1+y)`` with ``d = (x - y) / (1+y)`` so it stays
accurate as x approaches y and as 1+x approaches 0;
the linked effect to T is ``sum_t e_t k(r_t, b_t) / k(R_T, B_T)``.
GRAP: ``prod_{t<=T}(1+b_t) * sum_t e_t prod_{i<t}(1+r_i) / prod_{i<=t}(1+b_i)``.
Both are exact when each period's effects sum to ``r_t - b_t``. For a
total-return decomposition pass ``b_t = 0``.
"""

from collections.abc import Mapping

import numpy as np

from kaxanuk.attribution_analysis.entities.attribution_options import LinkingMethod
from kaxanuk.attribution_analysis.exceptions import (
    AttributionArgumentError,
    PerformanceAttributionError,
    SeriesAlignmentError,
)

_LOG1P_MIN_RATIO_CHANGE = -0.5
"""Ratio changes ``d`` above this use ``log1p(d)``; below it ``log(1 + d)`` is taken from the ratio itself."""

_GROWTH_ERROR = "Linking produced non-finite values; cumulative growth overflowed or underflowed"


[docs] def carino_coefficients(portfolio_returns: np.ndarray, benchmark_returns: np.ndarray) -> np.ndarray: """ Carino scaling coefficients, element-wise. Parameters ---------- portfolio_returns, benchmark_returns : np.ndarray Returns of the same shape, each > -1. Returns ------- np.ndarray ``(ln(1+r) - ln(1+b)) / (r - b)``, computed as ``ln(1+d) / d / (1+b)`` with ``d = (r - b) / (1+b)``: accurate for ``r`` close to ``b`` and for ``r`` close to -1. Equal to its limit ``1/(1+b)`` where ``r == b``. """ r = np.asarray(portfolio_returns, dtype=np.float64) b = np.asarray(benchmark_returns, dtype=np.float64) return _carino_k((r - b) / (1.0 + b), 1.0 + b, (1.0 + r) / (1.0 + b))
def _carino_k(d: np.ndarray, benchmark_growth: np.ndarray, growth_ratio: np.ndarray) -> np.ndarray: """ Carino coefficient ``ln(growth_ratio) / (d * benchmark_growth)`` without cancellation. ``d`` is ``growth_ratio - 1``, passed in separately because it is accurate when the ratio is near 1 (``log1p(d)`` is then exact), while ``log(growth_ratio)`` is accurate when the ratio is near 0, where ``1 + d`` would lose all precision. """ with np.errstate(divide="ignore", invalid="ignore"): log_ratio = np.where(d > _LOG1P_MIN_RATIO_CHANGE, np.log1p(d), np.log(growth_ratio)) k = log_ratio / d return np.where(d == 0.0, 1.0, k) / benchmark_growth def _validate_returns(label: str, values: np.ndarray) -> None: bad = np.flatnonzero(~np.isfinite(values) | (values <= -1.0)) if bad.size: i = int(bad[0]) raise PerformanceAttributionError( f"Linking: {label} return {float(values[i])!r} at period index {i} (0-based) " "is not a finite value above -100%" ) def _link_compounded( arrays: Mapping[str, np.ndarray], r: np.ndarray, b: np.ndarray, method: LinkingMethod, ) -> dict[str, np.ndarray]: growth_p = np.cumprod(1.0 + r) growth_b = np.cumprod(1.0 + b) for growth in (growth_p, growth_b): if not np.all(np.isfinite(growth) & (growth > 0.0)): raise PerformanceAttributionError(_GROWTH_ERROR) if method is LinkingMethod.CARINO: k_period = carino_coefficients(r, b) # Same coefficient as carino_coefficients(R_T, B_T), written with growth ratios so that # no "growth - 1.0" cancellation occurs when cumulative growth is tiny. k_total = _carino_k((growth_p - growth_b) / growth_b, growth_b, growth_p / growth_b) return {name: np.cumsum(array * k_period) / k_total for name, array in arrays.items()} prior_p = np.concatenate(([1.0], growth_p[:-1])) return {name: growth_b * np.cumsum(array * prior_p / growth_b) for name, array in arrays.items()}