Le conseiller du backtest raisonne desormais comme le moteur de decision : besoin d abord, anticipation seulement si le gain depasse le seuil du vehicule, et plancher d appoint qui interdit de repasser a la pompe pour quelques litres. La campagne precedente le montrait : sans ce plancher, la strategie multipliait les passages quotidiens et le verdict la refusait a juste titre. Ajout de la validation par regimes : chaque periode atypique est evaluee avec un apprentissage arrete la veille de son debut, plus l experience ou la crise actuelle reste entierement hors entrainement.
421 lines
19 KiB
Python
421 lines
19 KiB
Python
"""Backtest J+0→J+21 : modèles simples, régimes séparés, résultats par carburant et par horizon.
|
||
|
||
Aucune prévision n'est branchée au conseil réel par ce module : il mesure et rend un verdict.
|
||
Le rapport produit répond, pour chaque carburant et chaque horizon, aux questions posées :
|
||
période d'apprentissage et de test, nombre de prévisions, MAE naïve et modèle, amélioration,
|
||
justesse du sens, calibration, amplitude moyenne prévue et réelle, et résultat économique simulé.
|
||
"""
|
||
|
||
import statistics
|
||
from datetime import datetime
|
||
|
||
import features
|
||
import models
|
||
import validation
|
||
|
||
# Périodes atypiques : on veut savoir ce que le modèle fait **pendant** les chocs, pas seulement
|
||
# en moyenne. Un modèle perdu pendant un choc ne doit pas afficher une forte confiance.
|
||
REGIMES = {
|
||
"covid_2020": ("2020-02-01", "2020-09-30", "crise Covid"),
|
||
"choc_2022": ("2022-02-01", "2022-10-31", "choc énergétique"),
|
||
"calme_2023": ("2023-06-01", "2024-06-30", "période plus calme"),
|
||
"crise_2026": ("2026-01-01", "2026-12-31", "crise actuelle"),
|
||
}
|
||
HOLDOUT_CURRENT = "2026-01-01" # la crise actuelle reste entièrement hors entraînement
|
||
MIN_REGIME_PREDICTIONS = 20
|
||
SHOCK_REGIMES = ("covid_2020", "choc_2022", "crise_2026")
|
||
SHOCK_CONFIDENCE_LIMIT = 0.75
|
||
SHOCK_ACCURACY_FLOOR = 0.55
|
||
FUEL_HORIZONS = models.HORIZONS
|
||
|
||
|
||
def metrics_in_cents(metrics):
|
||
"""Les métriques de ``validation`` sont en euros : on les rend en centimes par litre."""
|
||
out = dict(metrics)
|
||
for key in ("mae", "rmse", "bias", "amplitude_mae"):
|
||
if out.get(key) is not None:
|
||
out[f"{key}_cents"] = round(out[key] * 100, 4)
|
||
if out.get("naive"):
|
||
out["naive"] = metrics_in_cents(out["naive"])
|
||
if out.get("skill_vs_naive") is not None:
|
||
out["improvement_pct"] = round(out["skill_vs_naive"] * 100, 2)
|
||
return out
|
||
|
||
|
||
def _predictions(fitted, samples, horizon, trained_until):
|
||
"""Prédictions au format attendu par le banc de validation (prix en euros, variation en c€)."""
|
||
rows = []
|
||
for sample in samples:
|
||
actual = sample["targets"].get(horizon)
|
||
if actual is None or fitted is None:
|
||
continue
|
||
forecast = models.predict(fitted, sample)
|
||
rows.append(
|
||
dict(
|
||
day=sample["day"],
|
||
horizon=horizon,
|
||
trained_until=trained_until,
|
||
last_known_price=sample["price"],
|
||
predicted_price=round(sample["price"] + forecast["mu_cents"] / 100, 5),
|
||
actual_price=round(sample["price"] + actual / 100, 5),
|
||
predicted_change=forecast["mu_cents"],
|
||
actual_change=actual,
|
||
confidence=forecast["confidence"],
|
||
model=fitted["name"],
|
||
interval=forecast["interval"],
|
||
p_up=forecast["p_up"],
|
||
sigma_cents=forecast["sigma_cents"],
|
||
)
|
||
)
|
||
return rows
|
||
|
||
|
||
def amplitude(rows):
|
||
"""Amplitude moyenne prévue et réelle, en centimes par litre."""
|
||
if not rows:
|
||
return dict(predicted_cents=None, actual_cents=None)
|
||
return dict(
|
||
predicted_cents=round(statistics.fmean(abs(row["predicted_change"]) for row in rows), 3),
|
||
actual_cents=round(statistics.fmean(abs(row["actual_change"]) for row in rows), 3),
|
||
)
|
||
|
||
|
||
def regime_report(predictions):
|
||
"""Performance séparée par régime, avec la confiance annoncée pendant les chocs."""
|
||
out = {}
|
||
for key, (start, end, label) in REGIMES.items():
|
||
scoped = [row for row in predictions if start <= row["day"] <= end]
|
||
if not scoped:
|
||
out[key] = dict(label=label, period=f"{start} → {end}", count=0)
|
||
continue
|
||
metrics = metrics_in_cents(validation.evaluate(scoped, horizon=scoped[0]["horizon"], naive_mae=None))
|
||
confidences = [row["confidence"] for row in scoped if row.get("confidence") is not None]
|
||
out[key] = dict(
|
||
label=label,
|
||
period=f"{start} → {end}",
|
||
count=metrics["count"],
|
||
mae_cents=metrics["mae_cents"],
|
||
improvement_pct=metrics.get("improvement_pct"),
|
||
direction=(metrics["direction"] or {}).get("accuracy"),
|
||
calibration=(metrics["calibration"] or {}).get("calibration_quality"),
|
||
mean_confidence=round(statistics.fmean(confidences), 3) if confidences else None,
|
||
amplitude=amplitude(scoped),
|
||
)
|
||
return out
|
||
|
||
|
||
def shock_verdict(regimes):
|
||
"""Un modèle perdu pendant un choc ne doit pas afficher une forte confiance pendant ce choc."""
|
||
problems = []
|
||
for key in SHOCK_REGIMES:
|
||
entry = regimes.get(key) or {}
|
||
if (entry.get("count") or 0) < MIN_REGIME_PREDICTIONS:
|
||
continue
|
||
confidence = entry.get("mean_confidence")
|
||
accuracy = entry.get("direction")
|
||
if confidence is None or accuracy is None:
|
||
continue
|
||
if confidence >= SHOCK_CONFIDENCE_LIMIT and accuracy <= SHOCK_ACCURACY_FLOOR:
|
||
problems.append(
|
||
f"{entry['label']} : confiance {confidence:.0%} pour une justesse de "
|
||
f"sens {accuracy:.0%} sur {entry['count']} prévisions"
|
||
)
|
||
return dict(passed=not problems, problems=problems)
|
||
|
||
|
||
def economics(predictions, levels, vehicle, horizon, min_change_cents=1.0, min_confidence=0.6):
|
||
"""Résultat économique simulé : stratégie naïve contre stratégie guidée par les prévisions."""
|
||
forecast_by_day = {}
|
||
for row in predictions:
|
||
if row["horizon"] != horizon:
|
||
continue
|
||
if abs(row["predicted_change"]) < min_change_cents or row["confidence"] < min_confidence:
|
||
continue
|
||
forecast_by_day[row["day"]] = dict(
|
||
direction="up" if row["predicted_change"] > 0 else "down",
|
||
change_cents=row["predicted_change"],
|
||
confidence=row["confidence"],
|
||
)
|
||
price_series = [dict(day=point["day"], price=point["median"]) for point in levels if point["median"]]
|
||
if predictions:
|
||
start, end = min(row["day"] for row in predictions), max(row["day"] for row in predictions)
|
||
price_series = [point for point in price_series if start <= point["day"] <= end]
|
||
if len(price_series) < 30:
|
||
return dict(reason="période trop courte pour une simulation économique")
|
||
comparison = validation.compare_strategies(price_series, vehicle, forecasts=forecast_by_day)
|
||
comparison["forecast_days"] = len(forecast_by_day)
|
||
comparison["period"] = (price_series[0]["day"], price_series[-1]["day"])
|
||
return comparison
|
||
|
||
|
||
def run_variant(
|
||
fuel,
|
||
variant_key,
|
||
lat,
|
||
lon,
|
||
radius,
|
||
train_ratio=0.7,
|
||
days=4000,
|
||
holdout_start=None,
|
||
horizons=FUEL_HORIZONS,
|
||
vehicle=None,
|
||
verbose=False,
|
||
built=None,
|
||
regime=None,
|
||
):
|
||
"""Un couple (carburant, variante) : entraînement, test chronologique, régimes, verdict."""
|
||
variant = {item["key"]: item for item in features.VARIANTS}[variant_key]
|
||
market = variant_key != "local_long"
|
||
built = built or models.build_samples(lat, lon, radius, fuel, horizons=horizons, days=days, market=market)
|
||
samples = built.get("samples") or []
|
||
result = dict(
|
||
fuel=fuel,
|
||
variant=variant_key,
|
||
label=variant["label"],
|
||
coverage=models.fuel_coverage(fuel),
|
||
samples=len(samples),
|
||
reason=built.get("reason"),
|
||
reconstruction=built.get("reconstructed", {}).get("basis"),
|
||
)
|
||
if not samples:
|
||
result["reason"] = result["reason"] or "aucun échantillon exploitable"
|
||
return result
|
||
ordered = sorted(samples, key=lambda item: item["day"])
|
||
if regime:
|
||
start, end, label = REGIMES[regime]
|
||
result["regime"] = dict(key=regime, label=label, period=f"{start} → {end}")
|
||
train = [row for row in ordered if row["day"] < start]
|
||
test = [row for row in ordered if start <= row["day"] <= end]
|
||
elif holdout_start:
|
||
train = [row for row in ordered if row["day"] < holdout_start]
|
||
test = [row for row in ordered if row["day"] >= holdout_start]
|
||
else:
|
||
train, test = validation.split_chronologically(ordered, ratio=train_ratio)
|
||
if len(train) < models.MIN_TRAIN_SAMPLES or len(test) < 30:
|
||
result["reason"] = (
|
||
f"{len(train)} échantillons d’apprentissage, {len(test)} de test : trop peu pour conclure"
|
||
)
|
||
return result
|
||
trained_until = max(row["day"] for row in train)
|
||
validation.assert_no_leakage([dict(day=row["day"], trained_until=trained_until) for row in test])
|
||
result["train"] = (min(row["day"] for row in train), trained_until)
|
||
result["test"] = (min(row["day"] for row in test), max(row["day"] for row in test))
|
||
result["train_samples"] = len(train)
|
||
result["test_samples"] = len(test)
|
||
per_horizon, selections, all_predictions = {}, {}, []
|
||
for horizon in horizons:
|
||
fitted, selection = models.select_model(train, horizon)
|
||
selections[str(horizon)] = dict(selection, fitted_model=(fitted or {}).get("name"))
|
||
rows = _predictions(fitted, test, horizon, trained_until)
|
||
all_predictions.extend(rows)
|
||
metrics = metrics_in_cents(validation.evaluate(all_predictions, horizon=horizon))
|
||
metrics["amplitude"] = amplitude(rows)
|
||
metrics["model"] = (fitted or {}).get("name")
|
||
metrics["interval_coverage"] = _interval_coverage(rows)
|
||
metrics["probability_up_calibration"] = _probability_calibration(rows)
|
||
per_horizon[str(horizon)] = metrics
|
||
result["horizons"] = per_horizon
|
||
result["selection"] = selections
|
||
result["regimes"] = regime_report(all_predictions)
|
||
result["shock"] = shock_verdict(result["regimes"])
|
||
horizon_for_economics = str(validation.DEFAULT_HORIZON)
|
||
chosen = per_horizon.get(horizon_for_economics) or {}
|
||
if vehicle:
|
||
result["economics"] = economics(all_predictions, built["levels"], vehicle, validation.DEFAULT_HORIZON)
|
||
result["profiles"] = {}
|
||
for key, profile in validation.VEHICLE_PROFILES.items():
|
||
simulation = economics(all_predictions, built["levels"], profile, validation.DEFAULT_HORIZON)
|
||
if simulation.get("advisor"):
|
||
result["profiles"][key] = dict(
|
||
label=profile.get("label", key),
|
||
fuel=profile.get("fuel"),
|
||
naive_cost=simulation["naive"]["cost_eur"],
|
||
advisor_cost=simulation["advisor"]["cost_eur"],
|
||
naive_refuels=simulation["naive"]["refuels"],
|
||
advisor_refuels=simulation["advisor"]["refuels"],
|
||
net_saving_eur=simulation["value"]["net_saving_eur"],
|
||
comfortable=simulation["comfort"]["comfortable"],
|
||
)
|
||
main = per_horizon.get(horizon_for_economics) or {}
|
||
if vehicle and result.get("economics") and "advisor" in result["economics"]:
|
||
result["verdict"] = validation.verdict(
|
||
{horizon_for_economics: _verdict_view(main)}, result["economics"]
|
||
)
|
||
if not result["shock"]["passed"]:
|
||
result["verdict"]["passed"] = False
|
||
result["verdict"]["failures"].extend(result["shock"]["problems"])
|
||
else:
|
||
result["verdict"] = dict(
|
||
passed=False,
|
||
failures=["simulation économique indisponible"],
|
||
reasons=[],
|
||
criteria=validation.CRITERIA,
|
||
)
|
||
result["main_horizon"] = horizon_for_economics
|
||
result["main_model"] = chosen.get("model")
|
||
return result
|
||
|
||
|
||
def _verdict_view(metrics):
|
||
"""Vue attendue par ``validation.verdict`` (clés du banc d'essai)."""
|
||
return dict(
|
||
count=metrics.get("count"),
|
||
direction=dict(accuracy=(metrics.get("direction") or {}).get("accuracy")),
|
||
calibration=dict(calibration_quality=(metrics.get("calibration") or {}).get("calibration_quality")),
|
||
skill_vs_naive=metrics.get("skill_vs_naive"),
|
||
)
|
||
|
||
|
||
def _interval_coverage(rows):
|
||
"""Part des variations réelles effectivement couvertes par la fourchette annoncée (80 % visés)."""
|
||
scoped = [row for row in rows if row.get("interval")]
|
||
if not scoped:
|
||
return None
|
||
inside = sum(1 for row in scoped if row["interval"][0] <= row["actual_change"] <= row["interval"][1])
|
||
return round(inside / len(scoped), 4)
|
||
|
||
|
||
def _probability_calibration(rows):
|
||
"""Probabilité de hausse annoncée contre fréquence réelle de hausse (écart moyen)."""
|
||
scoped = [row for row in rows if row.get("p_up") is not None]
|
||
if len(scoped) < 30:
|
||
return None
|
||
ups = sum(1 for row in scoped if row["actual_change"] > 0)
|
||
return dict(
|
||
forecast_mean=round(statistics.fmean(row["p_up"] for row in scoped), 4),
|
||
observed=round(ups / len(scoped), 4),
|
||
count=len(scoped),
|
||
)
|
||
|
||
|
||
def run_regimes(fuel, variant_key, lat, lon, radius, days=4200, vehicle=None, regimes=None):
|
||
"""Performance sur chaque période atypique : on n'apprend que **avant** chaque régime.
|
||
|
||
Un modèle doit être jugé sur sa réaction aux chocs, pas seulement en moyenne sur une période de
|
||
test continue : ici chaque régime est évalué avec un apprentissage qui s'arrête à sa veille.
|
||
"""
|
||
regimes = regimes or tuple(REGIMES)
|
||
market = variant_key != "local_long"
|
||
built = models.build_samples(lat, lon, radius, fuel, horizons=FUEL_HORIZONS, days=days, market=market)
|
||
out = {}
|
||
for key in regimes:
|
||
entry = run_variant(
|
||
fuel, variant_key, lat, lon, radius, days=days, vehicle=vehicle, built=built, regime=key
|
||
)
|
||
out[key] = entry
|
||
return out
|
||
|
||
|
||
def run_all(
|
||
fuels=("Gazole", "E10"),
|
||
variants=("local_long", "market", "enriched"),
|
||
lat=44.7737872,
|
||
lon=-0.5595029,
|
||
radius=15,
|
||
profiles=None,
|
||
verbose=True,
|
||
):
|
||
"""Lance les variantes sur les carburants couverts, puis rend un rapport lisible."""
|
||
profiles = profiles or validation.VEHICLE_PROFILES
|
||
vehicle = profiles["gros_rouleur_diesel"] if "gros_rouleur_diesel" in profiles else None
|
||
results, report = [], []
|
||
for fuel in fuels:
|
||
coverage = models.fuel_coverage(fuel)
|
||
report.append(
|
||
f"\n## {fuel} — couverture réelle : {coverage['first']} → {coverage['last']} "
|
||
f"({coverage['points']} points, {coverage['stations']} stations, "
|
||
f"{coverage['archived']} importés d’archives)"
|
||
)
|
||
for variant in variants:
|
||
entry = run_variant(fuel, variant, lat, lon, radius, vehicle=vehicle)
|
||
results.append(entry)
|
||
report.append(render_variant(entry))
|
||
if verbose:
|
||
print(
|
||
f" {fuel} · {variant} : "
|
||
f"{'ok' if entry.get('verdict', {}).get('passed') else 'refusé'} "
|
||
f"(modèle {entry.get('main_model')}, "
|
||
f"{entry.get('horizons', {}).get(str(validation.DEFAULT_HORIZON), {}).get('count', 0)} "
|
||
"prévisions)",
|
||
flush=True,
|
||
)
|
||
return dict(
|
||
results=results, report="\n".join(report), generated_at=datetime.now().isoformat(timespec="seconds")
|
||
)
|
||
|
||
|
||
def render_variant(entry):
|
||
"""Rendu lisible d'un couple (carburant, variante), horizon par horizon."""
|
||
if entry.get("reason"):
|
||
return f"\n### {entry['label']}\n- non exploitable : {entry['reason']}"
|
||
lines = [
|
||
f"\n### {entry['label']}",
|
||
f"- apprentissage : {entry['train'][0]} → {entry['train'][1]} "
|
||
f"({entry['train_samples']} échantillons)",
|
||
f"- test : {entry['test'][0]} → {entry['test'][1]} ({entry['test_samples']} échantillons)",
|
||
f"- modèle retenu à J+{validation.DEFAULT_HORIZON} : {entry.get('main_model')}",
|
||
"",
|
||
"- par horizon : horizon · modèle · n · MAE naïve → modèle (c€/L) · amélioration · "
|
||
"sens · calibration · amplitude prévue/réelle · couverture de fourchette",
|
||
]
|
||
for horizon, metrics in sorted(entry.get("horizons", {}).items(), key=lambda item: int(item[0])):
|
||
naive = (metrics.get("naive") or {}).get("mae_cents")
|
||
lines.append(
|
||
f" - J+{horizon} · {metrics.get('model')} · n={metrics.get('count')} · "
|
||
f"{_fmt(naive)} → {_fmt(metrics.get('mae_cents'))} · "
|
||
f"{_pct(metrics.get('improvement_pct'))} · "
|
||
f"sens {_pct((metrics.get('direction') or {}).get('accuracy'), scale=100)} · "
|
||
f"calib {_fmt((metrics.get('calibration') or {}).get('calibration_quality'), 2)} · "
|
||
f"amplitude {_fmt((metrics.get('amplitude') or {}).get('predicted_cents'))}/"
|
||
f"{_fmt((metrics.get('amplitude') or {}).get('actual_cents'))} · "
|
||
f"fourchette {_pct(metrics.get('interval_coverage'), scale=100)}"
|
||
)
|
||
lines.append("- régimes :")
|
||
for _key, regime in (entry.get("regimes") or {}).items():
|
||
if not regime.get("count"):
|
||
lines.append(f" - {regime['label']} ({regime['period']}) : aucune prévision")
|
||
continue
|
||
lines.append(
|
||
f" - {regime['label']} ({regime['period']}) : n={regime['count']} · "
|
||
f"MAE {_fmt(regime.get('mae_cents'))} c€/L · "
|
||
f"amélioration {_pct(regime.get('improvement_pct'))} · "
|
||
f"sens {_pct(regime.get('direction'), scale=100)} · "
|
||
f"confiance annoncée {_pct(regime.get('mean_confidence'), scale=100)}"
|
||
)
|
||
economics = entry.get("economics") or {}
|
||
if economics.get("advisor"):
|
||
naive, advisor = economics["naive"], economics["advisor"]
|
||
lines.append(
|
||
f"- économie simulée ({economics.get('period', ('', ''))[0]} → "
|
||
f"{economics.get('period', ('', ''))[1]}) : coût {advisor['cost_eur']} € contre "
|
||
f"{naive['cost_eur']} € · passages {advisor['refuels']} contre {naive['refuels']} "
|
||
f"· gain net {economics['value']['net_saving_eur']} € · confort "
|
||
f"{'ok' if economics['comfort']['comfortable'] else 'refusé'}"
|
||
)
|
||
if entry.get("profiles"):
|
||
lines.append("- profils d’usage (même carburant, même période) :")
|
||
for profile in entry["profiles"].values():
|
||
lines.append(
|
||
f" - {profile['label']} : coût {profile['advisor_cost']} € contre "
|
||
f"{profile['naive_cost']} € · passages {profile['advisor_refuels']} contre "
|
||
f"{profile['naive_refuels']} · gain net {profile['net_saving_eur']} € · "
|
||
f"confort {'ok' if profile['comfortable'] else 'refusé'}"
|
||
)
|
||
verdict = entry.get("verdict") or {}
|
||
lines.append(f"- verdict : {'PASSÉ' if verdict.get('passed') else 'REFUSÉ'}")
|
||
for failure in verdict.get("failures") or []:
|
||
lines.append(f" - motif : {failure}")
|
||
for reason in verdict.get("reasons") or []:
|
||
lines.append(f" - {reason}")
|
||
return "\n".join(lines)
|
||
|
||
|
||
def _fmt(value, digits=3):
|
||
return "—" if value is None else f"{value:.{digits}f}"
|
||
|
||
|
||
def _pct(value, scale=1):
|
||
if value is None:
|
||
return "—"
|
||
return f"{value * scale:+.1f} %" if scale == 1 else f"{value * scale:.0f} %"
|