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.
438 lines
19 KiB
Python
438 lines
19 KiB
Python
"""É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()
|