Coverage for scripts/v664_eos_repin.py: 100%
124 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""EOS leaves the book (V6.6.4, Problems #311): the installed sleeve re-pinned without the coin Coinbase delisted.
3The rule is unchanged: `t3_crypto_trend_blend`, the same code, the same windows as V6.5.0's pool (`ml/evaluation/v650/rules.json`). Only the universe loses EOSUSD, so the five rebalance phases
4and the long run are rebuilt and run in Lean, and the median phase is installed by R-LEAN19's rule, exactly as `scripts/v650_install.py` did. The owner decided this on 2026-11-07, so the result is
5reported beside the old pin and not judged against it.
7 python scripts/v664_eos_repin.py reproduce # with EOS, as installed: today's code must rebuild the installed weight file byte for byte
8 python scripts/v664_eos_repin.py make # drop EOSUSD from config.json, write the five phase runs and the long run
9 python scripts/v664_eos_repin.py install --status S # S: the Lean runner's status file; installs the median phase and records the comparison
10"""
12from __future__ import annotations
14import argparse
15import hashlib
16import json
17import shutil
18import sys
19from pathlib import Path
21ROOT = Path(__file__).resolve().parents[1]
22sys.path.insert(0, str(ROOT))
23sys.path.insert(0, str(ROOT / "scripts"))
25import numpy as np # noqa: E402
26from v650_install import INSTALLED_CANDIDATE, INSTALLED_WEIGHTS, median_phase # noqa: E402
27from v650_instrument import RUN_CONFIGS # noqa: E402
28from v650_lean import PHASES, candidate_rows, freeze_digest, lean_statistics, make_run, strategy_series # noqa: E402
29from v650_research import check_rules, load_context # noqa: E402
31COIN = "EOSUSD"
32NAME = "t3_crypto_trend_blend"
33OUT = ROOT / "ml" / "evaluation" / "v664"
34ANNUALIZATION = 365.0
37def drop_coin(config: dict, coin: str = COIN) -> dict:
38 """The config without the coin's asset entry. Nothing else changes."""
39 assets = config["phase1"]["universe"]["assets"]
40 kept = [asset for asset in assets if asset.get("ticker") != coin]
41 if len(kept) == len(assets):
42 raise SystemExit(f"{coin} is not in config.json's universe")
43 return {**config, "phase1": {**config["phase1"], "universe": {**config["phase1"]["universe"], "assets": kept}}}
46def stage_reproduce(args) -> int:
47 """V6.5.0's freeze guard is out of date by design: five files changed in V6.5.x and V6.6.x. What matters for the re-pin is that today's code, given the installed universe, still writes the installed
48 weight file, so the only difference the new pin carries is the coin. The installed file is the median phase (index 4) over the verification window."""
49 rules = check_rules()
50 config = json.loads((ROOT / "config.json").read_text(encoding="utf-8"))
51 if not any(asset.get("ticker") == COIN for asset in config["phase1"]["universe"]["assets"]):
52 print("config.json no longer lists EOSUSD: reproduce before `make`", file=sys.stderr)
53 return 1
54 installed = json.loads((ROOT / INSTALLED_CANDIDATE).read_text(encoding="utf-8"))
55 window = tuple(rules["windows"]["verification"])
56 rows = candidate_rows({"survivors": [NAME], "method": None}, load_context(), start=window[0], end=window[1], phase_index=int(installed["phase_index"]))
57 from portfolio.target_weights import write_weight_file
59 scratch = OUT / "reproduce_installed.csv"
60 OUT.mkdir(parents=True, exist_ok=True)
61 rebuilt = write_weight_file(rows, scratch)
62 expected = config["phase_v2"]["target_weights"]["weights_sha256"]
63 result = {"rebuilt_sha256": rebuilt, "installed_sha256": expected, "identical": rebuilt == expected, "code_digests": freeze_digest({"survivors": [NAME], "method": None})["code"]}
64 (OUT / "eos_reproduce.json").write_text(json.dumps(result, indent=1), encoding="utf-8", newline="\n")
65 print(json.dumps({key: result[key] for key in ("rebuilt_sha256", "installed_sha256", "identical")}, indent=1))
66 return 0 if result["identical"] else 1
69def stage_make(args) -> int:
70 rules = check_rules()
71 config_path = ROOT / "config.json"
72 config = json.loads(config_path.read_text(encoding="utf-8"))
73 if any(asset.get("ticker") == COIN for asset in config["phase1"]["universe"]["assets"]):
74 config_path.write_text(json.dumps(drop_coin(config), indent=4), encoding="utf-8", newline="\n")
75 base = json.loads(config_path.read_text(encoding="utf-8"))
76 definition = {"survivors": [NAME], "method": None}
77 context = load_context()
78 window, long_window = tuple(rules["windows"]["verification"]), tuple(rules["windows"]["long"])
79 runs = {}
80 for phase in range(PHASES):
81 name = f"v664_eos_p{phase}"
82 runs[name] = make_run(name, candidate_rows(definition, context, start=window[0], end=window[1], phase_index=phase), window, base)
83 runs["v664_eos_long"] = make_run("v664_eos_long", candidate_rows(definition, context, start=long_window[0], end=long_window[1], phase_index=0), long_window, base)
84 OUT.mkdir(parents=True, exist_ok=True)
85 (OUT / "eos_repin_runs.json").write_text(json.dumps(runs, indent=1), encoding="utf-8", newline="\n")
86 (OUT / "eos_repin_run_list.txt").write_text(" ".join(f"ml/evaluation/run_configs/{name}.json" for name in runs) + "\n", encoding="utf-8", newline="\n")
87 print(f"{len(runs)} runs written; config.json now lists {len(base['phase1']['universe']['assets'])} assets")
88 return 0
91def describe(run_dir: Path) -> dict:
92 from evaluation.alpha_proof import alpha_regression, benchmark_daily_returns, sharpe, to_sessions
94 config = json.loads((RUN_CONFIGS / f"{run_dir.name}.json").read_text(encoding="utf-8"))
95 y = strategy_series(run_dir, config)
96 stats = lean_statistics(run_dir)
97 stats["strategy_sharpe"] = sharpe(y.to_numpy(dtype=float), ANNUALIZATION)
98 log = (run_dir / "log.txt").read_text(encoding="utf-8", errors="replace")
99 stats["complete"] = "PythonInitializer.Shutdown(): start" in log and "Runtime Error" not in log
100 benchmarks = benchmark_daily_returns(ROOT, config, start=str(y.index.min()), end=str(y.index.max()))
101 alpha = alpha_regression(to_sessions(y, benchmarks.index), benchmarks)
102 stats["alpha_annual"], stats["alpha_t"] = alpha.get("alpha_annual"), alpha.get("t_hac")
103 stats["locked"] = "total_drawdown_limit_breached" in log or "kill_switch" in log
104 stats["run"] = run_dir.name
105 return stats
108def stage_install(args) -> int:
109 done = {}
110 for line in Path(args.status).read_text(encoding="utf-8-sig").splitlines():
111 parts = line.split()
112 if len(parts) == 3 and parts[0] == "LEAN_DONE":
113 done[parts[1]] = ROOT / parts[2]
114 phases = {f"p{phase}": describe(done[f"v664_eos_p{phase}"]) for phase in range(PHASES) if f"v664_eos_p{phase}" in done}
115 if len(phases) != PHASES or "v664_eos_long" not in done:
116 print(f"missing runs: have {sorted(done)}", file=sys.stderr)
117 return 1
118 incomplete = [phase for phase, entry in phases.items() if not entry["complete"]]
119 if incomplete:
120 print(f"phases {incomplete} did not finish (read the engine log.txt of each, AGENTS rule 7)", file=sys.stderr)
121 return 1
122 long_run = describe(done["v664_eos_long"])
123 phase = median_phase(phases)
124 run = phases[phase]["run"]
125 config = json.loads((RUN_CONFIGS / f"{run}.json").read_text(encoding="utf-8"))
126 target = config["phase_v2"]["target_weights"]
127 source = ROOT / target["weights_path"]
128 if hashlib.sha256(source.read_bytes()).hexdigest() != target["weights_sha256"]:
129 print(f"{source} is not the file the run froze", file=sys.stderr)
130 return 1
131 shutil.copyfile(source, ROOT / INSTALLED_WEIGHTS)
132 target["weights_path"] = INSTALLED_WEIGHTS
133 config["runtime"]["lean_window_override"] = None
134 (ROOT / "config.json").write_text(json.dumps(config, indent=4), encoding="utf-8", newline="\n")
135 candidate = {"survivors": [NAME], "method": None, "phase_index": int(phase[1:]), "history_start": "2023-07-01", "pinned_run": run}
136 (ROOT / INSTALLED_CANDIDATE).write_text(json.dumps(candidate, indent=1), encoding="utf-8", newline="\n")
137 (ROOT / "ml" / "evaluation" / "readme_lean_run.json").write_text(json.dumps({"run": run, "long_run": long_run["run"]}), encoding="utf-8", newline="\n")
138 old = json.loads((ROOT / "ml" / "evaluation" / "v650" / "r_lean19.json").read_text(encoding="utf-8"))["detail"][NAME]["phases"]
139 record = {
140 "decision": "owner, 2026-11-07: Coinbase delisted EOS-USD (Problems #311)", "median_phase": phase, "pinned_run": run, "long_run": long_run["run"],
141 "phases": phases, "long": long_run, "v650_phases_with_eos": {key: {"lean_sharpe": value["lean_sharpe"], "strategy_sharpe": value["strategy_sharpe"], "drawdown_pct": value["drawdown_pct"]} for key, value in old.items()},
142 "median_strategy_sharpe_without_eos": float(np.median([entry["strategy_sharpe"] for entry in phases.values()])),
143 "median_strategy_sharpe_with_eos": float(np.median([entry["strategy_sharpe"] for entry in old.values()])),
144 "config_sha256": hashlib.sha256((ROOT / "config.json").read_bytes()).hexdigest(), "weights_sha256": target["weights_sha256"],
145 }
146 OUT.mkdir(parents=True, exist_ok=True)
147 (OUT / "eos_repin.json").write_text(json.dumps(record, indent=1, default=str), encoding="utf-8", newline="\n")
148 print(json.dumps({key: record[key] for key in ("median_phase", "pinned_run", "long_run", "median_strategy_sharpe_without_eos", "median_strategy_sharpe_with_eos", "config_sha256", "weights_sha256")}, indent=1))
149 return 0
152def main(argv: list[str] | None = None) -> int:
153 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
154 sub = parser.add_subparsers(dest="stage", required=True)
155 sub.add_parser("reproduce")
156 sub.add_parser("make")
157 install = sub.add_parser("install")
158 install.add_argument("--status", required=True)
159 args = parser.parse_args(argv)
160 return {"reproduce": stage_reproduce, "make": stage_make, "install": stage_install}[args.stage](args)
163if __name__ == "__main__":
164 raise SystemExit(main())