Coverage for evaluation/generation_ledger.py: 100%

204 statements  

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

1"""The forward record of every generation, and the capital they share (V6.6.1). A new file on the `forward-ledger` branch, hash-chained, one Action run a session. 

2 

3`evaluation/forward_ledger.py`'s chain stays as it is, since a changed rule would start a new record. It also credits a crypto decision one bar the real book never earns: a decision at D's 

4close uses the mark from D's midnight, and its order fills at D's bar close, so the weights only earn from the next session on. This file lags each class to its real fill, so 

5compare generations here, and never a figure from here with one from there. 

6 

7A generation's return is its own, as if it held the whole book, at the cost of its own trades: conservative, since a blend nets positions. The blended book's true return comes from the engine or 

8Lean, never from a sum of these. 

9""" 

10 

11from __future__ import annotations 

12 

13import json 

14import math 

15from collections.abc import Mapping, Sequence 

16from pathlib import Path 

17from typing import TYPE_CHECKING, Any 

18 

19import numpy as np 

20import pandas as pd 

21 

22from audit.hash_chain import GENESIS_HASH, compute_entry_hash, verify_chain 

23from evaluation.alpha_decay import DecayConfig, decay_state 

24from evaluation.forward_ledger import COST_BPS_BY_CLASS, is_rebalance, judge_candidate, read_ledger, turnover 

25from evaluation.generation_registry import AdmissionEvidence, Generation, share_cap 

26from portfolio.generation_blend import ( 

27 EW_HALF_LIFE_SESSIONS, 

28 GlidePolicy, 

29 blend_due, 

30 blend_generation_rows, 

31 dynamic_generation_shares, 

32 ew_sharpe, 

33 ew_update, 

34 shrunk_sharpe, 

35 update_generation_shares, 

36) 

37from portfolio.premia_signals import ResearchPanel, SleeveSpec, WeightSettings, signal_to_weights, sleeve_signal 

38 

39if TYPE_CHECKING: 

40 from collections.abc import Iterable 

41 

42SESSION_EVENT = "generation_session" 

43ALLOCATION_EVENT = "generation_allocation" 

44ALLOCATION_ID = "__allocation__" 

45FILL_LAG_SESSIONS = {"crypto": 2, "forex": 2, "equity": 1, "bond": 1} 

46DEFAULT_LAG = 1 

47DEFAULT_COST_BPS = 4.5 

48MIN_COVERAGE = 0.98 

49GUARD_MAX_DRAWDOWN = 0.15 

50 

51 

52def decide_generation(definition: Mapping[str, Any], panel: ResearchPanel, date: str) -> dict[str, float]: 

53 """The frozen rule's weights at `date`. Unlike `forward_ledger.decide`, it passes a score table and `top_k` through, so a cross-sectional rule can't silently become a different one.""" 

54 spec = SleeveSpec( 

55 str(definition["id"]), "forward", str(definition["kind"]), str(definition["family"]), tuple(definition["universe"]), 

56 int(definition["rebalance_every"]), dict(definition.get("params") or {}), 

57 ) 

58 settings = WeightSettings(**(definition.get("settings") or {})) 

59 if spec.family == "crypto_signal": 

60 # round 4C's trial, computed from the marks (portfolio/crypto_signals.py forward_table); every other family is untouched 

61 from portfolio.crypto_signals import forward_table 

62 

63 table = forward_table(spec.params["signal"], panel.known) 

64 panel = ResearchPanel(panel.known, panel.asset_class, panel.fred, {**panel.extras, "observer": table}) 

65 spec = SleeveSpec(spec.id, spec.track, spec.kind, "external_score", spec.universe, spec.rebalance_every, {"table": "observer", "top_k": spec.params.get("top_k")}) 

66 rows = signal_to_weights(sleeve_signal(spec, panel), panel, kind=spec.kind, rebalance_every=1, settings=settings, start=date, end=date, top_k=spec.params.get("top_k")) 

67 return {ticker: float(weight) for ticker, weight in rows.get(date, {}).items()} 

68 

69 

70def session_return_covered( 

71 held: Mapping[str, float], marks: pd.DataFrame, previous: str, date: str, *, classes: Mapping[str, str], traded: Mapping[str, float], 

72 cost_by_class: Mapping[str, float] = COST_BPS_BY_CLASS, min_coverage: float = MIN_COVERAGE, 

73) -> dict[str, Any]: 

74 """What the held weights earned between two marks, less the cost of what traded. One delisted holding doesn't blank every row until the next decision: the rest counts while 

75 at least `min_coverage` of the gross has a mark. Below that the session is `no_data`, never a guess.""" 

76 gross = covered = earned = 0.0 

77 for ticker, weight in held.items(): 

78 size = abs(float(weight)) 

79 gross += size 

80 if ticker not in marks.columns: 

81 continue 

82 before, after = marks.at[previous, ticker], marks.at[date, ticker] 

83 if np.isfinite(before) and np.isfinite(after) and before > 0.0: 

84 covered += size 

85 earned += float(weight) * (float(after) / float(before) - 1.0) 

86 coverage = covered / gross if gross > 0.0 else 1.0 

87 if coverage < min_coverage: 

88 return {"session_return": None, "coverage": coverage, "reason": f"marks cover {coverage:.3f} of the gross, under {min_coverage}"} 

89 cost = sum(abs(float(amount)) * float(cost_by_class.get(classes.get(ticker), DEFAULT_COST_BPS)) / 1e4 for ticker, amount in traded.items()) 

90 return {"session_return": earned - cost, "coverage": coverage, "reason": None} 

91 

92 

93def rows_for(rows: Sequence[Mapping], generation: str) -> list[dict]: 

94 """The payloads of one generation's ledger rows, oldest first.""" 

95 return [row["payload"] for row in rows if row["payload"].get("candidate") == generation] 

96 

97 

98def _lagged(mine: Sequence[Mapping], lag: int, initial: Mapping[str, float]) -> Mapping[str, float]: 

99 """What was decided `lag` sessions ago. Before the record starts, the rule's frozen starting weights.""" 

100 if lag <= 0: 

101 raise ValueError("a decision can't earn the bar it was made on") 

102 return (mine[-lag].get("decided") or {}) if len(mine) >= lag else initial 

103 

104 

105def held_by_lag(mine: Sequence[Mapping], classes: Mapping[str, str], initial: Mapping[str, float], *, lags: Mapping[str, int] = FILL_LAG_SESSIONS) -> dict[str, float]: 

106 """The weights in place at this session's start, class by class: each class holds what it decided as long ago as its order takes to fill.""" 

107 out: dict[str, float] = {} 

108 needed = {int(lags.get(name, DEFAULT_LAG)) for name in set(classes.values())} | {DEFAULT_LAG} 

109 for lag in needed: 

110 row = _lagged(mine, lag, initial) 

111 for ticker, weight in row.items(): 

112 if int(lags.get(classes.get(ticker), DEFAULT_LAG)) == lag: 

113 out[ticker] = float(weight) 

114 return out 

115 

116 

117def row_for_generation( 

118 generation: Generation, rows: Sequence[Mapping], session: str, sessions: Sequence[str], marks: pd.DataFrame, benchmarks: Mapping[str, float], *, 

119 decision: Mapping[str, float] | None = None, definition_sha: str = "", 

120) -> dict[str, Any]: 

121 """One session's payload. A rule with no `needs` decides here, on the runner; one with `needs` reads the `decision` a host dated earlier.""" 

122 definition = generation.definition 

123 mine = rows_for(rows, generation.id) 

124 classes = dict(definition.get("asset_class") or {}) 

125 initial = dict(definition.get("initial_weights") or {}) 

126 held = held_by_lag(mine, classes, initial) 

127 before = held_by_lag(mine[:-1], classes, initial) if mine else dict(initial) 

128 last_decided = dict((mine[-1].get("decided") if mine else initial) or {}) 

129 if generation.needs: 

130 decided, rebalance = (dict(decision), True) if decision is not None else (last_decided, False) 

131 else: 

132 rebalance = is_rebalance(sessions, session, anchor=str(definition["anchor_date"]), every=int(definition["rebalance_every"])) 

133 decided = decide_generation(definition, ResearchPanel(marks.loc[:session], classes, {}, {}), session) if rebalance else last_decided 

134 earlier = [day for day in sessions if day < session] 

135 traded = {ticker: float(held.get(ticker, 0.0)) - float(before.get(ticker, 0.0)) for ticker in set(held) | set(before)} 

136 if earlier: 

137 result = session_return_covered(held, marks, earlier[-1], session, classes=classes, traded=traded) 

138 else: 

139 result = {"session_return": 0.0, "coverage": 1.0, "reason": None} 

140 return { 

141 "status": "ok" if result["session_return"] is not None else "no_data", "reason": result["reason"], "definition_sha256": definition_sha, "rebalance": rebalance, "decided": decided, 

142 "held": held, "turnover": turnover(before, held), "coverage": result["coverage"], "session_return": result["session_return"], "benchmarks": dict(benchmarks), 

143 "data_sources": sorted(definition.get("data_sources") or []), 

144 } 

145 

146 

147def no_data_row(generation: Generation, rows: Sequence[Mapping], *, reason: str, benchmarks: Mapping[str, float], definition_sha: str = "") -> dict[str, Any]: 

148 """A failed fetch is a row with its reason, never a gap. The held weights don't change.""" 

149 mine = rows_for(rows, generation.id) 

150 decided = (mine[-1].get("decided") if mine else generation.definition.get("initial_weights")) or {} 

151 return { 

152 "status": "no_data", "reason": str(reason)[:200], "definition_sha256": definition_sha, "rebalance": False, "decided": dict(decided), "held": dict(mine[-1].get("held") or {}) if mine else {}, 

153 "turnover": 0.0, "coverage": None, "session_return": None, "benchmarks": dict(benchmarks), "data_sources": sorted(generation.definition.get("data_sources") or []), 

154 } 

155 

156 

157def append_event(path: Path, *, event: str, session: str, candidate: str, payload: Mapping[str, Any], created_at: str) -> dict[str, Any]: 

158 """Links a row to the chain. The session is in the hashed payload, so rewriting a date breaks it.""" 

159 rows = read_ledger(path) 

160 previous = rows[-1]["hash"] if rows else GENESIS_HASH 

161 body = {"session": session, "candidate": candidate, **payload} 

162 row = {"prev_hash": previous, "event_type": event, "created_at": created_at, "payload": body} 

163 row["hash"] = compute_entry_hash(previous, event, created_at, body) 

164 path = Path(path) 

165 path.parent.mkdir(parents=True, exist_ok=True) 

166 with path.open("a", encoding="utf-8", newline="\n") as handle: 

167 handle.write(json.dumps(row, sort_keys=True) + "\n") 

168 return row 

169 

170 

171def _max_drawdown(values: Sequence[float]) -> float: 

172 """Largest fall from a running peak of the compounded curve, in [0, 1] (formal/AetherFormal/DrawdownGuard.lean). 

173 

174 V6.6.7 (#369): fail closed. A non-finite session return gave a NaN drawdown, and `nan >= ceiling` is False, so the guard 

175 never tripped; a return at or below -1 (everything lost) took the curve through zero. Both now read as a drawdown of 1.""" 

176 if not len(values): 

177 return 0.0 

178 returns = np.asarray(values, dtype=float) 

179 if not np.isfinite(returns).all() or (returns <= -1.0).any(): 

180 return 1.0 

181 curve = np.cumprod(1.0 + returns) 

182 peak = np.maximum.accumulate(np.concatenate([[1.0], curve]))[1:] 

183 return float(min(1.0, max(0.0, 1.0 - (curve / peak).min()))) 

184 

185 

186def generation_state(generation: Generation, mine: Sequence[Mapping], *, config: DecayConfig | None = None, guard_max_drawdown: float = GUARD_MAX_DRAWDOWN) -> dict[str, Any]: 

187 """The decay report, with the guard first: a drawdown past the owner's ceiling is `tripped`, whatever the statistic says, and it latches.""" 

188 returns = [float(row["session_return"]) for row in mine if row.get("status") == "ok" and row.get("session_return") is not None] 

189 previous = next((row["state"] for row in reversed(mine) if row.get("state")), "healthy") 

190 report = decay_state(returns, expected_sharpe=float(generation.expected_sharpe), previous="healthy" if previous == "tripped" else previous, config=config) 

191 drawdown = _max_drawdown(returns) 

192 tripped = previous == "tripped" or drawdown >= guard_max_drawdown 

193 return {"state": "tripped" if tripped else report.state, "statistic": report.statistic, "ew_sharpe": report.ew_sharpe, "sessions": report.sessions, "max_drawdown": drawdown, "reason": report.reason} 

194 

195 

196def judge_generations(rows: Sequence[Mapping]) -> dict[str, Any]: 

197 """Chain first: a broken chain makes every figure meaningless.""" 

198 valid, broken_at = verify_chain(list(rows)) 

199 report: dict = {"chain_valid": valid, "first_broken_row": broken_at, "rows": len(rows)} 

200 if not valid: 

201 return report 

202 names = sorted({row["payload"].get("candidate") for row in rows if row["payload"].get("candidate") != ALLOCATION_ID}) 

203 report["generations"] = {name: judge_candidate(rows, name) for name in names} 

204 allocations = [row["payload"] for row in rows if row["payload"].get("candidate") == ALLOCATION_ID] 

205 report["latest_allocation"] = allocations[-1] if allocations else None 

206 return report 

207 

208 

209def evidence_for(generation: Generation, judged: Mapping[str, Any], *, incumbent_returns: Mapping[str, float] | None, own_returns: Mapping[str, float], holdouts_spent: bool, state: Mapping[str, Any]) -> AdmissionEvidence: 

210 """The admission rule's inputs from the record, with the flags a round's verdict set. The mean difference is on sessions both have.""" 

211 admission = generation.admission or {} 

212 difference = None 

213 if incumbent_returns: 

214 shared = sorted(set(own_returns) & set(incumbent_returns)) 

215 if shared: 

216 difference = float(np.mean([own_returns[day] - incumbent_returns[day] for day in shared])) 

217 rows = int(judged.get("rows") or 0) 

218 alpha = judged.get("alpha") or {} 

219 t = alpha.get("t_hac") 

220 record = record_of(own_returns.values() if isinstance(own_returns, Mapping) else own_returns, prior=float(generation.expected_sharpe)) 

221 return AdmissionEvidence( 

222 selection_pass=bool(admission.get("selection_pass")), hold_pass=bool(admission.get("hold_pass")), edge_pass=bool(admission.get("edge_pass")), holdouts_spent=holdouts_spent, 

223 forward_ok_sessions=int(judged.get("sessions") or 0), no_data_share=(float(judged.get("no_data_sessions") or 0) / rows) if rows else 0.0, mean_diff_vs_incumbent=difference, 

224 guard_tripped=state.get("state") == "tripped", decay_state=str(state.get("state") or "healthy"), forward_alpha_t=None if t is None or not math.isfinite(float(t)) else float(t), 

225 score=shrunk_sharpe(record["ew_sharpe"], record["sessions"], record["prior"], GlidePolicy().prior_sessions) if record["sessions"] else None, 

226 ) 

227 

228 

229def record_of(returns: Iterable[float], *, prior: float) -> dict[str, Any]: 

230 """What the allocator reads about one generation: its exponentially weighted Sharpe, its sessions of record, and what it claimed at admission.""" 

231 state = (0.0, 0.0, 0.0, 0) 

232 for value in returns: 

233 state = ew_update(state, value, EW_HALF_LIFE_SESSIONS) 

234 return {"ew_sharpe": ew_sharpe(state), "sessions": state[3], "prior": float(prior)} 

235 

236 

237def allocation_row( 

238 generations: Mapping[str, Generation], shares_before: Mapping[str, float], states: Mapping[str, Mapping], caps: Mapping[str, float], rows_by_generation: Mapping[str, Mapping[str, float]], 

239 policy: GlidePolicy, *, decided_today: bool, sessions_since_blend: int, records: Mapping[str, Mapping] | None = None, 

240) -> dict[str, Any]: 

241 """Today's shares, by the policy's mode, and a blended row when one is due. A row retargets every name, so it isn't written daily.""" 

242 stages = {name: generation.stage for name, generation in generations.items()} 

243 labels = {name: str(state.get("state") or "healthy") for name, state in states.items()} 

244 if policy.mode == "dynamic": 

245 shares = dynamic_generation_shares(shares_before, stages, labels, records or {}, caps, policy) 

246 else: 

247 shares = update_generation_shares(shares_before, stages, labels, caps, policy) 

248 moved_off = any(float(shares_before.get(name, 0.0)) > 0.0 and shares.get(name, 0.0) == 0.0 for name in generations) 

249 due = blend_due(decided_today=decided_today, sessions_since_blend=int(sessions_since_blend), guard_tripped=moved_off, policy=policy) 

250 return { 

251 "status": "allocation", "shares_before": {name: float(value) for name, value in shares_before.items()}, "shares": shares, "tbills": max(0.0, 1.0 - sum(shares.values())), "stages": stages, 

252 "states": labels, "caps": {name: float(value) for name, value in caps.items()}, "blend_due": due, "sessions_since_blend": 0 if due else int(sessions_since_blend), 

253 "blended": blend_generation_rows(rows_by_generation, shares) if due else None, 

254 } 

255 

256 

257def replay_handover( 

258 rows_by_generation: Mapping[str, Mapping[str, Mapping[str, float]]], sessions: Sequence[str], *, incumbent: str, successor: str, start: str, policy: GlidePolicy, 

259) -> dict[str, Any]: 

260 """The blended weight file a handover would have written: `incumbent` holds the book until `start`, then the ladder moves it to `successor`. Uses the running functions, so a 

261 backtest of this file tests what would trade. {"rows": {date: weights}, "shares": {date: shares}}.""" 

262 shares = {incumbent: 1.0, successor: 0.0} 

263 latest: dict[str, Mapping[str, float]] = {incumbent: {}, successor: {}} 

264 rows: dict[str, dict[str, float]] = {} 

265 path: dict[str, dict[str, float]] = {} 

266 since = 0 

267 for session in sessions: 

268 decided = False 

269 for name in (incumbent, successor): 

270 row = rows_by_generation[name].get(session) 

271 if row is not None: 

272 latest[name] = row 

273 decided = decided or shares.get(name, 0.0) > 0.0 

274 stages = {incumbent: "active", successor: "ramping" if session >= start else "shadow"} 

275 before = dict(shares) 

276 shares = update_generation_shares(shares, stages, {}, {}, policy) 

277 since += 1 

278 moved_off = before.get(incumbent, 0.0) > 0.0 and shares.get(incumbent, 0.0) == 0.0 

279 if blend_due(decided_today=decided, sessions_since_blend=since, guard_tripped=moved_off, policy=policy): 

280 rows[session] = blend_generation_rows(latest, shares) 

281 path[session] = dict(shares) 

282 since = 0 

283 return {"rows": rows, "shares": path} 

284 

285 

286def replay_dynamic( 

287 rows_by_generation: Mapping[str, Mapping[str, Mapping[str, float]]], returns_by_generation: Mapping[str, Mapping[str, float]], sessions: Sequence[str], *, 

288 born: Mapping[str, str], priors: Mapping[str, float], policy: GlidePolicy, initial: Mapping[str, float] | None = None, 

289) -> dict[str, Any]: 

290 """The blended file the `dynamic` mode would have written, reading only returns known by each session. Used by the running functions, so a backtest of it tests what would trade. 

291 {"rows", "shares", "scores"}, with `shares` and `scores` on each session a row is written.""" 

292 names = list(rows_by_generation) 

293 shares = {name: float((initial or {}).get(name, 0.0)) for name in names} 

294 latest: dict[str, Mapping[str, float]] = {name: {} for name in names} 

295 states = dict.fromkeys(names, (0.0, 0.0, 0.0, 0)) 

296 rows: dict[str, dict[str, float]] = {} 

297 path: dict[str, dict[str, float]] = {} 

298 scores: dict[str, dict[str, float]] = {} 

299 since = 0 

300 for session in sessions: 

301 decided = False 

302 for name in names: 

303 row = rows_by_generation[name].get(session) 

304 if row is not None: 

305 latest[name] = row 

306 decided = decided or (shares.get(name, 0.0) > 0.0 and session >= born[name]) 

307 value = returns_by_generation[name].get(session) 

308 if value is not None and session >= born[name]: 

309 states[name] = ew_update(states[name], value, EW_HALF_LIFE_SESSIONS) 

310 stages = {name: "active" if session >= born[name] else "shadow" for name in names} 

311 records = {name: {"ew_sharpe": ew_sharpe(states[name]), "sessions": states[name][3], "prior": float(priors[name])} for name in names} 

312 before = dict(shares) 

313 shares = dynamic_generation_shares(shares, stages, {}, records, {}, policy) 

314 since += 1 

315 moved_off = any(before.get(name, 0.0) > 0.0 and shares.get(name, 0.0) == 0.0 for name in names) 

316 if blend_due(decided_today=decided, sessions_since_blend=since, guard_tripped=moved_off, policy=policy): 

317 rows[session] = blend_generation_rows(latest, shares) 

318 path[session] = dict(shares) 

319 scores[session] = {name: shrunk_sharpe(records[name]["ew_sharpe"], records[name]["sessions"], records[name]["prior"], policy.prior_sessions) for name in names} 

320 since = 0 

321 return {"rows": rows, "shares": path, "scores": scores} 

322 

323 

324def caps_for(generations: Mapping[str, Generation], evidence: Mapping[str, AdmissionEvidence], policy: GlidePolicy) -> dict[str, float]: 

325 """Each generation's share cap under the admission rule, from its tier, evidence and the policy's paper cap.""" 

326 return {name: share_cap(generation, evidence[name], policy.tier2_paper_cap) for name, generation in generations.items()}