Coverage for evaluation/alpha_decay.py: 100%
91 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""Is a generation's alpha decaying? A one-sided CUSUM of its net daily returns against what it was expected to earn (V6.6.1).
3Decay is slow to see: at one false alarm in five years, a fall from Sharpe 1 to 0 takes on the order of 400 sessions to show. `average_run_lengths` reports what a threshold
4buys, and the allocator (`portfolio/generation_blend.py`) therefore never lets this alone drive capital except at `dead`. Compare against the selection Sharpe halved, not the backtest's figure.
6States: healthy -> watch -> decaying -> dead, with hysteresis: a state falls back only after `recover_sessions` below the lower threshold. Too few or non-finite returns keep the previous state.
7"""
9from __future__ import annotations
11import math
12from collections.abc import Sequence
13from dataclasses import dataclass
14from typing import Any
16import numpy as np
18STATES = ("healthy", "watch", "decaying", "dead")
19TRADING_DAYS = 252.0
22@dataclass(frozen=True)
23class DecayConfig:
24 """Settings of the CUSUM decay monitor: the alarm threshold, the watch fraction and the minimum sessions before a verdict."""
25 threshold: float = 26.0 # about one false alarm in five years at this slack; `average_run_lengths` reports the simulated figure
26 watch_fraction: float = 0.5
27 min_sessions: int = 60
28 recover_sessions: int = 40
29 dead_multiple: float = 2.0
30 slack: float = 0.5 # half the annual Sharpe shift worth detecting, the CUSUM's reference value
33@dataclass(frozen=True)
34class DecayReport:
35 """The decay monitor's state for one generation (healthy, watch, decaying), with its statistic and the sessions it saw."""
36 state: str
37 statistic: float
38 sessions: int
39 ew_sharpe: float | None
40 reason: str
43def _standardised(returns: np.ndarray, expected_sharpe: float, slack: float) -> np.ndarray:
44 """Each session's distance below expectation, in daily standard deviations, less the slack that keeps ordinary noise from adding up."""
45 deviation = returns.std(ddof=1)
46 if not np.isfinite(deviation) or deviation <= 0.0:
47 return np.zeros_like(returns)
48 daily_expected = float(expected_sharpe) / math.sqrt(TRADING_DAYS)
49 return daily_expected - returns / deviation - float(slack) / math.sqrt(TRADING_DAYS)
52def cusum_path(returns: np.ndarray, *, expected_sharpe: float, slack: float = 0.5) -> np.ndarray:
53 """The running statistic: it rises while returns fall short and rests at zero, so old good years can't hide today's loss."""
54 steps = _standardised(np.asarray(returns, dtype=float), expected_sharpe, slack)
55 path = np.zeros(len(steps))
56 level = 0.0
57 for position, step in enumerate(steps):
58 level = max(0.0, level + float(step))
59 path[position] = level
60 return path
63def cusum_lower(returns: np.ndarray, *, expected_sharpe: float, threshold: float, slack: float = 0.5) -> float:
64 """Today's statistic as a share of the threshold: 1.0 is an alarm."""
65 path = cusum_path(returns, expected_sharpe=expected_sharpe, slack=slack)
66 return float(path[-1] / threshold) if len(path) and threshold > 0.0 else 0.0
69def _ew_sharpe(returns: np.ndarray, half_life: float = 126.0) -> float | None:
70 if len(returns) < 20:
71 return None
72 weights = 0.5 ** (np.arange(len(returns))[::-1] / half_life)
73 mean = float(np.average(returns, weights=weights))
74 variance = float(np.average((returns - mean) ** 2, weights=weights))
75 return mean / math.sqrt(variance) * math.sqrt(TRADING_DAYS) if variance > 0.0 else None
78def decay_state(returns: Sequence[float], *, expected_sharpe: float, previous: str = "healthy", config: DecayConfig | None = None) -> DecayReport:
79 """A generation's state today. `previous` carries the hysteresis, so a state can't flicker on one good week."""
80 config = config or DecayConfig()
81 previous = previous if previous in STATES else "healthy"
82 values = np.asarray(list(returns), dtype=float)
83 if len(values) < config.min_sessions:
84 return DecayReport(previous, 0.0, len(values), None, f"only {len(values)} sessions; minimum {config.min_sessions}")
85 if not np.isfinite(values).all() or not math.isfinite(float(expected_sharpe)):
86 return DecayReport(previous, 0.0, len(values), None, "non-finite evidence: holding the state")
87 path = cusum_path(values, expected_sharpe=expected_sharpe, slack=config.slack)
88 statistic = float(path[-1])
89 if statistic >= config.threshold * config.dead_multiple:
90 raw = "dead"
91 elif statistic >= config.threshold:
92 raw = "decaying"
93 elif statistic >= config.threshold * config.watch_fraction:
94 raw = "watch"
95 else:
96 raw = "healthy"
97 state = raw
98 if STATES.index(raw) < STATES.index(previous):
99 # Going down a level needs a run of sessions below that level's floor. A dead generation stays dead: its capital is gone, and only a fresh candidate returns.
100 floor = {"healthy": 0.0, "watch": config.watch_fraction, "decaying": 1.0, "dead": config.dead_multiple}[previous] * config.threshold
101 recovered = len(path) >= config.recover_sessions and bool((path[-config.recover_sessions:] < floor).all())
102 state = previous if previous == "dead" or not recovered else raw
103 return DecayReport(state, statistic, len(values), _ew_sharpe(values), f"CUSUM {statistic:.2f} against {config.threshold:.2f}")
106def average_run_lengths(*, expected_sharpe: float, config: DecayConfig | None = None, paths: int = 2000, seed: int = 1, horizon: int = 2520, decayed_sharpe: float | None = None) -> dict[str, Any]:
107 """Simulated sessions to the first `decaying` alarm: with the alpha intact (a false alarm) and after it falls to `decayed_sharpe`, default zero. Paths that never alarm count at `horizon`."""
108 config = config or DecayConfig()
109 decayed = 0.0 if decayed_sharpe is None else float(decayed_sharpe)
110 rng = np.random.default_rng(seed)
112 def first_alarm(sharpe: float) -> np.ndarray:
113 daily = sharpe / math.sqrt(TRADING_DAYS)
114 step_noise = rng.normal(size=(paths, horizon))
115 steps = float(expected_sharpe) / math.sqrt(TRADING_DAYS) - (daily + step_noise) - config.slack / math.sqrt(TRADING_DAYS)
116 out = np.full(paths, horizon, dtype=float)
117 level = np.zeros(paths)
118 alive = np.ones(paths, dtype=bool)
119 for session in range(horizon):
120 level = np.maximum(0.0, level + steps[:, session])
121 hit = alive & (level >= config.threshold) & (session + 1 >= config.min_sessions)
122 out[hit] = session + 1
123 alive &= ~hit
124 if not alive.any():
125 break
126 return out
128 intact, fallen = first_alarm(float(expected_sharpe)), first_alarm(decayed)
129 return {
130 "expected_sharpe": float(expected_sharpe), "decayed_sharpe": decayed, "threshold": config.threshold, "slack": config.slack, "paths": paths, "horizon": horizon,
131 "median_false_alarm_sessions": float(np.median(intact)), "false_alarm_within_1y": float(np.mean(intact <= 252)), "false_alarm_within_5y": float(np.mean(intact <= 1260)),
132 "median_detection_sessions": float(np.median(fallen)), "detected_within_1y": float(np.mean(fallen <= 252)), "detected_within_2y": float(np.mean(fallen <= 504)),
133 }