Historique officiel 2007-2026, percentiles separes espace/temps, cout du detour et banc de validation
Les archives annuelles officielles de prix-carburants.gouv.fr sont importees retrospectivement depuis 2007 (20 annees, 354597 lignes sur 117 stations) avec la date declaree par la station, un marqueur d origine, sans ecrasement ni continuite inventee. Le percentile spatial et le percentile historique sont desormais deux indicateurs distincts : seul le second peut declencher un achat anticipe, et son affichage exige une fenetre reellement couverte. Le cout du detour est calcule automatiquement (distance routiere supplementaire x consommation x prix) et deduit du gain, tandis que le seuil de gain net pour un ravitaillement supplementaire reste configurable par vehicule. La quantite de carburant du reservoir est clairement presentee comme une estimation. Le banc de validation impose un backtest chronologique sans fuite, des metriques par horizon avec calibration de la confiance, et une simulation economique naive contre Fuel Advisor ; aucune prevision ne sera branchee avant que les criteres ne soient atteints.
This commit is contained in:
131
tests/test_backfill.py
Normal file
131
tests/test_backfill.py
Normal file
@@ -0,0 +1,131 @@
|
||||
"""Archives officielles : formats, sélection, dates réelles, et aucune continuité inventée."""
|
||||
|
||||
import io
|
||||
import zipfile
|
||||
|
||||
import backfill
|
||||
|
||||
XML = """<?xml version="1.0" encoding="ISO-8859-1" standalone="yes"?><pdv_liste>
|
||||
<pdv id="1111111" latitude="4477000" longitude="-56000" cp="33000" pop="R">
|
||||
<ville>VILLENAVE D ORNON</ville>
|
||||
<prix nom="Gazole" id="1" maj="2007-01-04 18:43:38.841521" valeur="999"/>
|
||||
<prix nom="Gazole" id="1" maj="2007-01-04 21:10:00.000000" valeur="1005"/>
|
||||
<prix nom="Gazole" id="1" maj="2007-03-13 11:44:26.673271" valeur="1009"/>
|
||||
<prix nom="E10" id="5" maj="2007-03-13T12:00:00" valeur="1.052"/>
|
||||
<prix nom="E85" id="4" maj="2007-03-13T12:00:00" valeur="0.850"/>
|
||||
<prix nom="Gazole" id="8" maj="0000-00-00 00:00:00" valeur="1111"/>
|
||||
<prix nom="Gazole" id="9" maj="2007-04-01T09:00:00" valeur="0"/>
|
||||
</pdv>
|
||||
<pdv id="2222222" latitude="4800000" longitude="200000" cp="75000" pop="R">
|
||||
<ville>PARIS</ville>
|
||||
<prix nom="Gazole" id="1" maj="2007-02-02T08:00:00" valeur="1050"/>
|
||||
</pdv>
|
||||
<pdv id="3333333" latitude="4477100" longitude="-55900" cp="33140" pop="R">
|
||||
<ville>BEGLES</ville>
|
||||
<prix nom="Gazole" id="1" maj="2007-02-02T08:00:00" valeur="20000"/>
|
||||
<prix nom="Gazole" id="1" maj="2007-02-03T08:00:00" valeur="1.078"/>
|
||||
</pdv>
|
||||
</pdv_liste>"""
|
||||
|
||||
BBOX = (44.5, 45.0, -0.9, -0.2) # Gironde
|
||||
|
||||
|
||||
def archive_bytes(xml=XML):
|
||||
buffer = io.BytesIO()
|
||||
with zipfile.ZipFile(buffer, "w") as archive:
|
||||
archive.writestr("PrixCarburants_annuel_2007.xml", xml.encode("iso-8859-1"))
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def test_price_formats_both_eras_are_accepted():
|
||||
assert backfill.parse_price("999") == 0.999, "millièmes d’euro (premières années)"
|
||||
assert backfill.parse_price("1.707") == 1.707, "euros décimaux (années récentes)"
|
||||
assert backfill.parse_price("1,707") == 1.707
|
||||
assert backfill.parse_price("") is None
|
||||
assert backfill.parse_price(None) is None
|
||||
assert backfill.parse_price("0") is None, "valeur nulle : pas un prix"
|
||||
assert backfill.parse_price("99") is None, "0,099 €/L : implausible"
|
||||
assert backfill.parse_price("20000") is None, "20 €/L : implausible"
|
||||
|
||||
|
||||
def test_declared_dates_both_formats():
|
||||
assert backfill.parse_declared("2007-01-04 18:43:38.841521") == "2007-01-04T18:43:38"
|
||||
assert backfill.parse_declared("2025-01-02T00:37:00") == "2025-01-02T00:37:00"
|
||||
assert backfill.parse_declared("0000-00-00 00:00:00") is None
|
||||
assert backfill.parse_declared("") is None
|
||||
assert backfill.parse_declared(None) is None
|
||||
|
||||
|
||||
def test_fuel_names_are_normalised():
|
||||
assert backfill.normalize_fuel("Gazole") == "Gazole"
|
||||
assert backfill.normalize_fuel("SP95-E10") == "E10"
|
||||
assert backfill.normalize_fuel("e10") == "E10"
|
||||
assert backfill.normalize_fuel("GPLc") == "GPLc"
|
||||
assert backfill.normalize_fuel("SP95") == "SP95"
|
||||
assert backfill.normalize_fuel("inconnu") is None
|
||||
|
||||
|
||||
def test_scan_keeps_only_the_target_box_and_the_declared_dates():
|
||||
rows, stations = backfill.scan_archive(archive_bytes(), bbox=BBOX, fuels=("Gazole", "E10"))
|
||||
assert set(stations) == {"1111111", "3333333"}, "Paris est hors zone"
|
||||
by_key = {(row["station_id"], row["fuel"], row["day"]): row for row in rows}
|
||||
assert ("1111111", "Gazole", "2007-01-04") in by_key, "la date est celle déclarée"
|
||||
assert by_key[("1111111", "Gazole", "2007-01-04")]["price"] == 1.005, "dernière valeur du jour"
|
||||
assert by_key[("1111111", "Gazole", "2007-01-04")]["declared_at"] == "2007-01-04T21:10:00"
|
||||
assert by_key[("1111111", "Gazole", "2007-03-13")]["price"] == 1.009
|
||||
assert by_key[("1111111", "E10", "2007-03-13")]["price"] == 1.052
|
||||
assert ("1111111", "E85", "2007-03-13") not in by_key, "carburant non demandé"
|
||||
assert not any(row["price"] in (0.0, 1.111, 20.0) for row in rows), "valeurs invalides écartées"
|
||||
assert stations["1111111"]["first_day"] == "2007-01-04"
|
||||
assert stations["1111111"]["last_day"] == "2007-03-13"
|
||||
assert stations["1111111"]["days"] == 2
|
||||
|
||||
|
||||
def test_stations_outside_the_box_are_ignored_even_when_targeted_by_id():
|
||||
rows, stations = backfill.scan_archive(
|
||||
archive_bytes(), bbox=BBOX, fuels=("Gazole",), station_ids={"2222222"}
|
||||
)
|
||||
assert "2222222" in stations, "un identifiant suivi est repris même hors zone"
|
||||
assert "1111111" in stations, "et la zone reste prise en compte"
|
||||
assert any(
|
||||
row["station_id"] == "2222222" and row["day"] == "2007-02-02" and row["price"] == 1.05 for row in rows
|
||||
)
|
||||
|
||||
|
||||
def test_no_price_is_ever_invented_for_an_absent_year():
|
||||
"""Une archive sans la station ne produit aucune ligne : aucune continuité fabriquée."""
|
||||
empty = XML.split('<pdv id="3333333"')[0] + "</pdv_liste>"
|
||||
rows, stations = backfill.scan_archive(archive_bytes(empty), bbox=BBOX, fuels=("Gazole",))
|
||||
assert "3333333" not in stations
|
||||
assert {row["station_id"] for row in rows} == {"1111111"}
|
||||
|
||||
|
||||
def test_import_marks_origin_and_keeps_declared_dates(store):
|
||||
rows, _stations = backfill.scan_archive(archive_bytes(), bbox=BBOX, fuels=("Gazole", "E10"))
|
||||
imported = store.save_archive_observations(rows, "archive:2007")
|
||||
assert imported == len(rows) > 0
|
||||
with store.connect() as db:
|
||||
sample = db.execute("SELECT * FROM observations ORDER BY station_id, day LIMIT 1").fetchone()
|
||||
assert sample["origin"] == "archive:2007"
|
||||
assert sample["day"] == "2007-01-04" and sample["source_updated"].startswith("2007-01-04T21:10")
|
||||
assert sample["fetched_at"] and not sample["fetched_at"].startswith("2007"), (
|
||||
"l’heure d’import est distincte de la date déclarée"
|
||||
)
|
||||
assert store.save_archive_observations(rows, "archive:2007") == 0, "import idempotent"
|
||||
|
||||
|
||||
def test_archived_rows_never_pass_as_todays_prices(store):
|
||||
"""Un import historique ne doit jamais être présenté comme un prix du jour."""
|
||||
rows, _stations = backfill.scan_archive(archive_bytes(), bbox=BBOX, fuels=("Gazole",))
|
||||
store.save_archive_observations(rows, "archive:2007")
|
||||
history = store.history(44.7737872, -0.5595029, 15, "Gazole")
|
||||
assert history["days"] == 0, "les lignes importées ne comptent pas comme relevés récents"
|
||||
assert store.fresh_price(rows[0]["declared_at"]) is False
|
||||
|
||||
|
||||
def test_backfill_runs_are_recorded_per_year(store):
|
||||
store.save_backfill_run(2007, "ok", 3, 42, "détail")
|
||||
store.save_backfill_run(2008, "error", 0, 0, "HTTP 404")
|
||||
runs = store.backfill_runs()
|
||||
assert runs[2007]["status"] == "ok" and runs[2007]["prices"] == 42
|
||||
assert runs[2008]["status"] == "error"
|
||||
93
tests/test_positions.py
Normal file
93
tests/test_positions.py
Normal file
@@ -0,0 +1,93 @@
|
||||
"""Deux indicateurs distincts : position dans l'espace (aujourd'hui) et dans le temps (historique)."""
|
||||
|
||||
from datetime import date, timedelta
|
||||
|
||||
|
||||
def days_ago(n):
|
||||
return (date.today() - timedelta(days=n)).isoformat()
|
||||
|
||||
|
||||
def seed_observation(store, station_id, fuel, day, price, lat=44.7737872, lon=-0.5595029):
|
||||
store.save_archive_observations(
|
||||
[
|
||||
dict(
|
||||
station_id=station_id,
|
||||
fuel=fuel,
|
||||
day=day,
|
||||
price=price,
|
||||
declared_at=f"{day}T10:00:00",
|
||||
lat=lat,
|
||||
lon=lon,
|
||||
)
|
||||
],
|
||||
"archive:test",
|
||||
)
|
||||
|
||||
|
||||
def test_local_position_ranks_stations_today(store):
|
||||
for index, price in enumerate((2.30, 2.10, 1.99, 2.20)):
|
||||
seed_observation(store, f"station{index}", "E10", days_ago(0), price)
|
||||
local = store.local_position(44.7737872, -0.5595029, 15, "E10")
|
||||
assert local["kind"] == "local"
|
||||
assert local["stations"] == 4
|
||||
assert local["percentile"] == 0.25, "le meilleur prix est le 1ᵉʳ des 4"
|
||||
assert local["best"] == 1.99
|
||||
assert "dans l’espace" in local["summary"] and "pas dans le temps" in local["summary"]
|
||||
|
||||
|
||||
def test_historical_position_uses_daily_medians_over_windows(store):
|
||||
"""Un jour = un point (médiane du panel), pour que les jours chargés ne pèsent pas plus."""
|
||||
for offset in range(40, 0, -1):
|
||||
day = days_ago(offset)
|
||||
seed_observation(store, "a", "E10", day, 2.20 + (offset - 40) * 0.01)
|
||||
seed_observation(store, "b", "E10", day, 2.30 + (offset - 40) * 0.01)
|
||||
seed_observation(store, "a", "E10", days_ago(39), 2.19)
|
||||
seed_observation(store, "b", "E10", days_ago(39), 2.29)
|
||||
seed_observation(store, "c", "E10", days_ago(39), 2.39)
|
||||
for index, price in enumerate((1.95, 2.05, 2.15)):
|
||||
seed_observation(store, f"today{index}", "E10", days_ago(0), price)
|
||||
position = store.historical_position(44.7737872, -0.5595029, 15, "E10", windows=(30, 90, 365))
|
||||
assert position["kind"] == "historique"
|
||||
assert position["daily_series"][1]["stations"] == 3, "médiane du jour sur 3 stations"
|
||||
assert position["current"] == 2.05, "médiane du jour pour aujourd’hui"
|
||||
assert position["windows"]["30"]["percentile"] is not None
|
||||
assert position["windows"]["30"]["days"] <= 31
|
||||
assert position["windows"]["365"]["percentile"] is None, (
|
||||
"40 jours d’historique ne suffisent pas pour un percentile à 365 jours"
|
||||
)
|
||||
assert (
|
||||
"Historique" in position["windows"]["365"]["summary"]
|
||||
or "insuffisant" in position["windows"]["365"]["summary"]
|
||||
)
|
||||
|
||||
|
||||
def test_historical_position_is_insufficient_without_history(store):
|
||||
for index, price in enumerate((2.0, 2.1, 2.2)):
|
||||
seed_observation(store, f"today{index}", "E10", days_ago(0), price)
|
||||
position = store.historical_position(44.7737872, -0.5595029, 15, "E10")
|
||||
assert position["percentile"] is None
|
||||
assert position["windows"]["30"]["percentile"] is None
|
||||
assert "insuffisant" in position["windows"]["30"]["summary"]
|
||||
|
||||
|
||||
def test_positions_are_two_different_distributions(store):
|
||||
"""Le même jour peut être excellent localement et cher dans le temps."""
|
||||
for offset in range(25, 0, -1):
|
||||
for index, base in enumerate((1.70, 1.75, 1.80)):
|
||||
seed_observation(store, f"old{index}", "E10", days_ago(offset), base)
|
||||
for index, price in enumerate((2.40, 2.45, 2.50)):
|
||||
seed_observation(store, f"today{index}", "E10", days_ago(0), price)
|
||||
local = store.local_position(44.7737872, -0.5595029, 15, "E10")
|
||||
historical = store.historical_position(44.7737872, -0.5595029, 15, "E10")
|
||||
assert local["percentile"] == round(1 / 3, 3), "meilleur prix du jour"
|
||||
assert historical["percentile"] >= 0.9, "mais cher par rapport à son propre passé"
|
||||
assert local["percentile"] < 0.5 < historical["percentile"]
|
||||
|
||||
|
||||
def test_stations_outside_the_radius_are_excluded(store):
|
||||
seed_observation(store, "loin", "E10", days_ago(0), 1.50, lat=48.8566, lon=2.3522)
|
||||
seed_observation(store, "proche", "E10", days_ago(1), 2.00)
|
||||
seed_observation(store, "proche", "E10", days_ago(0), 2.05)
|
||||
local = store.local_position(44.7737872, -0.5595029, 15, "E10")
|
||||
assert local["stations"] == 1, "la station parisienne est hors rayon"
|
||||
assert local["best"] == 2.05
|
||||
@@ -60,8 +60,32 @@ def outlook_up(confidence=0.81, days_max=7, low=0.05, high=0.08):
|
||||
)
|
||||
|
||||
|
||||
def position(percentile, current=1.62):
|
||||
return dict(percentile=percentile, current=current, observations=500, days=90)
|
||||
def historical_position(percentile, current=1.62, days=120):
|
||||
"""Position **historique** (fenêtres 30/90/365 jours). Seule utilisée pour anticiper."""
|
||||
return dict(
|
||||
kind="historique",
|
||||
percentile=percentile,
|
||||
current=current,
|
||||
days=days,
|
||||
windows={
|
||||
str(window): dict(percentile=percentile, days=days, current=current, median=1.60, summary="test")
|
||||
for window in (30, 90, 365)
|
||||
},
|
||||
summary="1.620 €/L se situe au test.",
|
||||
)
|
||||
|
||||
|
||||
def local_position(percentile, stations=36):
|
||||
"""Position **locale** du jour : classement dans l'espace, jamais dans le temps."""
|
||||
return dict(
|
||||
kind="local",
|
||||
percentile=percentile,
|
||||
stations=stations,
|
||||
day="2026-09-12",
|
||||
best=1.99,
|
||||
median=2.11,
|
||||
summary="test local",
|
||||
)
|
||||
|
||||
|
||||
def test_bands_refuse_false_precision():
|
||||
@@ -78,7 +102,11 @@ def test_daily_km_never_assumes_an_average_for_occasional_use():
|
||||
def test_wait_plan_buys_the_minimum_and_respects_comfort_floor():
|
||||
"""Baisse annoncée : appoint minimal, jamais 4 L qui obligeraient à revenir demain."""
|
||||
out = quantity.plan(
|
||||
REGULAR, remaining_km=150, price_now=1.62, position=position(0.5), outlook=outlook_down()
|
||||
REGULAR,
|
||||
remaining_km=150,
|
||||
price_now=1.62,
|
||||
historical_position=historical_position(0.5),
|
||||
outlook=outlook_down(),
|
||||
)
|
||||
assert out["action"] == "topup"
|
||||
assert out["usable_km"] == 70.0
|
||||
@@ -94,7 +122,11 @@ def test_wait_plan_buys_the_minimum_and_respects_comfort_floor():
|
||||
|
||||
def test_wait_plan_buys_nothing_when_the_autonomy_already_covers_the_window():
|
||||
out = quantity.plan(
|
||||
REGULAR, remaining_km=195, price_now=1.62, position=position(0.5), outlook=outlook_down()
|
||||
REGULAR,
|
||||
remaining_km=195,
|
||||
price_now=1.62,
|
||||
historical_position=historical_position(0.5),
|
||||
outlook=outlook_down(),
|
||||
)
|
||||
assert out["action"] == "wait"
|
||||
assert out["litres_low"] is None
|
||||
@@ -108,30 +140,38 @@ def test_wait_plan_warns_when_the_tank_cannot_reach_the_window():
|
||||
small_tank,
|
||||
remaining_km=95,
|
||||
price_now=1.62,
|
||||
position=position(0.5),
|
||||
historical_position=historical_position(0.5),
|
||||
outlook=outlook_down(days_min=14, days_max=17),
|
||||
)
|
||||
assert out["action"] == "topup"
|
||||
assert out["litres_target"] == pytest.approx(15.3, abs=0.4), "plafonné au réservoir"
|
||||
assert any("second ravitaillement" in caveat for caveat in out["caveats"])
|
||||
assert any("Quantité limitée" in caveat for caveat in out["caveats"])
|
||||
assert any("plafonnée" in caveat for caveat in out["caveats"])
|
||||
|
||||
|
||||
def test_full_tank_requires_both_favourable_price_and_upward_forecast():
|
||||
out = quantity.plan(
|
||||
REGULAR, remaining_km=195, price_now=1.55, position=position(0.10), outlook=outlook_up()
|
||||
REGULAR,
|
||||
remaining_km=195,
|
||||
price_now=1.55,
|
||||
historical_position=historical_position(0.10),
|
||||
outlook=outlook_up(),
|
||||
)
|
||||
assert out["action"] == "refill"
|
||||
assert out["litres_low"] == 30.0 and out["litres_high"] == 35.0
|
||||
assert out["economy"]["gain_low"] > 0 and out["economy"]["worth_it"] is True
|
||||
joined = " ".join(out["reasons"])
|
||||
assert "15% les plus bas" in joined
|
||||
assert "centile des prix journaliers" in joined
|
||||
assert "plancher garanti" in joined, "un bon prix n’est jamais présenté comme un plancher certain"
|
||||
|
||||
|
||||
def test_upward_forecast_with_ordinary_price_does_not_justify_a_full_tank():
|
||||
out = quantity.plan(
|
||||
REGULAR, remaining_km=195, price_now=1.72, position=position(0.70), outlook=outlook_up()
|
||||
REGULAR,
|
||||
remaining_km=195,
|
||||
price_now=1.72,
|
||||
historical_position=historical_position(0.70),
|
||||
outlook=outlook_up(),
|
||||
)
|
||||
assert out["action"] == "topup"
|
||||
assert out["action"] != "refill"
|
||||
@@ -143,11 +183,16 @@ def test_small_gain_is_rejected_to_avoid_a_pointless_stop():
|
||||
REGULAR,
|
||||
remaining_km=195,
|
||||
price_now=1.55,
|
||||
position=position(0.10),
|
||||
historical_position=historical_position(0.10),
|
||||
outlook=outlook_up(low=0.004, high=0.006),
|
||||
)
|
||||
assert out["economy"]["worth_it"] is False
|
||||
assert any("ne multipliez pas les passages" in caveat or "faible" in caveat for caveat in out["caveats"])
|
||||
assert any(
|
||||
"ne multipliez pas les passages" in caveat
|
||||
or "Gain net faible" in caveat
|
||||
or "inutile de multiplier" in caveat
|
||||
for caveat in out["caveats"]
|
||||
)
|
||||
|
||||
|
||||
def test_no_validated_forecast_means_no_anticipation(store):
|
||||
@@ -156,13 +201,15 @@ def test_no_validated_forecast_means_no_anticipation(store):
|
||||
REGULAR,
|
||||
remaining_km=420,
|
||||
price_now=1.55,
|
||||
position=position(0.10),
|
||||
historical_position=historical_position(0.10),
|
||||
local_position=local_position(0.16),
|
||||
outlook=dict(status="insufficient", reason="modèle non entraîné"),
|
||||
)
|
||||
assert out["action"] == "wait"
|
||||
assert out["litres_low"] is None
|
||||
assert out["forecast_note"] == "modèle non entraîné"
|
||||
assert any("bon prix dans l’historique" in reason for reason in out["reasons"])
|
||||
assert any("Position historique" in reason for reason in out["reasons"])
|
||||
assert any("Position locale" in reason for reason in out["reasons"])
|
||||
|
||||
|
||||
def test_without_forecast_a_short_runway_still_buys_the_need_only(store):
|
||||
@@ -171,7 +218,7 @@ def test_without_forecast_a_short_runway_still_buys_the_need_only(store):
|
||||
REGULAR,
|
||||
remaining_km=150,
|
||||
price_now=1.55,
|
||||
position=position(0.10),
|
||||
historical_position=historical_position(0.10),
|
||||
outlook=dict(status="insufficient", reason="modèle non entraîné"),
|
||||
)
|
||||
assert out["action"] == "topup"
|
||||
@@ -185,7 +232,7 @@ def test_low_confidence_forecast_does_not_drive_the_quantity():
|
||||
REGULAR,
|
||||
remaining_km=150,
|
||||
price_now=1.55,
|
||||
position=position(0.10),
|
||||
historical_position=historical_position(0.10),
|
||||
outlook=outlook_down(confidence=0.40),
|
||||
)
|
||||
assert out["horizon"] is None, "la prévision ne pilote pas la quantité sous le seuil"
|
||||
@@ -199,7 +246,7 @@ def test_no_forecast_but_immediate_need_still_buys_what_is_needed():
|
||||
REGULAR,
|
||||
remaining_km=110,
|
||||
price_now=1.62,
|
||||
position=None,
|
||||
historical_position=None,
|
||||
outlook=dict(status="insufficient", reason="modèle non entraîné"),
|
||||
)
|
||||
assert out["action"] == "topup"
|
||||
@@ -208,7 +255,9 @@ def test_no_forecast_but_immediate_need_still_buys_what_is_needed():
|
||||
|
||||
|
||||
def test_margin_reached_recommends_refuelling_without_waiting():
|
||||
out = quantity.plan(REGULAR, remaining_km=80, price_now=1.62, position=None, outlook=outlook_down())
|
||||
out = quantity.plan(
|
||||
REGULAR, remaining_km=80, price_now=1.62, historical_position=None, outlook=outlook_down()
|
||||
)
|
||||
assert out["action"] == "refuel"
|
||||
assert any("marge minimale est atteinte" in reason for reason in out["reasons"])
|
||||
|
||||
@@ -243,7 +292,11 @@ def test_occasional_vehicle_anticipates_before_a_rise_during_the_trip(store):
|
||||
|
||||
def test_declared_tank_caps_the_quantity(store):
|
||||
out = quantity.plan(
|
||||
REGULAR, remaining_km=780, price_now=1.55, position=position(0.10), outlook=outlook_up()
|
||||
REGULAR,
|
||||
remaining_km=780,
|
||||
price_now=1.55,
|
||||
historical_position=historical_position(0.10),
|
||||
outlook=outlook_up(),
|
||||
)
|
||||
assert out["action"] == "refill"
|
||||
assert out["litres_target"] == pytest.approx(4.0, abs=0.5), "réservoir presque plein"
|
||||
@@ -252,7 +305,11 @@ def test_declared_tank_caps_the_quantity(store):
|
||||
def test_missing_tank_is_declared_not_invented(store):
|
||||
vehicle = dict(REGULAR, tank_liters=None)
|
||||
out = quantity.plan(
|
||||
vehicle, remaining_km=150, price_now=1.62, position=position(0.5), outlook=outlook_down()
|
||||
vehicle,
|
||||
remaining_km=150,
|
||||
price_now=1.62,
|
||||
historical_position=historical_position(0.5),
|
||||
outlook=outlook_down(),
|
||||
)
|
||||
assert out["litres_target"] is not None
|
||||
assert any("Capacité du réservoir non déclarée" in caveat for caveat in out["caveats"])
|
||||
@@ -311,3 +368,87 @@ def test_absent_model_is_declared_absent(store):
|
||||
out = forecast.outlook("Gazole")
|
||||
assert out["status"] == "insufficient"
|
||||
assert "pas encore entraîné" in out["reason"]
|
||||
|
||||
|
||||
def test_local_rank_never_triggers_a_full_tank(store):
|
||||
"""Excellent localement mais cher dans le temps : aucune anticipation autorisée."""
|
||||
out = quantity.plan(
|
||||
REGULAR,
|
||||
remaining_km=200,
|
||||
historical_position=historical_position(0.72),
|
||||
local_position=local_position(0.01),
|
||||
outlook=outlook_up(),
|
||||
)
|
||||
assert out["action"] == "topup"
|
||||
assert out["action"] != "refill"
|
||||
assert any("n'est pas historiquement favorable" in reason for reason in out["reasons"])
|
||||
assert any("36 stations" in reason for reason in out["reasons"])
|
||||
|
||||
|
||||
def test_historical_rank_is_the_only_anticipation_trigger(store):
|
||||
out = quantity.plan(
|
||||
REGULAR,
|
||||
remaining_km=200,
|
||||
historical_position=historical_position(0.05),
|
||||
local_position=local_position(0.90),
|
||||
outlook=outlook_up(),
|
||||
)
|
||||
assert out["action"] == "refill"
|
||||
assert any("Position historique favorable" in reason for reason in out["reasons"])
|
||||
assert any("ne participe pas à cette décision" in caveat for caveat in out["caveats"])
|
||||
|
||||
|
||||
def test_detour_fuel_is_deducted_from_the_net_gain(store):
|
||||
"""Un détour peut annuler une économie : le gain net doit le montrer."""
|
||||
from quantity import detour_cost
|
||||
|
||||
detour = dict(extra_km=40.0, nearest_km=3.0, chosen_km=43.0)
|
||||
detour["cost_eur"] = detour_cost(detour, REGULAR, 1.55)
|
||||
assert detour["cost_eur"] == round(40 * 5 / 100 * 1.55, 2), "km × consommation × prix"
|
||||
out = quantity.plan(
|
||||
REGULAR,
|
||||
remaining_km=200,
|
||||
price_now=1.55,
|
||||
historical_position=historical_position(0.05),
|
||||
local_position=local_position(0.9),
|
||||
outlook=outlook_up(),
|
||||
detour=detour,
|
||||
)
|
||||
assert out["economy"]["detour_eur"] == detour["cost_eur"]
|
||||
assert out["economy"]["net_high"] == round(out["economy"]["gain_high"] - detour["cost_eur"], 2)
|
||||
assert out["economy"]["worth_it"] is False, "gain net sous le seuil : pas un passage de plus"
|
||||
assert any("Gain net faible" in caveat for caveat in out["caveats"])
|
||||
|
||||
|
||||
def test_a_small_detour_can_be_absorbed_by_the_expected_gain(store):
|
||||
from quantity import detour_cost
|
||||
|
||||
detour = dict(extra_km=2.0, nearest_km=3.0, chosen_km=5.0)
|
||||
detour["cost_eur"] = detour_cost(detour, REGULAR, 1.55)
|
||||
out = quantity.plan(
|
||||
REGULAR,
|
||||
remaining_km=200,
|
||||
price_now=1.55,
|
||||
historical_position=historical_position(0.05),
|
||||
local_position=local_position(0.9),
|
||||
outlook=outlook_up(),
|
||||
detour=detour,
|
||||
)
|
||||
assert out["economy"]["worth_it"] is True
|
||||
assert out["economy"]["net_high"] > out["economy"]["gain_high"] - 1.0
|
||||
|
||||
|
||||
def test_detour_cost_is_computed_by_the_engine(store):
|
||||
from quantity import detour_cost
|
||||
|
||||
assert detour_cost(None, REGULAR, 2.0) is None
|
||||
assert detour_cost(dict(extra_km=0.0), REGULAR, 2.0) == 0.0
|
||||
assert detour_cost(dict(extra_km=10.0), REGULAR, 2.0) == 1.0, "10 km × 5 L/100 × 2 €/L"
|
||||
|
||||
|
||||
def test_tank_content_is_always_an_estimate(store):
|
||||
out = quantity.plan(
|
||||
REGULAR, remaining_km=150, historical_position=historical_position(0.5), outlook=outlook_down()
|
||||
)
|
||||
assert out["estimated_in_tank_liters"] == 7.5, "estimation issue de l’autonomie affichée"
|
||||
assert any("estimé" in caveat or "estimation" in caveat for caveat in out["caveats"])
|
||||
|
||||
222
tests/test_validation.py
Normal file
222
tests/test_validation.py
Normal file
@@ -0,0 +1,222 @@
|
||||
"""Banc de validation : aucune fuite, métriques exigées, et verdict économique."""
|
||||
|
||||
import pytest
|
||||
|
||||
import validation
|
||||
|
||||
VEHICLE = dict(
|
||||
name="Fictif", fuel="E10", consumption=6.0, tank_liters=45.0, min_range_km=80.0, monthly_km=1000.0
|
||||
)
|
||||
|
||||
|
||||
def series(prices, step_days=1, start_day=1):
|
||||
return [
|
||||
dict(day=f"2026-01-{start_day + index * step_days:02d}", price=price)
|
||||
for index, price in enumerate(prices)
|
||||
]
|
||||
|
||||
|
||||
def prediction(
|
||||
day, horizon=7, predicted=None, actual=None, reference=None, confidence=0.8, trained_until=None
|
||||
):
|
||||
return dict(
|
||||
day=day,
|
||||
horizon=horizon,
|
||||
predicted_change=predicted,
|
||||
actual_change=actual,
|
||||
predicted_price=(reference or 0) + (predicted or 0),
|
||||
actual_price=(reference or 0) + (actual or 0),
|
||||
last_known_price=reference,
|
||||
confidence=confidence,
|
||||
trained_until=trained_until or day,
|
||||
)
|
||||
|
||||
|
||||
def test_chronological_split_never_trains_on_the_future():
|
||||
samples = [dict(day=f"2026-01-{day:02d}") for day in range(1, 11)]
|
||||
train, test = validation.split_chronologically(samples, ratio=0.6)
|
||||
assert len(train) == 6 and len(test) == 4
|
||||
assert max(item["day"] for item in train) < min(item["day"] for item in test)
|
||||
|
||||
|
||||
def test_leakage_is_refused_outright():
|
||||
leaky = [prediction("2026-03-01", trained_until="2026-03-05")]
|
||||
with pytest.raises(ValueError) as error:
|
||||
validation.assert_no_leakage(leaky)
|
||||
assert "fuite de données" in str(error.value)
|
||||
validation.assert_no_leakage([prediction("2026-03-05", trained_until="2026-03-01")])
|
||||
|
||||
|
||||
def test_perfect_model_beats_the_naive_rule():
|
||||
predictions = [
|
||||
prediction(f"2026-0{month}-15", predicted=delta, actual=delta, reference=2.0)
|
||||
for month in (1, 2)
|
||||
for delta in (0.05, -0.03, 0.02)
|
||||
]
|
||||
metrics = validation.evaluate(predictions, horizon=7)
|
||||
assert metrics["count"] == 6
|
||||
assert metrics["mae"] == 0
|
||||
assert metrics["skill_vs_naive"] == 1.0
|
||||
assert metrics["direction"]["accuracy"] == 1.0
|
||||
|
||||
|
||||
def test_a_useless_model_scores_no_better_than_the_naive_rule():
|
||||
predictions = [
|
||||
prediction(f"2026-01-{day:02d}", predicted=0.01, actual=-0.02, reference=2.0, confidence=0.9)
|
||||
for day in range(1, 11)
|
||||
]
|
||||
metrics = validation.evaluate(predictions, horizon=7)
|
||||
assert metrics["skill_vs_naive"] <= 0.1, "aucun progrès sur la règle « prix identique »"
|
||||
assert metrics["direction"]["accuracy"] == 0.0
|
||||
|
||||
|
||||
def test_direction_accuracy_counts_only_real_moves():
|
||||
predictions = [
|
||||
prediction("2026-01-01", predicted=0.05, actual=0.04, reference=2.0),
|
||||
prediction("2026-01-02", predicted=-0.05, actual=0.04, reference=2.0),
|
||||
prediction("2026-01-03", predicted=0.0, actual=0.04, reference=2.0),
|
||||
]
|
||||
scored = validation.direction_accuracy(predictions)
|
||||
assert scored["count"] == 2, "un « stable » annoncé n’est pas compté comme un sens juste"
|
||||
assert scored["accuracy"] == 0.5
|
||||
assert scored["flat_predicted"] == 1
|
||||
|
||||
|
||||
def test_confidence_calibration_penalises_overconfidence():
|
||||
"""Confiance annoncée contre réussite réelle : une surconfiance doit coûter cher."""
|
||||
honest, confident = [], []
|
||||
for day in range(1, 11):
|
||||
sign = 1 if day % 2 else -1 # une fois sur deux le sens est faux
|
||||
hit = dict(predicted=0.02, actual=0.02 * sign, reference=2.0)
|
||||
honest.append(prediction(f"2026-01-{day:02d}", confidence=0.55, **hit))
|
||||
confident.append(prediction(f"2026-01-{day:02d}", confidence=0.95, **hit))
|
||||
assert (
|
||||
validation.confidence_calibration(honest)["calibration_quality"]
|
||||
> validation.confidence_calibration(confident)["calibration_quality"]
|
||||
)
|
||||
assert validation.confidence_calibration([])["expected_calibration_error"] is None
|
||||
|
||||
|
||||
def test_every_horizon_is_measured_separately():
|
||||
predictions = []
|
||||
for horizon in validation.HORIZONS:
|
||||
for day in range(1, 6):
|
||||
predictions.append(
|
||||
prediction(
|
||||
f"2026-01-{day:02d}",
|
||||
horizon=horizon,
|
||||
predicted=0.03 * horizon / 10,
|
||||
actual=0.02,
|
||||
reference=2.0,
|
||||
)
|
||||
)
|
||||
metrics = validation.evaluate_all_horizons(predictions)
|
||||
assert set(metrics) == {str(horizon) for horizon in validation.HORIZONS}
|
||||
assert metrics["21"]["count"] == 5
|
||||
|
||||
|
||||
def test_naive_strategy_refuels_only_when_needed():
|
||||
prices = series([2.00] * 40)
|
||||
result = validation.simulate(prices, VEHICLE, strategy="naive")
|
||||
assert result["refuels"] >= 1
|
||||
assert result["cost_eur"] > 0
|
||||
assert result["cost_per_liter"] == pytest.approx(2.0, abs=0.01)
|
||||
|
||||
|
||||
def test_advisor_strategy_can_wait_for_a_falling_price():
|
||||
"""Prix qui baisse : attendre coûte moins cher que remplir au début."""
|
||||
prices = series([2.00] * 5 + [1.80] * 20 + [2.00] * 15)
|
||||
forecasts = {point["day"]: dict(direction="down") for point in prices[:6]}
|
||||
comparison = validation.compare_strategies(prices, VEHICLE, forecasts=forecasts)
|
||||
assert comparison["advisor"]["cost_eur"] <= comparison["naive"]["cost_eur"]
|
||||
|
||||
|
||||
def test_strategy_comparison_reports_cost_refuels_and_detour():
|
||||
prices = series([1.95] * 30)
|
||||
forecasts = {point["day"]: dict(direction="up") for point in prices}
|
||||
comparison = validation.compare_strategies(prices, VEHICLE, forecasts=forecasts, detour_km_per_stop=4.0)
|
||||
assert set(comparison) == {"naive", "advisor"}
|
||||
for side in comparison.values():
|
||||
assert {"cost_eur", "refuels", "detour_km", "litres"} <= set(side)
|
||||
assert comparison["advisor"]["detour_km"] == 4.0 * comparison["advisor"]["refuels"]
|
||||
|
||||
|
||||
def test_verdict_refuses_a_model_that_saves_nothing():
|
||||
metrics = {
|
||||
str(validation.DEFAULT_HORIZON): dict(
|
||||
count=500,
|
||||
direction=dict(accuracy=0.6),
|
||||
calibration=dict(calibration_quality=0.9),
|
||||
skill_vs_naive=0.02,
|
||||
)
|
||||
}
|
||||
economics = dict(
|
||||
naive=dict(cost_eur=100.0, refuels=10, detour_km=0.0),
|
||||
advisor=dict(
|
||||
cost_eur=100.0, refuels=10, detour_km=0.0, saving_eur=0.0, cost_ratio=1.0, refuels_ratio=1.0
|
||||
),
|
||||
)
|
||||
verdict = validation.verdict(metrics, economics)
|
||||
assert verdict["passed"] is False
|
||||
assert any("économie simulée" in failure for failure in verdict["failures"])
|
||||
|
||||
|
||||
def test_verdict_refuses_more_refuels_even_with_a_saving():
|
||||
metrics = {
|
||||
str(validation.DEFAULT_HORIZON): dict(
|
||||
count=500,
|
||||
direction=dict(accuracy=0.62),
|
||||
calibration=dict(calibration_quality=0.9),
|
||||
skill_vs_naive=0.05,
|
||||
)
|
||||
}
|
||||
economics = dict(
|
||||
naive=dict(cost_eur=100.0, refuels=10, detour_km=0.0),
|
||||
advisor=dict(
|
||||
cost_eur=96.0, refuels=13, detour_km=12.0, saving_eur=4.0, cost_ratio=0.96, refuels_ratio=1.3
|
||||
),
|
||||
)
|
||||
verdict = validation.verdict(metrics, economics)
|
||||
assert verdict["passed"] is False
|
||||
assert any("passages" in failure for failure in verdict["failures"])
|
||||
|
||||
|
||||
def test_verdict_refuses_a_small_sample_or_a_leaky_score():
|
||||
thin = {
|
||||
str(validation.DEFAULT_HORIZON): dict(
|
||||
count=12,
|
||||
direction=dict(accuracy=0.9),
|
||||
calibration=dict(calibration_quality=0.95),
|
||||
skill_vs_naive=0.2,
|
||||
)
|
||||
}
|
||||
economics = dict(
|
||||
naive=dict(cost_eur=100.0, refuels=10, detour_km=0.0),
|
||||
advisor=dict(
|
||||
cost_eur=90.0, refuels=9, detour_km=0.0, saving_eur=10.0, cost_ratio=0.9, refuels_ratio=0.9
|
||||
),
|
||||
)
|
||||
verdict = validation.verdict(thin, economics)
|
||||
assert verdict["passed"] is False
|
||||
assert any("pour conclure" in failure for failure in verdict["failures"])
|
||||
|
||||
|
||||
def test_verdict_accepts_a_genuinely_useful_model():
|
||||
metrics = {
|
||||
str(validation.DEFAULT_HORIZON): dict(
|
||||
count=800,
|
||||
direction=dict(accuracy=0.64),
|
||||
calibration=dict(calibration_quality=0.88),
|
||||
skill_vs_naive=0.12,
|
||||
)
|
||||
}
|
||||
economics = dict(
|
||||
naive=dict(cost_eur=100.0, refuels=10, detour_km=0.0),
|
||||
advisor=dict(
|
||||
cost_eur=92.5, refuels=9, detour_km=8.0, saving_eur=7.5, cost_ratio=0.925, refuels_ratio=0.9
|
||||
),
|
||||
)
|
||||
verdict = validation.verdict(metrics, economics)
|
||||
assert verdict["passed"] is True
|
||||
assert verdict["failures"] == []
|
||||
assert any("économisé" in reason or "saving" in reason or "€" in reason for reason in verdict["reasons"])
|
||||
Reference in New Issue
Block a user