Coverage for evaluation/trial_registry.py: 100%
53 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"""The trial registry (V6.3.0, moved here from scripts/build_trial_registry.py in V6.4.3 so the library can use it):
2every research variant ever scored by a pre-registered rule, as one trial list - the deflated Sharpe ratio's N and
3Sharpe variance (`evaluation/backtest_statistics.py`).
5Each rule chain's `ml/evaluation/<phase>/research.json` stores, per variant and scoring mode, one summary per split with
6`median_net_sharpe` over the rebalance phases. A trial is one (phase, stage, variant, mode) scored on the backtest split
7(the split variants were selected on); a summary repeated verbatim (the base book re-scored in every stage) counts once.
8"""
10from __future__ import annotations
12import json
13import math
14from pathlib import Path
15from typing import Any
17SPLIT = "backtest"
20def collect_trials(payload: Any, phase: str, path: tuple[str, ...] = ()) -> list[dict]:
21 """(phase, path, median Sharpe) for every `<...>/backtest/{median_net_sharpe}` summary in a research payload."""
22 trials: list[dict] = []
23 if isinstance(payload, dict):
24 summary = payload.get(SPLIT)
25 if isinstance(summary, dict) and isinstance(summary.get("median_net_sharpe"), (int, float)):
26 value = float(summary["median_net_sharpe"])
27 if math.isfinite(value):
28 trials.append({
29 "phase": phase, "trial": "/".join(path), "split": SPLIT, "median_sharpe": value,
30 "phases": summary.get("phases"), "annualization": 252,
31 })
32 for key, child in payload.items():
33 if key != SPLIT:
34 trials.extend(collect_trials(child, phase, path + (str(key),)))
35 elif isinstance(payload, list):
36 for index, child in enumerate(payload):
37 trials.extend(collect_trials(child, phase, path + (str(index),)))
38 return trials
41def dedupe(trials: list[dict]) -> list[dict]:
42 """One trial per distinct (phase, score): the same configuration re-scored in a later stage is not a new trial."""
43 seen: set[tuple[str, float]] = set()
44 unique = []
45 for trial in trials:
46 key = (trial["phase"], round(trial["median_sharpe"], 9))
47 if key in seen:
48 continue
49 seen.add(key)
50 unique.append(trial)
51 return unique
54def _ledger_trials(path: Path) -> list[dict]:
55 """A V6.5.0 ledger's selectable candidates, one trial each by its last score; placebos and plumbing runs are nulls and never count."""
56 from evaluation.trial_ledger import read_ledger
58 latest: dict[str, dict] = {}
59 for entry in read_ledger(path):
60 if entry["role"] == "candidate" and entry["annualised_sharpe"] is not None:
61 latest[entry["trial_id"]] = entry
62 return [
63 {"phase": path.parent.name, "trial": name, "split": entry["window"], "median_sharpe": float(entry["annualised_sharpe"]),
64 "phases": None, "annualization": 365}
65 for name, entry in sorted(latest.items())
66 ]
69def build_registry(evaluation_dir: Path) -> dict[str, Any]:
70 """Every trial ever scored, collected from the research reports under `evaluation_dir`, for the deflated Sharpe's N."""
71 trials: list[dict] = []
72 sources = []
73 for research in sorted(Path(evaluation_dir).glob("v*/research.json")):
74 try:
75 payload = json.loads(research.read_text(encoding="utf-8"))
76 except (OSError, ValueError):
77 continue
78 sources.append(research.relative_to(evaluation_dir).as_posix())
79 trials.extend(collect_trials(payload, research.parent.name))
80 for ledger in sorted(Path(evaluation_dir).glob("v*/trial_ledger.jsonl")):
81 sources.append(ledger.relative_to(evaluation_dir).as_posix())
82 trials.extend(_ledger_trials(ledger))
83 trials = dedupe(trials)
84 return {"sources": sources, "num_trials": len(trials), "split": SPLIT, "trials": trials}