Sens et references des facteurs amont, distances statiques vs trafic, cache de routes normalise
Chaque facteur distingue desormais la donnee observee et son effet suppose sur les prix, avec fleche justifiee, ecarts chiffres a J-1, J-7, a la publication precedente et a la moyenne 30 jours. Les inversions de signe sont verrouillees par tests : un euro plus fort face au dollar est baissier, une baisse du trafic de petroliers est haussiere. La mesure PortWatch d Ormuz, tombant a 0-2 petroliers par jour, est declared non exploitable plutot que transformee en signal. Les durees OSRM sont etiquetees hors trafic et le cache separe la distance statique (90 jours) de l ETA de trafic (15 minutes, Google TRAFFIC_AWARE uniquement) : une ancienne ETA n est jamais presentee comme actuelle. Le cache de routes normalise l origine a environ 100 m et la rattache au favori quand la position mesuree lui correspond. Benchmark etiquete Gemma 12B contre Mistral 24B : le 24b reste primaire (rappel et JSON), le 12b en repli.
This commit is contained in:
163
tests/test_factor_signs.py
Normal file
163
tests/test_factor_signs.py
Normal file
@@ -0,0 +1,163 @@
|
||||
"""Sens des facteurs : chaque flèche doit être justifiable, et les écarts chiffrés présents.
|
||||
|
||||
Ces tests verrouillent les inversions de signe, qui sont la principale source d'erreur :
|
||||
- USD par euro en hausse = euro plus fort = facture en euros allégée → effet **baissier** ;
|
||||
- trafic de pétroliers en baisse = approvisionnement tendu → effet **haussière**.
|
||||
"""
|
||||
|
||||
from datetime import date, timedelta
|
||||
|
||||
import storage
|
||||
import synthesis
|
||||
|
||||
|
||||
def days_ago(n):
|
||||
return (date.today() - timedelta(days=n)).isoformat()
|
||||
|
||||
|
||||
def seed(series, unit, rows):
|
||||
return storage.save_upstream(series, rows, unit, "test")
|
||||
|
||||
|
||||
def seed_hormuz(values):
|
||||
rows = []
|
||||
for index, value in enumerate(values):
|
||||
rows.append(
|
||||
(
|
||||
"Strait of Hormuz",
|
||||
dict(
|
||||
day=days_ago(28 - index * 4),
|
||||
transit_tankers=value,
|
||||
transit_total=value * 2,
|
||||
capacity_tankers=1000,
|
||||
capacity_total=2000,
|
||||
),
|
||||
)
|
||||
)
|
||||
storage.save_chokepoints(rows, "IMF PortWatch")
|
||||
|
||||
|
||||
def test_ormuz_traffic_drop_pushes_prices_up(store):
|
||||
seed_hormuz([40, 40, 40, 40, 40, 40, 22])
|
||||
factor = synthesis.factor_logistique()
|
||||
assert factor["change_pct"] < 0, "la donnée observée est bien un trafic en baisse"
|
||||
assert factor["direction"] == synthesis.UP, "moins de trafic disponible n’est jamais baissier"
|
||||
assert factor["arrow"] == "↑"
|
||||
assert "↑ pression sur les prix" == factor["effect"]
|
||||
assert "vs normale" in factor["observation"]
|
||||
assert "inverse" in factor["relation"]
|
||||
assert factor["observation_change"]
|
||||
|
||||
|
||||
def test_ormuz_traffic_recovery_pushes_prices_down(store):
|
||||
seed_hormuz([30, 30, 30, 30, 30, 30, 45])
|
||||
factor = synthesis.factor_logistique()
|
||||
assert factor["change_pct"] > 0, "trafic en reprise"
|
||||
assert factor["direction"] == synthesis.DOWN
|
||||
assert factor["arrow"] == "↓"
|
||||
assert "détend" in factor["explanation"]
|
||||
|
||||
|
||||
def test_chokepoint_with_implausible_volume_yields_no_arrow(store):
|
||||
"""La mesure PortWatch d'Ormuz tombe à 0–2 pétroliers/jour : on ne conclut pas."""
|
||||
seed_hormuz([1, 0, 1, 2, 0, 1, 2])
|
||||
factor = synthesis.factor_logistique()
|
||||
assert factor["direction"] == synthesis.UNKNOWN
|
||||
assert factor["arrow"] == "?"
|
||||
assert "trop faible" in factor["observation"]
|
||||
assert "trompeur" in factor["relation"]
|
||||
assert "change_pct" not in factor
|
||||
|
||||
|
||||
def test_chokepoint_with_usable_volume_still_concludes(store):
|
||||
seed_hormuz([40, 41, 39, 42, 40, 41, 22])
|
||||
factor = synthesis.factor_logistique()
|
||||
assert factor["direction"] == synthesis.UP
|
||||
assert factor["change_pct"] < 0
|
||||
|
||||
|
||||
def test_stronger_euro_pushes_prices_down(store):
|
||||
# Le taux BCE « USD par euro » monte : l'euro vaut plus de dollars, le baril coûte moins d'euros.
|
||||
seed("usd_per_eur", "USD/EUR", [dict(day=days_ago(6), value=1.10), dict(day=days_ago(1), value=1.16)])
|
||||
factor = synthesis.factor_change()
|
||||
assert factor["change_pct"] > 0
|
||||
assert factor["direction"] == synthesis.DOWN, "euro plus fort = pression baissière en euros"
|
||||
assert factor["inverted"] is True
|
||||
assert "renforcé" in factor["explanation"]
|
||||
assert "inverse" in factor["relation"]
|
||||
assert factor["observation"].startswith("1 € =")
|
||||
|
||||
|
||||
def test_weaker_euro_pushes_prices_up(store):
|
||||
seed("usd_per_eur", "USD/EUR", [dict(day=days_ago(6), value=1.18), dict(day=days_ago(1), value=1.08)])
|
||||
factor = synthesis.factor_change()
|
||||
assert factor["change_pct"] < 0
|
||||
assert factor["direction"] == synthesis.UP
|
||||
assert "affaibli" in factor["explanation"]
|
||||
|
||||
|
||||
def test_brut_raffinage_and_products_keep_same_sign(store):
|
||||
seed(
|
||||
"brent_eur_daily", "EUR/baril", [dict(day=days_ago(9), value=80.0), dict(day=days_ago(1), value=92.0)]
|
||||
)
|
||||
seed(
|
||||
"dgec_margin_eur_per_tonne",
|
||||
"EUR/tonne",
|
||||
[dict(day=days_ago(40), value=200.0), dict(day=days_ago(2), value=260.0)],
|
||||
)
|
||||
seed("fr_htt_Gazole", "EUR/L", [dict(day=days_ago(21), value=1.20), dict(day=days_ago(1), value=1.28)])
|
||||
brut, raffinage, produits = (
|
||||
synthesis.factor_brut(),
|
||||
synthesis.factor_raffinage(),
|
||||
synthesis.factor_produits("Gazole"),
|
||||
)
|
||||
assert brut["direction"] == synthesis.UP and brut["inverted"] is False
|
||||
assert raffinage["direction"] == synthesis.UP and raffinage["inverted"] is False
|
||||
assert produits["direction"] == synthesis.UP and produits["inverted"] is False
|
||||
assert "EUR/baril" in brut["observation"]
|
||||
assert "€/tonne" in raffinage["observation"]
|
||||
assert "hors taxes" in produits["observation"]
|
||||
|
||||
|
||||
def test_factors_carry_references_d1_d7_d30_and_mean(store):
|
||||
rows = [dict(day=days_ago(1), value=92.0)]
|
||||
rows += [dict(day=days_ago(off), value=90.0 - off * 0.1) for off in range(2, 41)]
|
||||
seed("brent_eur_daily", "EUR/baril", rows)
|
||||
factor = synthesis.factor_brut()
|
||||
changes = factor["changes"]
|
||||
assert {"d1", "d7", "d30", "prev", "mean30"} <= set(changes)
|
||||
assert changes["d1"]["reference_day"] == days_ago(2)
|
||||
assert changes["d7"]["reference_day"] <= days_ago(7)
|
||||
assert changes["d30"]["reference_day"] <= days_ago(30) or changes["d30"]["reference_day"]
|
||||
assert changes["mean30"]["points"] >= 25
|
||||
assert "vs J-7" in factor["observation_change"]
|
||||
assert "moyenne 30 jours" in factor["observation_change"]
|
||||
|
||||
|
||||
def test_every_factor_explains_observation_and_effect(store):
|
||||
built = synthesis.build("Gazole")
|
||||
assert len(built["factors"]) == 6
|
||||
for factor in built["factors"]:
|
||||
assert factor["observation"], f"{factor['key']} sans observation"
|
||||
assert factor["effect"], f"{factor['key']} sans effet affiché"
|
||||
assert factor["relation"], f"{factor['key']} sans relation expliquée"
|
||||
assert factor["arrow"] in ("↑", "↓", "→", "?")
|
||||
if factor["direction"] == synthesis.UNKNOWN:
|
||||
assert factor["effect"] == "? effet non évalué"
|
||||
assert factor["relation"], f"{factor['key']} doit expliquer pourquoi rien n’est évalué"
|
||||
assert any(
|
||||
word in factor["observation"] + factor["relation"]
|
||||
for word in ("Sans ", "Aucun", "non disponible")
|
||||
)
|
||||
|
||||
|
||||
def test_pressure_uses_effect_not_observed_move(store):
|
||||
# Trafic en nette baisse : la donnée baisse, l'effet monte. La pression doit être HAUSSE.
|
||||
seed_hormuz([40, 40, 40, 40, 40, 40, 20])
|
||||
seed(
|
||||
"brent_eur_daily", "EUR/baril", [dict(day=days_ago(9), value=80.0), dict(day=days_ago(1), value=90.0)]
|
||||
)
|
||||
built = synthesis.build("Gazole")
|
||||
assert built["pressure"] == "HAUSSE"
|
||||
logistique = [f for f in built["factors"] if f["key"] == "logistique"][0]
|
||||
assert logistique["direction"] == "up" and logistique["change_pct"] < 0
|
||||
126
tests/test_routes_cache.py
Normal file
126
tests/test_routes_cache.py
Normal file
@@ -0,0 +1,126 @@
|
||||
"""Cache de routes : origine normalisée, rattachement au favori, séparation statique / trafic."""
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import pytest
|
||||
|
||||
import routing
|
||||
import storage
|
||||
|
||||
|
||||
def meters_between(origin, other):
|
||||
return storage.distance_km(origin[0], origin[1], other[0], other[1]) * 1000
|
||||
|
||||
|
||||
def test_gps_jitter_of_a_few_dozens_of_meters_shares_one_cache_key(store):
|
||||
target = (44.795280, -0.604509)
|
||||
first = (44.78060, -0.57060)
|
||||
second = (44.78063, -0.57064) # ~5 m plus loin : bruit normal d'une mesure téléphone
|
||||
third = (44.78110, -0.57110) # ~70 m plus loin
|
||||
assert meters_between(first, second) < 10
|
||||
keys = {storage.route_key(point, target) for point in (first, second, third)}
|
||||
assert len(keys) == 1, f"positions quasi identiques, clés distinctes : {keys}"
|
||||
|
||||
|
||||
def test_two_positions_hundreds_of_meters_apart_use_distinct_keys(store):
|
||||
target = (44.795280, -0.604509)
|
||||
near = storage.route_key((44.78060, -0.57060), target)
|
||||
far = storage.route_key((44.81000, -0.61000), target)
|
||||
assert near != far
|
||||
|
||||
|
||||
def test_distinct_stations_never_share_a_key(store):
|
||||
origin = (44.7806, -0.5706)
|
||||
key_a = storage.route_key(origin, (44.795280, -0.604509))
|
||||
key_b = storage.route_key(origin, (44.777000, -0.610000))
|
||||
assert key_a != key_b
|
||||
|
||||
|
||||
def test_favourite_tag_replaces_raw_coordinates(store):
|
||||
target = (44.795280, -0.604509)
|
||||
key = storage.route_key((44.78055, -0.57051), target, origin_tag="fav:3")
|
||||
assert key.startswith("fav:3|")
|
||||
assert storage.route_key((44.79999, -0.57051), target, origin_tag="fav:3") == key
|
||||
|
||||
|
||||
def test_match_favorite_absorbs_gps_jitter(store):
|
||||
storage.save_entity("favorites", dict(name="Villenave", lat=44.78060, lon=-0.57060, radius_km=10))
|
||||
favorite = storage.match_favorite(44.78068, -0.57070)
|
||||
assert favorite and favorite["name"] == "Villenave"
|
||||
assert favorite["distance_km"] <= 0.15
|
||||
assert storage.match_favorite(44.90000, -0.57070) is None
|
||||
|
||||
|
||||
def test_osrm_duration_is_static_and_never_an_eta(store, monkeypatch):
|
||||
monkeypatch.setitem(
|
||||
routing.PROVIDERS,
|
||||
"osrm",
|
||||
lambda origin, targets: {
|
||||
t[0]: dict(distance_m=5000.0, duration_s=600.0, duration_kind=routing.STATIC) for t in targets
|
||||
},
|
||||
)
|
||||
monkeypatch.setenv("FUEL_ROUTING_PROVIDERS", "osrm")
|
||||
routes, info = routing.routes((44.78, -0.57), [("A", 44.79, -0.60)])
|
||||
assert routes["A"]["duration_kind"] == routing.STATIC
|
||||
assert routes["A"]["duration_label"] == "hors trafic"
|
||||
assert routes["A"]["eta_min"] is None
|
||||
assert info["eta_count"] == 0
|
||||
assert "hors trafic" in info["eta_note"]
|
||||
assert store.eta_lookup([storage.route_key((44.78, -0.57), (44.79, -0.60))]) == {}
|
||||
|
||||
|
||||
def test_google_traffic_duration_goes_to_short_cache_only(store, monkeypatch):
|
||||
monkeypatch.setattr(routing, "GOOGLE_KEY", "clé-de-test")
|
||||
monkeypatch.setitem(
|
||||
routing.PROVIDERS,
|
||||
"google",
|
||||
lambda origin, targets: {
|
||||
t[0]: dict(distance_m=8000.0, duration_s=900.0, duration_kind=routing.TRAFFIC) for t in targets
|
||||
},
|
||||
)
|
||||
monkeypatch.setenv("FUEL_ROUTING_PROVIDERS", "google")
|
||||
routes, info = routing.routes((44.78, -0.57), [("A", 44.79, -0.60)])
|
||||
assert routes["A"]["distance_km"] == pytest.approx(8.0)
|
||||
assert routes["A"]["duration_min"] is None, "une durée de trafic n’est pas une durée statique"
|
||||
assert routes["A"]["eta_min"] == pytest.approx(15.0)
|
||||
assert routes["A"]["eta_age_seconds"] is not None
|
||||
assert info["eta_count"] == 1 and info["eta_provider"] == "google"
|
||||
cached = store.route_lookup([storage.route_key((44.78, -0.57), (44.79, -0.60))])
|
||||
assert list(cached.values())[0]["duration_s"] is None, "pas de durée trafic dans le cache long"
|
||||
|
||||
|
||||
def test_stale_eta_is_ignored_and_static_duration_is_used(store, monkeypatch):
|
||||
monkeypatch.setattr(routing, "GOOGLE_KEY", "clé-de-test")
|
||||
monkeypatch.setitem(
|
||||
routing.PROVIDERS,
|
||||
"google",
|
||||
lambda origin, targets: {
|
||||
t[0]: dict(distance_m=8000.0, duration_s=900.0, duration_kind=routing.TRAFFIC) for t in targets
|
||||
},
|
||||
)
|
||||
monkeypatch.setenv("FUEL_ROUTING_PROVIDERS", "google")
|
||||
routing.routes((44.78, -0.57), [("A", 44.79, -0.60)])
|
||||
key = storage.route_key((44.78, -0.57), (44.79, -0.60))
|
||||
stale = (datetime.now(timezone.utc) - timedelta(hours=3)).isoformat()
|
||||
store.eta_save([dict(key=key, duration_s=1800.0, provider="google")])
|
||||
with store.connect() as db:
|
||||
db.execute("UPDATE route_eta SET computed_at=? WHERE key=?", (stale, key))
|
||||
routes, info = routing.routes((44.78, -0.57), [("A", 44.79, -0.60)], eta_ttl=900)
|
||||
assert routes["A"]["eta_min"] is None, "une ETA de 3 heures n’est pas une ETA actuelle"
|
||||
assert info["eta_count"] == 0
|
||||
assert "Aucune ETA de trafic" in info["eta_note"]
|
||||
|
||||
|
||||
def test_eta_key_is_separate_for_tagged_origin(store, monkeypatch):
|
||||
monkeypatch.setattr(routing, "GOOGLE_KEY", "clé-de-test")
|
||||
monkeypatch.setitem(
|
||||
routing.PROVIDERS,
|
||||
"google",
|
||||
lambda origin, targets: {
|
||||
t[0]: dict(distance_m=4000.0, duration_s=600.0, duration_kind=routing.TRAFFIC) for t in targets
|
||||
},
|
||||
)
|
||||
monkeypatch.setenv("FUEL_ROUTING_PROVIDERS", "google")
|
||||
_, info = routing.routes((44.78, -0.57), [("A", 44.79, -0.60)], origin_tag="fav:7")
|
||||
assert info["eta_count"] == 1
|
||||
assert store.eta_lookup(["fav:7|44.7900|-0.6000"]) != {}
|
||||
@@ -6,6 +6,7 @@ import pytest
|
||||
|
||||
import app
|
||||
import routing
|
||||
import storage
|
||||
|
||||
|
||||
def station_row(station_id, lat, lon, price=1.9, fuel="Gazole"):
|
||||
@@ -70,7 +71,7 @@ def test_provider_google_requires_key_and_parses_matrix(monkeypatch):
|
||||
assert captured["url"] == "https://routes.googleapis.com/distanceMatrix/v2:computeRouteMatrix"
|
||||
assert len(captured["body"]["destinations"]) == 2
|
||||
assert captured["body"]["travelMode"] == "DRIVE"
|
||||
assert found == {"A": dict(distance_m=4200.0, duration_s=720.0)}
|
||||
assert found == {"A": dict(distance_m=4200.0, duration_s=720.0, duration_kind=routing.TRAFFIC)}
|
||||
|
||||
|
||||
def test_routes_uses_cache_then_provider(store, monkeypatch):
|
||||
@@ -91,7 +92,7 @@ def test_routes_uses_cache_then_provider(store, monkeypatch):
|
||||
second, info2 = routing.routes(origin, targets)
|
||||
assert info2["from_cache"] == 1 and info2["computed"] == 0
|
||||
assert len(calls) == 1, "la seconde demande ne doit pas rappeler le fournisseur"
|
||||
assert store.route_lookup(["|".join(f"{v:.4f}" for v in (*origin, 48.86, 2.30))])
|
||||
assert store.route_lookup([storage.route_key(origin, (48.86, 2.30))], max_age_days=1)
|
||||
|
||||
|
||||
def test_routes_without_provider_says_so_and_invents_nothing(store, monkeypatch):
|
||||
@@ -112,12 +113,16 @@ def test_nearest_stations_applies_radius_on_road_distance(store, monkeypatch):
|
||||
]
|
||||
monkeypatch.setattr(app, "load_fuel_data", lambda **kwargs: rows)
|
||||
|
||||
def fake_routes(origin, targets):
|
||||
def fake_routes(origin, targets, origin_tag=None, **kwargs):
|
||||
distances = {"proche": 1200.0, "loin": 18500.0, "hors": 40000.0}
|
||||
return (
|
||||
{
|
||||
station_id: dict(
|
||||
distance_km=distances[station_id] / 1000, duration_min=5.0, provider="osrm", cached=False
|
||||
distance_km=distances[station_id] / 1000,
|
||||
duration_min=5.0,
|
||||
duration_label="hors trafic",
|
||||
provider="osrm",
|
||||
cached=False,
|
||||
)
|
||||
for station_id, _lat, _lon in targets
|
||||
},
|
||||
|
||||
@@ -52,22 +52,25 @@ def test_brut_factor_detects_a_rise_and_a_fall(store):
|
||||
|
||||
|
||||
def test_brut_factor_marks_stale_data_and_flat_move(store):
|
||||
# Le brut tolère une donnée mensuelle (DGEC) : l'ancienneté se juge donc à ~45 jours.
|
||||
seed(
|
||||
"brent_eur_daily",
|
||||
"EUR/baril",
|
||||
[dict(day=days_ago(18), value=80.0), dict(day=days_ago(12), value=80.4)],
|
||||
[dict(day=days_ago(60), value=80.0), dict(day=days_ago(50), value=80.4)],
|
||||
)
|
||||
factor = synthesis.factor_brut()
|
||||
assert factor["direction"] == synthesis.FLAT, "variation sous le seuil : peu d’effet"
|
||||
assert factor["fresh"] is False and factor["age_days"] >= 11
|
||||
assert factor["fresh"] is False and factor["age_days"] >= 45
|
||||
|
||||
|
||||
def test_change_factor_inverts_direction(store):
|
||||
# Un euro plus faible (USD/EUR en hausse) renchérit le baril : pression haussière.
|
||||
# Le taux BCE est « dollars par euro » : un euro plus fort allège la facture en euros.
|
||||
# Les deux signes sont verrouillés dans tests/test_factor_signs.py.
|
||||
seed("usd_per_eur", "USD/EUR", [dict(day=days_ago(6), value=1.10), dict(day=days_ago(1), value=1.16)])
|
||||
factor = synthesis.factor_change()
|
||||
assert factor["direction"] == synthesis.UP
|
||||
assert factor["direction"] == synthesis.DOWN
|
||||
assert factor["change_pct"] > 0
|
||||
assert factor["effect"] == "↓ pression sur les prix"
|
||||
|
||||
|
||||
def test_logistique_factor_reads_chokepoint_traffic(store):
|
||||
|
||||
Reference in New Issue
Block a user