Isole les features locales des labels et lance un protocole temporel propre
This commit is contained in:
51
CLEAN_BACKTEST.md
Normal file
51
CLEAN_BACKTEST.md
Normal file
@@ -0,0 +1,51 @@
|
||||
# Backtest local v2 — expérimental, jamais activé
|
||||
|
||||
L'ancien backtest est invalide (fuite de cible). Aucun de ses scores n'est réutilisé.
|
||||
|
||||
## Séparation et chronologie
|
||||
|
||||
- `clean_features.features_asof(prefix, t)` ne lit aucune base, aucun label, aucun module target.
|
||||
Le préfixe des 90 derniers états disponibles est construit avant les labels. Tout état
|
||||
dont available_at > t est refusé. Deltas passés sur stations communes à t-1 et t-1-lookback.
|
||||
- `clean_targets.target(states,t,h)` calcule séparément la médiane des différences futures
|
||||
en c€/L sur le même panel. L'assemblage des features et labels intervient ensuite seulement.
|
||||
- Chaque feature porte source, lookback, disponibilité maximale, nature calculée et horizons.
|
||||
Le manifeste est vérifié pour **chaque** prédiction et conservé dans les JSON détaillés.
|
||||
- Archives : disponibilité **estimée au lendemain de l'état décrit**, et non publication prouvée.
|
||||
Cette estimation n'élimine pas le risque de corrections rétrospectives des archives officielles.
|
||||
|
||||
## Expériences
|
||||
|
||||
Six carburants, J+1/3/7/14/21, zone Villenave-d'Ornon 15 km. Couverture calculée par carburant.
|
||||
Naïve, tendance, autorégressif régularisé, ridge local (sans Brent ni aucune variable externe).
|
||||
Coefficients/scaling ajustés exclusivement au train. Hyperparamètres fixes : AR 0,5, ridge 10.
|
||||
Sélection entre candidats et intervalles empiriques sur 180 observations passées de validation,
|
||||
avec purge des labels dont la disponibilité atteint cette période. Aucun refit train+validation.
|
||||
|
||||
- Rolling quotidien 2025→présent : entraînement/sélection à chaque t avec labels disponibles
|
||||
strictement avant t. Train sur 5 ans maximum, échantillonné chaque semaine pour borner le coût.
|
||||
- Holdout 2026 : modèles/scalers/calibration/sélection gelés avant le 01/01/2026.
|
||||
- Holdout 2022 : même protocole, coupure 01/01/2022.
|
||||
|
||||
**Attention** : les périodes ont déjà été consultées dans le chantier antérieur. Il s'agit
|
||||
d'expériences rétrospectives avec entraînement gelé, pas d'un nouveau test final aveugle.
|
||||
|
||||
## Sorties et limites
|
||||
|
||||
`reports/clean-results.json`, `reports/clean-report.md` et détails par carburant/horizon/protocole.
|
||||
MAE naïve/modèle, amélioration, RMSE, exactitude de direction en trois classes (zone neutre
|
||||
±0,1 c€/L), couverture intervalle 80 %, Brier hausse, amplitudes prévue/réelle, dates/effectifs.
|
||||
La couverture d'intervalle n'est PAS présentée comme une « confiance » générique.
|
||||
Probabilités empiriques issues des résidus de validation ; elles restent non validées sous choc.
|
||||
|
||||
Économie véhicule, kNN et protocole Covid/calme dédié non achevés dans cette passe : pas de gain
|
||||
économique revendiqué ni d'autorisation d'activation. `forecast.outlook` reste verrouillé.
|
||||
|
||||
## Vérification
|
||||
|
||||
`.venv/bin/python -m pytest tests/test_clean_pipeline.py -q`
|
||||
Tests : invariance aux mutations futures, préfixe futur refusé, ablation indépendante, cibles
|
||||
isolées, labels aléatoires détruisant le signal synthétique, invariance du modèle/scaling/sélection
|
||||
aux modifications du holdout et assertion globale des disponibilités à la prédiction.
|
||||
|
||||
Lancer : `.venv/bin/python clean_backtest.py` (plusieurs minutes, pas de collecte marché).
|
||||
@@ -1,5 +1,6 @@
|
||||
"""Vérification réelle dans Chromium, avec fixture de stress explicitement synthétique."""
|
||||
import json
|
||||
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
with sync_playwright() as p:
|
||||
|
||||
233
clean_backtest.py
Normal file
233
clean_backtest.py
Normal file
@@ -0,0 +1,233 @@
|
||||
"""Campagne locale v2 isolée, jamais consommée par forecast.outlook.
|
||||
|
||||
Calendrier journalier ; disponibilité historique estimée J+1. Les archives ne prouvent pas
|
||||
la disponibilité effective des corrections rétrospectives. Aucune variable externe.
|
||||
"""
|
||||
|
||||
import json
|
||||
from datetime import date, timedelta
|
||||
from pathlib import Path
|
||||
from statistics import fmean
|
||||
|
||||
import storage
|
||||
from clean_features import HORIZONS, features_asof
|
||||
from clean_targets import target
|
||||
from models import _ridge, _ridge_predict # algèbre seule, aucun build_samples/predict historique
|
||||
|
||||
NAMES = ["past_delta_1", "past_delta_3", "past_delta_7", "past_delta_14", "past_delta_30", "percentile_90"]
|
||||
CANDIDATES = ("naive", "trend", "ar", "ridge")
|
||||
|
||||
|
||||
def states_for(fuel):
|
||||
events = {}
|
||||
for r in storage.price_journal(fuel, "2007-01-01", date.today().isoformat()):
|
||||
if storage.distance_km(44.7737872, -0.5595029, r["lat"], r["lon"]) > 15:
|
||||
continue
|
||||
if r["price"] is not None:
|
||||
events.setdefault(r["day"], []).append(r)
|
||||
if not events:
|
||||
return {}
|
||||
day, last = date.fromisoformat(min(events)), date.fromisoformat(max(events))
|
||||
active, states = {}, {}
|
||||
while day <= last:
|
||||
for r in events.get(day.isoformat(), []):
|
||||
active[r["station_id"]] = (r["price"], day)
|
||||
prices = {s: p for s, (p, d) in active.items() if (day - d).days <= 30}
|
||||
states[day.isoformat()] = dict(
|
||||
day=day.isoformat(), prices=prices, available_at=(day + timedelta(days=1)).isoformat()
|
||||
)
|
||||
day += timedelta(days=1)
|
||||
return states
|
||||
|
||||
|
||||
def feature_rows(states):
|
||||
# Ce filtre précède tout calcul. Aucun label n'existe à cette étape.
|
||||
points = list(states.values())
|
||||
result = {}
|
||||
for i, p in enumerate(points):
|
||||
if len(p["prices"]) < 3 or i < 90:
|
||||
continue
|
||||
row = features_asof(tuple(points[max(0, i - 89) : i + 1]), p["available_at"])
|
||||
if row:
|
||||
result[p["available_at"]] = row
|
||||
return result
|
||||
|
||||
|
||||
def fit(train, candidate, horizon):
|
||||
assert train
|
||||
if candidate == "naive":
|
||||
return lambda x: 0.0
|
||||
if candidate == "trend":
|
||||
return lambda x: x["past_delta_7"] * horizon / 7
|
||||
names = NAMES[:4] if candidate == "ar" else NAMES
|
||||
reg = _ridge(
|
||||
[r["x"] for r in train], names, [r["y"] for r in train], lam=0.5 if candidate == "ar" else 10.0
|
||||
)
|
||||
return lambda x: _ridge_predict(reg, x)
|
||||
|
||||
|
||||
def frozen_package(rows, cutoff, horizon):
|
||||
known = [r for r in rows if r["label_available"] < cutoff]
|
||||
if len(known) < 400:
|
||||
return None
|
||||
boundary = known[-180]["t"]
|
||||
training = [r for r in known if r["label_available"] < boundary]
|
||||
# Echantillonnage hebdomadaire d'un train passé borné, identique pour tous modèles.
|
||||
training = training[-1820::7]
|
||||
validation = [r for r in known if r["t"] >= boundary]
|
||||
if len(training) < 100 or len(validation) < 60:
|
||||
return None
|
||||
candidates = {}
|
||||
for name in CANDIDATES:
|
||||
pred = fit(training, name, horizon)
|
||||
residuals = sorted(r["y"] - pred(r["x"]) for r in validation)
|
||||
candidates[name] = dict(predict=pred, residuals=residuals, val_mae=fmean(abs(x) for x in residuals))
|
||||
selected = min(candidates, key=lambda n: candidates[n]["val_mae"])
|
||||
return dict(
|
||||
candidates=candidates,
|
||||
selected=selected,
|
||||
train_start=training[0]["t"],
|
||||
train_end=training[-1]["t"],
|
||||
max_label=training[-1]["label_available"],
|
||||
validation_start=validation[0]["t"],
|
||||
validation_end=validation[-1]["label_available"],
|
||||
cutoff=cutoff,
|
||||
)
|
||||
|
||||
|
||||
def forecast(package, row, horizon):
|
||||
assert package["validation_end"] < row["t"]
|
||||
assert all(
|
||||
f["max_available_at"] <= row["t"] and horizon in f["allowed_horizons"] for f in row["manifest"]
|
||||
)
|
||||
outputs = {}
|
||||
for name, model in package["candidates"].items():
|
||||
mu = model["predict"](row["x"])
|
||||
errors = model["residuals"]
|
||||
low, high = mu + errors[int(0.1 * (len(errors) - 1))], mu + errors[int(0.9 * (len(errors) - 1))]
|
||||
p_up = sum(mu + e > 0.1 for e in errors) / len(errors)
|
||||
p_down = sum(mu + e < -0.1 for e in errors) / len(errors)
|
||||
outputs[name] = dict(mu_cents=mu, low=low, high=high, p_up=p_up, p_down=p_down)
|
||||
return dict(
|
||||
t=row["t"],
|
||||
actual=row["y"],
|
||||
forecasts=outputs,
|
||||
selected=package["selected"],
|
||||
manifest=row["manifest"],
|
||||
train_start=package["train_start"],
|
||||
train_end=package["train_end"],
|
||||
max_train_label=package["max_label"],
|
||||
validation_end=package["validation_end"],
|
||||
)
|
||||
|
||||
|
||||
def metrics(predictions, name):
|
||||
if not predictions:
|
||||
return None
|
||||
pairs = [
|
||||
(p["forecasts"][p["selected"] if name == "selected" else name], p["actual"]) for p in predictions
|
||||
]
|
||||
naive = fmean(abs(y) for _, y in pairs)
|
||||
mae = fmean(abs(o["mu_cents"] - y) for o, y in pairs)
|
||||
|
||||
def sign(v):
|
||||
return 1 if v > 0.1 else -1 if v < -0.1 else 0
|
||||
|
||||
return dict(
|
||||
n=len(pairs),
|
||||
test_start=predictions[0]["t"],
|
||||
test_end=predictions[-1]["t"],
|
||||
train_start=min(p["train_start"] for p in predictions),
|
||||
train_end=max(p["train_end"] for p in predictions),
|
||||
mae_naive=naive,
|
||||
mae_model=mae,
|
||||
improvement_pct=100 * (1 - mae / naive) if naive else None,
|
||||
rmse=fmean((o["mu_cents"] - y) ** 2 for o, y in pairs) ** 0.5,
|
||||
direction_accuracy=fmean(sign(o["mu_cents"]) == sign(y) for o, y in pairs),
|
||||
interval_80_coverage=fmean(o["low"] <= y <= o["high"] for o, y in pairs),
|
||||
brier_up=fmean((o["p_up"] - (y > 0.1)) ** 2 for o, y in pairs),
|
||||
amplitude_predicted=fmean(abs(o["mu_cents"]) for o, y in pairs),
|
||||
amplitude_actual=naive,
|
||||
economic_result=None,
|
||||
economic_reason="Simulation véhicule non encore validée : aucun gain revendiqué",
|
||||
)
|
||||
|
||||
|
||||
def run():
|
||||
output = Path("reports")
|
||||
output.mkdir(exist_ok=True)
|
||||
report = dict(
|
||||
status="experimental_not_validated",
|
||||
availability="estimated_J_plus_1",
|
||||
external_features=[],
|
||||
entries=[],
|
||||
coverage={},
|
||||
limitations=[
|
||||
"Les archives ne prouvent pas la vraie publication historique. Hypothèse conservatrice J+1.",
|
||||
"Pas de test final vierge après consultation du régime 2026 dans le premier chantier.",
|
||||
"Rolling quotidien : fit et validation réévalués chaque date ; train échantillonné hebdomadaire sur 5 ans.",
|
||||
"Holdout modèle et calibration figés ; hyperparamètres fixes, sélection interne passée.",
|
||||
"Economie et kNN non évalués dans cette première passe propre.",
|
||||
],
|
||||
)
|
||||
for fuel in ("Gazole", "SP95", "SP98", "E10", "E85", "GPLc"):
|
||||
states = states_for(fuel)
|
||||
features = feature_rows(states)
|
||||
report["coverage"][fuel] = dict(
|
||||
first_raw=min(states), first_feature=min(features), last_feature=max(features)
|
||||
)
|
||||
for h in HORIZONS:
|
||||
rows = []
|
||||
# Assemblage tardif : features déjà intégralement matérialisées sans labels.
|
||||
for t, x in features.items():
|
||||
y = target(states, t, h)
|
||||
if y:
|
||||
rows.append(
|
||||
dict(
|
||||
t=t,
|
||||
x=x["values"],
|
||||
manifest=x["manifest"],
|
||||
y=y["delta_cents"],
|
||||
label_available=y["available_at"],
|
||||
)
|
||||
)
|
||||
for mode, start, end in [
|
||||
("rolling", "2025-01-01", "2026-12-31"),
|
||||
("holdout_2026", "2026-01-01", "2026-12-31"),
|
||||
("holdout_2022", "2022-01-01", "2022-12-31"),
|
||||
]:
|
||||
frozen = frozen_package(rows, start, h) if mode != "rolling" else None
|
||||
predictions = []
|
||||
for r in rows:
|
||||
if not start <= r["t"] <= end:
|
||||
continue
|
||||
package = frozen if mode != "rolling" else frozen_package(rows, r["t"], h)
|
||||
if package:
|
||||
predictions.append(forecast(package, r, h))
|
||||
entry = dict(
|
||||
fuel=fuel,
|
||||
horizon=h,
|
||||
mode=mode,
|
||||
cutoff=start if mode != "rolling" else "daily",
|
||||
metrics={n: metrics(predictions, n) for n in (*CANDIDATES, "selected")},
|
||||
)
|
||||
report["entries"].append(entry)
|
||||
with (output / f"clean-{fuel}-{h}-{mode}-predictions.json").open("w") as f:
|
||||
json.dump(predictions, f, ensure_ascii=False)
|
||||
print(fuel, h, mode, entry["metrics"]["selected"], flush=True)
|
||||
(output / "clean-results.json").write_text(json.dumps(report, ensure_ascii=False, indent=2))
|
||||
lines = [
|
||||
"# Backtest local propre — expérimental, non validé",
|
||||
"\nAucun signal connecté au conseil. Les anciens chiffres sont invalides.",
|
||||
"\n## Limites",
|
||||
]
|
||||
lines += ["- " + s for s in report["limitations"]]
|
||||
for e in report["entries"]:
|
||||
lines.append(f"\n## {e['fuel']} J+{e['horizon']} — {e['mode']}")
|
||||
for n, m in e["metrics"].items():
|
||||
lines.append(f"- {n} : " + json.dumps(m, ensure_ascii=False))
|
||||
(output / "clean-report.md").write_text("\n".join(lines))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run()
|
||||
56
clean_features.py
Normal file
56
clean_features.py
Normal file
@@ -0,0 +1,56 @@
|
||||
"""Features pompe seules. Aucun import de cibles, accès base ou données futures."""
|
||||
|
||||
from datetime import date, timedelta
|
||||
from statistics import median
|
||||
|
||||
HORIZONS = (1, 3, 7, 14, 21)
|
||||
|
||||
|
||||
def features_asof(prefix, prediction_time, exclude=()):
|
||||
"""Reçoit exclusivement des états déjà disponibles. Rejette tout préfixe futur."""
|
||||
assert all(p["available_at"] <= prediction_time for p in prefix)
|
||||
points = {p["day"]: p for p in prefix}
|
||||
if not prefix:
|
||||
return None
|
||||
current = prefix[-1]
|
||||
day = date.fromisoformat(current["day"])
|
||||
values, manifest = {}, []
|
||||
for lag in (1, 3, 7, 14, 30):
|
||||
name = f"past_delta_{lag}"
|
||||
if name in exclude:
|
||||
continue
|
||||
previous = points.get((day - timedelta(days=lag)).isoformat())
|
||||
if previous is None:
|
||||
return None
|
||||
shared = current["prices"].keys() & previous["prices"].keys()
|
||||
if len(shared) < 3:
|
||||
return None
|
||||
values[name] = median((current["prices"][s] - previous["prices"][s]) * 100 for s in shared)
|
||||
manifest.append(
|
||||
dict(
|
||||
name=name,
|
||||
source="prix-carburants:journal",
|
||||
lookback_days=lag,
|
||||
max_available_at=current["available_at"],
|
||||
calculated=True,
|
||||
allowed_horizons=HORIZONS,
|
||||
availability_estimated=True,
|
||||
)
|
||||
)
|
||||
if "percentile_90" not in exclude:
|
||||
past = [median(p["prices"].values()) for p in prefix if len(p["prices"]) >= 3]
|
||||
level = median(current["prices"].values())
|
||||
values["percentile_90"] = sum(v <= level for v in past) / len(past)
|
||||
manifest.append(
|
||||
dict(
|
||||
name="percentile_90",
|
||||
source="prix-carburants:journal",
|
||||
lookback_days=90,
|
||||
max_available_at=current["available_at"],
|
||||
calculated=True,
|
||||
allowed_horizons=HORIZONS,
|
||||
availability_estimated=True,
|
||||
)
|
||||
)
|
||||
assert all(f["max_available_at"] <= prediction_time for f in manifest)
|
||||
return dict(prediction_time=prediction_time, values=values, manifest=manifest)
|
||||
22
clean_targets.py
Normal file
22
clean_targets.py
Normal file
@@ -0,0 +1,22 @@
|
||||
"""Labels futurs isolés : ce module n'est jamais importé par clean_features."""
|
||||
|
||||
from datetime import date, timedelta
|
||||
from statistics import median
|
||||
|
||||
|
||||
def target(states, prediction_time, horizon):
|
||||
# Le dernier état disponible à t est celui de la veille (hypothèse J+1).
|
||||
start = date.fromisoformat(prediction_time) - timedelta(days=1)
|
||||
end = start + timedelta(days=horizon)
|
||||
a, b = states.get(start.isoformat()), states.get(end.isoformat())
|
||||
if not a or not b:
|
||||
return None
|
||||
shared = a["prices"].keys() & b["prices"].keys()
|
||||
if len(shared) < 3:
|
||||
return None
|
||||
return dict(
|
||||
delta_cents=median((b["prices"][s] - a["prices"][s]) * 100 for s in shared),
|
||||
available_at=b["available_at"],
|
||||
stations=len(shared),
|
||||
horizon=horizon,
|
||||
)
|
||||
101
tests/test_clean_pipeline.py
Normal file
101
tests/test_clean_pipeline.py
Normal file
@@ -0,0 +1,101 @@
|
||||
import copy
|
||||
import random
|
||||
from datetime import date, timedelta
|
||||
from statistics import fmean
|
||||
|
||||
import pytest
|
||||
|
||||
from clean_backtest import fit, forecast, frozen_package
|
||||
from clean_features import features_asof
|
||||
from clean_targets import target
|
||||
|
||||
|
||||
def states():
|
||||
out = {}
|
||||
for i in range(110):
|
||||
day = date(2020, 1, 1) + timedelta(days=i)
|
||||
out[day.isoformat()] = dict(
|
||||
day=day.isoformat(),
|
||||
available_at=(day + timedelta(days=1)).isoformat(),
|
||||
prices={str(s): 2 + i * 0.001 for s in range(4)},
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def test_future_mutations_cannot_change_features():
|
||||
data = states()
|
||||
points = list(data.values())
|
||||
prefix = points[:90]
|
||||
before = features_asof(prefix, prefix[-1]["available_at"])
|
||||
for p in points[90:]:
|
||||
p["prices"] = {"future": 1000}
|
||||
assert before == features_asof(prefix, prefix[-1]["available_at"])
|
||||
with pytest.raises(AssertionError):
|
||||
features_asof(points, prefix[-1]["available_at"])
|
||||
assert before["values"]["past_delta_7"] == pytest.approx(0.7)
|
||||
assert all(f["max_available_at"] <= before["prediction_time"] for f in before["manifest"])
|
||||
|
||||
|
||||
def test_ablation_and_labels_do_not_mutate_prefix():
|
||||
data = states()
|
||||
prefix = list(data.values())[:90]
|
||||
original = copy.deepcopy(prefix)
|
||||
full = features_asof(prefix, prefix[-1]["available_at"])
|
||||
less = features_asof(prefix, prefix[-1]["available_at"], exclude=("past_delta_7",))
|
||||
assert less["values"] == {k: v for k, v in full["values"].items() if k != "past_delta_7"}
|
||||
assert target(data, prefix[-1]["available_at"], 7)["delta_cents"] == pytest.approx(0.7)
|
||||
assert prefix == original
|
||||
|
||||
|
||||
def synthetic(n=1400):
|
||||
rng = random.Random(42)
|
||||
out = []
|
||||
for i in range(n):
|
||||
t = date(2018, 1, 1) + timedelta(days=i)
|
||||
v = rng.uniform(-3, 3)
|
||||
out.append(
|
||||
dict(
|
||||
t=t.isoformat(),
|
||||
label_available=(t + timedelta(days=7)).isoformat(),
|
||||
x={f"past_delta_{h}": v for h in (1, 3, 7, 14, 30)} | {"percentile_90": 0.5},
|
||||
y=2 * v + rng.gauss(0, 0.1),
|
||||
manifest=[],
|
||||
)
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def test_shuffled_labels_lose_predictive_power():
|
||||
rows = synthetic()
|
||||
train = copy.deepcopy(rows[:500])
|
||||
test = rows[600:]
|
||||
proper = fit(train, "ridge", 7)
|
||||
ys = [r["y"] for r in train]
|
||||
random.Random(91).shuffle(ys)
|
||||
for r, y in zip(train, ys, strict=False):
|
||||
r["y"] = y
|
||||
shuffled = fit(train, "ridge", 7)
|
||||
def mae(pred):
|
||||
return fmean(abs(pred(r["x"]) - r["y"]) for r in test)
|
||||
assert mae(proper) < 0.2
|
||||
assert mae(shuffled) > 1
|
||||
|
||||
|
||||
def test_holdout_selection_and_preprocessing_are_frozen():
|
||||
rows = synthetic()
|
||||
cutoff = rows[1200]["t"]
|
||||
package = frozen_package(rows, cutoff, 7)
|
||||
before = {n: m["predict"](rows[1210]["x"]) for n, m in package["candidates"].items()}
|
||||
altered = copy.deepcopy(rows)
|
||||
for r in altered[1200:]:
|
||||
r["y"] = 99999
|
||||
r["x"] = {k: 99999 for k in r["x"]}
|
||||
other = frozen_package(altered, cutoff, 7)
|
||||
assert package["selected"] == other["selected"]
|
||||
assert before == {n: m["predict"](rows[1210]["x"]) for n, m in other["candidates"].items()}
|
||||
assert package["validation_end"] < cutoff
|
||||
assert package["max_label"] < package["validation_start"]
|
||||
bad = copy.deepcopy(rows[1210])
|
||||
bad["manifest"] = [dict(max_available_at="2099-01-01", allowed_horizons=[7])]
|
||||
with pytest.raises(AssertionError):
|
||||
forecast(package, bad, 7)
|
||||
Reference in New Issue
Block a user