Coverage for evaluation/glide_calibration.py: 100%

178 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1"""R-GLIDE1 (V6.6.1): which handover policy loses least to an oracle, when new generations often have no alpha and old ones decay. 

2 

3It simulates with the running code (`update_generation_shares`, `blend_due`, `decay_state`'s statistic), so what is calibrated is what would trade. Each year brings a generation of true 

4Sharpe `sharpe` with probability 1 - `zero_alpha_probability`, otherwise zero; a generation's alpha halves every `half_life_years`. Returns are correlated across generations. 

5The oracle holds, each session, the generation with the highest true Sharpe. Regret is the gap in annualised Sharpe to that oracle, and the rule also limits how long capital sits 

6mostly on a generation with no alpha. 

7""" 

8 

9from __future__ import annotations 

10 

11import math 

12from collections.abc import Mapping, Sequence 

13from typing import Any 

14 

15import numpy as np 

16 

17from evaluation.alpha_decay import DecayConfig 

18from portfolio.generation_blend import ( 

19 EW_HALF_LIFE_SESSIONS, 

20 GlidePolicy, 

21 blend_due, 

22 dynamic_generation_shares, 

23 ew_sharpe, 

24 ew_update, 

25 update_generation_shares, 

26) 

27 

28TRADING_DAYS = 252 

29FALLBACK_POLICY = "fixed_252" 

30VOL = 0.01 

31SWITCH_COST_PER_TURNOVER = 0.0005 

32DEADBAND = 0.002 

33 

34 

35def default_configs() -> list[dict]: 

36 """The grid of simulated worlds (Sharpe, alpha half-life, correlation, zero-alpha probability) the glide calibration runs over.""" 

37 return [ 

38 {"sharpe": sharpe, "half_life_years": half_life, "correlation": correlation, "zero_alpha_probability": zero} 

39 for sharpe in (0.5, 1.0) for half_life in (1.0, 2.0, 3.0) for correlation in (0.0, 0.3, 0.6) for zero in (0.5, 0.8) 

40 ] 

41 

42 

43def default_policies() -> list[dict]: 

44 """The handover policies the glide calibration compares: fixed glides of several lengths and the evidence-driven variants.""" 

45 fixed = [{"name": f"fixed_{sessions}", "kind": "glide", "glide_sessions": sessions} for sessions in (126, 252, 504)] 

46 evidence = [ 

47 {"name": "fixed_252_hold_on_watch", "kind": "glide", "glide_sessions": 252, "hold_on_watch": True}, 

48 {"name": "fixed_252_accelerate", "kind": "glide", "glide_sessions": 252, "accelerate_on_decaying": 2.0}, 

49 {"name": "fixed_252_hold_and_accelerate", "kind": "glide", "glide_sessions": 252, "hold_on_watch": True, "accelerate_on_decaying": 2.0}, 

50 ] 

51 return [{"name": "instant", "kind": "instant"}, {"name": "equal", "kind": "equal"}, *fixed, *evidence] 

52 

53 

54def glide2_policies() -> list[dict]: 

55 """R-GLIDE2's grid: the dynamic mode, and the two it must be judged against. Four generations may hold capital at once.""" 

56 grid = [ 

57 { 

58 "name": f"dynamic_h{half_life}_p{prior}_f{int(floor * 100):02d}_b{blend}", "kind": "dynamic", "half_life_sessions": half_life, "prior_sessions": float(prior), "score_floor": floor, 

59 "blend_every": blend, "max_generations": 4, 

60 } 

61 for half_life in (63, 126) for prior in (126, 252, 504) for floor in (0.0, 0.2) for blend in (5, 21) 

62 ] 

63 return [{"name": "fixed_252", "kind": "glide", "glide_sessions": 252}, {"name": "equal", "kind": "equal"}, *grid] 

64 

65 

66def simulate_generations(config: Mapping[str, Any], seed: int, *, years: int = 8) -> dict[str, Any]: 

67 """{"true_sharpe": sessions x generations, "returns": sessions x generations, "born": first session of each}. A generation exists from its birth.""" 

68 rng = np.random.default_rng(seed) 

69 sessions = years * TRADING_DAYS 

70 generations = years 

71 born = np.arange(generations) * TRADING_DAYS 

72 has_alpha = rng.random(generations) >= float(config["zero_alpha_probability"]) 

73 has_alpha[0] = True # the incumbent is the one that won its place 

74 decay = 0.5 ** (1.0 / (float(config["half_life_years"]) * TRADING_DAYS)) 

75 true = np.zeros((sessions, generations)) 

76 for index in range(generations): 

77 if has_alpha[index]: 

78 age = np.maximum(0, np.arange(sessions) - born[index]) 

79 true[:, index] = float(config["sharpe"]) * decay ** age 

80 true[: born[index], index] = 0.0 

81 common = rng.normal(size=(sessions, 1)) 

82 own = rng.normal(size=(sessions, generations)) 

83 rho = float(config["correlation"]) 

84 shocks = math.sqrt(rho) * common + math.sqrt(1.0 - rho) * own 

85 returns = true / math.sqrt(TRADING_DAYS) * VOL + VOL * shocks 

86 return {"true_sharpe": true, "returns": returns, "born": born, "has_alpha": has_alpha, "claimed_sharpe": float(config["sharpe"])} 

87 

88 

89def _cusum_step(level: np.ndarray, returns: np.ndarray, expected: np.ndarray, config: DecayConfig) -> np.ndarray: 

90 steps = expected / math.sqrt(TRADING_DAYS) - returns / VOL - config.slack / math.sqrt(TRADING_DAYS) 

91 return np.maximum(0.0, level + steps) 

92 

93 

94def _state_of(level: float, config: DecayConfig) -> str: 

95 if level >= config.threshold * config.dead_multiple: 

96 return "dead" 

97 if level >= config.threshold: 

98 return "decaying" 

99 if level >= config.threshold * config.watch_fraction: 

100 return "watch" 

101 return "healthy" 

102 

103 

104def run_policy(world: Mapping[str, Any], policy: Mapping[str, Any]) -> dict[str, Any]: 

105 """A path of shares and what they earned, net of turnover cost, with blended rows only when due and the deadband on.""" 

106 returns, true, born = world["returns"], world["true_sharpe"], world["born"] 

107 sessions, generations = returns.shape 

108 glide = GlidePolicy( 

109 glide_sessions=int(policy.get("glide_sessions", 252)), hold_on_watch=bool(policy.get("hold_on_watch", False)), 

110 accelerate_on_decaying=float(policy.get("accelerate_on_decaying", 1.0)), entry_share=float(policy.get("entry_share", 0.30)), 

111 mode="dynamic" if policy["kind"] == "dynamic" else "ladder", half_life_sessions=int(policy.get("half_life_sessions", 126)), prior_sessions=float(policy.get("prior_sessions", 252.0)), 

112 score_floor=float(policy.get("score_floor", 0.0)), blend_every=int(policy.get("blend_every", 21)), max_generations=int(policy.get("max_generations", 4)), 

113 ) 

114 records = [(0.0, 0.0, 0.0, 0) for _ in range(generations)] 

115 holders_total = 0 

116 traded_total = 0.0 

117 kind = policy["kind"] 

118 names = [f"g{index}" for index in range(generations)] 

119 wanted = {names[0]: 1.0} 

120 held = np.zeros(generations) 

121 held[0] = 1.0 

122 level = np.zeros(generations) 

123 earned = np.zeros(sessions) 

124 zero_alpha_majority = 0 

125 since_blend = 0 

126 config = DecayConfig() 

127 # Every generation is judged against the same claim, its selection Sharpe halved: a zero-alpha one also won its round, and nobody can know its true alpha when it arrives. 

128 expected = np.full(generations, float(world["claimed_sharpe"]) * 0.5) 

129 retired = np.zeros(generations, dtype=bool) 

130 births = set(born.tolist()) 

131 for session in range(sessions): 

132 alive = born <= session 

133 level = _cusum_step(level, returns[session], expected, config) * alive 

134 states = {names[index]: _state_of(float(level[index]), config) for index in range(generations)} 

135 retired |= np.array([states[name] == "dead" for name in names]) & alive 

136 new_today = bool(session in births and session > 0) 

137 if kind == "instant": 

138 if new_today: 

139 wanted = {names[int(np.nonzero(born == session)[0][0])]: 1.0} 

140 elif kind == "equal": 

141 live = [names[index] for index in np.nonzero(alive & ~retired)[0]] 

142 wanted = {name: 1.0 / len(live) for name in live} if live else {} 

143 elif kind == "dynamic": 

144 living = np.nonzero(alive)[0] 

145 for index in living: 

146 records[index] = ew_update(records[index], float(returns[session, index]), EW_HALF_LIFE_SESSIONS) 

147 stages = {names[index]: "retired" if retired[index] else "active" for index in living} 

148 evidence = {names[index]: {"ew_sharpe": ew_sharpe(records[index]), "sessions": records[index][3], "prior": float(world["claimed_sharpe"]) * 0.5} for index in living} 

149 wanted = dynamic_generation_shares({name: wanted.get(name, 0.0) for name in stages}, stages, states, evidence, {}, glide) 

150 else: 

151 stages = {} 

152 for index in np.nonzero(alive)[0]: 

153 name = names[index] 

154 if retired[index]: 

155 stages[name] = "retired" 

156 elif wanted.get(name, 0.0) >= 1.0 - 1e-9 and sum(1 for value in wanted.values() if value > 0.0) <= 1: 

157 stages[name] = "active" 

158 else: 

159 stages[name] = "ramping" if born[index] > 0 and index >= _newest_active(wanted, names) else "active" 

160 wanted = update_generation_shares({name: wanted.get(name, 0.0) for name in stages}, stages, states, {}, glide) 

161 target = np.array([wanted.get(name, 0.0) for name in names]) 

162 earned[session] = float(held @ returns[session]) 

163 since_blend += 1 

164 changed = np.abs(target - held).sum() 

165 if blend_due(decided_today=new_today, sessions_since_blend=since_blend, guard_tripped=bool(np.any(retired & (held > 0.0))), policy=glide) and changed > DEADBAND: 

166 earned[session] -= changed * SWITCH_COST_PER_TURNOVER 

167 traded_total += changed 

168 held = target 

169 since_blend = 0 

170 no_alpha = true[session] <= 0.0 

171 if float(held[no_alpha].sum()) > 0.5: 

172 zero_alpha_majority += 1 

173 holders_total += int((held >= glide.retire_share).sum()) 

174 years = sessions / TRADING_DAYS 

175 return { 

176 "daily": earned, "zero_alpha_majority_share": zero_alpha_majority / sessions, "mean_holders": holders_total / sessions, "turnover_per_year": traded_total / years, 

177 } 

178 

179 

180def _newest_active(wanted: Mapping[str, float], names: Sequence[str]) -> int: 

181 """Generations after the newest one holding capital wait their turn; the one directly at or after it may ramp.""" 

182 holding = [index for index, name in enumerate(names) if wanted.get(name, 0.0) > 0.0] 

183 return (holding[0] + 1) if holding else 0 

184 

185 

186def oracle_daily(world: Mapping[str, Any]) -> np.ndarray: 

187 """The daily return of an oracle that always holds the generations with the best true Sharpe, the calibration's upper bound.""" 

188 true, returns, born = world["true_sharpe"], world["returns"], world["born"] 

189 out = np.zeros(true.shape[0]) 

190 for session in range(true.shape[0]): 

191 alive = born <= session 

192 pick = int(np.argmax(np.where(alive, true[session], -np.inf))) 

193 out[session] = returns[session, pick] 

194 return out 

195 

196 

197def _sharpe(daily: np.ndarray) -> float: 

198 deviation = daily.std(ddof=1) 

199 return float(daily.mean() / deviation * math.sqrt(TRADING_DAYS)) if deviation > 0.0 else 0.0 

200 

201 

202def _score_worlds(job: tuple[Any, ...]) -> dict[str, Any]: 

203 """One config's worlds, for every policy. A worker's unit of work, so the result can't depend on how many workers ran.""" 

204 config, config_index, per_config, policies, seed, years = job 

205 out: dict[str, dict[str, list[float]]] = {policy["name"]: {"regret": [], "majority": [], "holders": [], "turnover": []} for policy in policies} 

206 for path in range(per_config): 

207 world = simulate_generations(config, seed * 1_000_003 + config_index * 1009 + path, years=years) 

208 oracle = _sharpe(oracle_daily(world)) 

209 for policy in policies: 

210 result = run_policy(world, policy) 

211 row = out[policy["name"]] 

212 row["regret"].append(oracle - _sharpe(result["daily"])) 

213 row["majority"].append(result["zero_alpha_majority_share"]) 

214 row["holders"].append(result["mean_holders"]) 

215 row["turnover"].append(result["turnover_per_year"]) 

216 return out 

217 

218 

219def evaluate_policies(configs: Sequence[Mapping], policies: Sequence[Mapping], *, paths: int = 2000, seed: int = 1, years: int = 8, workers: int = 1) -> dict[str, Any]: 

220 """{policy: median regret, time above half of capital on a zero-alpha generation, generations holding capital, turnover}. Every policy meets the same fixed-seed worlds, across all the configs.""" 

221 per_config = max(1, paths // max(1, len(configs))) 

222 jobs = [(config, index, per_config, list(policies), seed, years) for index, config in enumerate(configs)] 

223 if workers > 1: 

224 from concurrent.futures import ProcessPoolExecutor 

225 

226 with ProcessPoolExecutor(max_workers=workers) as pool: 

227 parts = list(pool.map(_score_worlds, jobs)) 

228 else: 

229 parts = [_score_worlds(job) for job in jobs] 

230 report = {} 

231 for policy in policies: 

232 name = policy["name"] 

233 merged = {key: [value for part in parts for value in part[name][key]] for key in ("regret", "majority", "holders", "turnover")} 

234 report[name] = { 

235 "median_regret": float(np.median(merged["regret"])), "zero_alpha_majority_share": float(np.mean(merged["majority"])), "mean_holders": float(np.mean(merged["holders"])), 

236 "turnover_per_year": float(np.mean(merged["turnover"])), "paths": len(merged["regret"]), 

237 "parameters": sum(key in policy for key in ("glide_sessions", "hold_on_watch", "accelerate_on_decaying", "half_life_sessions", "prior_sessions", "score_floor", "blend_every")), 

238 } 

239 return report 

240 

241 

242def pick_glide2(results: Mapping[str, Mapping], *, baseline: str = "fixed_252", tie: float = 0.005) -> dict[str, Any]: 

243 """R-GLIDE2: the dynamic policy with the lowest median regret among those no worse than the baseline on zero-alpha time, and it replaces the baseline only if its regret is no worse than the 

244 baseline's, within `tie`. Ties among dynamic policies go to less turnover. The owner asked for the dynamic form, so no worse is enough: it holds several generations, and the ladder can't.""" 

245 base = results[baseline] 

246 dynamic = {name: row for name, row in results.items() if name.startswith("dynamic_")} 

247 eligible = {name: row for name, row in dynamic.items() if row["zero_alpha_majority_share"] <= base["zero_alpha_majority_share"] + 1e-12} 

248 report = {"baseline": baseline, "baseline_row": dict(base), "eligible": sorted(eligible), "meets_r_glide1_limit": sorted(name for name, row in results.items() if row["zero_alpha_majority_share"] <= 0.20)} 

249 if not eligible: 

250 return {**report, "policy": baseline, "adopted": False, "reason": "no dynamic policy is as good on zero-alpha time"} 

251 best = min(row["median_regret"] for row in eligible.values()) 

252 close = [name for name, row in eligible.items() if row["median_regret"] <= best + tie] 

253 chosen = sorted(close, key=lambda name: (eligible[name]["turnover_per_year"], name))[0] 

254 adopted = eligible[chosen]["median_regret"] <= base["median_regret"] + tie 

255 reason = "no worse than the ladder on both counts" if adopted else "its regret is worse than the ladder's" 

256 return {**report, "policy": chosen if adopted else baseline, "best_dynamic": chosen, "best_dynamic_row": dict(eligible[chosen]), "adopted": adopted, "reason": reason} 

257 

258 

259def pick_policy(results: Mapping[str, Mapping], *, max_zero_alpha_share: float = 0.20, tie: float = 0.005) -> dict[str, Any]: 

260 """R-GLIDE1: the lowest median regret among policies whose time mostly on a zero-alpha generation is at most 20%. Ties go to fewer parameters. None qualifying: fixed 252.""" 

261 qualifying = {name: row for name, row in results.items() if row["zero_alpha_majority_share"] <= max_zero_alpha_share} 

262 if not qualifying: 

263 return {"policy": FALLBACK_POLICY, "reason": "no policy qualified", "results": dict(results)} 

264 best = min(row["median_regret"] for row in qualifying.values()) 

265 close = [name for name, row in qualifying.items() if row["median_regret"] <= best + tie] 

266 chosen = sorted(close, key=lambda name: (qualifying[name]["parameters"], qualifying[name]["median_regret"], name))[0] 

267 return {"policy": chosen, "reason": "lowest median regret among qualifying policies, ties to fewer parameters", "results": dict(results)}