157 lines
6.7 KiB
Python
157 lines
6.7 KiB
Python
"""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
|
|
value = (
|
|
score_value if score_value is not None else (threshold + 0.01 if index >= signal_from else 0.1)
|
|
)
|
|
out.append(
|
|
dict(
|
|
t=f"{index:04d}",
|
|
score={key: value for key in KEYS},
|
|
thresholds={
|
|
key: {
|
|
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,
|
|
)
|
|
}
|
|
for key in KEYS
|
|
},
|
|
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 = {key: [0.10] * 95 + [0.50] * 5 for key in KEYS}
|
|
table, source = threshold_table(past, "2025-01-01", "2025-12-31")
|
|
# Rang supérieur : q95 = 0,50 (les 5 % les plus hauts), q50 = 0,10.
|
|
assert table["up_3"]["q95"]["value"] == pytest.approx(0.50)
|
|
assert table["up_3"]["q50"]["value"] == pytest.approx(0.10)
|
|
assert table["down_3"]["q95"]["source_n"] == 100
|
|
assert "scores de validation" in source
|
|
# 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=0.50, score_value=0.11, label="q95")
|
|
assert not any(signal_flags(high, "up_3", "q95")), "le seuil passé ne doit pas s'adapter au test"
|
|
low = fake_predictions(n=100, threshold=0.10, score_value=0.11, label="q50")
|
|
assert all(signal_flags(low, "up_3", "q50")), "0,11 >= 0,10 : signal partout"
|
|
|
|
|
|
def test_coverage_is_measured_not_guaranteed():
|
|
predictions = fake_predictions(n=100, threshold=0.30, signal_from=13)
|
|
metrics = score_threshold(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 libellé dit la cible de validation"
|
|
assert metrics["threshold_source_period"] == "2025-01-01 → 2025-12-31"
|
|
assert metrics["lift_vs_base"] is not None and metrics["precision_ci"] 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
|
|
assert summary["mean_episode_length_days"] == pytest.approx(50.0)
|
|
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)
|
|
assert first == bootstrap_ci(values), "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=[[{k: score for k in KEYS}, 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"}
|
|
assert set(scores["local_regime"]) == set(KEYS), "un score par événement"
|
|
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, "up_3", "q95"), "up_3")
|
|
assert predictions == original
|