Coverage for evaluation/trial_ledger.py: 100%
56 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 ledger (V6.5.0): every run this phase scored, as an append-only JSONL file.
3`evaluation/trial_registry.py` reads only offline `research.json` summaries and has no idea which window a Sharpe came
4from. The deflated Sharpe needs both a count of the configurations ever selectable and the spread of Sharpes on the
5window being judged, so each entry states its window and role:
7 * `candidate`: could be selected; counts toward N and toward the variance on its window;
8 * `verification`: a frozen candidate re-read on a verification window; counts in no N (it is the same trial);
9 * `placebo`, `plumbing`: can never be selected (a null, a test of the machinery); they count in nothing.
11N keeps the legacy registry's trials. The variance has a floor, so a handful of similar candidates cannot shrink the
12bar to nothing; the legacy variance is reported next to it.
14Each ledger phase states its window under its own label (V6.6.0's are `v660_selection`), so one phase's variance never mixes
15with another's.
16"""
18from __future__ import annotations
20import json
21import math
22from pathlib import Path
23from typing import Any
25ROLES = ("candidate", "verification", "placebo", "plumbing")
26VARIANCE_FLOOR = 0.04
27LEDGER_PHASES = ("v650", "v660", "v669", "v6610")
30def append_trial(
31 path: Path | str,
32 *,
33 trial_id: str,
34 track: str,
35 window: str,
36 role: str,
37 annualised_sharpe: float | None,
38 n_obs: int,
39 config_sha: str = "",
40 weights_sha: str = "",
41 engine: str = "",
42 detail: dict[str, Any] | None = None,
43) -> dict[str, Any]:
44 """Append one trial's record to the append-only trial ledger."""
45 if role not in ROLES:
46 raise ValueError(f"unknown role {role!r}; expected one of {ROLES}")
47 value = None if annualised_sharpe is None or not math.isfinite(float(annualised_sharpe)) else float(annualised_sharpe)
48 entry = {
49 "trial_id": str(trial_id), "track": str(track), "window": str(window), "role": role, "annualised_sharpe": value,
50 "n_obs": int(n_obs), "config_sha": str(config_sha), "weights_sha": str(weights_sha), "engine": str(engine),
51 "detail": detail or {},
52 }
53 path = Path(path)
54 path.parent.mkdir(parents=True, exist_ok=True)
55 with path.open("a", encoding="utf-8", newline="\n") as handle:
56 handle.write(json.dumps(entry, sort_keys=True) + "\n")
57 return entry
60def read_ledger(path: Path | str) -> list[dict]:
61 """The trial ledger's rows, or [] when the file does not exist."""
62 path = Path(path)
63 if not path.exists():
64 return []
65 return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()]
68def candidate_ids(entries: list[dict]) -> set[str]:
69 """The ids of the ledger's candidate trials."""
70 return {entry["trial_id"] for entry in entries if entry["role"] == "candidate"}
73def legacy_trials(registry: dict[str, Any], exclude_phases: tuple[str, ...] = LEDGER_PHASES) -> list[dict]:
74 """The registry's trials not already in a ledger: the registry also holds V6.5.0's ledger, which `candidate_ids` counts
75 again, so N read 178 for what is 128."""
76 return [trial for trial in registry.get("trials", []) if trial.get("phase") not in exclude_phases]
79def deflation_inputs(entries: list[dict], legacy_registry: dict[str, Any], window: str) -> dict[str, Any]:
80 """{"N", "var", "legacy_var", "same_window_trials", "floored"} for a deflated Sharpe judged on `window`. A candidate
81 scored several times on a window counts once, by its last score. `entries` must hold every ledger phase's rows."""
82 # V6.6.7 (#377): a non-finite legacy Sharpe made legacy_var NaN; append_trial already drops one from the ledger
83 legacy_values = [float(trial["median_sharpe"]) for trial in legacy_trials(legacy_registry)]
84 legacy = [value for value in legacy_values if math.isfinite(value)]
85 latest: dict[str, float] = {}
86 for entry in entries:
87 if entry["role"] == "candidate" and entry["window"] == window and entry["annualised_sharpe"] is not None:
88 latest[entry["trial_id"]] = float(entry["annualised_sharpe"])
89 values = list(latest.values())
90 variance = _variance(values)
91 floored = variance is None or variance < VARIANCE_FLOOR
92 return {
93 "N": len(legacy_values) + len(candidate_ids(entries)),
94 "var": VARIANCE_FLOOR if floored else variance,
95 "legacy_var": _variance(legacy),
96 "same_window_trials": len(values),
97 "floored": floored,
98 }
101def _variance(values: list[float]) -> float | None:
102 if len(values) < 2:
103 return None
104 mean = sum(values) / len(values)
105 return sum((value - mean) ** 2 for value in values) / (len(values) - 1)
108PROJECT_LEDGERS = ("v650", "v669", "v6610", "v6610/book2", "v660", "v671")
111def project_deflation_inputs(evaluation_dir: Path | str, *, window: str | None = None) -> dict[str, Any]:
112 """`deflation_inputs` over the project's whole record: the legacy registry (`trial_registry.json`) and every phase's
113 ledger under `evaluation_dir`, judged on `window` (default V6.6.0's selection window). Adds the parts N is made of:
114 {"legacy", "ledger_candidates", "by_ledger"}."""
115 folder = Path(evaluation_dir)
116 registry_path = folder / "trial_registry.json"
117 registry = json.loads(registry_path.read_text(encoding="utf-8")) if registry_path.exists() else {}
118 by_ledger: dict[str, int] = {}
119 entries: list[dict] = []
120 for name in PROJECT_LEDGERS:
121 rows = read_ledger(folder / name / "trial_ledger.jsonl")
122 entries += rows
123 by_ledger[name] = len(candidate_ids(rows))
124 result = deflation_inputs(entries, registry, window or "v660_selection")
125 return result | {"legacy": len(legacy_trials(registry)) if registry else 0, "ledger_candidates": len(candidate_ids(entries)), "by_ledger": by_ledger}