235 lines
9.5 KiB
Python
235 lines
9.5 KiB
Python
"""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 and storage.observation_not_future(r.get("source_updated") or r["day"]):
|
|
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, as_of=None):
|
|
# Ce filtre précède tout calcul. Aucun label n'existe à cette étape.
|
|
as_of = as_of or date.today().isoformat()
|
|
points = [p for p in states.values() if p["available_at"] <= as_of and p["day"] <= as_of]
|
|
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 and y["available_at"] <= date.today().isoformat():
|
|
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()
|