Coverage for retraining/validation_gate.py: 100%
141 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"""Pure candidate-vs-active validation gate (Phase V2-17).
3Mirrors train.py's assess_expert_quality() failures/near_misses/status
4shape, but compares a candidate model's metrics against the CURRENTLY
5ACTIVE model's metrics (relative comparison) instead of assess_expert_quality's
6fixed absolute thresholds - there is no existing candidate-vs-active diff
7function anywhere else in this codebase.
9Inputs are the same JSON shapes train.py already produces:
10 candidate_metrics / active_metrics : ml/.../training_metrics.json (compute_binary_metrics shape)
11 candidate_report / active_report : ml/.../strategy_report.json (compute_strategy_metrics shape)
13No filesystem/Postgres I/O here - see retraining/artifacts.py for loading
14these dicts off disk and for "no missing scaler/schema/artifacts" checks.
15"""
17from __future__ import annotations
19import math
20from typing import Any
23def compute_overfitting_gap(metrics: dict[str, Any]) -> float:
24 """train.balanced_accuracy - backtest.balanced_accuracy.
26 No such field is pre-computed for the baseline model anywhere today
27 (unlike expert models' quality_gate.observed) - self-computed here from
28 training_metrics.json's train/backtest splits.
29 """
30 train_balanced_accuracy = float(metrics.get("train", {}).get("balanced_accuracy", 0.0) or 0.0)
31 backtest_balanced_accuracy = float(metrics.get("backtest", {}).get("balanced_accuracy", 0.0) or 0.0)
32 return train_balanced_accuracy - backtest_balanced_accuracy
35def evaluate_ranking_promotion_gate(
36 ranking_metrics_by_model: dict[str, Any], config: dict[str, Any], walk_forward_summary: dict[str, Any] | None = None
37) -> dict[str, Any]:
38 """Ranking promotion gate on one head, or on whichever of `heads` clears it.
40 `heads` (optional list, V5.6.0): the candidate passes when ANY listed head clears the gate, and the
41 verdict reports which one (`observed.gated_head`). Without it, the single `head` is gated exactly as
42 before. The default config lists the heads that drive the live book (`phase_v2.rank_signal.heads`);
43 gating on `residual_rank_20d`, which is demoted from the book and has never been promotable, rejected
44 every candidate regardless of the heads actually traded.
45 """
46 heads = config.get("heads")
47 if not heads:
48 return _evaluate_single_head_ranking_gate(ranking_metrics_by_model, config, walk_forward_summary)
50 results = [
51 _evaluate_single_head_ranking_gate(ranking_metrics_by_model, {**config, "head": str(head)}, walk_forward_summary)
52 for head in heads
53 ]
54 chosen = next((result for result in results if result["passed"]), results[0])
55 chosen = {**chosen, "observed": {**chosen["observed"], "gated_head": chosen["observed"]["head"], "candidate_heads": [str(h) for h in heads]}}
56 return chosen
59def _evaluate_single_head_ranking_gate(
60 ranking_metrics_by_model: dict[str, Any], config: dict[str, Any], walk_forward_summary: dict[str, Any] | None = None
61) -> dict[str, Any]:
62 """V5.1 Phase 4 (item 7 - "the dead end"): assess_ranking_quality()'s
63 verdict has always been written to a candidate's own
64 {sequence,multitask}_training_metrics.json, but nothing in retraining/
65 ever read it - a candidate could be `not_promotable` on every rank head
66 and still sail through evaluate_validation_gate() untouched, because
67 that function only ever looked at the BASELINE model's Sharpe/drawdown/
68 MCC. This closes that gap. Pure. Returns
69 {passed, failures, near_misses, thresholds, observed}.
71 ranking_metrics_by_model: {"sequence": <sequence_training_metrics.json
72 dict, or None>, "multitask": <multitask_training_metrics.json dict, or
73 None>} - the SAME two files retraining/orchestrator.py::validate()
74 already loads via _load_json_if_exists() for the baseline gate.
76 config: phase_v2.retraining.validation_gate.ranking (model/head to
77 gate on, require_quality_status, min_net_sharpe/max_annualized_turnover/
78 min_capacity_usd, min_walk_forward_windows/max_window_sign_flip_fraction,
79 missing_metrics_action).
81 Reads backtest.{head}_ranking_quality.quality_status and
82 backtest.{head}_net_performance (both written by
83 train_multitask.py/train_sequence.py's compute_*_metrics(), V5.1 Phases
84 2-4) off the configured model's metrics, plus walk_forward_summary's
85 stability_by_metric[f"{head}_ic"] when a walk-forward summary happens
86 to be passed in (optional, default None - no caller is required to go
87 find one; a candidate retrain has no walk-forward run of its own).
89 MISSING-METRICS CONTRACT: when the configured model/head has neither a
90 ranking_quality nor a net_performance entry (an older candidate trained
91 before V5.1, or net_performance simply disabled in config), the
92 outcome is governed by missing_metrics_action - "near_miss" (default,
93 passed=True but flagged) / "fail" (passed=False) / "ignore" (passed=True,
94 unflagged). WITHOUT the "near_miss" default, the very first retrain
95 after V5.1 ships would auto-reject itself for metrics that simply don't
96 exist yet on an older-format candidate."""
97 model_name = str(config.get("model", "sequence"))
98 head = str(config.get("head", "residual_rank_20d"))
99 require_quality_status = set(config.get("require_quality_status", ["promotable", "watchlist"]))
100 min_net_sharpe = float(config.get("min_net_sharpe", 0.0))
101 max_annualized_turnover = float(config.get("max_annualized_turnover", 1e9))
102 min_capacity_usd = float(config.get("min_capacity_usd", 0.0))
103 min_walk_forward_windows = int(config.get("min_walk_forward_windows", 0))
104 max_window_sign_flip_fraction = float(config.get("max_window_sign_flip_fraction", 1.0))
105 missing_metrics_action = str(config.get("missing_metrics_action", "near_miss"))
107 failures: list[str] = []
108 near_misses: list[str] = []
110 model_metrics = (ranking_metrics_by_model or {}).get(model_name) or {}
111 backtest_metrics = model_metrics.get("backtest", {}) or {}
112 ranking_quality = backtest_metrics.get(f"{head}_ranking_quality")
113 net_performance = backtest_metrics.get(f"{head}_net_performance")
115 observed: dict = {
116 "model": model_name,
117 "head": head,
118 "quality_status": (ranking_quality or {}).get("quality_status"),
119 "net_sharpe": (net_performance or {}).get("observed", {}).get("net_sharpe"),
120 "annualized_turnover": (net_performance or {}).get("observed", {}).get("annualized_turnover"),
121 "capacity_usd": (net_performance or {}).get("observed", {}).get("capacity_usd"),
122 }
124 if ranking_quality is None and net_performance is None:
125 if missing_metrics_action == "fail":
126 failures.append("ranking_gate_metrics_absent")
127 elif missing_metrics_action == "near_miss":
128 near_misses.append("ranking_gate_metrics_absent")
129 # "ignore" - neither list touched, this gate is a pure no-op for this candidate.
130 else:
131 if ranking_quality is not None and ranking_quality.get("quality_status") not in require_quality_status:
132 failures.append("ranking_quality_status_not_accepted")
134 if net_performance is not None:
135 net_observed = net_performance.get("observed", {}) or {}
136 if float(net_observed.get("net_sharpe", 0.0) or 0.0) < min_net_sharpe:
137 failures.append("net_sharpe_below_gate")
138 if float(net_observed.get("annualized_turnover", 0.0) or 0.0) > max_annualized_turnover:
139 failures.append("annualized_turnover_above_gate")
140 if float(net_observed.get("capacity_usd", 0.0) or 0.0) < min_capacity_usd:
141 failures.append("capacity_usd_below_gate")
143 if walk_forward_summary is not None:
144 stability = (walk_forward_summary.get("stability_by_metric") or {}).get(f"{head}_ic")
145 if stability is not None:
146 observed["walk_forward_num_windows"] = stability.get("num_windows")
147 observed["walk_forward_sign_flip_fraction"] = stability.get("sign_flip_fraction")
148 if int(stability.get("num_windows", 0) or 0) < min_walk_forward_windows:
149 failures.append("insufficient_walk_forward_windows")
150 if float(stability.get("sign_flip_fraction", 0.0) or 0.0) > max_window_sign_flip_fraction:
151 failures.append("walk_forward_sign_flip_fraction_above_gate")
153 return {
154 "passed": not failures,
155 "failures": failures,
156 "near_misses": near_misses,
157 "thresholds": {
158 "model": model_name,
159 "head": head,
160 "require_quality_status": sorted(require_quality_status),
161 "min_net_sharpe": min_net_sharpe,
162 "max_annualized_turnover": max_annualized_turnover,
163 "min_capacity_usd": min_capacity_usd,
164 "min_walk_forward_windows": min_walk_forward_windows,
165 "max_window_sign_flip_fraction": max_window_sign_flip_fraction,
166 "missing_metrics_action": missing_metrics_action,
167 },
168 "observed": observed,
169 }
172def evaluate_validation_gate(
173 candidate_metrics: dict[str, Any],
174 candidate_report: dict[str, Any],
175 active_metrics: dict[str, Any],
176 active_report: dict[str, Any],
177 config: dict[str, Any],
178 *,
179 candidate_ranking_metrics: dict[str, Any] | None = None,
180) -> dict[str, Any]:
181 """Returns {passed, failures: [...], near_misses: [...], thresholds: {...}, observed: {...}}.
183 Checks, in order:
184 - candidate max_drawdown not worse (not more negative) than active
185 - candidate backtest sharpe >= min_sharpe
186 - candidate validation loss not worse than active's by more than
187 max_validation_loss_increase_ratio
188 - compute_overfitting_gap(candidate) <= max_train_backtest_balanced_accuracy_gap
189 - candidate backtest trade_count >= min_trade_count
190 - candidate backtest exposure_rate >= min_exposure_rate
191 - candidate backtest balanced_accuracy >= min_balanced_accuracy OR
192 candidate backtest mcc >= min_mcc (skill floor - see below)
193 - V5.1 Phase 4 (item 7): when candidate_ranking_metrics is provided
194 (keyword-only, default None -> zero change for every existing
195 caller/test) AND `config["ranking"]["enabled"]` is true,
196 evaluate_ranking_promotion_gate() also runs against it, and its
197 failures/near_misses are merged into this function's own lists
198 before the final passed = not failures - one candidate, one combined
199 verdict, rather than two gates a caller could forget to check both of.
200 """
201 min_sharpe = float(config.get("min_sharpe", 0.3))
202 max_validation_loss_increase_ratio = float(config.get("max_validation_loss_increase_ratio", 0.10))
203 max_gap = float(config.get("max_train_backtest_balanced_accuracy_gap", 0.20))
204 min_trade_count = int(config.get("min_trade_count", 0))
205 min_exposure_rate = float(config.get("min_exposure_rate", 0.0))
206 watchlist_margin = float(config.get("watchlist_margin", 0.03))
207 # Skill floor (development/Problems.md): every prior check here is
208 # Sharpe/drawdown/exposure-shaped, which a model with ZERO
209 # discriminative power can pass trivially during any backtest window
210 # with a sustained trend (a constant "always slightly bullish" output
211 # rides a bull market to a positive Sharpe with full exposure - exactly
212 # what the shipped baseline model did: MCC 0.066, balanced-accuracy
213 # 0.519, positive_rate 0.91, yet a real 20% backtest return). Requires
214 # EITHER metric to clear a coin-flip-or-better bar (an OR, not AND -
215 # balanced_accuracy and MCC can disagree at the margin, and a model
216 # need only demonstrate skill on one recognized axis).
217 min_balanced_accuracy = float(config.get("min_balanced_accuracy", 0.50))
218 min_mcc = float(config.get("min_mcc", 0.0))
220 candidate_backtest_strategy = candidate_report.get("backtest", {}).get("strategy", {})
221 active_backtest_strategy = active_report.get("backtest", {}).get("strategy", {})
223 def _finite_or_none(value):
224 # V5.4.7 (development/Problems.md #122): a bare NaN previously
225 # passed every gate here (`nan < x` and `nan > x` are both False)
226 # and a MISSING file degraded to 0.0 - which on the active side
227 # meant "perfect baseline" (deadlocking the pipeline: every real
228 # drawdown < 0.0 failed, any positive loss exceeded a zero cap)
229 # and on the candidate side meant a vacuous pass. Non-finite or
230 # missing required metrics now fail closed with an explicit name.
231 if value is None:
232 return None
233 try:
234 as_float = float(value)
235 except (TypeError, ValueError):
236 return None
237 return as_float if math.isfinite(as_float) else None
239 def _floor_metric(value, default=0.0):
240 as_float = _finite_or_none(value)
241 return default if as_float is None else as_float
243 candidate_drawdown = _finite_or_none(candidate_backtest_strategy.get("max_drawdown"))
244 active_drawdown = _finite_or_none(active_backtest_strategy.get("max_drawdown"))
245 candidate_sharpe = _finite_or_none(candidate_backtest_strategy.get("sharpe"))
247 candidate_validation_loss = _finite_or_none(candidate_metrics.get("validation", {}).get("loss"))
248 active_validation_loss = _finite_or_none(active_metrics.get("validation", {}).get("loss"))
249 max_allowed_validation_loss = (
250 None if active_validation_loss is None
251 else active_validation_loss * (1.0 + max_validation_loss_increase_ratio)
252 )
254 candidate_gap = _finite_or_none(compute_overfitting_gap(candidate_metrics))
256 candidate_trade_count = int(_floor_metric(candidate_report.get("backtest", {}).get("trade_count"), 0.0))
257 candidate_exposure_rate = _floor_metric(candidate_report.get("backtest", {}).get("exposure_rate"), 0.0)
258 candidate_backtest_balanced_accuracy = _floor_metric(
259 candidate_metrics.get("backtest", {}).get("balanced_accuracy"), 0.0
260 )
261 candidate_backtest_mcc = _floor_metric(candidate_metrics.get("backtest", {}).get("mcc"), 0.0)
263 failures: list[str] = []
264 near_misses: list[str] = []
266 # 0. Baseline presence (V5.4.7, Problems.md #122): without the ACTIVE
267 # side's own drawdown/validation loss there is nothing honest to
268 # compare against - fail closed naming the cause instead of silently
269 # comparing against fake-perfect zeros.
270 if active_drawdown is None or active_validation_loss is None:
271 failures.append("active_baseline_metrics_missing")
273 # 1. Drawdown not worse than active (drawdowns are <= 0; "worse" = more negative).
274 if candidate_drawdown is None:
275 failures.append("candidate_max_drawdown_missing_or_non_finite")
276 elif active_drawdown is not None and candidate_drawdown < active_drawdown:
277 failures.append("candidate_drawdown_worse_than_active")
278 elif active_drawdown is not None and candidate_drawdown < active_drawdown + abs(active_drawdown) * watchlist_margin:
279 near_misses.append("candidate_drawdown_near_active")
281 # 2. Sharpe above minimum.
282 if candidate_sharpe is None:
283 failures.append("candidate_sharpe_missing_or_non_finite")
284 elif candidate_sharpe < min_sharpe:
285 failures.append("candidate_sharpe_below_minimum")
286 elif candidate_sharpe < min_sharpe + watchlist_margin:
287 near_misses.append("candidate_sharpe_near_minimum")
289 # 3. Validation loss stable (not much worse than active).
290 if candidate_validation_loss is None:
291 failures.append("candidate_validation_loss_missing_or_non_finite")
292 elif max_allowed_validation_loss is not None and candidate_validation_loss > max_allowed_validation_loss:
293 failures.append("candidate_validation_loss_unstable")
294 elif max_allowed_validation_loss is not None and candidate_validation_loss > max_allowed_validation_loss * (1.0 - watchlist_margin):
295 near_misses.append("candidate_validation_loss_near_limit")
297 # 4. No obvious overfitting.
298 if candidate_gap is None:
299 failures.append("candidate_overfitting_gap_missing_or_non_finite")
300 elif candidate_gap > max_gap:
301 failures.append("candidate_overfitting_gap_too_large")
302 elif candidate_gap > max_gap - watchlist_margin:
303 near_misses.append("candidate_overfitting_gap_near_limit")
305 # 5. Enough trades.
306 if candidate_trade_count < min_trade_count:
307 failures.append("candidate_trade_count_too_low")
309 # 6. Enough exposure/signals.
310 if candidate_exposure_rate < min_exposure_rate:
311 failures.append("candidate_exposure_rate_too_low")
313 # 7. Skill floor - see min_balanced_accuracy/min_mcc's own comment above.
314 has_balanced_accuracy_skill = candidate_backtest_balanced_accuracy >= min_balanced_accuracy
315 has_mcc_skill = candidate_backtest_mcc >= min_mcc
316 if not (has_balanced_accuracy_skill or has_mcc_skill):
317 failures.append("candidate_no_demonstrated_skill")
318 elif not has_balanced_accuracy_skill or not has_mcc_skill:
319 near_misses.append("candidate_skill_marginal_on_one_metric")
321 # V5.1 Phase 4 (item 7) - see this function's own docstring above.
322 ranking_gate_result = None
323 ranking_config = config.get("ranking", {})
324 if candidate_ranking_metrics is not None and ranking_config.get("enabled", False):
325 ranking_gate_result = evaluate_ranking_promotion_gate(candidate_ranking_metrics, ranking_config)
326 failures.extend(ranking_gate_result["failures"])
327 near_misses.extend(ranking_gate_result["near_misses"])
329 passed = not failures
331 thresholds = {
332 "min_sharpe": min_sharpe,
333 "max_validation_loss_increase_ratio": max_validation_loss_increase_ratio,
334 "max_train_backtest_balanced_accuracy_gap": max_gap,
335 "min_trade_count": min_trade_count,
336 "min_exposure_rate": min_exposure_rate,
337 "watchlist_margin": watchlist_margin,
338 "min_balanced_accuracy": min_balanced_accuracy,
339 "min_mcc": min_mcc,
340 }
341 observed = {
342 "candidate_drawdown": candidate_drawdown,
343 "active_drawdown": active_drawdown,
344 "candidate_sharpe": candidate_sharpe,
345 "candidate_validation_loss": candidate_validation_loss,
346 "active_validation_loss": active_validation_loss,
347 "max_allowed_validation_loss": max_allowed_validation_loss,
348 "candidate_overfitting_gap": candidate_gap,
349 "candidate_trade_count": candidate_trade_count,
350 "candidate_exposure_rate": candidate_exposure_rate,
351 "candidate_backtest_balanced_accuracy": candidate_backtest_balanced_accuracy,
352 "candidate_backtest_mcc": candidate_backtest_mcc,
353 }
354 if ranking_gate_result is not None:
355 thresholds["ranking"] = ranking_gate_result["thresholds"]
356 observed["ranking"] = ranking_gate_result["observed"]
358 return {
359 "passed": passed,
360 "failures": failures,
361 "near_misses": near_misses,
362 "thresholds": thresholds,
363 "observed": observed,
364 }