Aucune famille ne survit : Brier et PR-AUC degrades sur les endpoints pre-declares, placebo par blocs ou par decalage souvent meilleur que la vraie serie. Les seuils dIC exposent desormais n_blocks_total, n_blocks_with_signal et n_effective_signals, avec refus de toute significativite sur un intervalle non exploitable.
586 lines
25 KiB
Python
586 lines
25 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
|
|
MIN_USABLE_BLOCKS = 8 # en dessous, un IC par blocs est étroit par construction, pas par preuve
|
|
BOOTSTRAP_RESAMPLES = 150 # compromis coût/stabilité : 150 rééchantillonnages de blocs de 28 j
|
|
|
|
|
|
# ------------------------------------------------------------------ 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, flags=None):
|
|
# `values` contient un élément par jour évalué, `None` hors signal. Les blocs sont découpés
|
|
# sur la chronologie complète : sans cela, 53 jours signalés formeraient 2 blocs de 28 jours
|
|
# et l'intervalle serait étroit artificiellement.
|
|
"""Bootstrap par blocs temporels : respecte l'autocorrélation des séries de prix.
|
|
|
|
Le diagnostic de blocs est **toujours** renvoyé avec l'intervalle. Un intervalle étroit
|
|
n'est crédible que si plusieurs blocs indépendants portent le signal : le seuil q95
|
|
Gazole J+14 n'a que 53 jours signalés et 11 épisodes, son IC quotidien est artificiellement
|
|
étroit. Sans blocs suffisants, aucun intervalle et aucune significativité ne sont revendiqués.
|
|
"""
|
|
sample = [value for value in values if value is not None]
|
|
if len(sample) < 10:
|
|
return None
|
|
flags = [True] * len(values) if flags is None else flags
|
|
rng = random.Random(seed)
|
|
blocks = list(
|
|
zip(
|
|
[values[i : i + block] for i in range(0, len(values), block)],
|
|
[flags[i : i + block] for i in range(0, len(flags), block)],
|
|
strict=False,
|
|
)
|
|
)
|
|
means = []
|
|
for _ in range(resamples):
|
|
drawn = []
|
|
for _ in range(len(blocks)):
|
|
vals, fl = blocks[rng.randrange(len(blocks))]
|
|
drawn.extend(v for v, f in zip(vals, fl, strict=False) if f and v is not None)
|
|
if drawn:
|
|
means.append(fmean(drawn))
|
|
if not means:
|
|
return None
|
|
means.sort()
|
|
with_signal = sum(1 for _, fl in blocks if any(fl))
|
|
out = 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,
|
|
n_blocks_total=len(blocks),
|
|
n_blocks_with_signal=with_signal,
|
|
n_effective_signals=with_signal,
|
|
n_days_signaled=len(sample),
|
|
)
|
|
if with_signal < MIN_USABLE_BLOCKS:
|
|
out["usable"] = False
|
|
out["note"] = "intervalle non exploitable — effectif temporel insuffisant"
|
|
else:
|
|
out["usable"] = True
|
|
out["note"] = f"{with_signal} blocs porteurs de signaux sur {len(blocks)}"
|
|
return out
|
|
|
|
|
|
# ------------------------------------------------------------------ signaux et épisodes
|
|
|
|
|
|
def signal_flags(predictions, key, label):
|
|
"""Signal = score de l'événement >= seuil du jour, seuil lui-même issu du passé."""
|
|
return [p["score"][key] >= p["thresholds"][key][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, key, 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"])
|
|
day_hits = [
|
|
(1 if event["hit"] else 0) if flag else None
|
|
for event, flag in zip([p["target"]["events"][key] for p, _ in rows], flags, strict=False)
|
|
]
|
|
precision = len(correct) / len(signaled) if signaled else None
|
|
spec = predictions[0]["thresholds"][key][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(day_hits, flags=list(flags)) if len(signaled) >= 10 else None,
|
|
)
|
|
|
|
|
|
def non_overlapping(predictions, key, label, step):
|
|
subset = predictions[::step]
|
|
flags = signal_flags(subset, key, 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, key, 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]) if len(rows) >= 10 else None,
|
|
)
|
|
|
|
|
|
def pr_auc(predictions, key):
|
|
"""Aire sous la courbe précision-rappel : adaptée aux événements rares, appariée jour/jour."""
|
|
rows = sorted(
|
|
((p["score"][key], p["target"]["events"][key]["hit"]) for p in predictions), key=lambda item: -item[0]
|
|
)
|
|
positives = sum(1 for _, hit in rows if hit)
|
|
if not positives:
|
|
return None
|
|
area, cumulative_tp, cumulative_fp, previous_recall, index = 0.0, 0, 0, 0.0, 0
|
|
while index < len(rows):
|
|
score = rows[index][0]
|
|
while index < len(rows) and rows[index][0] == score:
|
|
if rows[index][1]:
|
|
cumulative_tp += 1
|
|
else:
|
|
cumulative_fp += 1
|
|
index += 1
|
|
# Précision **cumulative** : les faux positifs déjà rencontrés comptent, sinon la
|
|
# PR-AUC est gonflée vers 1,0 et ne vaut plus rien.
|
|
recall = cumulative_tp / positives
|
|
precision = cumulative_tp / (cumulative_tp + cumulative_fp)
|
|
area += (recall - previous_recall) * precision
|
|
previous_recall = recall
|
|
if cumulative_tp == positives:
|
|
break
|
|
return round(area, 4)
|
|
|
|
|
|
def score_brier(predictions, key):
|
|
values = [
|
|
(p["score"][key] - (1.0 if p["target"]["events"][key]["hit"] else 0.0)) ** 2 for p in predictions
|
|
]
|
|
return round(fmean(values), 5) if values else None
|
|
|
|
|
|
def decision_loss(predictions, key, label):
|
|
"""Perte de décision appariée : signal manqué (faux négatif) ou signal émis à tort."""
|
|
flags = signal_flags(predictions, key, label)
|
|
loss = [
|
|
0
|
|
if (
|
|
(flag and p["target"]["events"][key]["hit"])
|
|
or (not flag and not p["target"]["events"][key]["hit"])
|
|
)
|
|
else 1
|
|
for p, flag in zip(predictions, flags, strict=False)
|
|
]
|
|
return round(fmean(loss), 4) if loss else None
|
|
|
|
|
|
def expected_price_value_cents_per_signal(thresholds):
|
|
"""Valeur attendue par signal : gains des vrais positifs moins pertes adverses pondérées.
|
|
|
|
Métrique **expérimentale** : aucun effet sur le conseil véhicule.
|
|
"""
|
|
precision = thresholds.get("precision")
|
|
gain = thresholds.get("mean_opportunity_when_right_cents")
|
|
adverse = thresholds.get("mean_adverse_when_wrong_cents")
|
|
if precision is None or gain is None:
|
|
return None
|
|
return round(precision * gain - (1 - precision) * (adverse or 0.0), 2)
|
|
|
|
|
|
def paired_block_bootstrap(values_a, values_b, block=DEFAULT_BLOCK, resamples=BOOTSTRAP_RESAMPLES, seed=13):
|
|
"""Bootstrap apparié par blocs : IC de la **différence** jour par jour entre deux modèles.
|
|
|
|
Deux intervalles calculés séparément ne disent pas si l'écart est réel ; la différence
|
|
appariée, elle, élimine la variance commune aux deux modèles sur les mêmes journées.
|
|
"""
|
|
if len(values_a) != len(values_b) or len(values_a) < 10:
|
|
return None
|
|
diffs = [a - b for a, b in zip(values_a, values_b, strict=False)]
|
|
rng = random.Random(seed)
|
|
blocks = [diffs[i : i + block] for i in range(0, len(diffs), block)]
|
|
means = sorted(
|
|
fmean([v for b in [rng.choice(blocks) for _ in blocks] for v in b]) for _ in range(resamples)
|
|
)
|
|
low, high = means[int(0.025 * (len(means) - 1))], means[int(0.975 * (len(means) - 1))]
|
|
usable = len(blocks) >= MIN_USABLE_BLOCKS
|
|
return dict(
|
|
mean_difference=round(fmean(diffs), 5),
|
|
low=round(low, 5),
|
|
high=round(high, 5),
|
|
n_blocks_total=len(blocks),
|
|
block_days=block,
|
|
resamples=resamples,
|
|
usable=usable,
|
|
significant=bool(usable and (low > 0 or high < 0)),
|
|
note=None if usable else "intervalle non exploitable — effectif temporel insuffisant",
|
|
)
|
|
|
|
|
|
def per_day_brier(predictions, key):
|
|
return [(p["score"][key] - (1.0 if p["target"]["events"][key]["hit"] else 0.0)) ** 2 for p in predictions]
|
|
|
|
|
|
def per_day_decision_loss(predictions, key, label):
|
|
flags = signal_flags(predictions, key, label)
|
|
return [
|
|
0
|
|
if (
|
|
(flag and p["target"]["events"][key]["hit"])
|
|
or (not flag and not p["target"]["events"][key]["hit"])
|
|
)
|
|
else 1
|
|
for p, flag in zip(predictions, flags, strict=False)
|
|
]
|
|
|
|
|
|
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][key] >= 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][key], 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"][key], p["target"]["events"][key]["hit"]) for p in predictions]
|
|
platt = [
|
|
(calibrate(models[key]["platt"], p["score"][key]), p["target"]["events"][key]["hit"])
|
|
for p in predictions
|
|
]
|
|
isotone = [
|
|
(
|
|
calibrate(models[key]["isotonic"], p["score"][key]),
|
|
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()
|