Coverage for evaluation/head_audit.py: 100%
82 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"""Promotability of every model head and submodel in one table (V5.8.0, rule R-HEAD).
3Each trainer already writes a verdict next to its metrics (rank heads: `backtest.<head>_ranking_quality.quality_status`,
4regression heads: `magnitude_quality` / `volatility_quality`, experts: `quality_gate`), but they live in seven files and
5nothing reads them together, so a non-promotable head (residual_rank_20d, the gating network at MCC 0.0097) could stay
6in the decision path for releases. This module collects them, applies the gate each one already defines, and marks which
7heads the live decision path consumes, so "promotable or removed" can be checked mechanically.
9Pure: takes already-loaded JSON dicts. `load_head_metrics(ml_dir)` is the one loader.
10"""
12from __future__ import annotations
14import json
15import math
16from pathlib import Path
18PASSING_RANK_STATUSES = frozenset({"promotable", "watchlist"})
19RANK_HEADS = ("rank_5d", "rank_20d", "sector_neutral_rank_20d", "residual_rank_5d", "residual_rank_20d", "beta_neutral_rank_20d")
20DIRECTION_HEADS = ("direction", "direction_5d", "direction_20d")
23def _finite(value) -> float | None:
24 try:
25 number = float(value)
26 except (TypeError, ValueError):
27 return None
28 return number if math.isfinite(number) else None
31def load_head_metrics(ml_dir: Path) -> dict:
32 """Reads every metrics artifact that exists under `ml_dir` (missing files -> absent keys)."""
33 ml_dir = Path(ml_dir)
34 names = {
35 "baseline": "training_metrics.json",
36 "multitask": "multitask_training_metrics.json",
37 "sequence": "sequence_training_metrics.json",
38 "gating": "gating_training_metrics.json",
39 "experts": "expert_training_metrics.json",
40 "rl_sizing": "rl_sizing_training_metrics.json",
41 "rl_sizing_forex": "rl_sizing_forex_training_metrics.json",
42 "topology": "topology_training_metrics.json",
43 }
44 loaded = {}
45 for key, name in names.items():
46 path = ml_dir / name
47 if path.exists():
48 try:
49 loaded[key] = json.loads(path.read_text(encoding="utf-8"))
50 except ValueError:
51 loaded[key] = {"_unreadable": True}
52 return loaded
55def _direction_row(model: str, head: str, metrics: dict, min_mcc: float, consumers: set[str]) -> dict | None:
56 validation = (metrics.get("validation") or {}).get(head)
57 backtest = (metrics.get("backtest") or {}).get(head)
58 if not isinstance(validation, dict) and not isinstance(backtest, dict):
59 return None
60 validation_mcc = _finite((validation or {}).get("mcc"))
61 backtest_mcc = _finite((backtest or {}).get("mcc"))
62 passed = validation_mcc is not None and backtest_mcc is not None and validation_mcc > min_mcc and backtest_mcc > min_mcc
63 return {
64 "component": f"{model}.{head}", "kind": "direction", "metric": "mcc (validation / backtest)",
65 "value": [validation_mcc, backtest_mcc], "threshold": f"> {min_mcc}", "passed": bool(passed),
66 "in_decision_path": f"{model}.{head}" in consumers,
67 }
70def audit_heads(metrics: dict, *, consumers: set[str] | None = None, min_direction_mcc: float = 0.0) -> dict:
71 """`metrics` is load_head_metrics()'s dict. `consumers` names the components the live path reads
72 (e.g. {"multitask.rank_20d", "sequence.rank_5d", "gating"}); it only annotates the table."""
73 consumers = set(consumers or ())
74 rows: list[dict] = []
75 for model in ("multitask", "sequence"):
76 model_metrics = metrics.get(model)
77 if not model_metrics:
78 continue
79 backtest = model_metrics.get("backtest") or {}
80 for head in RANK_HEADS:
81 quality = backtest.get(f"{head}_ranking_quality")
82 if not isinstance(quality, dict):
83 continue
84 status = quality.get("quality_status")
85 rows.append({
86 "component": f"{model}.{head}", "kind": "rank", "metric": "ranking_quality", "value": status,
87 "threshold": sorted(PASSING_RANK_STATUSES), "passed": status in PASSING_RANK_STATUSES,
88 "failures": quality.get("failures", []), "in_decision_path": f"{model}.{head}" in consumers,
89 })
90 for head, key in (("magnitude", "magnitude_quality"), ("volatility", "volatility_quality")):
91 quality = model_metrics.get(key)
92 if isinstance(quality, dict):
93 rows.append({
94 "component": f"{model}.{head}", "kind": "regression", "metric": "quality_status",
95 "value": quality.get("quality_status"), "threshold": ["stable", "watchlist"],
96 "passed": quality.get("quality_status") in {"stable", "watchlist"},
97 "failures": quality.get("failures", []), "in_decision_path": f"{model}.{head}" in consumers,
98 })
99 for head in DIRECTION_HEADS:
100 row = _direction_row(model, head, model_metrics, min_direction_mcc, consumers)
101 if row:
102 rows.append(row)
103 baseline = metrics.get("baseline")
104 if baseline:
105 row = _direction_row("baseline", "direction", {"validation": {"direction": baseline.get("validation")},
106 "backtest": {"direction": baseline.get("backtest")}},
107 min_direction_mcc, consumers)
108 if row:
109 rows.append(row)
110 experts = (metrics.get("experts") or {}).get("experts") or {}
111 disabled = set((metrics.get("experts") or {}).get("disabled_for_gating_experts") or [])
112 for name, expert in sorted(experts.items()):
113 gate = expert.get("quality_gate") or {}
114 status = gate.get("quality_status") or expert.get("quality_status")
115 rows.append({
116 "component": f"expert.{name}", "kind": "expert", "metric": "quality_status",
117 "value": status, "threshold": ["stable", "watchlist"],
118 "passed": status in {"stable", "watchlist"} and name not in disabled,
119 "failures": gate.get("failures", []), "in_decision_path": f"expert.{name}" in consumers and name not in disabled,
120 })
121 gating = metrics.get("gating")
122 if gating:
123 mcc = _finite((gating.get("backtest") or {}).get("mcc"))
124 baseline_mcc = _finite(((baseline or {}).get("backtest") or {}).get("mcc"))
125 passed = mcc is not None and mcc > min_direction_mcc and (baseline_mcc is None or mcc >= baseline_mcc)
126 rows.append({
127 "component": "gating", "kind": "gating", "metric": "backtest mcc vs baseline", "value": [mcc, baseline_mcc],
128 "threshold": "> 0 and >= baseline", "passed": bool(passed), "in_decision_path": "gating" in consumers,
129 })
130 for key in ("rl_sizing", "rl_sizing_forex"):
131 rl = metrics.get(key)
132 if not rl:
133 continue
134 policy = _finite(rl.get("backtest_policy_expected_reward"))
135 constant = _finite(rl.get("backtest_constant_action_1_0_expected_reward"))
136 rows.append({
137 "component": key, "kind": "rl", "metric": "backtest reward policy vs constant 1.0", "value": [policy, constant],
138 "threshold": "policy > constant (R-RL half 1)", "passed": policy is not None and constant is not None and policy > constant,
139 "in_decision_path": key in consumers,
140 })
141 failing_in_path = [row["component"] for row in rows if not row["passed"] and row["in_decision_path"]]
142 return {
143 "rows": rows,
144 "num_components": len(rows),
145 "num_passed": sum(1 for row in rows if row["passed"]),
146 "failing": [row["component"] for row in rows if not row["passed"]],
147 "failing_in_decision_path": failing_in_path,
148 }