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:
@@ -1,39 +0,0 @@
|
|||||||
"""Ré-analyse des prédictions événementielles enregistrées : aucun recalcul de modèle."""
|
|
||||||
|
|
||||||
import json
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
from event_backtest import evaluate
|
|
||||||
|
|
||||||
root = Path("reports")
|
|
||||||
report = json.loads((root / "event-results.json").read_text())
|
|
||||||
for e in report["evaluations"]:
|
|
||||||
path = root / f"event-{e['fuel']}-{e['horizon']}-{e['mode']}-predictions.json"
|
|
||||||
preds = json.loads(path.read_text())
|
|
||||||
for p in preds:
|
|
||||||
assert all(p["max_train_label"] <= p["t"] for p in preds)
|
|
||||||
assert p["train_end"] < p["t"]
|
|
||||||
e["metrics"] = {m: evaluate(preds, e["event"], m) for m in ("frequency", "local_regime")}
|
|
||||||
(root / "event-results.json").write_text(json.dumps(report, ensure_ascii=False, indent=2))
|
|
||||||
lines = [
|
|
||||||
"# Probabilités événementielles locales — expérimental non validé",
|
|
||||||
"",
|
|
||||||
report["disclaimer"],
|
|
||||||
"",
|
|
||||||
"Paliers : « top X % » = seuls les X % de jours les plus probables émettent un signal.",
|
|
||||||
"Aucun ajout amont, aucun usage dans le conseil réel.",
|
|
||||||
"\n## Couverture",
|
|
||||||
]
|
|
||||||
lines += ["- " + f + " : " + json.dumps(c, ensure_ascii=False) for f, c in report["coverage"].items()]
|
|
||||||
for e in report["evaluations"]:
|
|
||||||
m = e["metrics"]["local_regime"]
|
|
||||||
if not m:
|
|
||||||
continue
|
|
||||||
lines.append(
|
|
||||||
f"\n## {e['fuel']} J+{e['horizon']} {e['mode']} {e['event']} — n={m['n']} base={m['event_rate']:.3f} brier={m['brier']:.4f}"
|
|
||||||
)
|
|
||||||
lines.append("Calibration : " + json.dumps(m["calibration"], ensure_ascii=False))
|
|
||||||
for a in m["abstention"]:
|
|
||||||
lines.append("- " + json.dumps(a, ensure_ascii=False))
|
|
||||||
(root / "event-report.md").write_text("\n".join(lines))
|
|
||||||
print(json.dumps({"evaluations": len(report["evaluations"])}, ensure_ascii=False))
|
|
||||||
@@ -5,10 +5,10 @@ Aucun réglage retenu d'après 2026. Aucun usage dans le conseil réel.
|
|||||||
|
|
||||||
import copy
|
import copy
|
||||||
import json
|
import json
|
||||||
|
import math
|
||||||
from collections import Counter
|
from collections import Counter
|
||||||
from datetime import date
|
from datetime import date
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from statistics import fmean
|
|
||||||
|
|
||||||
from clean_backtest import feature_rows, states_for
|
from clean_backtest import feature_rows, states_for
|
||||||
from event_targets import event_target
|
from event_targets import event_target
|
||||||
@@ -16,8 +16,14 @@ from event_targets import event_target
|
|||||||
KEYS = [f"{d}_{q}" for d in ("up", "down") for q in (2, 3, 5)]
|
KEYS = [f"{d}_{q}" for d in ("up", "down") for q in (2, 3, 5)]
|
||||||
# Paliers d'abstention RELATIFS : les événements sont rares (3-31 %), un seuil absolu de 0,5
|
# Paliers d'abstention RELATIFS : les événements sont rares (3-31 %), un seuil absolu de 0,5
|
||||||
# ne signalerait jamais. On mesure donc « signal seulement les X % de jours les plus probables ».
|
# ne signalerait jamais. On mesure donc « signal seulement les X % de jours les plus probables ».
|
||||||
TIERS = (0.05, 0.10, 0.20, 0.30, 0.50, 0.100)
|
# Un seuil appris sur la distribution du test n'est pas utilisable : au jour J, la distribution
|
||||||
ABSOLUTE_THRESHOLDS = (0.15, 0.20, 0.25, 0.30, 0.40)
|
# des scores futurs est inconnue. Chaque seuil est donc un quantile des scores **de validation
|
||||||
|
# antérieurs**, appliqué tel quel ensuite. La couverture réelle sur le test est mesurée, pas
|
||||||
|
# garantie : elle peut valoir 13 % là où la validation en annonçait 5 %, et c'est une information.
|
||||||
|
QUANTILES = (0.95, 0.90, 0.80, 0.70, 0.50)
|
||||||
|
SCORE_GRID = (0.10, 0.15, 0.20, 0.25, 0.30, 0.35, 0.40)
|
||||||
|
CALIBRATION_REFRESH_DAYS = 90
|
||||||
|
MIN_MATURED_LABELS = 365
|
||||||
|
|
||||||
|
|
||||||
def regime(x):
|
def regime(x):
|
||||||
@@ -36,69 +42,45 @@ def add(stats, row):
|
|||||||
stats["hits"][k] += row["target"]["events"][k]["hit"]
|
stats["hits"][k] += row["target"]["events"][k]["hit"]
|
||||||
|
|
||||||
|
|
||||||
def probabilities(global_stats, local_stats):
|
def threshold_table(past_scores, source_from, source_to):
|
||||||
|
"""Seuils déduits exclusivement de scores passés, avec leur fenêtre d'origine."""
|
||||||
|
values = sorted(past_scores)
|
||||||
|
if len(values) < 60:
|
||||||
|
return None, "moins de 60 scores de validation : aucun seuil publié"
|
||||||
|
out = {}
|
||||||
|
for quantile in QUANTILES:
|
||||||
|
# Rang « supérieur » : le seuil est la plus petite valeur telle que la part de scores
|
||||||
|
# au-dessus soit au plus (1 - quantile). Avec beaucoup d'égalités, un rang par
|
||||||
|
# interpolation donnerait un seuil qui couvre 100 % des cas.
|
||||||
|
rank = min(len(values) - 1, math.ceil(quantile * (len(values) - 1)))
|
||||||
|
out[f"q{int(quantile * 100)}"] = dict(
|
||||||
|
value=round(values[rank], 6),
|
||||||
|
calibrated_as=f"quantile {quantile:.0%} des scores de validation",
|
||||||
|
source_from=source_from,
|
||||||
|
source_to=source_to,
|
||||||
|
source_n=len(values),
|
||||||
|
)
|
||||||
|
for threshold in SCORE_GRID:
|
||||||
|
out[f"score>={threshold:.2f}"] = dict(
|
||||||
|
value=threshold,
|
||||||
|
calibrated_as="seuil absolu prédéfini",
|
||||||
|
source_from=source_from,
|
||||||
|
source_to=source_to,
|
||||||
|
source_n=len(values),
|
||||||
|
)
|
||||||
|
return out, f"{len(values)} scores de validation de {source_from} à {source_to}"
|
||||||
|
|
||||||
|
|
||||||
|
def risk_scores(global_stats, local_stats):
|
||||||
# Lissage bêta(1,1), puis rétrécissement local vers la base avec 30 pseudo-observations.
|
# Lissage bêta(1,1), puis rétrécissement local vers la base avec 30 pseudo-observations.
|
||||||
base = {k: (global_stats["hits"][k] + 1) / (global_stats["n"] + 2) for k in KEYS}
|
base = {k: (global_stats["hits"][k] + 1) / (global_stats["n"] + 2) for k in KEYS}
|
||||||
local = {k: (local_stats["hits"][k] + 30 * base[k]) / (local_stats["n"] + 30) for k in KEYS}
|
local = {k: (local_stats["hits"][k] + 30 * base[k]) / (local_stats["n"] + 30) for k in KEYS}
|
||||||
|
# Score de risque : rang relatif, PAS une probabilité calibrée (voir risk-report.md).
|
||||||
return {"frequency": base, "local_regime": local}
|
return {"frequency": base, "local_regime": local}
|
||||||
|
|
||||||
|
|
||||||
def evaluate(predictions, key, model):
|
# L'évaluation décisionnelle vit dans risk_report.py : seuils passés, calibration passée,
|
||||||
pairs = [(p["prob"][model][key], p["target"]["events"][key]) for p in predictions]
|
# épisodes et intervalles de confiance. Un évaluateur concurrent ici prêtait à confusion.
|
||||||
if not pairs:
|
|
||||||
return None
|
|
||||||
out = dict(
|
|
||||||
n=len(pairs),
|
|
||||||
event_rate=fmean(y["hit"] for _, y in pairs),
|
|
||||||
brier=fmean((prob - y["hit"]) ** 2 for prob, y in pairs),
|
|
||||||
calibration=[],
|
|
||||||
abstention=[],
|
|
||||||
)
|
|
||||||
for low in (0, 0.2, 0.4, 0.6, 0.8):
|
|
||||||
bucket = [(p, y) for p, y in pairs if low <= p < low + 0.2 or low == 0.8 and p == 1]
|
|
||||||
if bucket:
|
|
||||||
out["calibration"].append(
|
|
||||||
dict(
|
|
||||||
low=low,
|
|
||||||
n=len(bucket),
|
|
||||||
predicted=fmean(p for p, y in bucket),
|
|
||||||
observed=fmean(y["hit"] for p, y in bucket),
|
|
||||||
)
|
|
||||||
)
|
|
||||||
total_hits = sum(y["hit"] for p, y in pairs)
|
|
||||||
ranked = sorted(p for p, _y in pairs)
|
|
||||||
tiers = [(f"top_{int(t * 100)}pct", ranked[max(0, int(len(ranked) * (1 - t)))]) for t in TIERS]
|
|
||||||
tiers += [(f"p>={t}", t) for t in ABSOLUTE_THRESHOLDS]
|
|
||||||
for label, threshold in tiers:
|
|
||||||
signaled = [(p, y) for p, y in pairs if p >= threshold]
|
|
||||||
correct = [y for p, y in signaled if y["hit"]]
|
|
||||||
false = [y for p, y in signaled if not y["hit"]]
|
|
||||||
|
|
||||||
def avg(seq):
|
|
||||||
return fmean(seq) if seq else None
|
|
||||||
|
|
||||||
out["abstention"].append(
|
|
||||||
dict(
|
|
||||||
label=label,
|
|
||||||
threshold=round(threshold, 4),
|
|
||||||
n=len(signaled),
|
|
||||||
coverage=len(signaled) / len(pairs),
|
|
||||||
precision=len(correct) / len(signaled) if signaled else None,
|
|
||||||
recall=len(correct) / total_hits if total_hits else None,
|
|
||||||
false_positives=len(false),
|
|
||||||
false_positive_rate=len(false) / (len(pairs) - total_hits)
|
|
||||||
if len(pairs) > total_hits
|
|
||||||
else None,
|
|
||||||
mean_predicted=avg([p for p, y in signaled]),
|
|
||||||
opportunity_true_cents=avg([y["amplitude"] for y in correct]),
|
|
||||||
delay_true_days=avg([y["delay"] for y in correct]),
|
|
||||||
terminal_move_true_cents=avg([y["terminal"] for y in correct]),
|
|
||||||
terminal_move_false_cents=avg([y["terminal"] for y in false]),
|
|
||||||
adverse_terminal_false_cents=avg([max(0, -y["terminal"]) for y in false]),
|
|
||||||
economic_gain_eur=None,
|
|
||||||
)
|
|
||||||
)
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
def coverage_audit(states, features):
|
def coverage_audit(states, features):
|
||||||
@@ -135,8 +117,7 @@ def run():
|
|||||||
report = dict(
|
report = dict(
|
||||||
status="experimental_no_production",
|
status="experimental_no_production",
|
||||||
coverage={},
|
coverage={},
|
||||||
evaluations=[],
|
thresholds=dict(quantiles=QUANTILES, absolute=SCORE_GRID),
|
||||||
thresholds=TIERS + ABSOLUTE_THRESHOLDS,
|
|
||||||
external_features=[],
|
external_features=[],
|
||||||
disclaimer="Opportunités en c/L observées a posteriori, PAS gains véhicule exécutables. Pas de choix du meilleur seuil sur le test.",
|
disclaimer="Opportunités en c/L observées a posteriori, PAS gains véhicule exécutables. Pas de choix du meilleur seuil sur le test.",
|
||||||
)
|
)
|
||||||
@@ -160,22 +141,72 @@ def run():
|
|||||||
groups = {}
|
groups = {}
|
||||||
cursor = 0
|
cursor = 0
|
||||||
predictions = []
|
predictions = []
|
||||||
|
past_scores = []
|
||||||
|
snapshots = {}
|
||||||
|
snapshot_id = None
|
||||||
|
last_refresh = None
|
||||||
|
frozen = None
|
||||||
for row in rows:
|
for row in rows:
|
||||||
if not start <= row["t"] <= end:
|
|
||||||
continue
|
|
||||||
cutoff = row["t"] if mode == "rolling" else start
|
cutoff = row["t"] if mode == "rolling" else start
|
||||||
while cursor < len(rows) and rows[cursor]["target"]["available_at"] < cutoff:
|
while cursor < len(rows) and rows[cursor]["target"]["available_at"] < cutoff:
|
||||||
old = rows[cursor]
|
old = rows[cursor]
|
||||||
add(global_stats, old)
|
add(global_stats, old)
|
||||||
add(groups.setdefault(old["regime"], empty_stats()), old)
|
add(groups.setdefault(old["regime"], empty_stats()), old)
|
||||||
cursor += 1
|
cursor += 1
|
||||||
if global_stats["n"] < 365:
|
if global_stats["n"] < MIN_MATURED_LABELS:
|
||||||
continue
|
continue
|
||||||
|
score = risk_scores(global_stats, groups.get(row["regime"], empty_stats()))
|
||||||
|
row["score"] = score
|
||||||
|
if row["t"] < start:
|
||||||
|
# Préfixe hors fenêtre : sert uniquement d'historique de scores.
|
||||||
|
past_scores.append(score["local_regime"])
|
||||||
|
continue
|
||||||
|
if row["t"] > end:
|
||||||
|
break
|
||||||
|
window_from, window_to = rows[0]["t"], rows[cursor - 1]["t"]
|
||||||
|
if mode == "rolling":
|
||||||
|
thresholds, source = threshold_table(past_scores, window_from, window_to)
|
||||||
|
else:
|
||||||
|
if frozen is None:
|
||||||
|
frozen = threshold_table(past_scores, window_from, window_to)
|
||||||
|
thresholds, source = frozen
|
||||||
|
if thresholds is None:
|
||||||
|
continue
|
||||||
|
day = date.fromisoformat(row["t"])
|
||||||
|
need_refresh = last_refresh is None or (
|
||||||
|
mode == "rolling" and (day - last_refresh).days >= CALIBRATION_REFRESH_DAYS
|
||||||
|
)
|
||||||
|
if need_refresh:
|
||||||
|
snapshot_id = f"r{len(snapshots)}"
|
||||||
|
first = max(0, cursor - 730)
|
||||||
|
snapshots[snapshot_id] = dict(
|
||||||
|
from_day=rows[first]["t"],
|
||||||
|
to_day=rows[cursor - 1]["t"],
|
||||||
|
n=cursor - first,
|
||||||
|
pairs=[
|
||||||
|
[
|
||||||
|
round(rows[i]["score"]["local_regime"], 6),
|
||||||
|
{k: rows[i]["target"]["events"][k]["hit"] for k in KEYS},
|
||||||
|
]
|
||||||
|
for i in range(first, cursor)
|
||||||
|
],
|
||||||
|
)
|
||||||
|
last_refresh = day
|
||||||
assert all(m["max_available_at"] <= row["t"] for m in row["features"]["manifest"])
|
assert all(m["max_available_at"] <= row["t"] for m in row["features"]["manifest"])
|
||||||
predictions.append(
|
predictions.append(
|
||||||
dict(
|
dict(
|
||||||
t=row["t"],
|
t=row["t"],
|
||||||
prob=probabilities(global_stats, groups.get(row["regime"], empty_stats())),
|
score=score["local_regime"],
|
||||||
|
score_scale="rang relatif de fréquence passée, non calibré",
|
||||||
|
prob={"local_regime": score["local_regime"], "frequency": score["frequency"]},
|
||||||
|
thresholds=thresholds,
|
||||||
|
threshold_source=dict(
|
||||||
|
window_from=window_from,
|
||||||
|
window_to=window_to,
|
||||||
|
detail=source,
|
||||||
|
frozen=mode != "rolling",
|
||||||
|
),
|
||||||
|
calibration_refresh=snapshot_id,
|
||||||
target=row["target"],
|
target=row["target"],
|
||||||
train_n=global_stats["n"],
|
train_n=global_stats["n"],
|
||||||
train_start=rows[0]["t"],
|
train_start=rows[0]["t"],
|
||||||
@@ -184,20 +215,8 @@ def run():
|
|||||||
manifest=copy.deepcopy(row["features"]["manifest"]),
|
manifest=copy.deepcopy(row["features"]["manifest"]),
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
for key in KEYS:
|
(output / f"risk-calibration-{fuel}-{horizon}-{mode}.json").write_text(
|
||||||
report["evaluations"].append(
|
json.dumps(snapshots, ensure_ascii=False)
|
||||||
dict(
|
|
||||||
fuel=fuel,
|
|
||||||
horizon=horizon,
|
|
||||||
mode=mode,
|
|
||||||
event=key,
|
|
||||||
test_start=predictions[0]["t"] if predictions else None,
|
|
||||||
test_end=predictions[-1]["t"] if predictions else None,
|
|
||||||
metrics={
|
|
||||||
model: evaluate(predictions, key, model)
|
|
||||||
for model in ("frequency", "local_regime")
|
|
||||||
},
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
(output / f"event-{fuel}-{horizon}-{mode}-predictions.json").write_text(
|
(output / f"event-{fuel}-{horizon}-{mode}-predictions.json").write_text(
|
||||||
json.dumps(predictions, ensure_ascii=False)
|
json.dumps(predictions, ensure_ascii=False)
|
||||||
@@ -205,7 +224,8 @@ def run():
|
|||||||
print(fuel, horizon, "terminé", flush=True)
|
print(fuel, horizon, "terminé", flush=True)
|
||||||
(output / "event-results.json").write_text(json.dumps(report, ensure_ascii=False, indent=2))
|
(output / "event-results.json").write_text(json.dumps(report, ensure_ascii=False, indent=2))
|
||||||
lines = [
|
lines = [
|
||||||
"# Probabilités événementielles locales — expérimental non validé",
|
"Les scores sont des RANGS de fréquence passée, pas des probabilités calibrées.",
|
||||||
|
"# Scores de risque événementiels — expérimental non validé",
|
||||||
"",
|
"",
|
||||||
report["disclaimer"],
|
report["disclaimer"],
|
||||||
"Fréquence historique contre régime local discret prédéfini. Aucun hyperparamètre sélectionné sur 2026.",
|
"Fréquence historique contre régime local discret prédéfini. Aucun hyperparamètre sélectionné sur 2026.",
|
||||||
|
|||||||
437
risk_report.py
Normal file
437
risk_report.py
Normal file
@@ -0,0 +1,437 @@
|
|||||||
|
"""Évaluation décisionnelle des scores de risque.
|
||||||
|
|
||||||
|
Trois exigences tenues ici :
|
||||||
|
|
||||||
|
- **seuils passés uniquement** : chaque seuil vient de `threshold_source` (fenêtre de validation
|
||||||
|
antérieure) ; la couverture annoncée sur le test est mesurée, pas garantie ;
|
||||||
|
- **calibration ajustée sur validation passée seulement** : Platt et isotone sont appris sur un
|
||||||
|
instantané `risk-calibration-*` figé (jamais sur la fenêtre évaluée) ;
|
||||||
|
- **indépendance** : en plus du quotidien, évaluation sur origines non chevauchantes et par
|
||||||
|
épisodes, avec intervalles de confiance par bootstrap par blocs temporels.
|
||||||
|
|
||||||
|
Aucun de ces résultats n'alimente le conseil réel.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import math
|
||||||
|
import random
|
||||||
|
from pathlib import Path
|
||||||
|
from statistics import fmean
|
||||||
|
|
||||||
|
KEYS = [f"{d}_{q}" for d in ("up", "down") for q in (2, 3, 5)]
|
||||||
|
BIN_BOUNDS = (0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 1.01)
|
||||||
|
DEFAULT_BLOCK = 28
|
||||||
|
BOOTSTRAP_RESAMPLES = 400
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------ calibration (validation seule)
|
||||||
|
|
||||||
|
|
||||||
|
def platt_fit(pairs):
|
||||||
|
"""Régression logistique 1D sur (score, événement) : apprise sur validation uniquement."""
|
||||||
|
if len(pairs) < 50:
|
||||||
|
return None
|
||||||
|
a, b = 0.0, 1.0
|
||||||
|
for _ in range(60):
|
||||||
|
ga = gb = 0.0
|
||||||
|
haa = hab = hbb = 0.0
|
||||||
|
for score, hit in pairs:
|
||||||
|
z = a + b * score
|
||||||
|
p = 1 / (1 + math.exp(-max(-30.0, min(30.0, z))))
|
||||||
|
d = p - hit
|
||||||
|
ga += d
|
||||||
|
gb += d * score
|
||||||
|
w = max(1e-9, p * (1 - p))
|
||||||
|
haa += w
|
||||||
|
hab += w * score
|
||||||
|
hbb += w * score * score
|
||||||
|
haa += 1e-6
|
||||||
|
hbb += 1e-6
|
||||||
|
det = haa * hbb - hab * hab
|
||||||
|
if abs(det) < 1e-12:
|
||||||
|
break
|
||||||
|
da = (hbb * ga - hab * gb) / det
|
||||||
|
db = (-hab * ga + haa * gb) / det
|
||||||
|
a -= da
|
||||||
|
b -= db
|
||||||
|
if abs(da) + abs(db) < 1e-10:
|
||||||
|
break
|
||||||
|
return dict(kind="platt", a=a, b=b)
|
||||||
|
|
||||||
|
|
||||||
|
def isotonic_fit(pairs):
|
||||||
|
"""Régression isotone (PAV) sur validation uniquement."""
|
||||||
|
if len(pairs) < 50:
|
||||||
|
return None
|
||||||
|
ordered = sorted(pairs)
|
||||||
|
levels = [[score, hit, 1] for score, hit in ordered]
|
||||||
|
blocks = []
|
||||||
|
for level in levels:
|
||||||
|
blocks.append(level)
|
||||||
|
while len(blocks) > 1 and blocks[-2][1] / blocks[-2][2] > blocks[-1][1] / blocks[-1][2]:
|
||||||
|
last = blocks.pop()
|
||||||
|
blocks[-1][0] = last[0]
|
||||||
|
blocks[-1][1] += last[1]
|
||||||
|
blocks[-1][2] += last[2]
|
||||||
|
return dict(kind="isotonic", knots=[(b[0], b[1] / b[2]) for b in blocks])
|
||||||
|
|
||||||
|
|
||||||
|
def calibrate(model, score):
|
||||||
|
if not model:
|
||||||
|
return None
|
||||||
|
if model["kind"] == "platt":
|
||||||
|
return 1 / (1 + math.exp(-max(-30.0, min(30.0, model["a"] + model["b"] * score))))
|
||||||
|
value = model["knots"][0][1]
|
||||||
|
for limit, level in model["knots"]:
|
||||||
|
if score <= limit:
|
||||||
|
value = level
|
||||||
|
break
|
||||||
|
value = level
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def brier(pairs):
|
||||||
|
return fmean((p - y) ** 2 for p, y in pairs) if pairs else None
|
||||||
|
|
||||||
|
|
||||||
|
def reliability(pairs):
|
||||||
|
out = []
|
||||||
|
for low, high in zip(BIN_BOUNDS, BIN_BOUNDS[1:], strict=False):
|
||||||
|
bucket = [(p, y) for p, y in pairs if low <= p < high]
|
||||||
|
if bucket:
|
||||||
|
out.append(
|
||||||
|
dict(
|
||||||
|
range=f"[{low:.2f},{high:.2f}[",
|
||||||
|
n=len(bucket),
|
||||||
|
mean_score=round(fmean(p for p, _ in bucket), 4),
|
||||||
|
observed_rate=round(fmean(y for _, y in bucket), 4),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------ intervalles de confiance
|
||||||
|
|
||||||
|
|
||||||
|
def bootstrap_ci(values, block=DEFAULT_BLOCK, resamples=BOOTSTRAP_RESAMPLES, seed=7):
|
||||||
|
"""Bootstrap par blocs temporels : respecte l'autocorrélation des séries de prix."""
|
||||||
|
if len(values) < 10:
|
||||||
|
return None
|
||||||
|
rng = random.Random(seed)
|
||||||
|
blocks = [values[i : i + block] for i in range(0, len(values), block)]
|
||||||
|
means = []
|
||||||
|
for _ in range(resamples):
|
||||||
|
drawn = []
|
||||||
|
for _ in range(len(blocks)):
|
||||||
|
drawn.extend(blocks[rng.randrange(len(blocks))])
|
||||||
|
if drawn:
|
||||||
|
means.append(fmean(drawn))
|
||||||
|
means.sort()
|
||||||
|
return dict(
|
||||||
|
low=round(means[int(0.025 * (len(means) - 1))], 4),
|
||||||
|
high=round(means[int(0.975 * (len(means) - 1))], 4),
|
||||||
|
block_days=block,
|
||||||
|
resamples=resamples,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------ signaux et épisodes
|
||||||
|
|
||||||
|
|
||||||
|
def signal_flags(predictions, label):
|
||||||
|
"""Signal = score >= seuil du jour, seuil lui-même issu du passé."""
|
||||||
|
return [p["score"] >= p["thresholds"][label]["value"] for p in predictions]
|
||||||
|
|
||||||
|
|
||||||
|
def episodes(predictions, flags, key):
|
||||||
|
"""Regroupe les signaux consécutifs : deux jours d'affilée = une seule opportunité."""
|
||||||
|
out = []
|
||||||
|
current = None
|
||||||
|
for prediction, flagged in zip(predictions, flags, strict=False):
|
||||||
|
if flagged:
|
||||||
|
if current is None:
|
||||||
|
current = dict(start=prediction["t"], days=1, hits=0, best=None)
|
||||||
|
else:
|
||||||
|
current["days"] += 1
|
||||||
|
event = prediction["target"]["events"][key]
|
||||||
|
current["hits"] += 1 if event["hit"] else 0
|
||||||
|
if event["hit"]:
|
||||||
|
values = [event["amplitude"], event["delay"]]
|
||||||
|
if current["best"] is None or (values[0] or 0) > current["best"][0]:
|
||||||
|
current["best"] = values
|
||||||
|
elif current is not None:
|
||||||
|
out.append(current)
|
||||||
|
current = None
|
||||||
|
if current is not None:
|
||||||
|
out.append(current)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def score_threshold(predictions, key, label, flags=None):
|
||||||
|
"""Métriques d'un seuil : couverture réelle, précision, lift, rappel, amplitudes, IC."""
|
||||||
|
flags = flags if flags is not None else signal_flags(predictions, label)
|
||||||
|
rows = [(p, f) for p, f in zip(predictions, flags, strict=False)]
|
||||||
|
base = fmean(p["target"]["events"][key]["hit"] for p, _ in rows)
|
||||||
|
signaled = [p["target"]["events"][key] for p, flag in rows if flag]
|
||||||
|
correct = [event for event in signaled if event["hit"]]
|
||||||
|
wrong = [event for event in signaled if not event["hit"]]
|
||||||
|
total_hits = sum(1 for p, _flag in rows if p["target"]["events"][key]["hit"])
|
||||||
|
hits_vector = [1 if event["hit"] else 0 for event in signaled]
|
||||||
|
precision = len(correct) / len(signaled) if signaled else None
|
||||||
|
spec = predictions[0]["thresholds"][label]
|
||||||
|
return dict(
|
||||||
|
label=label,
|
||||||
|
threshold_value=spec["value"],
|
||||||
|
calibrated_as=spec["calibrated_as"],
|
||||||
|
threshold_source_period=f"{spec['source_from']} → {spec['source_to']}",
|
||||||
|
threshold_source_n=spec["source_n"],
|
||||||
|
n_days=len(rows),
|
||||||
|
n_signaled=len(signaled),
|
||||||
|
actual_test_coverage=round(len(signaled) / len(rows), 4) if rows else None,
|
||||||
|
base_rate=round(base, 4),
|
||||||
|
precision=round(precision, 4) if precision is not None else None,
|
||||||
|
lift_vs_base=round(precision / base, 3) if precision and base else None,
|
||||||
|
recall=round(len(correct) / total_hits, 4) if total_hits else None,
|
||||||
|
false_positives=len(wrong),
|
||||||
|
mean_opportunity_when_right_cents=round(fmean(e["amplitude"] for e in correct), 2)
|
||||||
|
if correct
|
||||||
|
else None,
|
||||||
|
mean_delay_when_right_days=round(fmean(e["delay"] for e in correct), 2) if correct else None,
|
||||||
|
mean_adverse_when_wrong_cents=round(fmean(max(0.0, -e["terminal"]) for e in wrong), 2)
|
||||||
|
if wrong
|
||||||
|
else None,
|
||||||
|
mean_terminal_when_wrong_cents=round(fmean(e["terminal"] for e in wrong), 2) if wrong else None,
|
||||||
|
precision_ci=bootstrap_ci(hits_vector) if len(signaled) >= 10 else None,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def non_overlapping(predictions, key, label, step):
|
||||||
|
subset = predictions[::step]
|
||||||
|
flags = signal_flags(subset, label)
|
||||||
|
out = score_threshold(subset, key, label, flags)
|
||||||
|
out["step_days"] = step
|
||||||
|
out["window_shared"] = f"une origine tous les {step} jours : fenêtres J+1..J+{step} disjointes"
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def episode_summary(predictions, key, label):
|
||||||
|
flags = signal_flags(predictions, label)
|
||||||
|
rows = episodes(predictions, flags, key)
|
||||||
|
if not rows:
|
||||||
|
return dict(n_episodes=0)
|
||||||
|
wins = [r for r in rows if r["hits"]]
|
||||||
|
base = fmean(p["target"]["events"][key]["hit"] for p in predictions)
|
||||||
|
precision = len(wins) / len(rows)
|
||||||
|
return dict(
|
||||||
|
n_episodes=len(rows),
|
||||||
|
n_days_signaled=sum(r["days"] for r in rows),
|
||||||
|
precision_episode=round(precision, 4),
|
||||||
|
lift_vs_base=round(precision / base, 3) if base else None,
|
||||||
|
mean_episode_length_days=round(fmean(r["days"] for r in rows), 2),
|
||||||
|
mean_delay_when_right_days=round(fmean(r["best"][1] for r in wins), 2) if wins else None,
|
||||||
|
precision_ci=bootstrap_ci([1 if r["hits"] else 0 for r in rows]),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def select_on_validation(snapshot, key):
|
||||||
|
"""Seuil absolu choisi EXCLUSIVEMENT sur les paires de validation passées."""
|
||||||
|
pairs = snapshot["pairs"]
|
||||||
|
base = fmean(row[1][key] for row in pairs)
|
||||||
|
best = None
|
||||||
|
for threshold in (0.10, 0.15, 0.20, 0.25, 0.30, 0.35, 0.40):
|
||||||
|
signaled = [row for row in pairs if row[0] >= threshold]
|
||||||
|
if len(signaled) < max(30, 0.05 * len(pairs)):
|
||||||
|
continue
|
||||||
|
precision = fmean(row[1][key] for row in signaled)
|
||||||
|
candidate = dict(
|
||||||
|
threshold=threshold,
|
||||||
|
validation_coverage=len(signaled) / len(pairs),
|
||||||
|
validation_precision=precision,
|
||||||
|
validation_lift=precision / base if base else None,
|
||||||
|
)
|
||||||
|
if best is None or candidate["validation_lift"] > best["validation_lift"]:
|
||||||
|
best = candidate
|
||||||
|
return best
|
||||||
|
|
||||||
|
|
||||||
|
def calibrators(snapshot):
|
||||||
|
out = {}
|
||||||
|
for key in KEYS:
|
||||||
|
pairs = [(row[0], row[1][key]) for row in snapshot["pairs"]]
|
||||||
|
out[key] = dict(platt=platt_fit(pairs), isotonic=isotonic_fit(pairs), raw=pairs)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def run():
|
||||||
|
root = Path("reports")
|
||||||
|
results = json.loads((root / "event-results.json").read_text())
|
||||||
|
coverage = results.get("coverage", {})
|
||||||
|
report = dict(
|
||||||
|
status="experimental_no_production",
|
||||||
|
score_scale="rang relatif de fréquence passée, calibré seulement après mesure",
|
||||||
|
protocol=dict(
|
||||||
|
thresholds="quantiles de scores de validation antérieurs",
|
||||||
|
calibration="Platt et isotone appris sur instantané de validation, gelés",
|
||||||
|
independence="quotidien + origines non chevauchantes + épisodes",
|
||||||
|
ci=f"bootstrap par blocs de {DEFAULT_BLOCK} jours, {BOOTSTRAP_RESAMPLES} rééchantillonnages",
|
||||||
|
),
|
||||||
|
per_event=[],
|
||||||
|
selection_on_validation=[],
|
||||||
|
calibration_comparison=[],
|
||||||
|
)
|
||||||
|
for fuel in ("Gazole", "SP95", "SP98", "E10", "E85", "GPLc"):
|
||||||
|
for horizon in (7, 14):
|
||||||
|
for mode in ("rolling", "holdout_2026", "holdout_2022"):
|
||||||
|
path = root / f"event-{fuel}-{horizon}-{mode}-predictions.json"
|
||||||
|
if not path.exists():
|
||||||
|
continue
|
||||||
|
predictions = json.loads(path.read_text())
|
||||||
|
if not predictions:
|
||||||
|
continue
|
||||||
|
snapshots = json.loads((root / f"risk-calibration-{fuel}-{horizon}-{mode}.json").read_text())
|
||||||
|
for key in KEYS:
|
||||||
|
entry = dict(
|
||||||
|
fuel=fuel,
|
||||||
|
horizon=horizon,
|
||||||
|
mode=mode,
|
||||||
|
event=key,
|
||||||
|
direction="hausse" if key.startswith("up") else "baisse",
|
||||||
|
test_period=f"{predictions[0]['t']} → {predictions[-1]['t']}",
|
||||||
|
threshold_source_frozen=predictions[0]["threshold_source"]["frozen"],
|
||||||
|
thresholds=[
|
||||||
|
score_threshold(predictions, key, label)
|
||||||
|
for label in (
|
||||||
|
"q95",
|
||||||
|
"q90",
|
||||||
|
"q80",
|
||||||
|
"q70",
|
||||||
|
"q50",
|
||||||
|
"score>=0.10",
|
||||||
|
"score>=0.15",
|
||||||
|
"score>=0.20",
|
||||||
|
"score>=0.25",
|
||||||
|
"score>=0.30",
|
||||||
|
"score>=0.35",
|
||||||
|
"score>=0.40",
|
||||||
|
)
|
||||||
|
],
|
||||||
|
non_overlapping=[
|
||||||
|
non_overlapping(predictions, key, label, horizon)
|
||||||
|
for label in ("q95", "q90", "q80")
|
||||||
|
],
|
||||||
|
episodes=[
|
||||||
|
episode_summary(predictions, key, label) for label in ("q95", "q90", "q80")
|
||||||
|
],
|
||||||
|
)
|
||||||
|
report["per_event"].append(entry)
|
||||||
|
# Calibration : comparée sur la fenêtre évaluée, apprise sur validation seule.
|
||||||
|
first_id = predictions[0]["calibration_refresh"]
|
||||||
|
snapshot = snapshots[first_id]
|
||||||
|
models = calibrators(snapshot)
|
||||||
|
for key in KEYS:
|
||||||
|
raw = [(p["score"], p["target"]["events"][key]["hit"]) for p in predictions]
|
||||||
|
platt = [
|
||||||
|
(calibrate(models[key]["platt"], p["score"]), p["target"]["events"][key]["hit"])
|
||||||
|
for p in predictions
|
||||||
|
]
|
||||||
|
isotone = [
|
||||||
|
(calibrate(models[key]["isotonic"], p["score"]), p["target"]["events"][key]["hit"])
|
||||||
|
for p in predictions
|
||||||
|
]
|
||||||
|
report["calibration_comparison"].append(
|
||||||
|
dict(
|
||||||
|
fuel=fuel,
|
||||||
|
horizon=horizon,
|
||||||
|
mode=mode,
|
||||||
|
event=key,
|
||||||
|
validation_period=f"{snapshot['from_day']} → {snapshot['to_day']}",
|
||||||
|
validation_n=snapshot["n"],
|
||||||
|
brier_raw=brier(raw),
|
||||||
|
brier_platt=brier(platt),
|
||||||
|
brier_isotonic=brier(isotone),
|
||||||
|
reliability_raw=reliability(raw),
|
||||||
|
reliability_platt=reliability(platt),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
for key in ("up_2", "up_3", "up_5", "down_2", "down_3", "down_5"):
|
||||||
|
choice = select_on_validation(snapshot, key)
|
||||||
|
if not choice:
|
||||||
|
continue
|
||||||
|
label = f"score>={choice['threshold']:.2f}"
|
||||||
|
test = score_threshold(predictions, key, label)
|
||||||
|
report["selection_on_validation"].append(
|
||||||
|
dict(
|
||||||
|
fuel=fuel,
|
||||||
|
horizon=horizon,
|
||||||
|
mode=mode,
|
||||||
|
event=key,
|
||||||
|
**choice,
|
||||||
|
test=dict(
|
||||||
|
coverage=test["actual_test_coverage"],
|
||||||
|
precision=test["precision"],
|
||||||
|
lift=test["lift_vs_base"],
|
||||||
|
recall=test["recall"],
|
||||||
|
mean_opportunity_when_right_cents=test["mean_opportunity_when_right_cents"],
|
||||||
|
mean_adverse_when_wrong_cents=test["mean_adverse_when_wrong_cents"],
|
||||||
|
mean_delay_when_right_days=test["mean_delay_when_right_days"],
|
||||||
|
precision_ci=test["precision_ci"],
|
||||||
|
),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
print(fuel, horizon, "évalué", flush=True)
|
||||||
|
(root / "risk-results.json").write_text(json.dumps(report, ensure_ascii=False, indent=2))
|
||||||
|
lines = [
|
||||||
|
"# Scores de risque — seuils passés, calibration passée, indépendance",
|
||||||
|
"",
|
||||||
|
"## Couverture par carburant (motifs d'exclusion)",
|
||||||
|
json.dumps(coverage, ensure_ascii=False, indent=2),
|
||||||
|
"",
|
||||||
|
"Les scores sont des RANGS, pas des probabilités. Aucun usage dans le conseil réel.",
|
||||||
|
f"- seuils : {report['protocol']['thresholds']}",
|
||||||
|
f"- calibration : {report['protocol']['calibration']}",
|
||||||
|
f"- indépendance : {report['protocol']['independence']}",
|
||||||
|
f"- intervalles : {report['protocol']['ci']}",
|
||||||
|
"",
|
||||||
|
]
|
||||||
|
for entry in report["per_event"]:
|
||||||
|
lines.append(
|
||||||
|
f"\n## {entry['fuel']} J+{entry['horizon']} {entry['mode']} {entry['event']} "
|
||||||
|
f"({entry['direction']}) — test {entry['test_period']}"
|
||||||
|
)
|
||||||
|
for item in entry["thresholds"]:
|
||||||
|
lines.append(
|
||||||
|
f"- seuil {item['label']} ({item['calibrated_as']}, source {item['threshold_source_period']}, "
|
||||||
|
f"n={item['threshold_source_n']}) valeur {item['threshold_value']} : "
|
||||||
|
f"couverture observée {item['actual_test_coverage']}, précision {item['precision']}, "
|
||||||
|
f"lift {item['lift_vs_base']}, rappel {item['recall']}, "
|
||||||
|
f"opportunité {item['mean_opportunity_when_right_cents']} c€, "
|
||||||
|
f"mouvement adverse {item['mean_adverse_when_wrong_cents']} c€, "
|
||||||
|
f"délai {item['mean_delay_when_right_days']} j, IC précision {item['precision_ci']}"
|
||||||
|
)
|
||||||
|
for item in entry["episodes"]:
|
||||||
|
lines.append(f" - épisodes {item.get('label', '')} : {json.dumps(item, ensure_ascii=False)}")
|
||||||
|
for item in entry["non_overlapping"]:
|
||||||
|
lines.append(f" - origines disjointes : {json.dumps(item, ensure_ascii=False)}")
|
||||||
|
lines.append("\n## Seuils choisis sur validation, mesurés sur le test")
|
||||||
|
for item in report["selection_on_validation"]:
|
||||||
|
lines.append(
|
||||||
|
f"- {item['fuel']} J+{item['horizon']} {item['mode']} {item['event']} : "
|
||||||
|
f"seuil {item['threshold']} (validation : couverture {item['validation_coverage']:.3f}, "
|
||||||
|
f"précision {item['validation_precision']:.3f}, lift {item['validation_lift']:.2f}) → "
|
||||||
|
f"test {json.dumps(item['test'], ensure_ascii=False)}"
|
||||||
|
)
|
||||||
|
lines.append("\n## Calibration avant/après (apprise sur validation uniquement)")
|
||||||
|
for item in report["calibration_comparison"]:
|
||||||
|
lines.append(
|
||||||
|
f"- {item['fuel']} J+{item['horizon']} {item['mode']} {item['event']} "
|
||||||
|
f"(validation {item['validation_period']}, n={item['validation_n']}) : "
|
||||||
|
f"Brier brut {item['brier_raw']:.5f} · Platt {item['brier_platt']:.5f} · "
|
||||||
|
f"isotone {item['brier_isotonic']:.5f}"
|
||||||
|
)
|
||||||
|
lines.append(f" - fiabilité brute : {json.dumps(item['reliability_raw'], ensure_ascii=False)}")
|
||||||
|
lines.append(f" - fiabilité Platt : {json.dumps(item['reliability_platt'], ensure_ascii=False)}")
|
||||||
|
(root / "risk-report.md").write_text("\n".join(lines))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
run()
|
||||||
@@ -7,7 +7,7 @@ from test_clean_pipeline import states
|
|||||||
import storage
|
import storage
|
||||||
from clean_backtest import feature_rows
|
from clean_backtest import feature_rows
|
||||||
from clean_features import features_asof
|
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
|
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)
|
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()
|
stat = empty_stats()
|
||||||
original = copy.deepcopy(stat)
|
original = copy.deepcopy(stat)
|
||||||
p = probabilities(stat, empty_stats())
|
p = risk_scores(stat, empty_stats())
|
||||||
assert stat == original
|
assert stat == original
|
||||||
assert p["frequency"]["down_2"] == 0.5
|
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)}))
|
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)
|
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"]
|
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():
|
# L'évaluation d'abstention vit dans tests/test_risk_protocol.py : seuils passés et
|
||||||
y = dict(hit=False, amplitude=0, delay=None, terminal=-1)
|
# couverture mesurée. Ici on ne teste que les cibles et les scores.
|
||||||
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"}
|
|
||||||
|
|||||||
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