Coverage for evaluation/model_book_round.py: 100%

322 statements  

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

1"""The V6.6.9 model-book round, stage by stage (rules R-BOOK1, R-MIX1, R-INSTALL2, R-LEAN23). 

2 

3`scripts/v669_book.py` only parses arguments and calls these. Each stage reads what the stage before wrote under `out`, refuses to 

4run when `rules.json` no longer matches its recorded hash, and nothing here reads a row past the selection window until the candidate 

5is frozen (`freeze_stage`). The numbers come from the same offline engine the V6.5.0 and V6.6.0 rounds used. 

6""" 

7 

8from __future__ import annotations 

9 

10import dataclasses 

11import hashlib 

12import json 

13import math 

14import re 

15from collections.abc import Callable, Mapping, Sequence 

16from pathlib import Path 

17from typing import Any 

18 

19import numpy as np 

20import pandas as pd 

21 

22from evaluation import model_book_research as research 

23from evaluation.premia_research import ( 

24 ResearchContext, 

25 annual_sharpe, 

26 annual_volatility, 

27 class_breadth, 

28 max_drawdown, 

29 nulls_for, 

30 passes_sharpe_clauses, 

31 phase_offsets, 

32 placebo_p_value, 

33 placebo_sharpes, 

34 score_sleeve, 

35 selection_gate, 

36 weights_for, 

37) 

38from evaluation.trial_ledger import append_trial 

39from portfolio.premia_signals import ResearchPanel, SleeveSpec, WeightSettings, sleeve_signal 

40 

41TRIAL_WINDOW = "v669_selection" 

42VERIFICATION_SPLIT = "2025-03-01" 

43PBO_PRIOR = "ml/evaluation/v650/selection_daily.parquet" 

44PBO_PRIOR_COLUMNS = ("t2_a1_20_top6", "t2_a1_20_full", "t5_st_a", "t5_gbm_a") 

45 

46RULES_TEXT = { 

47 "R-BOOK1": ( 

48 "Twelve optimizer trials b02-b13 on one fixed signal (ml_a1 through load_score_table, universe the config's four classes). " 

49 "Controls b01 (V6.5.0's top-6 book, aligned) and core (the model-free risk-parity core) are scored and never selected, and count in no N." 

50 ), 

51 "R-MIX1": "Six signal trials m01-m06 on one fixed optimizer (pooled ranks, every 20 sessions).", 

52 "D1": "Eight counted looks: the rank IC of ml_a1 by class (4) and horizon (5 and 20 sessions) on the selection window. They select nothing.", 

53 "R-SLEEVE2": ( 

54 "Net of costs and financing, the median over 5 rebalance phases: Sharpe >= 0.40 in both halves and >= 0.50 pooled, and p < 0.05 against the " 

55 "asset_block and time_shift nulls (100 draws each, only for trials that pass the Sharpe clauses). Survivors correlated above 0.7 drop the " 

56 "lower Sharpe; at most 5 remain. PBO by CSCV over 16 blocks, with V6.5.0's T2 and T5 columns on the shared window: PBO >= 0.5 and no survivor counts." 

57 ), 

58 "R-INSTALL2": ( 

59 "Pool: the 18 model-driven trials. Eligible on the selection window (median of 5 phases): max drawdown <= 15%, annual volatility <= 10%, mean gross <= 2.0, " 

60 "a non-zero weight in at least 3 of the 4 classes on at least 80% of rebalance rows. The candidate is the eligible trial with the highest pooled Sharpe " 

61 "(tie: lower turnover); with none eligible, the model-free core. Frozen before any later row exists. It installs iff on the verification window, with the " 

62 "installed models' scores: volatility <= 10%, drawdown <= 15%, gross <= 2.0, the Lean run completes with a clean engine log, and Lean against the engine " 

63 "keeps daily correlation >= 0.90 and an annual return gap <= 100 bps. Sharpe is reported, not required. Share: a gate survivor blends with the crypto " 

64 "sleeve by inverse volatility; a non-survivor gets a fixed 30% and the crypto sleeve 70%. Label: reinstated, not verified." 

65 ), 

66 "R-LEAN23": ( 

67 "The in-Lean mode is documented as verified iff its parity run completes with a clean engine log, its daily returns correlate >= 0.95 with the " 

68 "engine-backed run of the same rows, and the mean absolute weight difference between its logged rows and the file's rows on shared dates is <= 0.01. " 

69 "Otherwise it is documented as built, parity not reached, with the numbers and the first diverging date; the default source stays the file." 

70 ), 

71} 

72 

73 

74def rules_payload(*, written: str) -> dict[str, Any]: 

75 """Everything the round fixes before a score exists: windows, sizing, the trial lists and the rule texts.""" 

76 return { 

77 "written": written, 

78 "disclosure": [ 

79 "The installed models were trained on 2014-2021 and validated on 2022-2023; the walk-forward score tables of the selection window come from V6.5.0's walk-forward refits.", 

80 "Score tables of V6.5.0 were read without the next-bar shift for crypto and forex (Problems #390); every score here passes through load_score_table.", 

81 "Holdouts V1, V2, V3, P and CV stay unread. The verification window was read by earlier runs of other books, never for this one.", 

82 "The universe was chosen with hindsight and has no delisted names; the null time_shift partly catches it.", 

83 "The forex name cap is 6% because forex_min_trade_usd is $5,000 of a $100,000 book: a 3% name could never open (audit item 4).", 

84 "The class loss guard holds a guarded class out until it has 60 sessions of paper record, so forex joins about three months after a window starts.", 

85 ], 

86 "windows": {"selection": list(research.SELECTION), "verification": list(research.VERIFICATION)}, 

87 "weight_settings": research.MODEL_SETTINGS, 

88 "guard": research.GUARD, 

89 "eligibility": research.ELIGIBLE, 

90 "lean_vs_engine": research.LEAN_VS_ENGINE, 

91 "non_survivor_share": research.NON_SURVIVOR_SHARE, 

92 "trials": { 

93 spec.id: {"table": spec.params["table"], "every": spec.rebalance_every, **{k: v for k, v in spec.params.items() if k not in research.GUARD and k != "table"}} 

94 for spec in [*research.book_trials(), *research.mix_trials(), *research.control_trials()] 

95 }, 

96 "counted_trials": 12 + 6 + 8, 

97 "rules": RULES_TEXT, 

98 } 

99 

100 

101def read_json(path: Path, default: Any = None) -> Any: 

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

103 

104 

105def write_json(path: Path, payload: Any) -> None: 

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

107 path.write_text(json.dumps(payload, indent=1, sort_keys=True, default=float), encoding="utf-8", newline="\n") 

108 

109 

110def write_rules(out: Path, payload: Mapping[str, Any]) -> str: 

111 """Writes `rules.json` and its sha256 once; a second write is refused, because a rule is never edited after a score exists.""" 

112 rules, sha = out / "rules.json", out / "rules.sha256" 

113 if rules.exists() or sha.exists(): 

114 raise FileExistsError(f"{rules} already exists: a rule is never rewritten (re-register a defective trial instead)") 

115 out.mkdir(parents=True, exist_ok=True) 

116 text = json.dumps(payload, indent=1, sort_keys=True) 

117 rules.write_text(text, encoding="utf-8", newline="\n") 

118 digest = hashlib.sha256(text.encode("utf-8")).hexdigest() 

119 sha.write_text(digest + "\n", encoding="utf-8", newline="\n") 

120 return digest 

121 

122 

123def check_rules(out: Path) -> dict[str, Any]: 

124 """The rules, after proving they are the ones that were recorded.""" 

125 text = (out / "rules.json").read_text(encoding="utf-8") 

126 expected = (out / "rules.sha256").read_text(encoding="utf-8").strip() 

127 actual = hashlib.sha256(text.encode("utf-8")).hexdigest() 

128 if actual != expected: 

129 raise SystemExit(f"rules.json changed: {actual} is not the recorded {expected}") 

130 return json.loads(text) 

131 

132 

133def with_tables(context: ResearchContext, tables: Mapping[str, pd.DataFrame], *, settings: WeightSettings | None = None) -> ResearchContext: 

134 """The context with its signal tables replaced by `tables` (kept: the panel's other extras) and, when given, other sizing settings.""" 

135 extras = {**context.panel.extras, **tables} 

136 panel = ResearchPanel(context.panel.known, context.panel.asset_class, context.panel.fred, extras) 

137 return dataclasses.replace(context, panel=panel, **({"settings": settings} if settings is not None else {})) 

138 

139 

140def settings_for(spec: SleeveSpec) -> WeightSettings: 

141 """The control b01 is V6.5.0's book and keeps V6.5.0's sizing; everything else uses the round's.""" 

142 return WeightSettings() if spec.id == "b01" else research.model_settings() 

143 

144 

145def _selection_specs(ids: Sequence[str] | None = None, specs: Sequence[SleeveSpec] | None = None) -> list[SleeveSpec]: 

146 specs = [*research.candidate_pool(), *research.control_trials()] if specs is None else list(specs) 

147 return [spec for spec in specs if ids is None or spec.id in ids] 

148 

149 

150def _pool(pool: Sequence[SleeveSpec] | None) -> list[SleeveSpec]: 

151 """The round's selectable trials: R-BOOK1 and R-MIX1's by default, or another round's own list (V6.6.10, R-BOOK2).""" 

152 return research.candidate_pool() if pool is None else list(pool) 

153 

154 

155def score_stage( 

156 context: ResearchContext, out: Path, *, window: tuple[str, str, str] = research.SELECTION, ids: Sequence[str] | None = None, 

157 force: bool = False, log: Callable[[str], None] = print, specs: Sequence[SleeveSpec] | None = None, 

158 control_ids: Sequence[str] = research.CONTROL_IDS, 

159) -> dict[str, Any]: 

160 """Scores every trial (controls too) on the selection window and appends the candidates to the ledger. `specs` and `control_ids` 

161 name another round's trials and controls (V6.6.10).""" 

162 check_rules(out) 

163 start, split, end = window 

164 if end > research.SELECTION[2]: 

165 raise SystemExit(f"{end} is past the selection window ({research.SELECTION[2]})") 

166 scores = read_json(out / "selection_scores.json", {}) 

167 daily_path = out / "selection_daily.parquet" 

168 frames: dict[str, pd.Series] = {} 

169 if daily_path.exists(): 

170 stored = pd.read_parquet(daily_path) 

171 frames = {column: stored[column].dropna() for column in stored.columns} 

172 for spec in _selection_specs(ids, specs): 

173 if spec.id in scores and not force: 

174 continue 

175 score = score_sleeve(spec, dataclasses.replace(context, settings=settings_for(spec)), start=start, split=split, end=end) 

176 daily = score.pop("daily") 

177 frames[spec.id] = daily[min(daily)] 

178 scores[spec.id] = score 

179 role = "plumbing" if spec.id in control_ids else "candidate" 

180 append_trial(out / "trial_ledger.jsonl", trial_id=spec.id, track=spec.track, window=TRIAL_WINDOW, role=role, 

181 annualised_sharpe=score["sharpe"], n_obs=len(frames[spec.id]), engine="offline") 

182 log(f"{spec.id:6s} sharpe {_show(score['sharpe'])} h1 {_show(score['sharpe_first_half'])} h2 {_show(score['sharpe_second_half'])} " 

183 f"dd {score['max_drawdown']:.3f} vol {_show(score['volatility'])} gross {score['mean_gross']:.2f} breadth {score['class_breadth']:.2f}") 

184 write_json(out / "selection_scores.json", scores) 

185 pd.DataFrame(frames).sort_index().to_parquet(daily_path) 

186 return scores 

187 

188 

189def _show(value: float | None) -> str: 

190 return " n/a" if value is None else f"{value:5.2f}" 

191 

192 

193def placebo_stage( 

194 context: ResearchContext, out: Path, *, draws: int = 100, only: Sequence[str] | None = None, force: bool = False, 

195 window: tuple[str, str, str] = research.SELECTION, log: Callable[[str], None] = print, suffix: str = "", modes: Sequence[str] | None = None, 

196 pool: Sequence[SleeveSpec] | None = None, 

197) -> dict[str, Any]: 

198 """Placebo p-values for the trials that pass R-SLEEVE2's Sharpe clauses (and only those: the clause is the gate to the expensive test).""" 

199 check_rules(out) 

200 scores = read_json(out / "selection_scores.json", {}) 

201 path = out / f"selection_placebos{suffix}.json" 

202 done = read_json(path, {}) 

203 start, _, end = window 

204 for spec in _pool(pool): 

205 score = scores.get(spec.id) 

206 if score is None or not passes_sharpe_clauses(score) or (spec.id in done and not force) or (only and spec.id not in only): 

207 continue 

208 sized = dataclasses.replace(context, settings=settings_for(spec)) 

209 result = {} 

210 for mode in nulls_for(spec): 

211 if modes is not None and mode not in modes: 

212 continue 

213 sharpes = placebo_sharpes(spec, sized, mode, start=start, end=end, draws=draws) 

214 result[mode] = {"p": placebo_p_value(score["sharpe"], sharpes), "draws": len(sharpes), 

215 "median": float(np.median(sharpes)) if sharpes else None, 

216 "q95": float(np.quantile(sharpes, 0.95)) if sharpes else None} 

217 log(f"{spec.id} {mode} p {result[mode]['p']:.3f}") 

218 for value in sharpes: 

219 append_trial(out / f"trial_ledger{suffix}.jsonl", trial_id=f"{spec.id}:{mode}", track=spec.track, window=TRIAL_WINDOW, role="placebo", 

220 annualised_sharpe=value, n_obs=0, engine="offline") 

221 done[spec.id] = result 

222 write_json(path, done) 

223 return done 

224 

225 

226def gate_stage(out: Path, *, pool: Sequence[SleeveSpec] | None = None) -> dict[str, Any]: 

227 """R-SLEEVE2 over the pool: survivors, the clause each other trial failed, and the trials with no placebo run.""" 

228 check_rules(out) 

229 scores = read_json(out / "selection_scores.json", {}) 

230 placebos: dict[str, Any] = {} 

231 for part in sorted(out.glob("selection_placebos*.json")): 

232 for name, tests in read_json(part, {}).items(): 

233 placebos.setdefault(name, {}).update(tests) 

234 daily = pd.read_parquet(out / "selection_daily.parquet") 

235 ids = {spec.id for spec in _pool(pool)} 

236 rows = [{**score, "id": name, "daily": {0: daily[name].dropna()}} for name, score in scores.items() if name in ids and name in daily] 

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

238 gate = selection_gate(rows, p_values) 

239 gate["unscored"] = sorted(ids - set(scores)) 

240 write_json(out / "selection_gate.json", gate) 

241 return gate 

242 

243 

244def pbo_stage(out: Path, *, root: Path, blocks: int = 16, pool: Sequence[SleeveSpec] | None = None) -> dict[str, Any]: 

245 """The probability of backtest overfitting over this round's daily columns plus V6.5.0's model sleeves on the shared window.""" 

246 from evaluation.research_round import pbo_report 

247 

248 check_rules(out) 

249 frames = [pd.read_parquet(out / "selection_daily.parquet")] 

250 prior = Path(root) / PBO_PRIOR 

251 if prior.exists(): 

252 frames.append(pd.read_parquet(prior)) 

253 columns = [spec.id for spec in _pool(pool)] + list(PBO_PRIOR_COLUMNS) 

254 report = pbo_report(frames, columns, window=(research.SELECTION[0], research.SELECTION[2]), blocks=blocks) 

255 write_json(out / "selection_pbo.json", report) 

256 return report 

257 

258 

259def diagnostics_stage(context: ResearchContext, out: Path, *, table: str = "ml_a1", log: Callable[[str], None] = print) -> dict[str, Any]: 

260 """D1: eight counted looks at where the score has rank IC. Each is a ledger candidate without a Sharpe (it counts in N, selects nothing).""" 

261 check_rules(out) 

262 path = out / "diagnostics_d1.json" 

263 if path.exists(): 

264 return read_json(path) 

265 looks = research.rank_ic_diagnostics( 

266 context.panel.extras[table], context.panel.known, context.panel.asset_class, start=research.SELECTION[0], end=research.SELECTION[2], 

267 ) 

268 for name, entry in looks.items(): 

269 append_trial(out / "trial_ledger.jsonl", trial_id=f"d1_{name}", track="D1", window=TRIAL_WINDOW, role="candidate", annualised_sharpe=None, 

270 n_obs=entry["n_dates"], engine="offline", detail=entry) 

271 log(f"d1 {name}: ic {entry['mean_ic']} t {entry['t_hac']}") 

272 write_json(path, looks) 

273 return looks 

274 

275 

276def report_stage(out: Path, *, name: str = "r_book1.json", survivors_only: bool = False) -> dict[str, Any]: 

277 """One file with every trial's numbers, the gate, the PBO, the diagnostics and the candidate R-INSTALL2 names. `survivors_only` 

278 (V6.6.10, R-BOOK2): only a gate survivor can be the candidate, and with none there is no candidate.""" 

279 check_rules(out) 

280 scores = read_json(out / "selection_scores.json", {}) 

281 gate = read_json(out / "selection_gate.json", {}) 

282 pbo = read_json(out / "selection_pbo.json", {}) 

283 survivors = [] if (pbo.get("pbo") is None or pbo["pbo"] >= 0.5) else gate.get("survivors", []) 

284 pool = [{"id": key, **score} for key, score in scores.items() if not survivors_only or key in survivors] 

285 pick = research.pick_candidate(pool) if pool or not survivors_only else {"candidate": None, "reason": "no trial survived the gate and the PBO"} 

286 report = {"trials": scores, "gate": gate, "pbo": pbo, "survivors": survivors, "diagnostics": read_json(out / "diagnostics_d1.json", {}), "install": pick} 

287 write_json(out / name, report) 

288 return report 

289 

290 

291def freeze_stage( 

292 out: Path, *, root: Path, code_files: Sequence[str], report_name: str = "r_book1.json", specs: Sequence[SleeveSpec] | None = None, 

293) -> tuple[Path, str]: 

294 """Freezes the candidate's definition and the code that produces its rows, once. Nothing after the selection window is read before this.""" 

295 check_rules(out) 

296 path = out / "freeze.json" 

297 if path.exists(): 

298 raise FileExistsError(f"{path} exists: a candidate is frozen once") 

299 report = read_json(out / report_name) 

300 if report is None: 

301 raise SystemExit("run `report` first: there is no candidate to freeze") 

302 name = report["install"]["candidate"] 

303 if name is None: 

304 raise SystemExit(f"nothing to freeze: {report['install']['reason']}") 

305 spec = next(item for item in _selection_specs(None, specs) if item.id == name) 

306 payload = { 

307 "candidate": name, "survivor": name in report["survivors"], "kind": "model_book", 

308 "definition": {"id": spec.id, "table": spec.params["table"], "every": spec.rebalance_every, "params": dict(spec.params), "universe": list(spec.universe)}, 

309 "settings": research.MODEL_SETTINGS, "reason": report["install"]["reason"], 

310 "code_sha256": {file: hashlib.sha256((Path(root) / file).read_bytes()).hexdigest() for file in code_files if (Path(root) / file).exists()}, 

311 } 

312 text = json.dumps(payload, indent=1, sort_keys=True) 

313 path.write_text(text, encoding="utf-8", newline="\n") 

314 digest = hashlib.sha256(text.encode("utf-8")).hexdigest() 

315 (out / "freeze.sha256").write_text(digest + "\n", encoding="utf-8", newline="\n") 

316 return path, digest 

317 

318 

319def check_freeze(out: Path) -> dict[str, Any]: 

320 """The frozen candidate, after proving its file is the one that was recorded. Verification rows exist only behind this.""" 

321 text = (out / "freeze.json").read_text(encoding="utf-8") 

322 expected = (out / "freeze.sha256").read_text(encoding="utf-8").strip() 

323 if hashlib.sha256(text.encode("utf-8")).hexdigest() != expected: 

324 raise SystemExit("freeze.json changed since it was recorded") 

325 return json.loads(text) 

326 

327 

328def candidate_spec(frozen: Mapping[str, Any]) -> SleeveSpec: 

329 """The frozen candidate as a spec, from its definition.""" 

330 definition = frozen["definition"] 

331 from portfolio.premia_signals import XS 

332 

333 return SleeveSpec(definition["id"], "FROZEN", XS, "external_score", tuple(definition["universe"]), int(definition["every"]), dict(definition["params"])) 

334 

335 

336def combine_score_files(selection: Path, verification: Path, destination: Path, *, last_selection: str) -> Path: 

337 """One score file over both windows: the selection tables up to `last_selection`, then the installed models' rows. The seam is the model change.""" 

338 first = pd.read_csv(selection, dtype={"date": str, "ticker": str}) 

339 second = pd.read_csv(verification, dtype={"date": str, "ticker": str}) 

340 merged = pd.concat([first[first["date"] <= last_selection], second[second["date"] > last_selection]], ignore_index=True) 

341 merged.sort_values(["date", "ticker"]).to_csv(destination, index=False, lineterminator="\n", float_format="%.6f") 

342 return destination 

343 

344 

345def phase_rows(spec: SleeveSpec, context: ResearchContext, *, start: str, end: str) -> dict[int, dict[str, dict[str, float]]]: 

346 """The spec's weight rows over [start, end] for every rebalance phase.""" 

347 signal = sleeve_signal(spec, context.panel) 

348 return {offset: weights_for(spec, context, signal, start=start, end=end, phase_offset=offset) for offset in phase_offsets(spec.rebalance_every)} 

349 

350 

351def verify_stage( 

352 context: ResearchContext, out: Path, *, window: tuple[str, str] = research.VERIFICATION, log: Callable[[str], None] = print, 

353) -> dict[str, Any]: 

354 """The frozen candidate on the verification window, for every phase, scored on the offline engine. Returns the median-phase summary 

355 and writes the median phase's rows (`weights/model_book.csv`) for the Lean run.""" 

356 from portfolio.target_weights import write_weight_file 

357 

358 check_rules(out) 

359 frozen = check_freeze(out) 

360 spec = candidate_spec(frozen) 

361 sized = dataclasses.replace(context, settings=research.model_settings()) 

362 rows = phase_rows(spec, sized, start=window[0], end=window[1]) 

363 sessions = sized.sessions_for(spec) 

364 summaries = {} 

365 for offset, weights in rows.items(): 

366 result = sized.simulate(weights, window[0], window[1]) 

367 strategy = result["strategy_excess"] 

368 summaries[offset] = { 

369 "sharpe": annual_sharpe(strategy, sessions=sessions), "volatility": annual_volatility(strategy, sessions=sessions), 

370 "max_drawdown": max_drawdown(strategy), "mean_gross": float(result["gross"].mean()) if not result["gross"].empty else 0.0, 

371 "turnover": result["turnover"], "class_breadth": class_breadth(weights, sized.panel.asset_class), "rows": len(weights), 

372 } 

373 log(f"phase {offset}: {summaries[offset]}") 

374 ordered = sorted(summaries, key=lambda offset: (summaries[offset]["sharpe"] if summaries[offset]["sharpe"] is not None else -math.inf)) 

375 middle = ordered[len(ordered) // 2] 

376 

377 def median(key: str) -> float | None: 

378 values = [item[key] for item in summaries.values() if item[key] is not None] 

379 return float(np.median(values)) if values else None 

380 

381 summary = {key: median(key) for key in ("sharpe", "volatility", "max_drawdown", "mean_gross", "turnover", "class_breadth")} 

382 summary.update(median_phase=middle, phases=summaries, window=list(window), candidate=frozen["candidate"]) 

383 (out / "weights").mkdir(parents=True, exist_ok=True) 

384 write_weight_file(rows[middle], out / "weights" / "model_book.csv") 

385 write_json(out / "verification.json", summary) 

386 return summary 

387 

388 

389def selection_rows_for( 

390 spec: SleeveSpec, context: ResearchContext, *, start: str, end: str, phase_index: int, 

391) -> dict[str, dict[str, float]]: 

392 """The spec's rows from one phase (by index into its offsets), as the Lean runs read them.""" 

393 offsets = phase_offsets(spec.rebalance_every) 

394 signal = sleeve_signal(spec, context.panel) 

395 return weights_for(spec, dataclasses.replace(context, settings=research.model_settings()), signal, start=start, end=end, phase_offset=offsets[phase_index % len(offsets)]) 

396 

397 

398CRYPTO_SPEC = SleeveSpec( 

399 "t3_crypto_trend_blend", "T3", "time_series", "crypto_trend", ("crypto",), 5, {"lookback_a": 20, "lookback_b": 60, "lookback_c": 120}, 

400) 

401CRYPTO_PHASE = 4 # the phase the installed crypto sleeve's pinned run used 

402 

403 

404def load_round_context(root: Path, sources: Mapping[str, Path], *, end: str | None = None) -> ResearchContext: 

405 """The research context for this round: the config with forex enabled (the engine then holds forex as the installed config will), 

406 the model-book sizing, and every signal table built from `sources` (table name -> score file), each through `load_score_table`.""" 

407 from evaluation.premia_research import build_context 

408 

409 root = Path(root) 

410 config = json.loads((root / "config.json").read_text(encoding="utf-8")) 

411 config["phase_v2"]["forex_risk"]["enabled"] = True 

412 context = build_context(root, config, respect_disabled_classes=True) 

413 sessions = list(context.panel.known.index) 

414 universe = research.universe_tickers(config) 

415 scores = {name: research.load_score_table(path, sessions, context.panel.asset_class, universe=universe, end=end) for name, path in sources.items()} 

416 return with_tables(context, research.signal_tables(context.panel, scores), settings=research.model_settings()) 

417 

418 

419def crypto_rows(context: ResearchContext, *, start: str, end: str) -> dict[str, dict[str, float]]: 

420 """The installed crypto sleeve's rows over [start, end] on the pinned phase, sized by the default settings it was frozen with.""" 

421 sized = dataclasses.replace(context, settings=WeightSettings()) 

422 offsets = phase_offsets(CRYPTO_SPEC.rebalance_every) 

423 return weights_for(CRYPTO_SPEC, sized, sleeve_signal(CRYPTO_SPEC, sized.panel), start=start, end=end, phase_offset=offsets[CRYPTO_PHASE % len(offsets)]) 

424 

425 

426def inverse_vol_share(model_volatility: float, crypto_volatility: float) -> float: 

427 """The model book's share when the candidate is a gate survivor: weights proportional to 1 / volatility.""" 

428 return (1.0 / model_volatility) / (1.0 / model_volatility + 1.0 / crypto_volatility) 

429 

430 

431def blend_stage( 

432 context: ResearchContext, out: Path, *, name: str, start: str, end: str, share: float, phase_index: int, 

433) -> dict[str, Any]: 

434 """`weights/<name>.csv`: the frozen candidate's rows blended with the crypto sleeve's by `share`, and the same sleeves' offline numbers.""" 

435 from portfolio.target_weights import write_weight_file 

436 

437 check_rules(out) 

438 frozen = check_freeze(out) 

439 spec = candidate_spec(frozen) 

440 model = selection_rows_for(spec, context, start=start, end=end, phase_index=phase_index) 

441 crypto = crypto_rows(context, start=start, end=end) 

442 rows = research.blend_rows({"model": model, "crypto": crypto}, {"model": share, "crypto": 1.0 - share}) 

443 destination = out / "weights" / f"{name}.csv" 

444 destination.parent.mkdir(parents=True, exist_ok=True) 

445 write_weight_file(rows, destination) 

446 result = context.simulate(rows, start, end) 

447 sessions = None 

448 summary = { 

449 "name": name, "window": [start, end], "model_share": share, "rows": len(rows), "model_rows": len(model), "crypto_rows": len(crypto), 

450 "sha256": hashlib.sha256(destination.read_bytes()).hexdigest(), "sharpe": annual_sharpe(result["strategy_excess"], sessions=sessions), 

451 "volatility": annual_volatility(result["strategy_excess"], sessions=sessions), "max_drawdown": max_drawdown(result["strategy_excess"]), 

452 "mean_gross": float(result["gross"].mean()), "turnover": result["turnover"], 

453 } 

454 write_json(out / f"blend_{name}.json", summary) 

455 return summary 

456 

457 

458def lean_summary(report: Mapping[str, Any], *, completed: bool, engine_log_clean: bool) -> dict[str, Any]: 

459 """What R-INSTALL2 reads of one Lean run: the engine-vs-Lean comparison of `scripts/v650_instrument.py compare` plus the two facts a log shows.""" 

460 gap = report.get("annual_gap_bps") 

461 return { 

462 "completed": bool(completed), "engine_log_clean": bool(engine_log_clean), "correlation": report.get("corr_lag0"), 

463 "annual_return_gap": None if gap is None else float(gap) / 1e4, "run": report.get("run"), "name": report.get("name"), 

464 } 

465 

466 

467def judge_stage(out: Path, *, lean: Mapping[str, Any] | None) -> dict[str, Any]: 

468 """R-INSTALL2's verdict from the frozen candidate's verification numbers and the Lean run, every clause with its number.""" 

469 check_rules(out) 

470 frozen = check_freeze(out) 

471 verification = read_json(out / "verification.json") 

472 verdict = research.install_verdict(verification, lean, survivor=bool(frozen["survivor"])) 

473 verdict.update(candidate=frozen["candidate"], verification_window=verification["window"]) 

474 write_json(out / "r_install2.json", verdict) 

475 return verdict 

476 

477 

478_TARGET_BLOCK = re.compile(r'("target_weights": \{\s*"enabled": true,\s*"weights_path": "[^"]+",\s*"weights_sha256": ")[0-9a-f]{64}(",)(?!\s*"uses_model")(\s*)') 

479_FOREX_BLOCK = re.compile(r'("forex_risk": \{\s*"enabled": )false') 

480 

481 

482def install_config_text(text: str, *, weights_sha256: str) -> str: 

483 """`config.json` with the three installed values changed and nothing else: the weight file's hash, `uses_model: true` (the file now 

484 comes from models, so the kill switch's model-age check applies) and `forex_risk.enabled: true` (a forex name is held, not swept).""" 

485 changed, count = _TARGET_BLOCK.subn(lambda m: f'{m.group(1)}{weights_sha256}{m.group(2)}{m.group(3)}"uses_model": true,{m.group(3)}', text, count=1) 

486 if count != 1: 

487 raise ValueError("the target_weights block is not in the shape the install expects (uses_model may already be set)") 

488 changed, forex = _FOREX_BLOCK.subn(r"\g<1>true", changed, count=1) 

489 if forex != 1: 

490 raise ValueError("phase_v2.forex_risk.enabled is not false") 

491 return changed 

492 

493 

494MAX_SCORE_LAG_DAYS = 5 

495 

496 

497def blend_row(raw: Mapping[str, Any], context: ResearchContext, session: str) -> dict[str, float] | None: 

498 """The row an installed blend (`ml/target_weights_candidate.json`, `kind: blend`) decides at `session`, or None when no part decides then. Computed from 

499 the closes and scores the context holds up to the session, counting rebalances from the file's `history_start`, so it equals the file's own row.""" 

500 from portfolio.model_book import parse_definition, row_for_session, weight_settings 

501 

502 definition = parse_definition(raw) 

503 book, sleeve = weight_settings(definition) 

504 return row_for_session(definition, context.panel, context.panel.extras, session, settings=book, sleeve_settings=sleeve, listed=context.listed, sleeve_signal=sleeve_signal) 

505GENERATION_ID = "g0006" 

506 

507 

508def register_generation( 

509 registry_path: Path, lifecycle_path: Path, *, frozen: Mapping[str, Any], freeze_sha256: str, installed: bool, procedure_sha256: str, born: str, created_at: str, 

510) -> dict[str, Any]: 

511 """Adds the model book to the generations' registry once (Problems #388): the installed book (`tier: installed`, `stage: active`) when R-INSTALL2 says 

512 install, else a shadow observer holding nothing (`tier: none`). It `needs: model`, so a host that has the models decides it 

513 (`scripts/model_book_decide.py`); the runner never fakes a row for it. A refit adds a vintage to this entry (`register_vintage`).""" 

514 from evaluation.generation_registry import Generation, append_lifecycle, load_registry, save_registry 

515 

516 registry = load_registry(Path(registry_path)) 

517 if GENERATION_ID in registry: 

518 return {"added": False, "reason": f"{GENERATION_ID} is already registered"} 

519 definition = { 

520 **dict(frozen["definition"]), "family": "model_book", "kind": "cross_sectional", "installed": bool(installed), "freeze_sha256": freeze_sha256, "settings": research.MODEL_SETTINGS, 

521 } 

522 note = ( 

523 "the multi-asset model book (R-INSTALL2, V6.6.9): reinstated, not verified. No trial survived R-SLEEVE2, so it holds a fixed 30% beside the crypto sleeve by the owner's rule, on paper." 

524 if installed else 

525 "the multi-asset model book (V6.6.9) as a shadow observer: R-INSTALL2 did not install it, so it holds nothing; not verified." 

526 ) 

527 registry[GENERATION_ID] = Generation( 

528 GENERATION_ID, "model", "installed" if installed else "none", "active" if installed else "shadow", born, procedure_sha256, definition, 

529 "ml/evaluation/v669/freeze.json", "model", (), 0.0, note, {}, 

530 ) 

531 save_registry(Path(registry_path), registry) 

532 append_lifecycle(Path(lifecycle_path), event="generation_added", created_at=created_at, payload={"generation": GENERATION_ID, "tier": registry[GENERATION_ID].tier, "stage": registry[GENERATION_ID].stage}) 

533 return {"added": True, "generation": GENERATION_ID, "tier": registry[GENERATION_ID].tier, "stage": registry[GENERATION_ID].stage} 

534 

535 

536def set_installed_shares(policy_path: Path, shares: Mapping[str, float]) -> dict[str, float]: 

537 """Records an installed blend's fixed shares in `ml/generations/policy.json`, where `aq cycle status` reads them (the glide stays off).""" 

538 policy = read_json(Path(policy_path), {}) 

539 policy["installed_shares"] = {name: float(share) for name, share in shares.items()} 

540 write_json(Path(policy_path), policy) 

541 return policy["installed_shares"] 

542 

543 

544def book_definition(frozen: Mapping[str, Any], verification: Mapping[str, Any] | None = None) -> Any: 

545 """The frozen candidate as a one-part definition (share 1): the model book alone, as its own generation decides it. Its rebalances count 

546 from the first day of the verification window, on the phase of the verification's median run, the same count the verification rows used.""" 

547 from portfolio.model_book import BlendDefinition, BookPart 

548 

549 definition = frozen["definition"] 

550 spec = {"id": definition["id"], "track": "BOOK", "kind": "cross_sectional", "family": "external_score", "universe": list(definition["universe"]), 

551 "rebalance_every": int(definition["every"]), "params": dict(definition["params"])} 

552 return BlendDefinition((BookPart("model", 1.0, "book", spec, phase_index_of(frozen, verification)),), research.VERIFICATION[0], None, {"model": 1.0}) 

553 

554 

555def phase_index_of(frozen: Mapping[str, Any], verification: Mapping[str, Any] | None = None) -> int: 

556 """The phase of the median verification run, as an index into the candidate's offsets (0 before a verification exists).""" 

557 if not verification or "median_phase" not in verification: 

558 return 0 

559 from portfolio.model_book import phase_offsets as offsets_for 

560 

561 return offsets_for(int(frozen["definition"]["every"])).index(int(verification["median_phase"])) 

562 

563 

564def score_problem(context: ResearchContext, session: str, *, table: str = "ml_a1") -> str | None: 

565 """Why `session` can't be decided from the scores: the newest score the table holds is more than `MAX_SCORE_LAG_DAYS` older than it, so a 

566 decision would rank on stale models' output or none. None when the scores are current.""" 

567 scored = context.panel.extras[table].dropna(how="all") 

568 if scored.empty: 

569 return f"the {table} table holds no score" 

570 lag = (pd.Timestamp(session) - pd.Timestamp(scored.index[-1])).days 

571 return None if lag <= MAX_SCORE_LAG_DAYS else f"the newest {table} score is {lag} days older than {session} (limit {MAX_SCORE_LAG_DAYS})" 

572 

573 

574def decide_row(context: ResearchContext, frozen: Mapping[str, Any], session: str, verification: Mapping[str, Any] | None = None) -> dict[str, float] | None: 

575 """The model book's holding after `session`, from the frozen candidate and the context's closes and scores.""" 

576 from portfolio.model_book import holding_for_session 

577 

578 return holding_for_session( 

579 book_definition(frozen, verification), context.panel, context.panel.extras, session, settings=research.model_settings(), sleeve_settings=WeightSettings(), 

580 listed=context.listed, sleeve_signal=sleeve_signal, 

581 ) 

582 

583 

584def candidate_file(frozen: Mapping[str, Any], verification: Mapping[str, Any], *, share: float, pinned_run: str | None) -> dict[str, Any]: 

585 """The installed book as `ml/target_weights_candidate.json`: the crypto sleeve (generation g0001) and the model book (g0006), each with the spec that 

586 rebuilds its rows, the model book's sizing, and the phase the pinned run used. `scripts/model_book_decide.py` and the in-Lean mode read it.""" 

587 from portfolio.model_book import phase_offsets as offsets_for 

588 

589 definition = frozen["definition"] 

590 book = {"id": definition["id"], "track": "BOOK", "kind": "cross_sectional", "family": "external_score", "universe": list(definition["universe"]), 

591 "every": int(definition["every"]), "params": dict(definition["params"])} 

592 sleeve = {"id": CRYPTO_SPEC.id, "track": CRYPTO_SPEC.track, "kind": CRYPTO_SPEC.kind, "family": CRYPTO_SPEC.family, "universe": list(CRYPTO_SPEC.universe), 

593 "rebalance_every": CRYPTO_SPEC.rebalance_every, "params": dict(CRYPTO_SPEC.params)} 

594 book_phase = offsets_for(int(definition["every"])).index(int(verification["median_phase"])) 

595 return { 

596 "kind": "blend", "history_start": research.VERIFICATION[0], "pinned_run": pinned_run, "settings": research.MODEL_SETTINGS, 

597 "parts": [ 

598 {"generation": "g0001", "share": round(1.0 - float(share), 10), "sleeve": sleeve, "phase_index": CRYPTO_PHASE}, 

599 {"generation": "g0006", "share": float(share), "book": book, "phase_index": book_phase}, 

600 ], 

601 }