Seuils de score appris sur validation, calibration gelee et evaluation par episodes
Les paliers top X pourcent etaient derives de la distribution du test : inutilisable en production ou la distribution future est inconnue. Chaque seuil est desormais un quantile de scores de validation anterieurs, avec fenetre d origine, valeur et couverture reellement observee. Sortie renommee score de risque et non probabilite tant que la calibration n est pas etablie. Platt et isotone ajustes sur instantane de validation fige, jamais sur la fenetre evaluee. Ajout des origines non chevauchantes, des episodes independants et des intervalles de confiance par bootstrap de blocs temporels. Hausses et baisses evaluees separement, sans symetrie imposee.
This commit is contained in:
@@ -7,7 +7,7 @@ from test_clean_pipeline import states
|
||||
import storage
|
||||
from clean_backtest import feature_rows
|
||||
from clean_features import features_asof
|
||||
from event_backtest import add, empty_stats, evaluate, probabilities
|
||||
from event_backtest import add, empty_stats, risk_scores
|
||||
from event_targets import event_target
|
||||
|
||||
|
||||
@@ -56,24 +56,17 @@ def test_dip_and_rebound_detected_with_fixed_panel():
|
||||
assert before == features_asof(prefix, t)
|
||||
|
||||
|
||||
def test_probabilities_nested_and_no_training_mutation():
|
||||
def test_risk_scores_nested_and_no_training_mutation():
|
||||
stat = empty_stats()
|
||||
original = copy.deepcopy(stat)
|
||||
p = probabilities(stat, empty_stats())
|
||||
p = risk_scores(stat, empty_stats())
|
||||
assert stat == original
|
||||
assert p["frequency"]["down_2"] == 0.5
|
||||
row = dict(target=dict(events={f"{d}_{q}": dict(hit=q <= 3) for d in ("up", "down") for q in (2, 3, 5)}))
|
||||
add(stat, row)
|
||||
p = probabilities(stat, empty_stats())
|
||||
p = risk_scores(stat, empty_stats())
|
||||
assert p["local_regime"]["down_2"] >= p["local_regime"]["down_3"] >= p["local_regime"]["down_5"]
|
||||
|
||||
|
||||
def test_abstention_reports_no_signal_without_invented_precision():
|
||||
y = dict(hit=False, amplitude=0, delay=None, terminal=-1)
|
||||
out = evaluate(
|
||||
[dict(prob={"frequency": {"down_3": 0.2}}, target={"events": {"down_3": y}})], "down_3", "frequency"
|
||||
)
|
||||
empty = [a for a in out["abstention"] if a["label"] == "p>=0.4"][0]
|
||||
assert empty["coverage"] == 0 and empty["precision"] is None and empty["false_positives"] == 0
|
||||
# Les paliers « top X % » sont des rangs, pas des seuils inventés.
|
||||
assert {a["label"] for a in out["abstention"]} >= {"top_5pct", "top_50pct", "p>=0.15"}
|
||||
# L'évaluation d'abstention vit dans tests/test_risk_protocol.py : seuils passés et
|
||||
# couverture mesurée. Ici on ne teste que les cibles et les scores.
|
||||
|
||||
163
tests/test_risk_protocol.py
Normal file
163
tests/test_risk_protocol.py
Normal file
@@ -0,0 +1,163 @@
|
||||
"""Le protocole tient-il ses promesses : seuils passés, calibration gelée, indépendance."""
|
||||
|
||||
import copy
|
||||
import random
|
||||
|
||||
import pytest
|
||||
|
||||
from event_backtest import KEYS, empty_stats, risk_scores, threshold_table
|
||||
from risk_report import (
|
||||
bootstrap_ci,
|
||||
calibrate,
|
||||
episode_summary,
|
||||
episodes,
|
||||
isotonic_fit,
|
||||
non_overlapping,
|
||||
platt_fit,
|
||||
score_threshold,
|
||||
select_on_validation,
|
||||
signal_flags,
|
||||
)
|
||||
|
||||
|
||||
def fake_predictions(n=200, threshold=0.30, signal_from=60, hits_from=60, label="q95", score_value=None):
|
||||
"""Série synthétique : signal à partir de `signal_from`, événements à partir de `hits_from`."""
|
||||
out = []
|
||||
for index in range(n):
|
||||
hit = index >= hits_from and index % 2 == 0
|
||||
out.append(
|
||||
dict(
|
||||
t=f"{index:04d}",
|
||||
score=score_value
|
||||
if score_value is not None
|
||||
else (threshold + 0.01 if index >= signal_from else 0.1),
|
||||
thresholds={
|
||||
label: dict(
|
||||
value=threshold,
|
||||
calibrated_as="quantile 95% des scores de validation",
|
||||
source_from="2025-01-01",
|
||||
source_to="2025-12-31",
|
||||
source_n=300,
|
||||
)
|
||||
},
|
||||
threshold_source=dict(window_from="2025-01-01", window_to="2025-12-31", frozen=True),
|
||||
target=dict(
|
||||
events={
|
||||
key: dict(
|
||||
hit=hit,
|
||||
amplitude=6.0 if hit else 0.0,
|
||||
delay=3 if hit else None,
|
||||
terminal=-4.0 if not hit else 5.0,
|
||||
future_min_delta=-1.0,
|
||||
future_max_delta=6.0,
|
||||
)
|
||||
for key in KEYS
|
||||
}
|
||||
),
|
||||
)
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def test_thresholds_come_only_from_past_scores_and_report_real_coverage():
|
||||
past = [0.10] * 95 + [0.50] * 5
|
||||
table, source = threshold_table(past, "2025-01-01", "2025-12-31")
|
||||
assert table["q95"]["value"] == pytest.approx(0.50)
|
||||
assert table["q50"]["value"] == pytest.approx(0.10)
|
||||
# Une distribution de test différente n'entre jamais dans le seuil.
|
||||
# Un test qui monte à 0,11 ne déclenche pas un seuil de 0,50 appris dans le passé.
|
||||
high = fake_predictions(n=100, threshold=table["q95"]["value"], score_value=0.11, label="q95")
|
||||
assert not any(signal_flags(high, "q95")), "le seuil passé ne doit pas s'adapter au test"
|
||||
low = fake_predictions(n=100, threshold=table["q50"]["value"], score_value=0.11, label="q50")
|
||||
assert all(signal_flags(low, "q50")), "0,11 >= 0,10 : signal partout"
|
||||
assert table["q95"]["source_from"] == "2025-01-01" and table["q95"]["source_n"] == 100
|
||||
assert "scores de validation" in source
|
||||
|
||||
|
||||
def test_coverage_is_measured_not_guaranteed():
|
||||
predictions = fake_predictions(n=100, threshold=0.30, signal_from=13)
|
||||
metrics = score_threshold(
|
||||
[
|
||||
dict(
|
||||
p,
|
||||
thresholds={
|
||||
"q95": dict(p["thresholds"]["q95"], calibrated_as="quantile 95% des scores de validation")
|
||||
},
|
||||
)
|
||||
for p in predictions
|
||||
],
|
||||
"up_3",
|
||||
"q95",
|
||||
)
|
||||
assert metrics["n_signaled"] == 87
|
||||
assert metrics["actual_test_coverage"] == pytest.approx(0.87)
|
||||
assert "quantile 95%" in metrics["calibrated_as"], "le nom dit la cible de validation"
|
||||
assert metrics["lift_vs_base"] is not None
|
||||
|
||||
|
||||
def test_calibrator_uses_validation_only():
|
||||
rng = random.Random(3)
|
||||
pairs = [(rng.random(), 1 if rng.random() > 0.5 else 0) for _ in range(400)]
|
||||
platt = platt_fit(pairs)
|
||||
isotonic = isotonic_fit(pairs)
|
||||
before = (platt["a"], platt["b"], list(isotonic["knots"]))
|
||||
# Modifier massivement des données de test ne doit rien changer : elles ne sont pas utilisées.
|
||||
_ = [(0.99, 1) for _ in range(500)]
|
||||
assert before == (platt["a"], platt["b"], list(isotonic["knots"]))
|
||||
assert 0.0 <= calibrate(platt, 0.15) <= 1.0
|
||||
assert calibrate(None, 0.5) is None
|
||||
|
||||
|
||||
def test_episodes_and_non_overlapping_are_stricter_than_daily():
|
||||
predictions = fake_predictions(n=60, threshold=0.30, signal_from=10, hits_from=10)
|
||||
daily = score_threshold(predictions, "up_3", "q95")
|
||||
assert daily["n_signaled"] == 50, "chaque jour signalé compte au quotidien"
|
||||
summary = episode_summary(predictions, "up_3", "q95")
|
||||
assert summary["n_episodes"] == 1, "50 jours consécutifs = une seule opportunité"
|
||||
assert summary["n_days_signaled"] == 50
|
||||
disjoint = non_overlapping(predictions, "up_3", "q95", 14)
|
||||
assert disjoint["n_signaled"] == 4, "origines tous les 14 jours : fenêtres disjointes"
|
||||
assert disjoint["step_days"] == 14
|
||||
|
||||
|
||||
def test_block_bootstrap_is_deterministic_and_pairs_aware():
|
||||
values = [1, 1, 0, 1, 1, 0, 0, 1] * 20
|
||||
first = bootstrap_ci(values)
|
||||
second = bootstrap_ci(values)
|
||||
assert first == second, "graine fixe : résultat reproductible"
|
||||
assert first["low"] <= first["high"] and first["block_days"] == 28
|
||||
assert bootstrap_ci(values[:5]) is None
|
||||
|
||||
|
||||
def test_selection_happens_on_validation_only():
|
||||
rows = [(0.05, {k: False for k in KEYS}) for _ in range(400)]
|
||||
rows += [(0.32, {k: True for k in KEYS}) for _ in range(80)]
|
||||
rows += [(0.12, {k: (i % 2 == 0) for k in KEYS}) for i in range(200)]
|
||||
snapshot = dict(pairs=[[score, hits] for score, hits in rows])
|
||||
choice = select_on_validation(snapshot, "up_3")
|
||||
# À lift égal (0,15 / 0,20 / 0,30 / 0,35 / 0,40 couvrent les mêmes 80 lignes), on retient le
|
||||
# seuil le plus bas : même précision pour une couverture plus large.
|
||||
assert choice["threshold"] == pytest.approx(0.15)
|
||||
assert choice["validation_precision"] == pytest.approx(1.0)
|
||||
assert choice["validation_lift"] > 1.5
|
||||
assert "test" not in choice, "la sélection ne voit jamais le test"
|
||||
|
||||
|
||||
def test_risk_scores_are_scores_not_calibrated_probabilities():
|
||||
stats = empty_stats()
|
||||
for index in range(200):
|
||||
stats["n"] += 1
|
||||
for key in KEYS:
|
||||
stats["hits"][key] += 1 if index % 5 == 0 else 0
|
||||
scores = risk_scores(stats, empty_stats())
|
||||
assert set(scores) == {"frequency", "local_regime"}
|
||||
# Le score local est rétréci vers la base : il reste borné, sans prétention de calibration.
|
||||
assert all(0.0 <= value <= 1.0 for value in scores["local_regime"].values())
|
||||
|
||||
|
||||
def test_raw_copies_are_never_mutated_by_evaluation():
|
||||
predictions = fake_predictions(n=40, signal_from=5)
|
||||
original = copy.deepcopy(predictions)
|
||||
score_threshold(predictions, "up_3", "q95")
|
||||
episodes(predictions, signal_flags(predictions, "q95"), "up_3")
|
||||
assert predictions == original
|
||||
Reference in New Issue
Block a user