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.
254 lines
8.4 KiB
Python
254 lines
8.4 KiB
Python
"""Synthèse amont : pression, facteurs en langage courant, « En clair » et prudence."""
|
||
|
||
from datetime import date, timedelta
|
||
|
||
import pytest
|
||
|
||
import news
|
||
import promotions
|
||
import storage
|
||
import synthesis
|
||
|
||
|
||
def seed(series, unit, rows):
|
||
return storage.save_upstream(series, rows, unit, "test")
|
||
|
||
|
||
def days_ago(n):
|
||
return (date.today() - timedelta(days=n)).isoformat()
|
||
|
||
|
||
def test_factors_report_unknown_without_data(store):
|
||
built = synthesis.build("Gazole")
|
||
assert len(built["factors"]) == 6
|
||
assert built["pressure"] == "INCERTAINE"
|
||
assert built["confidence"] is None
|
||
assert all(factor["arrow"] == "?" for factor in built["factors"])
|
||
assert "pas assez de données" in built["plain"]
|
||
assert "pas encore" in built["plain"] and "prévision" in built["disclaimer"]
|
||
|
||
|
||
def test_brut_factor_detects_a_rise_and_a_fall(store):
|
||
seed(
|
||
"brent_eur_daily",
|
||
"EUR/baril",
|
||
[
|
||
dict(day=days_ago(9), value=80.0),
|
||
dict(day=days_ago(3), value=84.0),
|
||
dict(day=days_ago(1), value=88.0),
|
||
],
|
||
)
|
||
factor = synthesis.factor_brut()
|
||
assert factor["direction"] == synthesis.UP
|
||
assert factor["arrow"] == "↑"
|
||
assert factor["change_pct"] == pytest.approx(10.0)
|
||
assert factor["fresh"] is True
|
||
assert factor["observed_at"] == days_ago(1)
|
||
seed(
|
||
"brent_eur_daily", "EUR/baril", [dict(day=days_ago(8), value=88.0), dict(day=days_ago(1), value=72.0)]
|
||
)
|
||
fall = synthesis.factor_brut()
|
||
assert fall["direction"] == synthesis.DOWN and fall["arrow"] == "↓"
|
||
|
||
|
||
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(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"] >= 45
|
||
|
||
|
||
def test_change_factor_inverts_direction(store):
|
||
# 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.DOWN
|
||
assert factor["change_pct"] > 0
|
||
assert factor["effect"] == "↓ pression sur les prix"
|
||
|
||
|
||
def test_logistique_factor_reads_chokepoint_traffic(store):
|
||
rows = []
|
||
for index in range(6):
|
||
rows.append(
|
||
(
|
||
"Strait of Hormuz",
|
||
dict(
|
||
day=days_ago(25 - index * 4),
|
||
transit_tankers=40,
|
||
transit_total=90,
|
||
capacity_tankers=1000,
|
||
capacity_total=2000,
|
||
),
|
||
)
|
||
)
|
||
rows.append(
|
||
(
|
||
"Strait of Hormuz",
|
||
dict(
|
||
day=days_ago(1),
|
||
transit_tankers=22,
|
||
transit_total=60,
|
||
capacity_tankers=600,
|
||
capacity_total=1200,
|
||
),
|
||
)
|
||
)
|
||
storage.save_chokepoints(rows, "IMF PortWatch")
|
||
factor = synthesis.factor_logistique()
|
||
assert factor["direction"] == synthesis.UP, "moins de pétroliers : approvisionnement tendu"
|
||
assert "Hormuz" in factor["evidence_text"]
|
||
assert "PortWatch" in factor["source"]
|
||
|
||
|
||
def test_evenements_factor_weighs_confidence_and_expiry(store):
|
||
base = dict(
|
||
topic="ormuz",
|
||
event_type="chokepoint",
|
||
magnitude="forte",
|
||
fuels=["gazole"],
|
||
zone="Ormuz",
|
||
horizon_days=10,
|
||
observed_at=days_ago(1),
|
||
published_at=days_ago(1),
|
||
source_url="https://exemple.fr/a",
|
||
extracted_by="test",
|
||
)
|
||
storage.save_news_event(
|
||
dict(
|
||
base,
|
||
url_hash="h1",
|
||
direction="hausse",
|
||
confidence=0.9,
|
||
valid_from=days_ago(1),
|
||
valid_until=days_ago(-5),
|
||
)
|
||
)
|
||
storage.save_news_event(
|
||
dict(
|
||
base,
|
||
url_hash="h2",
|
||
direction="baisse",
|
||
confidence=0.2,
|
||
valid_from=days_ago(1),
|
||
valid_until=days_ago(-5),
|
||
)
|
||
)
|
||
factor = synthesis.factor_evenements()
|
||
assert factor["direction"] == synthesis.UP
|
||
assert factor["count"] == 2 and factor["confidence_used"] == pytest.approx(1.1)
|
||
# Un événement expiré ne doit plus peser.
|
||
storage.save_news_event(
|
||
dict(
|
||
base,
|
||
url_hash="h3",
|
||
direction="baisse",
|
||
confidence=1.0,
|
||
valid_from=days_ago(20),
|
||
valid_until=days_ago(5),
|
||
)
|
||
)
|
||
assert synthesis.factor_evenements()["direction"] == synthesis.UP
|
||
|
||
|
||
def test_pressure_aggregates_weights_and_confidence(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)],
|
||
)
|
||
built = synthesis.build("Gazole")
|
||
assert built["pressure"] == "HAUSSE"
|
||
assert built["confidence"] is not None and 0 < built["confidence"] <= 0.8
|
||
assert built["known_factors"] >= 2
|
||
up = [f["label"] for f in built["factors"] if f["direction"] == "up"]
|
||
assert "Pétrole brut" in up
|
||
assert "montent" in built["plain"] and "pèse le plus" in built["plain"]
|
||
assert "jamais comme une prévision validée" in built["plain"]
|
||
assert "délai de transmission" in built["plain"]
|
||
|
||
|
||
def test_prefilter_rejects_non_fuel_articles_and_duplicates():
|
||
keep, dropped = news.prefilter(
|
||
[
|
||
dict(
|
||
hash="a",
|
||
title="Le détroit d’Ormuz perturbe les livraisons de pétrole brut",
|
||
summary="Les pétroliers ralentissent.",
|
||
),
|
||
dict(hash="b", title="Recette de gâteau au chocolat", summary="Sucre et farine."),
|
||
dict(
|
||
hash="c",
|
||
title="Le détroit d’Ormuz perturbe les livraisons de pétrole brut",
|
||
summary="Doublon du même flux.",
|
||
),
|
||
dict(hash="d", title="Nouvelle taxe carburant", summary="Le gazole et l’essence concernés."),
|
||
]
|
||
)
|
||
assert [article["hash"] for article in keep] == ["a", "d"]
|
||
reasons = {article["hash"]: reason for article, reason in dropped}
|
||
assert "carburant" in reasons["b"]
|
||
assert "déjà vu" in reasons["c"]
|
||
|
||
|
||
def test_prefilter_promotions_needs_brand_and_fuel_words():
|
||
keep, dropped = promotions.prefilter(
|
||
[
|
||
dict(
|
||
hash="p1",
|
||
title="Carburant à prix coûtant chez E.Leclerc ce week-end",
|
||
summary="Le gazole au prix coûtant samedi.",
|
||
),
|
||
dict(hash="p2", title="E.Leclerc ouvre un nouveau magasin", summary="Ouverture lundi."),
|
||
]
|
||
)
|
||
assert [article["hash"] for article in keep] == ["p1"]
|
||
assert dropped[0][1], "une raison d’écartement est toujours fournie"
|
||
|
||
|
||
def test_queue_metrics_expose_backlog_age_and_durations(store):
|
||
storage.save_articles(
|
||
[
|
||
dict(
|
||
hash="a",
|
||
url="https://exemple.fr/a",
|
||
title="Ormuz",
|
||
source="Test",
|
||
published_at=days_ago(3),
|
||
observed_at=days_ago(3),
|
||
)
|
||
],
|
||
"geo",
|
||
)
|
||
storage.save_articles(
|
||
[
|
||
dict(
|
||
hash="b",
|
||
url="https://exemple.fr/b",
|
||
title="Suez",
|
||
source="Test",
|
||
published_at=days_ago(1),
|
||
observed_at=days_ago(1),
|
||
)
|
||
],
|
||
"geo",
|
||
)
|
||
storage.mark_skipped(["b"], "préfiltrage automatique")
|
||
storage.record_llm_run("x", "ormuz", "gemma4:12b", 40.0, ok=True)
|
||
storage.record_llm_run("y", "ormuz", "gemma4:12b", 60.0, ok=False, detail="TimeoutError")
|
||
queue = storage.llm_queue()
|
||
assert queue["pending"] == 1 and queue["skipped"] == 1 and queue["total"] == 2
|
||
assert queue["oldest_pending_at"] and queue["oldest_pending_age_hours"] is not None
|
||
assert queue["analysed_24h_avg_seconds"] == pytest.approx(50.0)
|
||
assert queue["analysed_24h_failures"] == 1
|
||
assert queue["by_model"][0]["model"] == "gemma4:12b"
|