"""
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%"
)
[docs]
def link_cumulative(
effects: Mapping[str, np.ndarray],
portfolio_returns: np.ndarray,
benchmark_returns: np.ndarray,
method: LinkingMethod | str,
) -> dict[str, np.ndarray]:
"""
Running linked cumulative effects.
Parameters
----------
effects : Mapping[str, np.ndarray]
Per-period effects, one array per effect, all the same length as the
returns. For an exact result each period's effects must sum to
``r_t - b_t``.
portfolio_returns, benchmark_returns : np.ndarray
Per-period returns (``b = 0`` for a total-return decomposition).
method : LinkingMethod or str
``"carino"``, ``"grap"`` or ``"none"``.
Returns
-------
dict[str, np.ndarray]
For each effect, the linked cumulative value at every period T (the
effect's share of ``R_T - B_T`` under the chosen method).
Raises
------
AttributionArgumentError
If `method` is unknown (also a ``ValueError``).
SeriesAlignmentError
If the returns are not 1-D or array lengths differ (also a ``ValueError``).
PerformanceAttributionError
If a return is non-finite or <= -100%, an effect is non-finite, or the
linked result is non-finite or cumulative growth overflowed or underflowed
to zero.
"""
try:
method = LinkingMethod(method)
except (ValueError, TypeError):
raise AttributionArgumentError(f"linking method must be 'carino', 'grap' or 'none', got {method!r}") from None
r = np.asarray(portfolio_returns, dtype=np.float64)
b = np.asarray(benchmark_returns, dtype=np.float64)
if r.ndim != 1 or b.ndim != 1:
raise SeriesAlignmentError(f"returns must be 1-D, got shapes portfolio {r.shape}, benchmark {b.shape}")
if r.shape != b.shape:
raise SeriesAlignmentError(f"Return series length differs: portfolio {r.shape}, benchmark {b.shape}")
_validate_returns("portfolio", r)
_validate_returns("benchmark", b)
arrays = {}
for name, values in effects.items():
array = np.asarray(values, dtype=np.float64)
if array.shape != r.shape:
raise SeriesAlignmentError(f"Effect '{name}' length {array.shape} differs from returns {r.shape}")
if not np.all(np.isfinite(array)):
raise PerformanceAttributionError(f"Linking: effect '{name}' has non-finite values")
arrays[name] = array
if method is LinkingMethod.NONE:
linked = {name: np.cumsum(array) for name, array in arrays.items()}
else:
with np.errstate(over="ignore", invalid="ignore", divide="ignore"):
linked = _link_compounded(arrays, r, b, method)
if not all(np.all(np.isfinite(values)) for values in linked.values()):
raise PerformanceAttributionError(_GROWTH_ERROR)
return linked
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()}