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.
132 lines
6.4 KiB
Python
132 lines
6.4 KiB
Python
"""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"
|