Coverage for scripts/v669_book.py: 100%

191 statements  

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

1"""V6.6.9: the multi-asset model book, from rules to install (R-BOOK1, R-MIX1, R-INSTALL2). Logic lives in `evaluation/model_book_round.py`. 

2 

3 python scripts/v669_book.py rules # once: writes rules.json and its hash (then record it: scripts/vault_record.py) 

4 python scripts/v669_book.py score [--only b02 ..] # 18 trials and 2 controls on the selection window 

5 python scripts/v669_book.py placebo --draws 100 # only for the trials that pass the Sharpe clauses 

6 python scripts/v669_book.py gate | pbo | diagnostics | report 

7 python scripts/v669_book.py freeze # the candidate, before any row after 2023-06-30 exists 

8 python scripts/v669_book.py scores [--through D] # the installed models' scores, 2023-07-01..2026-11-02 or D (needs the freeze) 

9 python scripts/v669_book.py verify # the frozen candidate on the verification window 

10 python scripts/v669_book.py blend # blend.csv and blend_long.csv with the crypto sleeve 

11 python scripts/v669_book.py configs # the three Lean run configs (v669_bt_a, _b, _l) 

12 python scripts/v669_book.py candidate [--out f] # the blended book's definition (the in-Lean parity run reads it) 

13 python scripts/v669_book.py judge --lean-report r.json --completed --log-clean 

14 python scripts/v669_book.py install # copies blend.csv into place when R-INSTALL2 says so 

15 python scripts/v669_book.py register # adds the model book to the generations' registry as g0006 

16""" 

17 

18from __future__ import annotations 

19 

20import argparse 

21import datetime 

22import hashlib 

23import json 

24import shutil 

25import sys 

26from pathlib import Path 

27 

28ROOT = Path(__file__).resolve().parents[1] 

29sys.path.insert(0, str(ROOT)) 

30 

31from evaluation import model_book_research as research # noqa: E402 

32from evaluation import model_book_round as rnd # noqa: E402 

33 

34OUT = ROOT / "ml" / "evaluation" / "v669" 

35SELECTION_SCORES = ROOT / "ml" / "evaluation" / "v650" / "scores" 

36SCORES = OUT / "scores" 

37TABLES = ("ml_a1", "ml_a2", "ml_a3") 

38CODE_FILES = ( 

39 "portfolio/book_optimizer.py", "portfolio/premia_signals.py", "portfolio/target_weights.py", "portfolio/model_book.py", 

40 "evaluation/target_weights_engine.py", "evaluation/premia_research.py", "evaluation/model_book_research.py", "evaluation/model_book_round.py", "main.py", 

41 "ml/artifact_pins.json", 

42) 

43 

44 

45def selection_context(): 

46 return rnd.load_round_context(ROOT, {name: SELECTION_SCORES / f"{name}.csv" for name in TABLES}, end=research.SELECTION[2]) 

47 

48 

49def long_sources() -> dict[str, Path]: 

50 """Score files over both windows: the walk-forward tables up to the seam, the installed models' rows after it.""" 

51 paths = {} 

52 for name in TABLES: 

53 paths[name] = rnd.combine_score_files( 

54 SELECTION_SCORES / f"{name}.csv", SCORES / f"inst_{name[-2:]}.csv", SCORES / f"long_{name[-2:]}.csv", last_selection=research.SELECTION[2], 

55 ) 

56 return paths 

57 

58 

59def cmd_rules(args) -> int: 

60 digest = rnd.write_rules(OUT, rnd.rules_payload(written=datetime.date.today().isoformat())) 

61 print(f"rules.json written; sha256 {digest}") 

62 return 0 

63 

64 

65def cmd_score(args) -> int: 

66 rnd.score_stage(selection_context(), OUT, ids=args.only, force=args.force) 

67 return 0 

68 

69 

70def cmd_placebo(args) -> int: 

71 rnd.placebo_stage(selection_context(), OUT, draws=args.draws, only=args.only, force=args.force, suffix=args.suffix, modes=args.modes) 

72 return 0 

73 

74 

75def cmd_gate(args) -> int: 

76 print(json.dumps(rnd.gate_stage(OUT), indent=1)) 

77 return 0 

78 

79 

80def cmd_pbo(args) -> int: 

81 print(json.dumps(rnd.pbo_stage(OUT, root=ROOT), indent=1)) 

82 return 0 

83 

84 

85def cmd_diagnostics(args) -> int: 

86 rnd.diagnostics_stage(selection_context(), OUT) 

87 return 0 

88 

89 

90def cmd_report(args) -> int: 

91 print(json.dumps(rnd.report_stage(OUT)["install"], indent=1)) 

92 return 0 

93 

94 

95def cmd_freeze(args) -> int: 

96 path, digest = rnd.freeze_stage(OUT, root=ROOT, code_files=CODE_FILES) 

97 print(f"{path.name} written; sha256 {digest}") 

98 return 0 

99 

100 

101def cmd_scores(args) -> int: 

102 """The installed models' scores for the verification window. Refuses without a recorded freeze and on any model-file mismatch.""" 

103 from evaluation.dataset_io import read_dataset_columns 

104 from retraining.artifact_pins import artifact_problems 

105 

106 rnd.check_freeze(OUT) 

107 problems = artifact_problems(ROOT / "ml", ROOT / "ml" / "artifact_pins.json") 

108 if problems: 

109 raise SystemExit(f"the installed model files are not the pinned ones: {problems}") 

110 config = json.loads((ROOT / "config.json").read_text(encoding="utf-8")) 

111 exports = {} 

112 names = set() 

113 for kind, (model, schema) in {"multitask": ("multitask_model.json", "multitask_feature_schema.json"), "sequence": ("sequence_model.json", "sequence_feature_schema.json")}.items(): 

114 exports[kind] = (json.loads((ROOT / "ml" / model).read_text(encoding="utf-8")), json.loads((ROOT / "ml" / schema).read_text(encoding="utf-8"))) 

115 names.update(exports[kind][1]["model_input_names"]) 

116 # the sequence windows read 30 bars before the first scored row; start the read a quarter earlier 

117 dataset = read_dataset_columns(ROOT / "ml" / "datasets" / "full_dataset.csv", ["date", "ticker", *sorted(names)], start=args.context_start) 

118 tables = research.installed_score_tables(dataset, exports, start=research.VERIFICATION[0], end=args.through or research.VERIFICATION[1], universe=research.universe_tickers(config)) 

119 SCORES.mkdir(parents=True, exist_ok=True) 

120 for name, table in tables.items(): 

121 table.sort_values(["date", "ticker"]).to_csv(SCORES / f"{name}.csv", index=False, lineterminator="\n", float_format="%.6f") 

122 print(f"{name}: {len(table)} rows {table['date'].min()}..{table['date'].max()}, {table['ticker'].nunique()} tickers") 

123 long_sources() 

124 return 0 

125 

126 

127def cmd_verify(args) -> int: 

128 context = rnd.load_round_context(ROOT, long_sources()) 

129 print(json.dumps({key: value for key, value in rnd.verify_stage(context, OUT).items() if key != "phases"}, indent=1)) 

130 return 0 

131 

132 

133def cmd_blend(args) -> int: 

134 from evaluation.premia_research import phase_offsets 

135 

136 frozen = rnd.check_freeze(OUT) 

137 verification = rnd.read_json(OUT / "verification.json") 

138 spec = rnd.candidate_spec(frozen) 

139 phase_index = phase_offsets(spec.rebalance_every).index(verification["median_phase"]) 

140 if frozen["survivor"]: 

141 selection = rnd.read_json(OUT / "selection_scores.json") 

142 crypto = rnd.read_json(OUT / "crypto_volatility.json", {"volatility": 0.07})["volatility"] 

143 share = rnd.inverse_vol_share(float(selection[frozen["candidate"]]["volatility"]), float(crypto)) 

144 else: 

145 share = research.NON_SURVIVOR_SHARE 

146 context = rnd.load_round_context(ROOT, long_sources()) 

147 for name, window in (("blend", research.VERIFICATION), ("blend_long", (research.SELECTION[0], research.VERIFICATION[1]))): 

148 print(json.dumps(rnd.blend_stage(context, OUT, name=name, start=window[0], end=window[1], share=share, phase_index=phase_index), indent=1)) 

149 return 0 

150 

151 

152def cmd_configs(args) -> int: 

153 """The Lean run configs: the model book alone and the blend over the verification window, and the blend over the long window. Each is the shipped 

154 config with the target-weights path on that file, `uses_model` and forex on (what the install sets), and the risk settings of the earlier runs.""" 

155 sys.path.insert(0, str(ROOT / "scripts")) 

156 from v650_instrument import RUN_CONFIGS, target_path_config 

157 

158 base = json.loads((ROOT / "config.json").read_text(encoding="utf-8")) 

159 base["phase_v2"]["forex_risk"]["enabled"] = True 

160 base["phase_v2"]["target_weights"]["uses_model"] = True 

161 runs = { 

162 "v669_bt_a": ("model_book.csv", research.VERIFICATION), "v669_bt_b": ("blend.csv", research.VERIFICATION), 

163 "v669_bt_l": ("blend_long.csv", (research.SELECTION[0], research.VERIFICATION[1])), 

164 } 

165 RUN_CONFIGS.mkdir(parents=True, exist_ok=True) 

166 for name, (file, window) in runs.items(): 

167 weights = OUT / "weights" / file 

168 config = target_path_config(base, weights_path=weights.relative_to(ROOT).as_posix(), weights_sha256=hashlib.sha256(weights.read_bytes()).hexdigest(), window=window) 

169 (RUN_CONFIGS / f"{name}.json").write_text(json.dumps(config, indent=4), encoding="utf-8", newline="\n") 

170 print(f"{name}: {file} {window[0]}..{window[1]}") 

171 # the parity run (R-LEAN23): the same book, computed inside Lean from the models, over the same window 

172 parity = target_path_config(base, weights_path="", weights_sha256="", window=research.VERIFICATION) 

173 parity["phase_v2"]["target_weights"]["source"] = "model_book" 

174 parity["phase_v2"]["model_book"] = {"candidate_path": "ml/evaluation/v669/candidate_blend.json", "artifact_pins_path": "ml/artifact_pins.json"} 

175 (RUN_CONFIGS / "v669_bt_p.json").write_text(json.dumps(parity, indent=4), encoding="utf-8", newline="\n") 

176 print("v669_bt_p: computed in Lean from the models, " + research.VERIFICATION[0] + ".." + research.VERIFICATION[1]) 

177 return 0 

178 

179 

180def cmd_judge(args) -> int: 

181 lean = None 

182 if args.lean_report: 

183 lean = rnd.lean_summary(json.loads(Path(args.lean_report).read_text(encoding="utf-8")), completed=args.completed, engine_log_clean=args.log_clean) 

184 print(json.dumps(rnd.judge_stage(OUT, lean=lean), indent=1)) 

185 return 0 

186 

187 

188def _candidate_payload() -> dict: 

189 frozen = rnd.check_freeze(OUT) 

190 share = rnd.read_json(OUT / "blend_blend.json")["model_share"] 

191 pinned = rnd.read_json(OUT / "pinned_run.json", {}).get("run") 

192 return rnd.candidate_file(frozen, rnd.read_json(OUT / "verification.json"), share=share, pinned_run=pinned) 

193 

194 

195def cmd_candidate(args) -> int: 

196 """Writes the blended book's definition (both generations, the sizing, the phases) to `--out`: the file the in-Lean parity run and the daily tool read.""" 

197 destination = Path(args.out) if args.out else OUT / "candidate_blend.json" 

198 destination.write_text(json.dumps(_candidate_payload(), indent=1) + "\n", encoding="utf-8", newline="\n") 

199 print(f"candidate written to {destination}") 

200 return 0 

201 

202 

203def cmd_register(args) -> int: 

204 """Registers the model book as generation g0006: installed if R-INSTALL2 says so, else a shadow observer.""" 

205 sys.path.insert(0, str(ROOT / "scripts")) 

206 import datetime 

207 

208 from cycle_retrain import PROCEDURES, procedure_sha256 

209 

210 frozen = rnd.check_freeze(OUT) 

211 verdict = rnd.read_json(OUT / "r_install2.json", {}) 

212 stack = PROCEDURES["stack"] 

213 sha = procedure_sha256("stack", stack, b"".join((ROOT / trainer).read_bytes() for trainer in stack["trainers"])) 

214 now = datetime.datetime.now(datetime.timezone.utc).replace(microsecond=0) 

215 result = rnd.register_generation( 

216 ROOT / "ml" / "generations" / "registry.json", ROOT / "ml" / "generations" / "lifecycle.jsonl", frozen=frozen, 

217 freeze_sha256=(OUT / "freeze.sha256").read_text(encoding="utf-8").strip(), installed=bool(verdict.get("install")), procedure_sha256=sha, 

218 born=now.date().isoformat(), created_at=now.isoformat(), 

219 ) 

220 if result["added"] and verdict.get("install"): 

221 share = rnd.read_json(OUT / "blend_blend.json")["model_share"] 

222 rnd.set_installed_shares(ROOT / "ml" / "generations" / "policy.json", {"g0001": round(1.0 - share, 10), rnd.GENERATION_ID: share}) 

223 print(json.dumps(result)) 

224 return 0 

225 

226 

227def cmd_install(args) -> int: 

228 verdict = rnd.read_json(OUT / "r_install2.json") 

229 if not verdict or not verdict["install"]: 

230 print(f"not installed: failed clauses {verdict['failed'] if verdict else 'no verdict yet'}") 

231 return 1 

232 source = OUT / "weights" / "blend.csv" 

233 sha = hashlib.sha256(source.read_bytes()).hexdigest() 

234 config_path = ROOT / "config.json" 

235 before = config_path.read_bytes() 

236 after = rnd.install_config_text(before.decode("utf-8"), weights_sha256=sha) 

237 shutil.copyfile(source, ROOT / "ml" / "target_weights.csv") 

238 config_path.write_bytes(after.encode("utf-8")) 

239 candidate_path = ROOT / "ml" / "target_weights_candidate.json" 

240 if candidate_path.exists(): 

241 shutil.copyfile(candidate_path, OUT / "candidate_before_install.json") 

242 candidate_path.write_text(json.dumps(_candidate_payload(), indent=1) + "\n", encoding="utf-8", newline="\n") 

243 from retraining.artifact_pins import write_artifact_pins 

244 

245 write_artifact_pins(ROOT / "ml", ROOT / "ml" / "artifact_pins.json") 

246 print(f"config.json sha256 {hashlib.sha256(before).hexdigest()[:16]} -> {hashlib.sha256(after.encode('utf-8')).hexdigest()[:16]}; weights sha256 {sha}") 

247 return 0 

248 

249 

250def main(argv: list[str] | None = None) -> int: 

251 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) 

252 commands = parser.add_subparsers(dest="command", required=True) 

253 commands.add_parser("rules") 

254 commands.add_parser("configs") 

255 commands.add_parser("register") 

256 candidate = commands.add_parser("candidate") 

257 candidate.add_argument("--out", default=None) 

258 score = commands.add_parser("score") 

259 score.add_argument("--only", nargs="*", default=None) 

260 score.add_argument("--force", action="store_true") 

261 placebo = commands.add_parser("placebo") 

262 placebo.add_argument("--draws", type=int, default=100) 

263 placebo.add_argument("--only", nargs="*", default=None) 

264 placebo.add_argument("--force", action="store_true") 

265 placebo.add_argument("--suffix", default="", help="this process's own output files, so two can run at once; `gate` merges them") 

266 placebo.add_argument("--modes", nargs="*", default=None, help="only these nulls (asset_block, time_shift)") 

267 for name in ("gate", "pbo", "diagnostics", "report", "freeze", "verify", "blend", "install"): 

268 commands.add_parser(name) 

269 scores = commands.add_parser("scores") 

270 scores.add_argument("--context-start", default="2023-03-01") 

271 scores.add_argument("--through", default=None, help="score up to this date instead of the verification window's end (a daily decision)") 

272 judge = commands.add_parser("judge") 

273 judge.add_argument("--lean-report", default=None) 

274 judge.add_argument("--completed", action="store_true") 

275 judge.add_argument("--log-clean", action="store_true") 

276 args = parser.parse_args(argv) 

277 handler = { 

278 "rules": cmd_rules, "score": cmd_score, "placebo": cmd_placebo, "gate": cmd_gate, "pbo": cmd_pbo, "diagnostics": cmd_diagnostics, 

279 "report": cmd_report, "freeze": cmd_freeze, "scores": cmd_scores, "verify": cmd_verify, "blend": cmd_blend, "configs": cmd_configs, "register": cmd_register, "candidate": cmd_candidate, "judge": cmd_judge, "install": cmd_install, 

280 }[args.command] 

281 return handler(args) 

282 

283 

284if __name__ == "__main__": 

285 raise SystemExit(main())