Coverage for evaluation/alpha_behaviour.py: 100%
108 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"""How a signal's alpha behaves (V6.6.10, R-ALPHA1): over which horizon it predicts, how fast that fades, where it lives, what it costs
2to trade, and how much of it is a known premium in disguise.
4Every input is a wide table (session x ticker): `scores` as known at the session (higher = expected to do better), `closes` the
5known closes. A diagnostic selects nothing and counts as no trial; R-ALPHA1 only uses it to write the R-BOOK2 list.
6"""
8from __future__ import annotations
10import math
11from collections.abc import Mapping, Sequence
12from typing import Any
14import numpy as np
15import pandas as pd
17from evaluation.rank_ic_core import newey_west_t_stat
19HORIZONS = (1, 5, 10, 20, 40, 60)
20MIN_NAMES = 5
23def forward_returns(closes: pd.DataFrame, horizon: int) -> pd.DataFrame:
24 """The return from each session's close to the close `horizon` sessions later (NaN where that close does not exist)."""
25 return closes.shift(-horizon) / closes - 1.0
28def session_rank_ic(scores: pd.DataFrame, outcome: pd.DataFrame, *, min_names: int = MIN_NAMES) -> pd.Series:
29 """Per session, the Spearman correlation across tickers of the score with the outcome; NaN where fewer than `min_names` names have
30 both, or either side has no spread."""
31 scores, outcome = scores.align(outcome, join="inner")
32 both = scores.notna() & outcome.notna()
33 score_rank = scores.where(both).rank(axis=1)
34 outcome_rank = outcome.where(both).rank(axis=1)
35 sx = score_rank.sub(score_rank.mean(axis=1), axis=0)
36 sy = outcome_rank.sub(outcome_rank.mean(axis=1), axis=0)
37 denominator = np.sqrt((sx ** 2).sum(axis=1) * (sy ** 2).sum(axis=1))
38 ic = (sx * sy).sum(axis=1) / denominator.where(denominator > 0)
39 return ic.where(both.sum(axis=1) >= min_names)
42def ic_summary(ic: pd.Series, *, lags: int) -> dict[str, Any]:
43 """Mean, Newey-West t (lags ~ horizon - 1) and count of an IC series."""
44 values = ic.dropna()
45 if values.empty:
46 return {"mean_ic": None, "t_hac": None, "n": 0}
47 return {"mean_ic": float(values.mean()), "t_hac": float(newey_west_t_stat(values.to_numpy(), lags=max(0, int(lags)))), "n": int(len(values))}
50def ic_term_structure(scores: pd.DataFrame, closes: pd.DataFrame, horizons: Sequence[int] = HORIZONS) -> dict[int, dict[str, Any]]:
51 """The IC against the forward return over each horizon: where in time the signal's information sits."""
52 return {int(h): ic_summary(session_rank_ic(scores, forward_returns(closes, int(h))), lags=int(h) - 1) for h in horizons}
55def ic_lag_profile(scores: pd.DataFrame, closes: pd.DataFrame, *, step: int = 5, lags: int = 12) -> dict[int, float | None]:
56 """The IC of a score held k*step sessions stale against the next `step`-session return: how fast the information fades."""
57 outcome = forward_returns(closes, step)
58 profile: dict[int, float | None] = {}
59 for k in range(lags):
60 summary = ic_summary(session_rank_ic(scores, outcome.shift(-k * step)), lags=step - 1)
61 profile[k * step] = summary["mean_ic"]
62 return profile
65def half_life(profile: Mapping[int, float | None]) -> float | None:
66 """Sessions until the stale IC halves, from a log-linear fit over the leading run of positive ICs; None when the first IC is not
67 positive, fewer than two points are positive, or the fit does not decay."""
68 points = []
69 for lag in sorted(profile):
70 value = profile[lag]
71 if value is None or not value > 0:
72 break
73 points.append((float(lag), math.log(value)))
74 if len(points) < 2:
75 return None
76 x, y = np.array([p[0] for p in points]), np.array([p[1] for p in points])
77 slope = float(np.polyfit(x, y, 1)[0])
78 return math.log(2.0) / -slope if slope < 0 else None
81def ic_by_group(scores: pd.DataFrame, outcome: pd.DataFrame, groups: Mapping[str, str], *, min_names: int = 3, lags: int = 0) -> dict[str, dict[str, Any]]:
82 """The IC within each group of tickers (an asset class, a sector)."""
83 out = {}
84 for group in sorted(set(groups.values())):
85 members = [ticker for ticker in scores.columns if groups.get(ticker) == group]
86 out[group] = ic_summary(session_rank_ic(scores[members], outcome.reindex(columns=members), min_names=min_names), lags=lags)
87 return out
90def ic_by_period(ic: pd.Series, labels: pd.Series, *, lags: int = 0) -> dict[str, dict[str, Any]]:
91 """The IC series cut by a label per session (a year, a regime). Sessions without a label are left out."""
92 labels = labels.reindex(ic.index)
93 return {str(label): ic_summary(ic[labels == label], lags=lags) for label in sorted(labels.dropna().unique(), key=str)}
96def rank_weights(scores: pd.DataFrame) -> pd.DataFrame:
97 """Dollar-neutral weights from each session's ranks: centred, scaled to a gross of one."""
98 centred = scores.rank(axis=1, pct=True).sub(scores.rank(axis=1, pct=True).mean(axis=1), axis=0)
99 gross = centred.abs().sum(axis=1)
100 return centred.div(gross.where(gross > 0), axis=0)
103def spread_after_costs(scores: pd.DataFrame, closes: pd.DataFrame, *, horizon: int = 20, cost_bps: float = 10.0) -> dict[str, Any]:
104 """The rank-weighted long-short book rebalanced every `horizon` sessions: its gross return per rebalance, its turnover (half the sum
105 of absolute weight changes) and the return left after paying `cost_bps` on every unit traded, annualised at 252 sessions."""
106 sessions = scores.index[::horizon]
107 weights = rank_weights(scores.loc[sessions]).fillna(0.0)
108 realised = forward_returns(closes, horizon).reindex(index=sessions, columns=weights.columns)
109 gross = (weights * realised.fillna(0.0)).sum(axis=1)
110 turnover = weights.diff().abs().sum(axis=1).fillna(weights.abs().sum(axis=1)) / 2.0
111 net = gross - 2.0 * turnover * cost_bps / 1e4
112 periods = 252.0 / horizon
113 return {
114 "rebalances": int(len(sessions)), "turnover": float(turnover.mean()) if len(turnover) else None,
115 "gross_annual": float(gross.mean() * periods) if len(gross) else None, "net_annual": float(net.mean() * periods) if len(net) else None,
116 }
119def premia_exposure(scores: pd.DataFrame, factors: Mapping[str, pd.DataFrame], *, min_names: int = MIN_NAMES) -> dict[str, Any]:
120 """Per session, a cross-sectional least-squares fit of the score's ranks on the factors' ranks (with an intercept): the mean of
121 each factor's coefficient, the mean R-squared, and the residual score table (what the factors don't explain)."""
122 names = list(factors)
123 betas: dict[str, list[float]] = {name: [] for name in names}
124 r_squared: list[float] = []
125 residual = pd.DataFrame(np.nan, index=scores.index, columns=scores.columns)
126 ranked = {name: table.reindex(index=scores.index, columns=scores.columns).rank(axis=1, pct=True) for name, table in factors.items()}
127 score_rank = scores.rank(axis=1, pct=True)
128 for session in scores.index:
129 y = score_rank.loc[session]
130 x = pd.DataFrame({name: ranked[name].loc[session] for name in names})
131 usable = y.notna() & x.notna().all(axis=1)
132 if int(usable.sum()) < max(min_names, len(names) + 2):
133 continue
134 design = np.column_stack([np.ones(int(usable.sum())), x[usable].to_numpy(dtype=float)])
135 target = y[usable].to_numpy(dtype=float)
136 coefficients, *_ = np.linalg.lstsq(design, target, rcond=None)
137 fitted = design @ coefficients
138 total = float(((target - target.mean()) ** 2).sum())
139 r_squared.append(1.0 - float(((target - fitted) ** 2).sum()) / total if total > 1e-12 * len(target) else 0.0) # a constant score's ranks carry float noise
140 for index, name in enumerate(names):
141 betas[name].append(float(coefficients[index + 1]))
142 residual.loc[session, usable[usable].index] = target - fitted
143 return {
144 "betas": {name: (float(np.mean(values)) if values else None) for name, values in betas.items()},
145 "r_squared": float(np.mean(r_squared)) if r_squared else None, "sessions": len(r_squared), "residual": residual,
146 }
149def breadth(scores: pd.DataFrame, groups: Mapping[str, str] | None = None) -> dict[str, Any]:
150 """The mean number of names with a score per session, overall and per group."""
151 counts = scores.notna().sum(axis=1)
152 out: dict[str, Any] = {"mean_names": float(counts.mean()) if len(counts) else 0.0}
153 if groups:
154 out["by_group"] = {
155 group: float(scores[[t for t in scores.columns if groups.get(t) == group]].notna().sum(axis=1).mean()) for group in sorted(set(groups.values()))
156 }
157 return out
160def alpha_report(scores: pd.DataFrame, closes: pd.DataFrame, *, groups: Mapping[str, str], factors: Mapping[str, pd.DataFrame],
161 regimes: pd.Series | None = None, horizon: int = 20, cost_bps: float = 10.0) -> dict[str, Any]:
162 """R-ALPHA1's whole report for one signal: every diagnostic above, the residual IC after the factors, and nothing it selects."""
163 outcome = forward_returns(closes, horizon)
164 ic = session_rank_ic(scores, outcome)
165 profile = ic_lag_profile(scores, closes)
166 exposure = premia_exposure(scores, factors)
167 years = pd.Series([str(pd.Timestamp(day).year) for day in ic.index], index=ic.index)
168 report = {
169 "term_structure": ic_term_structure(scores, closes),
170 "lag_profile": profile,
171 "half_life_sessions": half_life(profile),
172 "by_class": ic_by_group(scores, outcome, groups, lags=horizon - 1),
173 "by_year": ic_by_period(ic, years, lags=horizon - 1),
174 "spread": spread_after_costs(scores, closes, horizon=horizon, cost_bps=cost_bps),
175 "premia": {key: value for key, value in exposure.items() if key != "residual"},
176 "residual_ic": ic_summary(session_rank_ic(exposure["residual"], outcome), lags=horizon - 1),
177 "breadth": breadth(scores, groups),
178 }
179 if regimes is not None:
180 report["by_regime"] = ic_by_period(ic, regimes, lags=horizon - 1)
181 return report