Identite Fuel Advisor, assets locaux et audit economique corrige
Renommage Fuel Advisor (titre, header, favicon SVG/PNG, apple-touch-icon, logo SVG servis localement). Oracle: contrainte de penalty corrigee (portee inversee), quantites non entieres ecartees avant rejeu, double comptage de penalite supprime. Audit economique regenerer: plafonds omniscients coherents et positifs; deux lignes non resolues conservees telles quelles.
This commit is contained in:
@@ -11,11 +11,9 @@ depuis plus de 30 jours écartées).
|
||||
"""
|
||||
|
||||
import json
|
||||
import math
|
||||
import statistics
|
||||
from datetime import date, timedelta
|
||||
from pathlib import Path
|
||||
from statistics import fmean
|
||||
|
||||
import validation
|
||||
from clean_backtest import states_for
|
||||
@@ -44,74 +42,65 @@ def daily_price_series(fuel, start=START, end=END, minimum_panel=3):
|
||||
point = states.get(day.isoformat())
|
||||
prices = point["prices"] if point else {}
|
||||
if len(prices) >= minimum_panel:
|
||||
out.append(dict(day=day.isoformat(),
|
||||
price=round(statistics.median(prices.values()), 4),
|
||||
panel=len(prices)))
|
||||
out.append(
|
||||
dict(
|
||||
day=day.isoformat(), price=round(statistics.median(prices.values()), 4), panel=len(prices)
|
||||
)
|
||||
)
|
||||
day += timedelta(days=1)
|
||||
return out
|
||||
|
||||
|
||||
def signals(fuel, horizon=14, key="up_3", statistic="median"):
|
||||
"""Signaux de hausse du modèle local, seuil appris sur les scores strictement antérieurs.
|
||||
"""Seuils strictement passés ; amplitudes de tous les signaux mûrs, jamais des seuls succès."""
|
||||
from signal_audit import audit_rows
|
||||
|
||||
L'amplitude attendue n'est pas inventée : c'est la médiane des hausses maximales **réalisées les
|
||||
jours où ce même signal s'était déclenché**, sur le passé uniquement. Utiliser la médiane
|
||||
inconditionnelle de tous les jours la sous-estimerait massivement (0,25 c€/L au lieu de ~12) et
|
||||
interdirait toute anticipation : ce serait conclure sur un mauvais estimateur, pas sur le signal.
|
||||
Tant qu'il n'y a pas assez d'antécédents de signal, aucune anticipation n'est autorisée.
|
||||
"""
|
||||
rows = local_rows(fuel, horizon)
|
||||
history, amplitudes, fired_amplitudes, out = [], [], [], {}
|
||||
for row in rows:
|
||||
score = row["score"].get(key)
|
||||
if score is None:
|
||||
continue
|
||||
fired = False
|
||||
if len(history) >= MIN_SCORES:
|
||||
ordered = sorted(history[-THRESHOLD_WINDOW:])
|
||||
rank = min(len(ordered) - 1, math.ceil(QUANTILE * (len(ordered) - 1)))
|
||||
threshold = ordered[rank]
|
||||
fired = score >= threshold
|
||||
recent = fired_amplitudes[-THRESHOLD_WINDOW:]
|
||||
change = (statistics.median(recent) if statistic == "median" else fmean(recent)) \
|
||||
if len(fired_amplitudes) >= MIN_SIGNAL_HISTORY else None
|
||||
if fired and change and change > 0:
|
||||
out[row["t"]] = dict(direction="up", change_cents=round(change, 2),
|
||||
score=round(score, 4), threshold=round(threshold, 4),
|
||||
sample=len(fired_amplitudes))
|
||||
history.append(score)
|
||||
amplitudes.append(row["target"]["future_max_delta"])
|
||||
if fired:
|
||||
fired_amplitudes.append(row["target"]["future_max_delta"])
|
||||
points = audit_rows(local_rows(fuel, horizon), key, minimum=MIN_SCORES, window=THRESHOLD_WINDOW)
|
||||
out = {}
|
||||
field = "median_amplitude_all_signals" if statistic == "median" else "expected_amplitude_all_signals"
|
||||
for point in points:
|
||||
change = point[field]
|
||||
if point["fired"] and change is not None and change > 0:
|
||||
out[point["t"]] = dict(
|
||||
direction="up",
|
||||
change_cents=change,
|
||||
expected_amplitude_all_signals=point["expected_amplitude_all_signals"],
|
||||
score=point["score"],
|
||||
threshold=point["threshold"],
|
||||
sample=point["amplitude_sample"],
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def simulate_profile(vehicle, series, forecasts):
|
||||
naive = validation.simulate(series, vehicle, strategy="naive",
|
||||
detour_km_per_stop=DETOUR_KM_PER_STOP)
|
||||
advisor = validation.simulate(series, vehicle, strategy="advisor", forecasts=forecasts,
|
||||
detour_km_per_stop=DETOUR_KM_PER_STOP)
|
||||
naive = validation.simulate(series, vehicle, strategy="naive", detour_km_per_stop=DETOUR_KM_PER_STOP)
|
||||
advisor = validation.simulate(
|
||||
series, vehicle, strategy="advisor", forecasts=forecasts, detour_km_per_stop=DETOUR_KM_PER_STOP
|
||||
)
|
||||
out = dict(profile=vehicle.get("label", "?"), fuel=vehicle["fuel"], vehicle=vehicle)
|
||||
for name, run in (("reference", naive), ("anticipation", advisor)):
|
||||
out[name] = dict(
|
||||
cost_eur=run["cost_eur"], litres=run["litres"], refuels=run["refuels"],
|
||||
litres_per_refuel=run["litres_per_refuel"], detour_km=run["detour_km"],
|
||||
cost_eur=run["cost_eur"],
|
||||
litres=run["litres"],
|
||||
refuels=run["refuels"],
|
||||
litres_per_refuel=run["litres_per_refuel"],
|
||||
detour_km=run["detour_km"],
|
||||
price_paid_per_liter=run["cost_per_liter"],
|
||||
refuels_per_month=run["refuels_per_month"],
|
||||
min_interval_days=run["min_interval_days"],
|
||||
below_reserve_days=run["below_reserve_days"], empty_days=run["empty_days"],
|
||||
below_reserve_days=run["below_reserve_days"],
|
||||
empty_days=run["empty_days"],
|
||||
)
|
||||
out["comfort"] = validation.comfort_check(advisor)
|
||||
out["anticipated_refuels"] = sum(1 for day in advisor["refuel_days"]
|
||||
if day in forecasts and day not in naive["refuel_days"])
|
||||
out["signal_days"] = len(forecasts)
|
||||
out["anticipated_refuels"] = sum(
|
||||
1 for day in advisor["refuel_days"] if day in forecasts and day not in naive["refuel_days"]
|
||||
)
|
||||
out["signal_days"] = sum(point["day"] in forecasts for point in series)
|
||||
for penalty in PENALTIES:
|
||||
value = validation.net_value(naive, advisor, penalty_per_extra_refuel=penalty)
|
||||
out[f"net_saving_penalty_{penalty:g}"] = value["net_saving_eur"]
|
||||
out["value"] = validation.net_value(naive, advisor,
|
||||
penalty_per_extra_refuel=PENALTIES[1])
|
||||
out["price_gain_cents_per_liter"] = round(
|
||||
100 * (naive["cost_per_liter"] - advisor["cost_per_liter"]), 3)
|
||||
out["value"] = validation.net_value(naive, advisor, penalty_per_extra_refuel=PENALTIES[1])
|
||||
out["price_gain_cents_per_liter"] = round(100 * (naive["cost_per_liter"] - advisor["cost_per_liter"]), 3)
|
||||
return out
|
||||
|
||||
|
||||
@@ -124,28 +113,40 @@ def verdict(results):
|
||||
useful, degraded, neutral, details = [], [], [], []
|
||||
for entry in results:
|
||||
net = entry["net_saving_penalty_3"]
|
||||
safety_ok = (entry["anticipation"]["below_reserve_days"]
|
||||
<= entry["reference"]["below_reserve_days"]
|
||||
and entry["anticipation"]["empty_days"] <= entry["reference"]["empty_days"])
|
||||
safety_ok = (
|
||||
entry["anticipation"]["below_reserve_days"] <= entry["reference"]["below_reserve_days"]
|
||||
and entry["anticipation"]["empty_days"] <= entry["reference"]["empty_days"]
|
||||
)
|
||||
comfort_ok = entry["comfort"]["comfortable"]
|
||||
if net > 0 and safety_ok and comfort_ok:
|
||||
useful.append(entry["profile"])
|
||||
status = "retenu"
|
||||
elif net < 0 or not safety_ok:
|
||||
degraded.append(entry["profile"])
|
||||
status = ("marge de sécurité dégradée" if not safety_ok else "coût réel dégradé")
|
||||
status = "marge de sécurité dégradée" if not safety_ok else "coût réel dégradé"
|
||||
else:
|
||||
neutral.append(entry["profile"])
|
||||
status = "neutre"
|
||||
details.append(dict(profile=entry["profile"], status=status,
|
||||
net_saving_penalty_3=net, safety_ok=safety_ok, comfort_ok=comfort_ok,
|
||||
below_reserve_naive=entry["reference"]["below_reserve_days"],
|
||||
below_reserve_advisor=entry["anticipation"]["below_reserve_days"]))
|
||||
return dict(useful=useful, degraded=degraded, neutral=neutral, details=details,
|
||||
conclusion="intéressant" if len(useful) >= 3 and not degraded
|
||||
else "intérêt non démontré",
|
||||
rule="utile si gain net > 0 sur au moins 3 profils sur 4, confort tenu et "
|
||||
"aucune dégradation de la marge de sécurité (pénalité de passage 3 €)")
|
||||
details.append(
|
||||
dict(
|
||||
profile=entry["profile"],
|
||||
status=status,
|
||||
net_saving_penalty_3=net,
|
||||
safety_ok=safety_ok,
|
||||
comfort_ok=comfort_ok,
|
||||
below_reserve_naive=entry["reference"]["below_reserve_days"],
|
||||
below_reserve_advisor=entry["anticipation"]["below_reserve_days"],
|
||||
)
|
||||
)
|
||||
return dict(
|
||||
useful=useful,
|
||||
degraded=degraded,
|
||||
neutral=neutral,
|
||||
details=details,
|
||||
conclusion="intéressant" if len(useful) >= 3 and not degraded else "intérêt non démontré",
|
||||
rule="utile si gain net > 0 sur au moins 3 profils sur 4, confort tenu et "
|
||||
"aucune dégradation de la marge de sécurité (pénalité de passage 3 €)",
|
||||
)
|
||||
|
||||
|
||||
def run():
|
||||
@@ -162,31 +163,46 @@ def run():
|
||||
entry["days"] = len(series)
|
||||
entry["window"] = f"{series[0]['day']} → {series[-1]['day']}" if series else None
|
||||
results.append(entry)
|
||||
print(f"[{statistic}] {entry['profile']:22s} référence {entry['reference']['cost_eur']:8.2f} €"
|
||||
f" · anticipation {entry['anticipation']['cost_eur']:8.2f} € · net "
|
||||
f"{entry['net_saving_penalty_3']:+.2f} € · pleins {entry['reference']['refuels']}"
|
||||
f"→{entry['anticipation']['refuels']}", flush=True)
|
||||
print(
|
||||
f"[{statistic}] {entry['profile']:22s} référence {entry['reference']['cost_eur']:8.2f} €"
|
||||
f" · anticipation {entry['anticipation']['cost_eur']:8.2f} € · net "
|
||||
f"{entry['net_saving_penalty_3']:+.2f} € · pleins {entry['reference']['refuels']}"
|
||||
f"→{entry['anticipation']['refuels']}",
|
||||
flush=True,
|
||||
)
|
||||
reports[statistic] = dict(
|
||||
status="experimental_no_production", amplitude_statistic=statistic,
|
||||
status="experimental_no_production",
|
||||
amplitude_statistic=statistic,
|
||||
window=f"{START} → {END}",
|
||||
signal="modèle local, cible hausse ≥3 c€/L à J+14, seuil q90 appris sur le passé",
|
||||
detour_km_per_stop=DETOUR_KM_PER_STOP, penalties=list(PENALTIES),
|
||||
detour_km_per_stop=DETOUR_KM_PER_STOP,
|
||||
penalties=list(PENALTIES),
|
||||
conservative="anticipation sur signal de hausse uniquement, jamais d'attente sur une "
|
||||
"baisse (signal de baisse non validé)",
|
||||
profiles=results, verdict=verdict(results))
|
||||
"baisse (signal de baisse non validé)",
|
||||
profiles=results,
|
||||
verdict=verdict(results),
|
||||
)
|
||||
(output / "vehicle-simulation.json").write_text(json.dumps(reports, ensure_ascii=False, indent=1))
|
||||
write_report(reports, output / "vehicle-simulation.md")
|
||||
for statistic, report in reports.items():
|
||||
print(statistic, json.dumps({k: report["verdict"][k] for k in
|
||||
("useful", "degraded", "neutral", "conclusion")},
|
||||
ensure_ascii=False))
|
||||
print(
|
||||
statistic,
|
||||
json.dumps(
|
||||
{k: report["verdict"][k] for k in ("useful", "degraded", "neutral", "conclusion")},
|
||||
ensure_ascii=False,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def write_report(reports, path):
|
||||
lines = ["# Simulation économique véhicule — baseline locale, stratégie conservatrice", "",
|
||||
"Deux hypothèses d'amplitude, toutes deux tirées du passé, sont publiées pour ne pas",
|
||||
"choisir après avoir vu le résultat : **médiane** (conservatrice) et **moyenne**",
|
||||
"(optimiste, dominée par les gros mouvements).", ""]
|
||||
lines = [
|
||||
"# Simulation économique véhicule — baseline locale, stratégie conservatrice",
|
||||
"",
|
||||
"Deux hypothèses d'amplitude, toutes deux tirées du passé, sont publiées pour ne pas",
|
||||
"choisir après avoir vu le résultat : **médiane** (conservatrice) et **moyenne**",
|
||||
"(optimiste, dominée par les gros mouvements).",
|
||||
"",
|
||||
]
|
||||
for statistic, report in reports.items():
|
||||
lines += _report_lines(statistic, report)
|
||||
Path(path).write_text("\n".join(lines))
|
||||
@@ -194,37 +210,58 @@ def write_report(reports, path):
|
||||
|
||||
def _report_lines(statistic, report):
|
||||
lines = [f"## Hypothèse d'amplitude : {statistic}", ""]
|
||||
lines = [f"Fenêtre : {report['window']}. Signal : {report['signal']}.", "",
|
||||
f"Détour par passage : {report['detour_km_per_stop']} km (hypothèse explicite).",
|
||||
"Pénalité testée : 0 / 3 / 6 € par passage supplémentaire.", "",
|
||||
f"Principe : {report['conservative']}.", "",
|
||||
"## Tableau synthétique", ""]
|
||||
lines = [
|
||||
f"Fenêtre : {report['window']}. Signal : {report['signal']}.",
|
||||
"",
|
||||
f"Détour par passage : {report['detour_km_per_stop']} km (hypothèse explicite).",
|
||||
"Pénalité testée : 0 / 3 / 6 € par passage supplémentaire.",
|
||||
"",
|
||||
f"Principe : {report['conservative']}.",
|
||||
"",
|
||||
"## Tableau synthétique",
|
||||
"",
|
||||
]
|
||||
for entry in report["profiles"]:
|
||||
reference, anticipation = entry["reference"], entry["anticipation"]
|
||||
lines.append(f"### {entry['profile']} ({entry['fuel']}, {entry['window']}, "
|
||||
f"{entry['days']} jours)")
|
||||
lines.append(f"- coût total du carburant : **{reference['cost_eur']} €** contre "
|
||||
f"**{anticipation['cost_eur']} €** "
|
||||
f"({reference['cost_eur'] - anticipation['cost_eur']:+.2f} €)")
|
||||
lines.append(f"- prix moyen payé : {reference['price_paid_per_liter']} contre "
|
||||
f"{anticipation['price_paid_per_liter']} €/L "
|
||||
f"({entry['price_gain_cents_per_liter']:+} c€/L)")
|
||||
lines.append(f"- passages : {reference['refuels']} contre {anticipation['refuels']}"
|
||||
f" ({anticipation['refuels_per_month']} par mois) · litres par passage : "
|
||||
f"{reference['litres_per_refuel']} contre {anticipation['litres_per_refuel']}")
|
||||
lines.append(f"- litres achetés : {reference['litres']} contre {anticipation['litres']} · "
|
||||
f"détour {reference['detour_km']} contre {anticipation['detour_km']} km")
|
||||
lines.append(f"- passages anticipés sur signal : {entry['anticipated_refuels']}"
|
||||
f" (sur {entry['signal_days']} jours signalés)")
|
||||
lines.append(f"- économie nette : {entry['net_saving_penalty_0']:+} € (sans pénalité) · "
|
||||
f"{entry['net_saving_penalty_3']:+} € (3 €) · "
|
||||
f"{entry['net_saving_penalty_6']:+} € (6 €)")
|
||||
lines.append(f"- marge de sécurité : {reference['below_reserve_days']} jour(s) sous la "
|
||||
f"réserve contre {anticipation['below_reserve_days']} · réservoir vide : "
|
||||
f"{reference['empty_days']} contre {anticipation['empty_days']}")
|
||||
lines.append(f"- confort : {entry['comfort']['comfortable']}"
|
||||
f" {entry['comfort']['problems'] or ''} · intervalle minimal "
|
||||
f"{entry['comfort']['min_interval_days']} jour(s)")
|
||||
lines.append(f"### {entry['profile']} ({entry['fuel']}, {entry['window']}, {entry['days']} jours)")
|
||||
lines.append(
|
||||
f"- coût total du carburant : **{reference['cost_eur']} €** contre "
|
||||
f"**{anticipation['cost_eur']} €** "
|
||||
f"({reference['cost_eur'] - anticipation['cost_eur']:+.2f} €)"
|
||||
)
|
||||
lines.append(
|
||||
f"- prix moyen payé : {reference['price_paid_per_liter']} contre "
|
||||
f"{anticipation['price_paid_per_liter']} €/L "
|
||||
f"({entry['price_gain_cents_per_liter']:+} c€/L)"
|
||||
)
|
||||
lines.append(
|
||||
f"- passages : {reference['refuels']} contre {anticipation['refuels']}"
|
||||
f" ({anticipation['refuels_per_month']} par mois) · litres par passage : "
|
||||
f"{reference['litres_per_refuel']} contre {anticipation['litres_per_refuel']}"
|
||||
)
|
||||
lines.append(
|
||||
f"- litres achetés : {reference['litres']} contre {anticipation['litres']} · "
|
||||
f"détour {reference['detour_km']} contre {anticipation['detour_km']} km"
|
||||
)
|
||||
lines.append(
|
||||
f"- passages anticipés sur signal : {entry['anticipated_refuels']}"
|
||||
f" (sur {entry['signal_days']} jours signalés)"
|
||||
)
|
||||
lines.append(
|
||||
f"- économie nette : {entry['net_saving_penalty_0']:+} € (sans pénalité) · "
|
||||
f"{entry['net_saving_penalty_3']:+} € (3 €) · "
|
||||
f"{entry['net_saving_penalty_6']:+} € (6 €)"
|
||||
)
|
||||
lines.append(
|
||||
f"- marge de sécurité : {reference['below_reserve_days']} jour(s) sous la "
|
||||
f"réserve contre {anticipation['below_reserve_days']} · réservoir vide : "
|
||||
f"{reference['empty_days']} contre {anticipation['empty_days']}"
|
||||
)
|
||||
lines.append(
|
||||
f"- confort : {entry['comfort']['comfortable']}"
|
||||
f" {entry['comfort']['problems'] or ''} · intervalle minimal "
|
||||
f"{entry['comfort']['min_interval_days']} jour(s)"
|
||||
)
|
||||
lines.append("")
|
||||
lines.append("## Verdict")
|
||||
lines.append("")
|
||||
@@ -233,16 +270,22 @@ def _report_lines(statistic, report):
|
||||
lines.append(f"- profils dégradés : {report['verdict']['degraded'] or 'aucun'}")
|
||||
lines.append(f"- profils neutres : {report['verdict']['neutral'] or 'aucun'}")
|
||||
for detail in report["verdict"]["details"]:
|
||||
lines.append(f" - {detail['profile']} : {detail['status']} (net "
|
||||
f"{detail['net_saving_penalty_3']:+} € · jours sous la réserve "
|
||||
f"{detail['below_reserve_naive']} → {detail['below_reserve_advisor']} · "
|
||||
f"confort {'tenu' if detail['comfort_ok'] else 'dégradé'})")
|
||||
lines.append(
|
||||
f" - {detail['profile']} : {detail['status']} (net "
|
||||
f"{detail['net_saving_penalty_3']:+} € · jours sous la réserve "
|
||||
f"{detail['below_reserve_naive']} → {detail['below_reserve_advisor']} · "
|
||||
f"confort {'tenu' if detail['comfort_ok'] else 'dégradé'})"
|
||||
)
|
||||
lines.append(f"- **{report['verdict']['conclusion']}**")
|
||||
lines.append("")
|
||||
lines.append("Aucun branchement au conseil réel : ces chiffres servent à décider si le moteur "
|
||||
"prédictif mérite un jour d'entrer dans le conseil véhicule.")
|
||||
lines.append(
|
||||
"Aucun branchement au conseil réel : ces chiffres servent à décider si le moteur "
|
||||
"prédictif mérite un jour d'entrer dans le conseil véhicule."
|
||||
)
|
||||
return lines
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run()
|
||||
raise SystemExit(
|
||||
"Rapport obsolète : utiliser research/economic_audit/run_economic_audit.py ; voir VEHICLE.md"
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user