Coverage for scripts/v660_research.py: 100%
287 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"""V6.6.0 selection, run on one of the free cells only (`evaluation/research_cells.py` refuses the rest).
3 python scripts/v660_research.py score [--only w01 w02 ...]
4 python scripts/v660_research.py placebo --draws 100 [--only ...] [--suffix _a]
5 python scripts/v660_research.py gate
6 python scripts/v660_research.py pbo
7 python scripts/v660_research.py combine
8 python scripts/v660_research.py blend # m5, from m2, m3 and m4
9 python scripts/v660_research.py vel # R-VEL1
10"""
12from __future__ import annotations
14import argparse
15import hashlib
16import json
17import math
18import sys
19from pathlib import Path
21import numpy as np
22import pandas as pd
24ROOT = Path(__file__).resolve().parents[1]
25sys.path.insert(0, str(ROOT))
26sys.path.insert(0, str(ROOT / "scripts"))
28from v660_trials import ALL_SPECS, COMBINATION_IDS, CRYPTO_CORE, MIN_IC_NAMES, NO_IC_CLAUSE, PBO_COLUMNS, cell_of, min_live_names # noqa: E402
30from evaluation.premia_research import ( # noqa: E402
31 annual_sharpe,
32 max_drawdown,
33 nulls_for,
34 passes_sharpe_clauses,
35 phase_offsets,
36 placebo_p_value,
37 placebo_sharpes,
38 score_sleeve,
39 selection_gate,
40 weights_for,
41)
42from evaluation.research_cells import CELLS, FREE_CELLS # noqa: E402
43from evaluation.trial_ledger import append_trial # noqa: E402
44from evaluation.wide_context import crypto_cell, equity_cell, signal_ic_t # noqa: E402
45from portfolio.premia_signals import combine_sleeves, sleeve_signal # noqa: E402
46from portfolio.wide_signals import live_names_per_rebalance # noqa: E402
48OUT = ROOT / "ml" / "evaluation" / "v660"
49RULES = OUT / "rules.json"
50RULES_SHA = OUT / "rules.sha256"
51SCORES = OUT / "selection_scores.json"
52DAILY = OUT / "selection_daily.parquet"
53GATE = OUT / "selection_gate.json"
54LEDGER = OUT / "trial_ledger.jsonl"
55ML_SCORES = OUT / "scores"
56WINDOW_LABEL = "v660_selection"
59def check_rules() -> dict:
60 """Every stage starts here: a changed rule file stops the phase."""
61 payload = RULES.read_bytes()
62 digest = hashlib.sha256(payload).hexdigest()
63 expected = RULES_SHA.read_text(encoding="utf-8").strip()
64 if digest != expected:
65 raise SystemExit(f"rules.json {digest} is not the recorded {expected}")
66 return json.loads(payload)
69def assert_selection_only(end: str) -> None:
70 if end > max(CELLS[name].end for name in FREE_CELLS):
71 raise SystemExit(f"{end} is past every selection cell")
74def read_json(path: Path, default):
75 return json.loads(path.read_text(encoding="utf-8")) if path.exists() else default
78def write_json(path: Path, payload) -> None:
79 path.write_text(json.dumps(payload, indent=1, default=str), encoding="utf-8", newline="\n")
82def base_config() -> dict:
83 return json.loads((ROOT / "config.json").read_text(encoding="utf-8"))
86def score_table(trial: str, index, columns) -> pd.DataFrame | None:
87 """A model trial's score file, as of each session. Scores are on equities only, so no late-bar shift is needed here."""
88 path = ML_SCORES / f"{trial}.csv"
89 if not path.exists():
90 return None
91 table = pd.read_csv(path, dtype={"date": str, "ticker": str})
92 return table.pivot_table(index="date", columns="ticker", values="score", aggfunc="last").reindex(index=index, columns=columns)
95def load_cells(specs) -> dict[str, object]:
96 """The cells these specs need, each once: building one takes minutes."""
97 base = base_config()
98 cells = {}
99 for name in sorted({cell_of(spec) for spec in specs}):
100 cells[name] = crypto_cell(ROOT, base, name) if CELLS[name].universe == "crypto" else equity_cell(ROOT, base, name)
101 cell = cells[name]
102 if cell.cell.universe == "equity":
103 known = cell.context.panel.known
104 # e3: a single asset on a volatility target. scale_and_cap sets the size.
105 spy = pd.DataFrame(np.nan, index=known.index, columns=known.columns)
106 spy["SPY"] = 1.0
107 cell.context.panel.extras["e3"] = spy.where(known.notna())
108 for trial in ("m1", "m2", "m3", "m4", "m5"):
109 table = score_table(trial, known.index, known.columns)
110 if table is not None:
111 cell.context.panel.extras[trial] = table.where(cell.member)
112 cell.tables[trial] = cell.context.panel.extras[trial]
113 else:
114 cell.context.panel.extras["c5"] = core_trend_table(cell.context.panel.known)
115 cell.tables["c5"] = cell.context.panel.extras["c5"]
116 return cells
119def core_trend_table(known: pd.DataFrame) -> pd.DataFrame:
120 """c5: the installed sleeve's votes, on BTC and ETH alone. Long while the trailing return is positive, over each lookback."""
121 votes = [(known / known.shift(lookback) - 1.0 > 0.0).astype(float).where(known.shift(lookback).notna()) for lookback in (20, 60, 120)]
122 table = sum(votes) / len(votes)
123 table.loc[:, ~table.columns.isin(CRYPTO_CORE)] = np.nan
124 return table
127def _signal_for(spec, cell) -> pd.DataFrame | None:
128 panel = cell.context.panel
129 if spec.family == "external_score" and spec.params["table"] not in panel.extras:
130 return None
131 return sleeve_signal(spec, panel)
134def _ic_clause(spec, cell, signal: pd.DataFrame) -> dict | None:
135 if spec.id in NO_IC_CLAUSE or cell.cell.universe == "crypto":
136 return None
137 if cell.label is None:
138 return None
139 return signal_ic_t(signal, cell.label, start=cell.cell.start, end=cell.cell.end, min_names=MIN_IC_NAMES[spec.track])
142def crypto_ic(spec, cell, signal: pd.DataFrame) -> dict | None:
143 """c1-c4's rank IC with the next 28 days' return, on the same coins."""
144 if spec.id in NO_IC_CLAUSE:
145 return None
146 from evaluation.wide_context import crypto_ic as shared_crypto_ic
148 return shared_crypto_ic(signal, cell.context.panel.known, start=cell.cell.start, end=cell.cell.end, min_names=MIN_IC_NAMES["C"])
151def stage_score(args) -> int:
152 check_rules()
153 specs = [spec for spec in ALL_SPECS if not args.only or spec.id in args.only]
154 cells = load_cells(specs)
155 scores = read_json(SCORES, {})
156 frames = pd.read_parquet(DAILY).to_dict("series") if DAILY.exists() else {}
157 for spec in specs:
158 if spec.id in scores and not args.force:
159 continue
160 cell = cells[cell_of(spec)]
161 signal = _signal_for(spec, cell)
162 if signal is None:
163 print(f"{spec.id:6s} has no table yet", flush=True)
164 continue
165 assert_selection_only(cell.cell.end)
166 live = live_names_per_rebalance(signal.loc[signal.index >= cell.cell.start], spec.rebalance_every)
167 if live["median"] < min_live_names(spec.id, spec.track):
168 print(f"{spec.id:6s} ranks only {live['median']:.0f} names; minimum {min_live_names(spec.id, spec.track)}", flush=True)
169 score = score_sleeve(spec, cell.context, start=cell.cell.start, split=cell.cell.split, end=cell.cell.end, signal=signal)
170 daily = score.pop("daily")
171 # one real path, as V6.5.0 kept: a median across phases per date isn't a return anyone could earn
172 middle = daily[min(daily)]
173 frames[spec.id] = middle
174 ic = crypto_ic(spec, cell, signal) if cell.cell.universe == "crypto" else _ic_clause(spec, cell, signal)
175 scores[spec.id] = {**score, "cell": cell.cell.name, "live_names": live, "ic": ic}
176 append_trial(LEDGER, trial_id=spec.id, track=spec.track, window=WINDOW_LABEL, role="candidate", annualised_sharpe=score["sharpe"],
177 n_obs=len(middle), engine="offline", detail={"cell": cell.cell.name})
178 write_json(SCORES, scores)
179 pd.DataFrame(frames).sort_index().to_parquet(DAILY)
180 print(f"{spec.id:6s} Sharpe {_show(score['sharpe'])} ({_show(score['sharpe_first_half'])}, {_show(score['sharpe_second_half'])}) IC t {_show((ic or {}).get('nonoverlap_t'))} live {live['median']:.0f}", flush=True)
181 return 0
184def _show(value) -> str:
185 return " n/a" if value is None else f"{value:5.2f}"
188def passes_earlier_clauses(spec_id: str, track: str, score: dict) -> bool:
189 if not passes_sharpe_clauses(score):
190 return False
191 if (score.get("live_names") or {}).get("median", 0.0) < min_live_names(spec_id, track):
192 return False
193 if spec_id in NO_IC_CLAUSE:
194 return True
195 t = (score.get("ic") or {}).get("nonoverlap_t")
196 return t is not None and t >= 2.0
199def stage_placebo(args) -> int:
200 check_rules()
201 scores = read_json(SCORES, {})
202 specs = [spec for spec in ALL_SPECS if spec.id in scores and passes_earlier_clauses(spec.id, spec.track, scores[spec.id])]
203 if args.only:
204 specs = [spec for spec in specs if spec.id in args.only]
205 if not specs:
206 print("no trial reached the placebo clause")
207 return 0
208 cells = load_cells(specs)
209 path = OUT / f"selection_placebos{args.suffix}.json"
210 ledger = OUT / f"trial_ledger{args.suffix}_placebos.jsonl"
211 done = read_json(path, {})
212 for spec in specs:
213 if spec.id in done and not args.force:
214 continue
215 cell = cells[cell_of(spec)]
216 out = {}
217 for mode in nulls_for(spec):
218 sharpes = placebo_sharpes(spec, cell.context, mode, start=cell.cell.start, end=cell.cell.end, draws=args.draws)
219 out[mode] = {"p": placebo_p_value(scores[spec.id]["sharpe"], sharpes), "draws": len(sharpes), "median": float(pd.Series(sharpes).median()) if sharpes else None,
220 "q95": float(pd.Series(sharpes).quantile(0.95)) if sharpes else None}
221 print(f"{spec.id:6s} {mode:12s} p {out[mode]['p']:.3f} placebo median {_show(out[mode]['median'])} q95 {_show(out[mode]['q95'])}", flush=True)
222 for sharpe in sharpes:
223 append_trial(ledger, trial_id=f"{spec.id}:{mode}", track=spec.track, window=WINDOW_LABEL, role="placebo", annualised_sharpe=sharpe, n_obs=0, engine="offline")
224 done[spec.id] = out
225 write_json(path, done)
226 return 0
229def stage_gate(args) -> int:
230 check_rules()
231 scores = read_json(SCORES, {})
232 placebos = {}
233 for path in sorted(OUT.glob("selection_placebos*.json")):
234 placebos.update(read_json(path, {}))
235 daily = pd.read_parquet(DAILY)
236 track = {spec.id: spec.track for spec in ALL_SPECS}
237 eligible = {name: score for name, score in scores.items() if passes_earlier_clauses(name, track[name], score)}
238 rows = [{**score, "id": name, "daily": {0: daily[name].dropna()}} for name, score in eligible.items() if name in daily]
239 p_values = {name: {mode: entry["p"] for mode, entry in tests.items()} for name, tests in placebos.items()}
240 gate = selection_gate(rows, p_values)
241 gate["failed_earlier_clauses"] = {
242 name: _why_failed(name, track[name], scores[name]) for name in scores if name not in eligible
243 }
244 gate["unscored"] = [spec.id for spec in ALL_SPECS if spec.id not in scores]
245 write_json(GATE, gate)
246 print(json.dumps({key: gate[key] for key in ("survivors", "failed", "unscored")}, indent=1))
247 return 0
250def _why_failed(name: str, track: str, score: dict) -> str:
251 if (score.get("live_names") or {}).get("median", 0.0) < min_live_names(name, track):
252 return "live_names"
253 if not passes_sharpe_clauses(score):
254 return "sharpe"
255 return "ic"
258def stage_pbo(args) -> int:
259 from evaluation.pbo import probability_of_backtest_overfitting
261 check_rules()
262 daily = pd.read_parquet(DAILY)
263 columns = [name for name in PBO_COLUMNS if name in daily.columns]
264 window = CELLS["S"]
265 matrix = daily[columns]
266 matrix = matrix[(matrix.index >= window.start) & (matrix.index <= window.end)].dropna(how="all").fillna(0.0)
267 result = probability_of_backtest_overfitting(matrix.to_numpy(dtype=float), blocks=16, periods_per_year=252)
268 report = {"pbo": result.get("pbo"), "num_trials": len(columns), "missing": [name for name in PBO_COLUMNS if name not in daily.columns], "window": f"{window.start}..{window.end}", **{k: v for k, v in result.items() if k != "pbo"}}
269 write_json(OUT / "selection_pbo.json", report)
270 print(json.dumps(report, indent=1, default=str))
271 return 0
274def stage_combine(args) -> int:
275 """t1 and t2 over the survivors plus the installed sleeve, on cell S. Weights are never fitted to returns."""
276 check_rules()
277 gate = read_json(GATE, {})
278 survivors = gate.get("survivors") or []
279 if not survivors:
280 print("no survivor: the verdict follows at once")
281 return 0
282 specs = {spec.id: spec for spec in ALL_SPECS}
283 equity = [name for name in survivors if cell_of(specs[name]) == "S"]
284 if not equity:
285 print("no equity survivor: the candidate is crypto only, combination is the survivor(s) alone")
286 return 0
287 cells = load_cells([specs[name] for name in equity])
288 cell = cells["S"]
289 window = cell.cell
290 sleeves = {}
291 for name in equity:
292 spec = specs[name]
293 sleeves[name] = weights_for(spec, cell.context, sleeve_signal(spec, cell.context.panel), start=window.start, end=window.end, phase_offset=phase_offsets(spec.rebalance_every)[0])
294 results = {}
295 sessions = cell.context.market.sessions
296 for name, method in zip(COMBINATION_IDS, ("inverse_vol", "hrp"), strict=False):
297 rows = combine_sleeves(sleeves, cell.context.panel, method=method, settings=cell.context.settings, start=window.start, end=window.end)
298 strategy = cell.context.simulate(rows, window.start, window.end)["strategy_excess"]
299 results[name] = {
300 "sharpe": annual_sharpe(strategy, sessions=sessions), "first_half": annual_sharpe(strategy[strategy.index < window.split], sessions=sessions),
301 "second_half": annual_sharpe(strategy[strategy.index >= window.split], sessions=sessions), "max_drawdown": max_drawdown(strategy),
302 }
303 append_trial(LEDGER, trial_id=name, track="T", window=WINDOW_LABEL, role="candidate", annualised_sharpe=results[name]["sharpe"], n_obs=len(strategy), engine="offline", detail={"cell": "S", "survivors": equity})
304 print(name, results[name], flush=True)
305 write_json(OUT / "selection_combination.json", {"survivors": survivors, "equity_survivors": equity, "results": results})
306 return 0
309def stage_blend(args) -> int:
310 """m5: the equal rank mean of m2, m3 and m4, or of m2 and m4 if rules.json's compute bound closed m3. Never fitted."""
311 check_rules()
312 parts = [name for name in ("m2", "m3", "m4") if (ML_SCORES / f"{name}.csv").exists()]
313 if len(parts) < 2:
314 print(f"m5 needs two parts, has {parts}")
315 return 1
316 ranked = []
317 for name in parts:
318 table = pd.read_csv(ML_SCORES / f"{name}.csv", dtype={"date": str, "ticker": str})
319 table["rank"] = table.groupby("date")["score"].rank(pct=True)
320 ranked.append(table.set_index(["date", "ticker"])["rank"])
321 mean = pd.concat(ranked, axis=1).mean(axis=1, skipna=False).dropna().rename("score").reset_index()
322 mean.to_csv(ML_SCORES / "m5.csv", index=False, lineterminator="\n", float_format="%.6f")
323 print(f"m5 from {parts}: {len(mean)} rows")
324 return 0
327def stage_vel(args) -> int:
328 """R-VEL1, on the installed sleeve's own panel and weight file."""
329 from evaluation.premia_research import build_context
330 from portfolio.target_weights import load_weight_file
332 check_rules()
333 base = base_config()
334 context = build_context(ROOT, base)
335 # the installed rule over the 12 years V6.5.0 ran it: the installed file itself starts in 2023-07
336 weights = load_weight_file(ROOT / "ml" / "evaluation" / "v650" / "weights" / "v650_pool_t3_crypto_trend_blend_long.csv")
337 start, end = "2014-12-01", "2026-11-02"
338 target_vol = 0.07
340 def run(velocity):
341 result = context.simulate(weights, start, end, max_drawdown_velocity=velocity, max_total_drawdown=0.15)
342 strategy = result["strategy"]
343 five_day = (1.0 + strategy).rolling(5).apply(np.prod, raw=True) - 1.0
344 locked = result.get("locked_on")
345 rows = list(strategy.index)
346 trading_share = (sum(1 for date in rows if locked is None or date <= locked) / len(rows)) if rows else 0.0
347 return {"velocity": velocity, "locked_on": locked, "sharpe": annual_sharpe(strategy), "worst_5_day": float(five_day.min()), "share_of_sessions_trading": trading_share, "max_drawdown": max_drawdown(strategy)}
349 off = run(None)
350 report = {"off": off, "options": {}}
351 adopted = None
352 for k in (5, 8):
353 velocity = k * target_vol / math.sqrt(252.0)
354 row = run(velocity)
355 row["cuts_worst_5_day_by"] = 1.0 - row["worst_5_day"] / off["worst_5_day"] if off["worst_5_day"] else 0.0
356 row["passes"] = row["share_of_sessions_trading"] >= 0.95 and row["cuts_worst_5_day_by"] >= 0.20
357 report["options"][str(k)] = row
358 if row["passes"] and adopted is None:
359 adopted = k
360 report["adopted_k"] = adopted
361 report["decision"] = f"velocity lock at k={adopted}" if adopted else "velocity stays off, by rule"
362 write_json(OUT / "r_vel1.json", report)
363 print(json.dumps(report, indent=1, default=str))
364 return 0
367def main() -> int:
368 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
369 commands = parser.add_subparsers(dest="stage", required=True)
370 score = commands.add_parser("score")
371 score.add_argument("--only", nargs="*", default=None)
372 score.add_argument("--force", action="store_true")
373 placebo = commands.add_parser("placebo")
374 placebo.add_argument("--draws", type=int, default=100)
375 placebo.add_argument("--only", nargs="*", default=None)
376 placebo.add_argument("--suffix", default="")
377 placebo.add_argument("--force", action="store_true")
378 for name in ("gate", "pbo", "combine", "vel", "blend"):
379 commands.add_parser(name)
380 args = parser.parse_args()
381 return {"score": stage_score, "placebo": stage_placebo, "gate": stage_gate, "pbo": stage_pbo, "combine": stage_combine, "vel": stage_vel, "blend": stage_blend}[args.stage](args)
384if __name__ == "__main__":
385 raise SystemExit(main())