Coverage for evaluation/research_round.py: 100%

385 statements  

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

1"""One pre-registered research round, from a rule file (V6.6.1): the stages each phase used to hand-write in a `scripts/v6xx_*.py`. 

2 

3A round's JSON is hashed before any score and never edited: every stage starts by checking that hash. Its stages are resumable, since the training 

4Codespace reboots about hourly: 

5 

6 rules -> score -> placebo -> gate -> pbo -> (survivors only) freeze -> hold -> report 

7 

8Selection reads a free cell only. A held-out cell opens through `evaluation/research_cells.py` with the digest of the one freeze, and 

9`record_holdout_read` refuses a second read of any cell. Every trial counts in the deflated Sharpe's N, whether it ran or not. 

10 

11Pure where it can be: `gate_report` and `pbo_report` work on stored scores, so a past round can be recomputed and compared. 

12""" 

13 

14from __future__ import annotations 

15 

16import dataclasses 

17import hashlib 

18import json 

19import math 

20from collections.abc import Callable, Mapping, Sequence 

21from dataclasses import dataclass, field 

22from pathlib import Path 

23from typing import TYPE_CHECKING, Any 

24 

25import numpy as np 

26import pandas as pd 

27 

28from evaluation.premia_research import ( 

29 nulls_for, 

30 passes_sharpe_clauses, 

31 placebo_p_value, 

32 placebo_sharpes, 

33 score_sleeve, 

34 selection_gate, 

35) 

36from evaluation.research_cells import CELLS, FREE_CELLS, freeze_digest_of, record_holdout_read, write_freeze 

37from evaluation.round_builders import BUILDERS, MissingInput, apply_gate, build_trial_table 

38from evaluation.trial_ledger import append_trial, read_ledger 

39from portfolio.premia_signals import DIRECT, POOLED, TS, XS, SleeveSpec 

40from portfolio.signal_construction import build_table 

41from portfolio.wide_signals import live_names_per_rebalance, rank_mean 

42 

43if TYPE_CHECKING: 

44 from evaluation.wide_context import WideCell 

45 

46HOLDOUT_LEDGER = Path("ml") / "generations" / "holdout_ledger.jsonl" 

47KINDS = {"pooled": POOLED, "cross_sectional": XS, "time_series": TS, "direct": DIRECT} 

48HOLDOUT_FAMILIES = {"equity": ("V1", "V2", "V3"), "crypto": ("CV",)} 

49 

50 

51@dataclass(frozen=True) 

52class RoundSpec: 

53 """A pre-registered research round: its name, cell, side, trials, rules file and the bar a trial must clear.""" 

54 name: str 

55 cell: str 

56 side: str 

57 bar: str 

58 rule: str 

59 trials: Mapping[str, Mapping] 

60 out_dir: Path 

61 ledger: Path 

62 window_label: str = "v660_selection" 

63 track: str = "W" 

64 min_live_names: int = 150 

65 min_ic_names: int = 20 

66 pbo_blocks: int = 16 

67 prior_daily: tuple[str, ...] = () 

68 prior_columns: tuple[str, ...] = () 

69 disclosures: tuple[str, ...] = () 

70 no_ic_clause: tuple[str, ...] = () 

71 raw: Mapping = field(default_factory=dict) 

72 

73 

74def _read_json(path: Path, default): 

75 return json.loads(path.read_text(encoding="utf-8")) if path.exists() else default 

76 

77 

78def _write_json(path: Path, payload) -> None: 

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

80 path.write_text(json.dumps(payload, indent=1, default=str), encoding="utf-8", newline="\n") 

81 

82 

83def rules_sha_path(path: Path) -> Path: 

84 """The `.sha256` file that pins a round's rules file.""" 

85 return Path(path).with_suffix(".sha256") 

86 

87 

88def write_rules(payload: Mapping[str, Any], path: Path) -> str: 

89 """Writes a round's rule file once, with its hash beside it. A second write refuses: a changed rule needs a dated amendment.""" 

90 path = Path(path) 

91 if path.exists(): 

92 raise FileExistsError(f"{path} is already written and is never overwritten") 

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

94 path.write_text(json.dumps(payload, indent=1), encoding="utf-8", newline="\n") 

95 digest = hashlib.sha256(path.read_bytes()).hexdigest() 

96 rules_sha_path(path).write_text(digest + "\n", encoding="utf-8", newline="\n") 

97 return digest 

98 

99 

100def load_round(path: Path, *, root: Path = Path(".")) -> RoundSpec: 

101 """The round, after its hash check. A changed file stops the round: no stage reads rules other than the ones recorded.""" 

102 path = Path(path) 

103 payload = path.read_bytes() 

104 digest = hashlib.sha256(payload).hexdigest() 

105 recorded = rules_sha_path(path).read_text(encoding="utf-8").strip() if rules_sha_path(path).exists() else None 

106 if digest != recorded: 

107 raise SystemExit(f"{path.name} {digest} is not the recorded {recorded}") 

108 raw = json.loads(payload) 

109 return RoundSpec( 

110 name=str(raw["name"]), cell=str(raw["cell"]), side=str(raw["side"]), bar=str(raw["bar"]), rule=str(raw.get("rule", "")), trials=raw["trials"], 

111 out_dir=Path(root) / str(raw["out_dir"]), ledger=Path(root) / str(raw["ledger"]), window_label=str(raw.get("window_label", "v660_selection")), 

112 track=str(raw.get("track", "W")), min_live_names=int(raw.get("min_live_names", 150)), min_ic_names=int(raw.get("min_ic_names", 20)), 

113 pbo_blocks=int(raw.get("pbo_blocks", 16)), prior_daily=tuple(raw.get("prior_daily") or ()), prior_columns=tuple(raw.get("prior_columns") or ()), 

114 disclosures=tuple(raw.get("disclosures") or ()), no_ic_clause=tuple(raw.get("no_ic_clause") or ()), raw=raw, 

115 ) 

116 

117 

118def _paths(spec: RoundSpec) -> dict[str, Path]: 

119 return {name: spec.out_dir / f"{prefix}_{spec.name}{suffix}" for name, prefix, suffix in ( 

120 ("scores", "selection_scores", ".json"), ("daily", "selection_daily", ".parquet"), ("placebos", "selection_placebos", ".json"), 

121 ("gate", "selection_gate", ".json"), ("pbo", "selection_pbo", ".json"), ("report", "r", ".json"), 

122 )} 

123 

124 

125def family_of(spec: RoundSpec) -> str: 

126 """The holdout family of a round's cell: `crypto` for the crypto universe, `equity` otherwise.""" 

127 return "crypto" if CELLS[spec.cell].universe == "crypto" else "equity" 

128 

129 

130def universe_for(spec: RoundSpec, trial: str) -> tuple[str, ...]: 

131 """What a trial trades: its own `universe`, else the coins of a crypto cell, else the eleven sectors.""" 

132 entry = spec.trials[trial] 

133 if entry.get("universe"): 

134 return tuple(entry["universe"]) 

135 if family_of(spec) == "crypto": 

136 return ("crypto",) 

137 from evaluation.wide_context import SECTORS 

138 

139 return tuple(SECTORS) 

140 

141 

142def spec_of(spec: RoundSpec, trial: str, universe: Sequence[str]) -> SleeveSpec: 

143 """The `SleeveSpec` a round's trial runs as, from its registered entry.""" 

144 entry = spec.trials[trial] 

145 params: dict = {"table": trial} 

146 if entry.get("top_k"): 

147 params["top_k"] = entry["top_k"] 

148 return SleeveSpec(trial, spec.track, KINDS[str(entry.get("kind", "pooled"))], "external_score", tuple(universe), int(entry.get("rebalance_every", 20)), params) 

149 

150 

151def score_file_table(path: Path, index: Sequence[str] | pd.Index, columns: Sequence[str] | pd.Index) -> pd.DataFrame | None: 

152 """A model's walk-forward scores as a session x ticker table, or None when the file isn't there.""" 

153 path = Path(path) 

154 if not path.exists(): 

155 return None 

156 frame = pd.read_csv(path, dtype={"date": str, "ticker": str}) 

157 return frame.pivot_table(index="date", columns="ticker", values="score", aggfunc="last").reindex(index=index, columns=columns) 

158 

159 

160def tradable_mask(entry: Mapping[str, Any], table: pd.DataFrame, cell) -> pd.DataFrame: 

161 """What a table may hold. A pooled or cross-sectional trial holds the cell's members. A time-series or direct trial that names its assets (`params.tickers` or `params.ticker`) 

162 holds exactly those: ETFs and SPY are never index members, so the member mask silently emptied round 4E's e4 and e5 (no live names, Sharpe 0.0; Problems #336).""" 

163 if entry.get("kind") in ("time_series", "direct"): 

164 params = entry.get("params") or {} 

165 named = set(params.get("tickers") or ()) | ({params["ticker"]} if params.get("ticker") else set()) 

166 if named: 

167 flags = table.columns.isin(sorted(named)) 

168 return pd.DataFrame(np.broadcast_to(flags, table.shape), index=table.index, columns=table.columns) 

169 return cell.member 

170 

171 

172def trial_table(spec: RoundSpec, trial: str, cell: WideCell, built: dict[str, pd.DataFrame], *, score_dir: Path, score_suffix: str = "") -> pd.DataFrame | None: 

173 """One trial's table on this cell, or None when it can't be built yet (a model that didn't run). `built` holds earlier trials, which a composite 

174 may name. Masked to the cell's members, so nothing outside them can be held.""" 

175 entry = spec.trials[trial] 

176 known = cell.context.panel.known 

177 if entry.get("score_file"): 

178 table = score_file_table(Path(score_dir) / f"{entry['score_file']}{score_suffix}.csv", known.index, known.columns) 

179 return None if table is None else table.where(cell.member) 

180 if entry.get("builder") == "fama_macbeth_ridge": 

181 from evaluation.walk_forward_linear import fama_macbeth_ridge 

182 

183 signs = {str(name): float(sign) for name, sign in entry["signs"].items()} 

184 start = str(entry.get("start") or cell.cell.start) 

185 features = {name: cell.features[name].where(cell.member.reindex(index=cell.features[name].index, columns=cell.features[name].columns, fill_value=False)) for name in signs if name in cell.features} 

186 if len(features) != len(signs): 

187 raise KeyError(f"{trial}: features {sorted(set(signs) - set(features))} are not in this cell") 

188 table = fama_macbeth_ridge(features, cell.label, signs=signs, start=start, kappa=int(entry.get("kappa", 36)), ridge=float(entry.get("ridge", 1.0))) 

189 return table.where(cell.member.reindex(index=table.index, columns=table.columns, fill_value=False)) 

190 if entry.get("builder") in BUILDERS: 

191 try: 

192 table = build_trial_table(str(entry["builder"]), entry.get("params"), cell) 

193 except MissingInput: 

194 return None 

195 gated = apply_gate(table, entry.get("gate"), cell) 

196 return gated.where(tradable_mask(entry, gated, cell)) 

197 if entry.get("builder"): 

198 raise KeyError(f"trial {trial}: unknown builder {entry['builder']!r}") 

199 recipe = entry["recipe"] 

200 lookup = {**cell.features, **cell.tables, **built} 

201 if recipe.get("optional_parts"): 

202 present = [name for name in recipe["parts"] if name in lookup] 

203 if len(present) < int(recipe.get("minimum", 2)): 

204 return None 

205 return apply_gate(rank_mean([lookup[name] for name in present], minimum=int(recipe.get("minimum", 2))), entry.get("gate"), cell).where(cell.member) 

206 missing = [name for name in [*recipe["parts"], *(recipe.get("exposures") or ())] if name not in lookup] 

207 if missing and any(name in spec.trials for name in missing): 

208 return None # a part is another trial that didn't run 

209 return apply_gate(build_table(recipe, lookup, cell.member, sectors=cell.sectors), entry.get("gate"), cell).where(cell.member) 

210 

211 

212def _trial_context(context, entry: Mapping[str, Any]): 

213 band = entry.get("min_weight_change") 

214 if band is None: 

215 return context 

216 return dataclasses.replace(context, config=dataclasses.replace(context.config, min_weight_change=float(band))) 

217 

218 

219def live_rows(signal: pd.DataFrame, entry: Mapping[str, Any]) -> pd.DataFrame: 

220 """The rows live names are counted on. A gated trial holds nothing while its gate is off, so the median over all rebalances would read the gate as a lack of names: it is counted on the rows 

221 where the gate is on (those with any value). An ungated trial counts every row, as before.""" 

222 if entry.get("gate"): 

223 return signal[signal.notna().any(axis=1)] 

224 return signal 

225 

226 

227def clause_overrides(spec: RoundSpec) -> dict[str, dict]: 

228 """Per trial: its own minimum of live names, and whether it has no IC clause. Empty for a round that sets neither, so earlier rounds recompute unchanged.""" 

229 out: dict[str, dict] = {} 

230 for trial, entry in spec.trials.items(): 

231 override: dict = {} 

232 if "min_live_names" in entry: 

233 override["min_live_names"] = int(entry["min_live_names"]) 

234 if trial in spec.no_ic_clause: 

235 override["no_ic"] = True 

236 if override: 

237 out[trial] = override 

238 return out 

239 

240 

241def passes_earlier_clauses(score: Mapping[str, Any], *, min_live_names: int, no_ic: bool = False) -> bool: 

242 """Everything in R-SLEEVE3 before the placebos: live names, the Sharpe clauses, and the rank-IC t (not for a trial the round lists in `no_ic_clause`).""" 

243 if not passes_sharpe_clauses(score): 

244 return False 

245 if (score.get("live_names") or {}).get("median", 0.0) < min_live_names: 

246 return False 

247 if no_ic: 

248 return True 

249 t = (score.get("ic") or {}).get("nonoverlap_t") 

250 return t is not None and t >= 2.0 

251 

252 

253def _failed_clause(score: Mapping[str, Any], *, min_live_names: int) -> str: 

254 if (score.get("live_names") or {}).get("median", 0.0) < min_live_names: 

255 return "live_names" 

256 return "sharpe" if not passes_sharpe_clauses(score) else "ic" 

257 

258 

259def _load_selection_cell(spec: RoundSpec, root: Path, *, with_info: bool = True): 

260 from evaluation.wide_context import crypto_cell, equity_cell 

261 

262 if spec.cell not in FREE_CELLS: 

263 raise PermissionError(f"selection reads free cells only, not {spec.cell}") 

264 base = json.loads((Path(root) / "config.json").read_text(encoding="utf-8")) 

265 if family_of(spec) == "crypto": 

266 return crypto_cell(Path(root), base, spec.cell) 

267 return equity_cell(Path(root), base, spec.cell, with_info=with_info) 

268 

269 

270def stage_score(spec: RoundSpec, *, cell: WideCell, score_dir: Path, only: Sequence[str] = (), force: bool = False, ic_fn: Callable[..., Any] | None = None, emit: Callable[[str], None] = print) -> dict[str, Any]: 

271 """Scores each trial not yet scored, saving after each one. A table that can't be built stays unscored and is named by the gate.""" 

272 if ic_fn is None: 

273 from evaluation.wide_context import signal_ic_t as ic_fn 

274 paths = _paths(spec) 

275 scores = _read_json(paths["scores"], {}) 

276 frames = pd.read_parquet(paths["daily"]).to_dict("series") if paths["daily"].exists() else {} 

277 context = cell.context 

278 overrides = clause_overrides(spec) 

279 built: dict[str, pd.DataFrame] = {} 

280 for trial, entry in spec.trials.items(): 

281 table = trial_table(spec, trial, cell, built, score_dir=score_dir) 

282 if table is None: 

283 emit(f"{trial}: no table yet") 

284 continue 

285 built[trial] = table 

286 context.panel.extras[trial] = table 

287 if (only and trial not in only) or (trial in scores and not force): 

288 continue 

289 sleeve = spec_of(spec, trial, universe_for(spec, trial)) 

290 start = str(entry.get("start") or cell.cell.start) 

291 signal = table 

292 live = live_names_per_rebalance(live_rows(signal.loc[signal.index >= start], entry), sleeve.rebalance_every) 

293 score = score_sleeve(sleeve, _trial_context(context, entry), start=start, split=cell.cell.split, end=cell.cell.end, signal=signal) 

294 daily = score.pop("daily") 

295 middle = daily[min(daily)] 

296 frames[trial] = middle 

297 if overrides.get(trial, {}).get("no_ic"): 

298 ic = None 

299 elif family_of(spec) == "crypto": 

300 from evaluation.wide_context import crypto_ic 

301 

302 ic = crypto_ic(signal, cell.context.panel.known, start=start, end=cell.cell.end, min_names=spec.min_ic_names) 

303 else: 

304 ic = ic_fn(signal, cell.label, start=start, end=cell.cell.end, min_names=spec.min_ic_names) if cell.label is not None else None 

305 scores[trial] = {**score, "cell": spec.cell, "live_names": live, "ic": ic, "round": spec.name} 

306 append_trial(spec.ledger, trial_id=trial, track=spec.track, window=spec.window_label, role="candidate", annualised_sharpe=score["sharpe"], n_obs=len(middle), engine="offline", 

307 detail={"cell": spec.cell, "round": spec.name}) 

308 _write_json(paths["scores"], scores) 

309 pd.DataFrame(frames).sort_index().to_parquet(paths["daily"]) 

310 emit(f"{trial} Sharpe {score['sharpe']} ({score['sharpe_first_half']}, {score['sharpe_second_half']}) IC t {(ic or {}).get('nonoverlap_t')} live {live['median']:.0f} turnover {score['turnover']}") 

311 return scores 

312 

313 

314def stage_placebo(spec: RoundSpec, *, cell: WideCell, score_dir: Path, draws: int = 100, force: bool = False, emit: Callable[[str], None] = print) -> dict[str, Any]: 

315 """R-SLEEVE3's placebos, only for trials that pass every earlier clause.""" 

316 paths = _paths(spec) 

317 scores = _read_json(paths["scores"], {}) 

318 overrides = clause_overrides(spec) 

319 eligible = [ 

320 trial for trial, score in scores.items() 

321 if passes_earlier_clauses(score, min_live_names=overrides.get(trial, {}).get("min_live_names", spec.min_live_names), no_ic=bool(overrides.get(trial, {}).get("no_ic"))) 

322 ] 

323 emit(f"reach the placebo clause: {eligible or 'none'}") 

324 done = _read_json(paths["placebos"], {}) 

325 if not eligible: 

326 _write_json(paths["placebos"], done) 

327 return done 

328 built: dict[str, pd.DataFrame] = {} 

329 for trial in spec.trials: 

330 table = trial_table(spec, trial, cell, built, score_dir=score_dir) 

331 if table is not None: 

332 built[trial] = table 

333 cell.context.panel.extras[trial] = table 

334 for trial in eligible: 

335 if trial in done and not force: 

336 continue 

337 sleeve = spec_of(spec, trial, universe_for(spec, trial)) 

338 entry = spec.trials[trial] 

339 start = str(entry.get("start") or cell.cell.start) 

340 out = {} 

341 for mode in nulls_for(sleeve): 

342 sharpes = placebo_sharpes(sleeve, _trial_context(cell.context, entry), mode, start=start, end=cell.cell.end, draws=draws) 

343 out[mode] = {"p": placebo_p_value(scores[trial]["sharpe"], sharpes), "draws": len(sharpes), "median": float(pd.Series(sharpes).median()) if sharpes else None} 

344 emit(f"{trial} {mode} p {out[mode]['p']:.3f} median {out[mode]['median']}") 

345 done[trial] = out 

346 _write_json(paths["placebos"], done) 

347 return done 

348 

349 

350def gate_report( 

351 scores: Mapping[str, Mapping], placebos: Mapping[str, Mapping], daily: pd.DataFrame, *, trials: Sequence[str], min_live_names: int = 150, overrides: Mapping[str, Mapping] | None = None, 

352) -> dict[str, Any]: 

353 """R-SLEEVE3 from stored scores: a pure function, so a past round can be recomputed and compared.""" 

354 overrides = overrides or {} 

355 eligible = { 

356 name: score for name, score in scores.items() 

357 if passes_earlier_clauses(score, min_live_names=overrides.get(name, {}).get("min_live_names", min_live_names), no_ic=bool(overrides.get(name, {}).get("no_ic"))) 

358 } 

359 rows = [{**score, "id": name, "daily": {0: daily[name].dropna()}} for name, score in eligible.items()] 

360 p_values = {name: {mode: entry["p"] for mode, entry in tests.items()} for name, tests in placebos.items()} 

361 gate = selection_gate(rows, p_values) 

362 gate["failed_earlier_clauses"] = {name: _failed_clause(score, min_live_names=overrides.get(name, {}).get("min_live_names", min_live_names)) for name, score in scores.items() if name not in eligible} 

363 gate["unscored"] = [trial for trial in trials if trial not in scores] 

364 return gate 

365 

366 

367def count_unrun_trials(spec: RoundSpec, unscored: Sequence[str], *, reason: str = "did not run") -> list[str]: 

368 """A pre-registered trial counts in N whether it ran or not. Appends a row only for those the ledger doesn't hold yet.""" 

369 held = {entry["trial_id"] for entry in read_ledger(spec.ledger)} 

370 added = [] 

371 for trial in unscored: 

372 if trial not in held: 

373 append_trial(spec.ledger, trial_id=trial, track=spec.track, window=spec.window_label, role="candidate", annualised_sharpe=None, n_obs=0, engine="offline", 

374 detail={"cell": spec.cell, "round": spec.name, "not_run": reason}) 

375 added.append(trial) 

376 return added 

377 

378 

379def stage_gate(spec: RoundSpec) -> dict[str, Any]: 

380 """Apply the round's selection gate to the scored and placebo-tested trials, and write the survivors.""" 

381 paths = _paths(spec) 

382 scores = _read_json(paths["scores"], {}) 

383 placebos = _read_json(paths["placebos"], {}) 

384 daily = pd.read_parquet(paths["daily"]) if paths["daily"].exists() else pd.DataFrame() 

385 gate = gate_report(scores, placebos, daily, trials=list(spec.trials), min_live_names=spec.min_live_names, overrides=clause_overrides(spec)) 

386 gate["counted_without_a_score"] = count_unrun_trials(spec, gate["unscored"]) 

387 _write_json(paths["gate"], gate) 

388 return gate 

389 

390 

391def pbo_report(frames: Sequence[pd.DataFrame], columns: Sequence[str], *, window: tuple[str, str], blocks: int = 16) -> dict[str, Any]: 

392 """The probability of backtest overfitting over the named columns. A trial with no return on a date reads as flat, as a trial that didn't exist yet would be.""" 

393 from evaluation.pbo import probability_of_backtest_overfitting 

394 

395 both = pd.concat(list(frames), axis=1) 

396 present = [name for name in columns if name in both.columns] 

397 matrix = both[present] 

398 matrix = matrix[(matrix.index >= window[0]) & (matrix.index <= window[1])].dropna(how="all").fillna(0.0) 

399 result = probability_of_backtest_overfitting(matrix.to_numpy(dtype=float), blocks=blocks, periods_per_year=252) 

400 return {"pbo": result.get("pbo"), "num_trials": len(present), "window": "..".join(window), "absent": [name for name in columns if name not in both.columns]} 

401 

402 

403def stage_pbo(spec: RoundSpec, *, root: Path = Path(".")) -> dict[str, Any]: 

404 """PBO by CSCV over the round's trials (and prior rounds' daily returns on the same cell), written beside the gate.""" 

405 paths = _paths(spec) 

406 cell = CELLS[spec.cell] 

407 frames = [pd.read_parquet(Path(root) / path) for path in spec.prior_daily] 

408 if paths["daily"].exists(): 

409 frames.append(pd.read_parquet(paths["daily"])) 

410 report = pbo_report(frames, [*spec.prior_columns, *spec.trials], window=(cell.start, cell.end), blocks=spec.pbo_blocks) 

411 _write_json(paths["pbo"], report) 

412 return report 

413 

414 

415def holdouts_spent(path: Path) -> list[str]: 

416 """Cells any freeze has read, from the once-only ledger.""" 

417 return sorted({cell for entry in read_ledger(path) for cell in entry.get("cells", ())}) 

418 

419 

420def stage_freeze(spec: RoundSpec, candidate: Mapping[str, Any], *, holdout_ledger: Path, code_digests: Mapping[str, str] | None = None) -> tuple[Path, str]: 

421 """Freezes one candidate, by rule. Refuses once any holdout has been read: the same data can't back a second candidate. Returns (path, digest).""" 

422 paths = _paths(spec) 

423 gate, pbo = _read_json(paths["gate"], {}), _read_json(paths["pbo"], {}) 

424 if candidate["trial"] not in (gate.get("survivors") or []): 

425 raise PermissionError(f"{candidate['trial']} is not a survivor in the stored gate: only a survivor may be frozen") 

426 pbo_value = pbo.get("pbo") 

427 if pbo_value is None or float(pbo_value) >= 0.5: 

428 raise PermissionError(f"PBO {pbo_value} is not below 0.5: no freeze") 

429 family = HOLDOUT_FAMILIES[family_of(spec)] 

430 spent = [cell for cell in holdouts_spent(holdout_ledger) if cell in family] 

431 if spent: 

432 raise PermissionError(f"holdouts {spent} are spent: a later candidate needs 252 forward sessions instead (R-ADMIT1)") 

433 path = spec.out_dir / f"freeze_{candidate['trial']}.json" 

434 rules_sha = hashlib.sha256(json.dumps(spec.raw, sort_keys=True).encode("utf-8")).hexdigest() 

435 digest = write_freeze(path, {"round": spec.name, "rules_sha256": rules_sha, "candidate": dict(candidate), "code_digests": dict(code_digests or {})}) 

436 return path, digest 

437 

438 

439def r_hold1(reads: Mapping[str, Mapping]) -> dict[str, Any]: 

440 """R-HOLD1's clauses: V3 Sharpe >= 0.50 and alpha t >= 2.0; V1 and V2 Sharpe > 0. A missing figure fails.""" 

441 def finite(value) -> float | None: 

442 return float(value) if value is not None and math.isfinite(float(value)) else None 

443 

444 v3_sharpe, v3_t = finite((reads.get("V3") or {}).get("sharpe")), finite((reads.get("V3") or {}).get("alpha_t")) 

445 v1, v2 = finite((reads.get("V1") or {}).get("sharpe")), finite((reads.get("V2") or {}).get("sharpe")) 

446 clauses = { 

447 "V3_sharpe": v3_sharpe is not None and v3_sharpe >= 0.50, "V3_alpha_t": v3_t is not None and v3_t >= 2.0, 

448 "V1_sharpe": v1 is not None and v1 > 0.0, "V2_sharpe": v2 is not None and v2 > 0.0, 

449 } 

450 return {"rule": "R-HOLD1", "passed": all(clauses.values()), "clauses": clauses, "reads": dict(reads)} 

451 

452 

453def r_hold1_crypto(reads: Mapping[str, Mapping]) -> dict[str, Any]: 

454 """R-HOLD1 for a crypto candidate: CV Sharpe >= 0.50 and alpha t >= 2.0. A missing figure fails.""" 

455 def finite(value) -> float | None: 

456 return float(value) if value is not None and math.isfinite(float(value)) else None 

457 

458 sharpe, t = finite((reads.get("CV") or {}).get("sharpe")), finite((reads.get("CV") or {}).get("alpha_t")) 

459 clauses = {"CV_sharpe": sharpe is not None and sharpe >= 0.50, "CV_alpha_t": t is not None and t >= 2.0} 

460 return {"rule": "R-HOLD1 (crypto)", "passed": all(clauses.values()), "clauses": clauses, "reads": dict(reads)} 

461 

462 

463def stage_hold( 

464 spec: RoundSpec, trial: str, *, root: Path, freeze_path: Path, digest: str, holdout_ledger: Path, created_at: str, score_dir: Path, 

465 read_cell: Callable[[str], object] | None = None, alpha_fn: Callable[[pd.Series], Mapping] | None = None, 

466) -> dict[str, Any]: 

467 """The one read of the holdouts. It records the read before opening anything: a crash after this still counts as spent.""" 

468 from evaluation.premia_research import annual_sharpe, weights_for 

469 if Path(freeze_path).name != f"freeze_{trial}.json" or freeze_digest_of(Path(freeze_path)) != digest: 

470 raise PermissionError("the freeze on disk is not this candidate's") 

471 family = family_of(spec) 

472 cells = HOLDOUT_FAMILIES[family] 

473 record_holdout_read(holdout_ledger, candidate=trial, cells=cells, digest=digest, created_at=created_at) 

474 if read_cell is None: 

475 from evaluation.wide_context import crypto_cell, equity_cell 

476 

477 opener = crypto_cell if family == "crypto" else equity_cell 

478 base = json.loads((Path(root) / "config.json").read_text(encoding="utf-8")) 

479 read_cell = lambda name: opener(Path(root), base, name, freeze_path=Path(freeze_path), freeze_digest=digest) # noqa: E731 

480 sleeve = spec_of(spec, trial, universe_for(spec, trial)) 

481 entry = spec.trials[trial] 

482 reads: dict[str, dict] = {} 

483 for name in cells: 

484 cell = read_cell(name) 

485 built: dict[str, pd.DataFrame] = {} 

486 for other in spec.trials: 

487 if other != trial and not _is_part_of(spec, trial, other): 

488 continue 

489 table = trial_table(spec, other, cell, built, score_dir=score_dir, score_suffix=f"_{name}") 

490 if table is not None: 

491 built[other] = table 

492 if trial not in built: 

493 reads[name] = {"sharpe": None, "alpha_t": None, "reason": "no table on this cell"} 

494 continue 

495 cell.context.panel.extras[trial] = built[trial] 

496 start, end = cell.cell.start, cell.cell.end 

497 result = _trial_context(cell.context, entry).simulate(weights_for(sleeve, cell.context, built[trial], start=start, end=end, phase_offset=0), start, end) 

498 series = result["strategy_excess"] 

499 reads[name] = {"sharpe": annual_sharpe(series, sessions=cell.context.sessions_for(sleeve)), "alpha_t": (alpha_fn(series) if alpha_fn else {}).get("t_hac")} 

500 verdict = r_hold1_crypto(reads) if family == "crypto" else r_hold1(reads) 

501 _write_json(spec.out_dir / f"r_hold1_{trial}.json", verdict) 

502 return verdict 

503 

504 

505def _is_part_of(spec: RoundSpec, trial: str, other: str) -> bool: 

506 recipe = spec.trials[trial].get("recipe") or {} 

507 return other in (recipe.get("parts") or ()) 

508 

509 

510def stage_report(spec: RoundSpec, *, alpha_fn: Callable[[pd.Series], Mapping] | None = None) -> dict[str, Any]: 

511 """The verdict in plain figures: survivors, PBO, and what this round can and can't exclude, per trial and at the best trial.""" 

512 from evaluation.power_analysis import excluded_alpha_sharpe 

513 

514 paths = _paths(spec) 

515 gate = _read_json(paths["gate"], {}) 

516 pbo = _read_json(paths["pbo"], {}) 

517 scores = _read_json(paths["scores"], {}) 

518 daily = pd.read_parquet(paths["daily"]) if paths["daily"].exists() else pd.DataFrame() 

519 trials: dict[str, dict] = {} 

520 for name, score in scores.items(): 

521 row = {key: score.get(key) for key in ("sharpe", "sharpe_first_half", "sharpe_second_half", "turnover", "max_drawdown", "mean_gross", "live_names")} 

522 row["ic_t"] = (score.get("ic") or {}).get("nonoverlap_t") 

523 row["ic"] = (score.get("ic") or {}).get("mean_ic") 

524 if alpha_fn is not None and name in daily.columns: 

525 series = daily[name].dropna() 

526 alpha = alpha_fn(series) 

527 t = alpha.get("t_hac") 

528 row["alpha_t"] = t 

529 row["alpha_annual"] = alpha.get("alpha_annual") 

530 if t is not None and np.isfinite(t): 

531 row["excluded_alpha_sharpe_95"] = excluded_alpha_sharpe(float(t), len(series) / 252.0) 

532 trials[name] = row 

533 survivors = list(gate.get("survivors") or []) 

534 pbo_value = pbo.get("pbo") 

535 stopped = None 

536 if not survivors: 

537 stopped = "zero trials survived R-SLEEVE3: no freeze, no holdout read" 

538 elif pbo_value is None or float(pbo_value) >= 0.5: 

539 stopped = f"PBO {pbo_value} is not below 0.5: no freeze, no holdout read" 

540 report = { 

541 "round": spec.name, "rule": spec.rule, "verdict": "not verified" if stopped else "survivors reach the freeze", "stopped_at": stopped, "survivors": survivors, 

542 "pbo": pbo_value, "trials": trials, "unscored": gate.get("unscored"), "failed": gate.get("failed"), "failed_earlier_clauses": gate.get("failed_earlier_clauses"), 

543 "disclosures": list(spec.disclosures), 

544 } 

545 _write_json(paths["report"], report) 

546 return report