Protocole amont apparie : IC diagnostiques, familles as-of, placebo et PR-AUC
This commit is contained in:
160
risk_report.py
160
risk_report.py
@@ -21,6 +21,7 @@ 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
|
||||
|
||||
|
||||
@@ -113,26 +114,58 @@ def reliability(pairs):
|
||||
# ------------------------------------------------------------------ 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:
|
||||
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 = [values[i : i + block] for i in range(0, len(values), block)]
|
||||
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)):
|
||||
drawn.extend(blocks[rng.randrange(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()
|
||||
return dict(
|
||||
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
|
||||
@@ -176,7 +209,10 @@ def score_threshold(predictions, key, label, flags=None):
|
||||
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]
|
||||
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(
|
||||
@@ -201,7 +237,7 @@ def score_threshold(predictions, key, label, flags=None):
|
||||
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) >= 20 else None,
|
||||
precision_ci=bootstrap_ci(day_hits, flags=list(flags)) if len(signaled) >= 10 else None,
|
||||
)
|
||||
|
||||
|
||||
@@ -229,10 +265,116 @@ def episode_summary(predictions, key, label):
|
||||
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) >= 20 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, seen_pos, index = 0.0, 0, 0
|
||||
while index < len(rows):
|
||||
score = rows[index][0]
|
||||
tp = fp = 0
|
||||
while index < len(rows) and rows[index][0] == score:
|
||||
tp += 1 if rows[index][1] else 0
|
||||
fp += 0 if rows[index][1] else 1
|
||||
index += 1
|
||||
recall_delta = tp / positives
|
||||
precision_at = tp / (tp + fp) if (tp + fp) else 0.0
|
||||
area += recall_delta * precision_at
|
||||
seen_pos += tp
|
||||
if seen_pos == 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"]
|
||||
|
||||
Reference in New Issue
Block a user