From 0a1e2dde5748774cecdcacd9d3dca4d06301c728 Mon Sep 17 00:00:00 2001 From: root Date: Sat, 12 Sep 2026 23:24:01 +0200 Subject: [PATCH] Detroits : niveau de perturbation vs dynamique, reference pre-crise, et Brent quotidien prioritaire Le garde-fou absolu sur le volume PortWatch est supprime : un effondrement mesure est un signal, pas une donnee impossible. Chaque detroit expose desormais deux dimensions separees, calculees avec la meme metrique que la valeur du jour (petroliers avec petroliers) : le niveau par rapport a une reference pre-crise (mediane de 1000 jours 2022-2025, job mensuel chokepoint_reference) et la dynamique recente face a la moyenne 10 jours, J-7 puis J-1, sans interpreter des variations trop faibles en valeur absolue. La confiance de la donnee combine qualite de mesure et corroboration par les articles suivis : un effondrement corrobore conserve le signal avec une confiance reduite et AIS explique. Le facteur brut n accepte plus qu une cotation quotidienne fraiche ; la moyenne mensuelle DGEC devient un contexte historique affiche a part, jamais un cours du jour. --- README.md | 37 ++++ collector.py | 18 ++ scheduler.py | 10 + storage.py | 43 ++++ style.css | 2 +- synthesis.py | 426 +++++++++++++++++++++++++++++-------- tests/test_factor_signs.py | 260 ++++++++++++++++------ tests/test_synthesis.py | 86 +------- ui.js | 3 + upstream.py | 58 +++++ 10 files changed, 708 insertions(+), 235 deletions(-) diff --git a/README.md b/README.md index 3b90593..119e2b9 100644 --- a/README.md +++ b/README.md @@ -120,6 +120,43 @@ dates, fraîcheur et sources restent disponibles derrière « Afficher les donn Les poids (`FACTOR_WEIGHTS`) sont explicites et lisibles ; le verdict est un vote pondéré calculé, jamais une appréciation d'un modèle. Ollama n'intervient pas dans ce calcul. +## Détroits : niveau de perturbation et dynamique récente + +Deux dimensions **séparées**, jamais mélangées : + +- **Niveau de perturbation** : trafic du jour comparé à une **référence pré-crise**, mesurée sur le + même jeu PortWatch (médiane de 1000 jours, 2022-09 → 2025-09) et **avec la même métrique** que la + valeur du jour : pétroliers avec pétroliers (`n_tanker`), tous navires avec tous navires + (`n_total`), capacité avec capacité (`capacity_tanker`). Étiquettes : EXTRÊME (< −70 %), + FORTE, MODÉRÉE, NORMALE, SUPÉRIEURE. +- **Dynamique récente** : évolution contre la moyenne 10 jours (puis J-7, puis J-1). Une variation + trop faible en valeur absolue (< 3 navires/jour, ou 5 % de la référence) n'est **pas** interprétée + comme une tendance : « trop faibles pour être interprétées » est affiché tel quel. + +Exemple réel : « Perturbation EXTRÊME : Strait of Hormuz à 2 pétroliers/jour, soit −96 % par rapport +à la référence pré-crise » → forte pression haussière persistante, la dynamique récente ne +l'annulant pas. + +**Aucune règle ne déclare un trafic faible « impossible »** : un effondrement mesuré est un signal. +La confiance affichée (`data_confidence`) dépend de la qualité de mesure (volume, régularité, +fraîcheur de publication) **et** de la corroboration par les articles suivis : un effondrement +corroboré conserve le signal avec une confiance réduite et explique pourquoi (AIS coupé, brouillage +ou spoofing possibles) ; non corroboré, la confiance est abaissée et la conclusion reste prudente. +Le job `chokepoint_reference` (mensuel) entretient la référence. + +**Pour le futur modèle J+0→J+21 : la normale d'un détroit est la référence pré-crise enregistrée +(`chokepoint_reference`), jamais l'historique local**, qui peut avoir commencé pendant une +perturbation. Apprendre « 5 pétroliers/jour = normal » à Ormuz serait une erreur de fond. + +## Brent : quotidien d'abord, mensuel en contexte + +Priorité stricte : **cotation quotidienne fraîche** (≤ 5 jours, cadence quotidienne vérifiée) > +autre série quotidienne > rien. La moyenne mensuelle DGEC n'est **jamais** présentée comme le cours +actuel ni utilisée pour piloter la pression quotidienne : elle est affichée à part comme contexte +historique. Sans cotation quotidienne fraîche, le facteur affiche « cours quotidien du brut +indisponible » avec la date de la dernière cotation, plutôt que de substituer silencieusement une +moyenne mensuelle. + ## File d'analyse Ollama supervisée - **Préfiltrage déterministe** avant tout appel de modèle : lexique carburant/pétrole obligatoire, diff --git a/collector.py b/collector.py index 5b9447b..0b64aaa 100644 --- a/collector.py +++ b/collector.py @@ -480,6 +480,24 @@ def job_portwatch(force=False): ) +def job_chokepoint_reference(force=False): + """Référence « normale » pré-crise des détroits, mesurée avant la période récente. + + Indispensable avant tout apprentissage : sans référence pré-crise, un historique local commencé + pendant une perturbation ferait passer un trafic effondré pour un niveau normal. + """ + rows = upstream.fetch_chokepoint_reference() + if not rows: + raise RuntimeError("aucune référence pré-crise récupérée") + saved = storage.save_chokepoint_reference(list(rows.values())) + detail = " · ".join( + f"{name} : médiane {row['tankers_median']:.0f} pétroliers/jour " + f"({row['observations']} jours, {row['window_start']} → {row['window_end']})" + for name, row in list(rows.items())[:4] + ) + return dict(status="ok", saved=saved, detail=detail) + + def job_news_geo(force=False): """Actualités géopolitiques et logistiques : contrôle toutes les 2 heures.""" import news diff --git a/scheduler.py b/scheduler.py index 9822a97..27904d5 100644 --- a/scheduler.py +++ b/scheduler.py @@ -104,6 +104,16 @@ JOBS = { func="job_portwatch", note="publication différée de plusieurs jours : la date affichée est celle de l’observation", ), + "chokepoint_reference": dict( + source="IMF PortWatch – référence pré-crise des détroits (médianes historiques)", + frequency="mensuel (la normale pré-crise ne bouge pas vite)", + cadence_seconds=30 * 86400, + retry_seconds=6 * 3600, + window=_daily_at(9, 0), + func="job_chokepoint_reference", + note="sans cette référence, un historique commencé pendant une crise ferait passer un " + "trafic effondré pour normal", + ), "news_geo": dict( source="Actualités géopolitiques et logistiques (Google News RSS, GDELT)", frequency="toutes les 2 heures", diff --git a/storage.py b/storage.py index 30d4f89..9ce2a4d 100644 --- a/storage.py +++ b/storage.py @@ -344,6 +344,44 @@ def match_favorite(lat, lon, tolerance_km=0.15): return dict(best, distance_km=round(best_distance, 3)) if best else None +def save_chokepoint_reference(rows, now=None): + """Référence pré-crise des détroits (médiane sur une période antérieure à la crise).""" + now = now or datetime.now(timezone.utc) + values = [ + ( + row["chokepoint"], + row["window_start"], + row["window_end"], + row["observations"], + row.get("tankers_median"), + row.get("tankers_mean"), + row.get("tankers_p10"), + row.get("tankers_p90"), + row.get("total_median"), + row.get("capacity_tanker_median"), + row.get("source"), + now.isoformat(), + ) + for row in rows + ] + if not values: + return 0 + with connect() as db: + db.executemany( + "REPLACE INTO chokepoint_reference(chokepoint,window_start,window_end,observations," + "tankers_median,tankers_mean,tankers_p10,tankers_p90,total_median," + "capacity_tanker_median,source,computed_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)", + values, + ) + return len(values) + + +def chokepoint_reference(): + """Références pré-crise enregistrées, indexées par détroit.""" + with connect() as db: + return {row["chokepoint"]: dict(row) for row in db.execute("SELECT * FROM chokepoint_reference")} + + def eta_lookup(keys, max_age_seconds=900, now=None): """ETA trafic encore fraîche. Une ETA périmée n'est jamais présentée comme actuelle.""" keys = list(keys) @@ -899,6 +937,11 @@ def connect(): key TEXT PRIMARY KEY, origin_lat REAL NOT NULL, origin_lon REAL NOT NULL, target_lat REAL NOT NULL, target_lon REAL NOT NULL, distance_m REAL NOT NULL, duration_s REAL, provider TEXT NOT NULL, computed_at TEXT NOT NULL); + CREATE TABLE IF NOT EXISTS chokepoint_reference ( + chokepoint TEXT PRIMARY KEY, window_start TEXT NOT NULL, window_end TEXT NOT NULL, + observations INTEGER NOT NULL, tankers_median REAL, tankers_mean REAL, + tankers_p10 REAL, tankers_p90 REAL, total_median REAL, + capacity_tanker_median REAL, source TEXT, computed_at TEXT NOT NULL); CREATE TABLE IF NOT EXISTS route_eta ( key TEXT PRIMARY KEY, duration_s REAL NOT NULL, provider TEXT NOT NULL, computed_at TEXT NOT NULL); diff --git a/style.css b/style.css index b29954d..b317086 100644 --- a/style.css +++ b/style.css @@ -1 +1 @@ -:root{color-scheme:dark;--bg:#0b1220;--panel:#142035;--line:#29374b;--text:#edf3fa;--muted:#a2b0c4;--accent:#68dfc3;--warn:#f9cb72;--bad:#ff9393}*{box-sizing:border-box}body{margin:0;background:radial-gradient(ellipse at top left,#193749,transparent 65%),var(--bg);font:15px/1.55 system-ui,-apple-system,Segoe UI,sans-serif;color:var(--text);min-height:100vh}main{max-width:1240px;margin:auto;padding:36px 24px}header{display:flex;justify-content:space-between;align-items:center;gap:24px;margin-bottom:30px}.eyebrow{font-size:11px;letter-spacing:.14em;text-transform:uppercase;color:var(--accent);font-weight:750}h1{font-size:clamp(32px,4vw,52px);line-height:1.08;letter-spacing:-.045em;margin:12px 0}h1 span{color:var(--accent)}h2{font-size:20px;letter-spacing:-.025em;margin:0 0 16px}h3{font-size:16px;margin:22px 0 10px}p{margin:10px 0}.header-actions,.inline,.section-title,.dialog-head,.item-actions{display:flex;align-items:center;gap:10px}.layout{display:grid;grid-template-columns:355px minmax(0,1fr);gap:20px}aside,#result{display:grid;gap:18px;align-content:start}.card{background:linear-gradient(135deg,#17263b,#101c2d);border:1px solid var(--line);border-radius:20px;padding:24px;box-shadow:0 12px 30px #0002}.compact{padding:20px}.section-title,.dialog-head{justify-content:space-between}.section-title h2{margin:0;font-size:17px}label{display:block;font-size:13px;font-weight:650;color:#c6d4e7;margin:16px 0 7px}input,select{display:block;width:100%;background:#0b1627;color:var(--text);border:1px solid #36465c;border-radius:10px;padding:11px 12px;font:inherit;min-height:44px}label input,label select{margin-top:7px}input:focus,select:focus,button:focus-visible{outline:2px solid var(--accent);outline-offset:2px}button{font:inherit;font-size:13px;font-weight:700;border:1px solid transparent;border-radius:10px;padding:11px 14px;cursor:pointer;min-height:42px;white-space:normal}.primary{background:var(--accent);color:#09211e}.secondary{background:#203048;color:var(--text);border-color:#34455b}button:hover{filter:brightness(1.12)}button:disabled{opacity:.55;cursor:wait}select:disabled{opacity:.75}.wide{width:100%;margin-top:20px}.small{padding:6px 10px;min-height:34px;font-size:12px}.hint,.muted{color:var(--muted);font-size:13px}.hint:empty,.form-error:empty{display:none}.inline>input,.inline>div{min-width:0;flex:1}.location-actions{margin-top:12px}.location-label{font-size:12px;color:var(--accent);padding-top:30px;overflow-wrap:anywhere}.empty{min-height:320px;padding-top:36px}.empty h2{font-size:26px;margin:16px 0}.empty p{max-width:520px;color:var(--muted)}.tags{display:flex;flex-wrap:wrap;gap:8px;margin-top:20px}.tags span,.badge{font-size:11px;background:#23374a;color:#cee5e5;padding:5px 9px;border-radius:7px}.badge{display:inline-block;margin:0 6px 6px 0}.badge.brand{background:#1d4a44;color:#a7f3e3;font-weight:700}.station-cards{display:grid;grid-template-columns:repeat(auto-fill,minmax(190px,1fr));gap:12px;margin:14px 0}.station-card{background:#0d192a;border:1px solid #25364b;border-radius:12px;padding:12px}.station-head{display:flex;justify-content:space-between;align-items:baseline;gap:8px}.station-head strong{font-size:14px;overflow-wrap:anywhere}.station-head span{font-size:17px;font-weight:750;color:var(--accent);white-space:nowrap}.station-head small{font-size:10px;color:var(--muted)}.station-card p{margin:4px 0}.job-head{display:flex;justify-content:space-between;align-items:baseline;gap:10px}.nav-actions{display:flex;gap:8px;margin-top:10px}.nav-btn{font-size:12px;font-weight:700;color:#09211e;background:var(--accent);border-radius:8px;padding:7px 11px;text-decoration:none;white-space:nowrap}.nav-btn+.nav-btn{background:#2f4a68;color:var(--text)}.pressure{display:flex;flex-wrap:wrap;align-items:center;gap:10px;padding:14px 16px;border-radius:12px;background:#0d192a;border:1px solid #25364b;margin-bottom:14px}.pressure strong{font-size:17px}.pressure-up{border-color:#8a6a3c;background:#2c2317}.pressure-down{border-color:#2f6a5c;background:#12261f}.factors{display:grid;gap:10px}.factor{display:grid;grid-template-columns:34px minmax(0,1fr);gap:12px;align-items:start;border-top:1px solid var(--line);padding-top:10px}.factor:first-child{border-top:0}.factor-arrow{font-size:20px;text-align:center}.arrow-up{color:var(--warn)}.arrow-down{color:var(--accent)}.arrow-flat{color:var(--muted)}.arrow-unknown{color:#8894a6}.factor p{margin:2px 0}.factor-chain{display:flex;flex-wrap:wrap;align-items:baseline;gap:8px;margin:6px 0}.measured{color:#dbe7f5;font-weight:600}.chain-arrow{color:var(--muted)}.effect{font-weight:750;white-space:nowrap}.effect-up{color:var(--warn)}.effect-down{color:var(--accent)}.effect-flat{color:var(--muted)}.effect-unknown{color:#8894a6}.mini{width:100%;height:52px;display:block;margin:8px 0}.mini polyline{stroke:var(--accent);stroke-width:2;fill:none;vector-effect:non-scaling-stroke}.mini circle{fill:var(--accent)}.verdict{font-size:clamp(24px,3vw,34px);line-height:1.2;margin:12px 0 20px}.tone-refuel,.tone-topup{color:var(--warn)}.tone-wait,.tone-none{color:var(--accent)}.metrics{display:grid;grid-template-columns:repeat(3,1fr);gap:10px;margin:18px 0}.metric{background:#0d192a;border:1px solid #25364b;border-radius:12px;padding:14px}.metric strong{display:block;font-size:22px;line-height:1.4}.metric span{font-size:11px;color:var(--muted)}.reasons{padding-left:19px;color:#c1cee0;font-size:13px}.reasons li{margin:8px 0}.notice{padding:12px;border:1px solid #78603c;background:#382d1e;color:#f3d9ac;border-radius:10px;font-size:13px}.station{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:10px;align-items:center;border-top:1px solid var(--line);padding:15px 0}.station:first-child{border-top:0}.station strong{font-size:14px;overflow-wrap:anywhere}.station .price{font-size:23px;font-weight:750;color:var(--accent);white-space:nowrap}.station .price small{font-size:11px}.station p{margin:2px 0}.buckets{display:flex;gap:6px;flex-wrap:wrap;max-height:110px;overflow:auto;margin:12px 0}.bucket{font-size:11px;padding:4px 7px;background:#203048;border-radius:6px}.chart{width:100%;height:170px;display:block;margin-top:16px}.chart polyline{stroke:var(--accent);stroke-width:2.5;fill:none;vector-effect:non-scaling-stroke}.chart circle{fill:var(--accent)}.chart text{fill:var(--muted);font-size:10px}.chart line{stroke:var(--line)}.error,.form-error{color:var(--bad);font-size:13px}.loading{color:var(--muted);padding:32px}.two{display:grid;grid-template-columns:1fr 1fr;gap:14px}dialog{border:1px solid #35465b;border-radius:20px;background:var(--panel);color:var(--text);width:min(560px,calc(100% - 24px));max-height:90vh;padding:24px;box-shadow:0 30px 100px #0009}dialog::backdrop{background:#030a16b8}dialog h2{margin:0}.close{font-size:24px;padding:0 12px}form h3{border-top:1px solid var(--line);padding-top:18px}form button[type=submit]{margin-top:20px}.item{padding:14px 0;border-bottom:1px solid var(--line)}.item-actions{margin-top:8px}.items{margin-bottom:16px}footer{font-size:11px;color:#8a9bb1;margin-top:30px;max-width:950px}details{margin-top:16px}summary{cursor:pointer;color:#cbd8e8;font-size:13px}[hidden]{display:none!important}@media(max-width:850px){main{padding:22px 16px}.layout{grid-template-columns:1fr}header{align-items:flex-start;flex-direction:column;gap:14px}.header-actions{width:100%}.header-actions button{flex:1}.card{padding:20px}.empty{min-height:240px}.metrics{gap:6px}.metric{padding:11px}.metric strong{font-size:19px}.two{gap:10px}.station .price{font-size:20px}} +:root{color-scheme:dark;--bg:#0b1220;--panel:#142035;--line:#29374b;--text:#edf3fa;--muted:#a2b0c4;--accent:#68dfc3;--warn:#f9cb72;--bad:#ff9393}*{box-sizing:border-box}body{margin:0;background:radial-gradient(ellipse at top left,#193749,transparent 65%),var(--bg);font:15px/1.55 system-ui,-apple-system,Segoe UI,sans-serif;color:var(--text);min-height:100vh}main{max-width:1240px;margin:auto;padding:36px 24px}header{display:flex;justify-content:space-between;align-items:center;gap:24px;margin-bottom:30px}.eyebrow{font-size:11px;letter-spacing:.14em;text-transform:uppercase;color:var(--accent);font-weight:750}h1{font-size:clamp(32px,4vw,52px);line-height:1.08;letter-spacing:-.045em;margin:12px 0}h1 span{color:var(--accent)}h2{font-size:20px;letter-spacing:-.025em;margin:0 0 16px}h3{font-size:16px;margin:22px 0 10px}p{margin:10px 0}.header-actions,.inline,.section-title,.dialog-head,.item-actions{display:flex;align-items:center;gap:10px}.layout{display:grid;grid-template-columns:355px minmax(0,1fr);gap:20px}aside,#result{display:grid;gap:18px;align-content:start}.card{background:linear-gradient(135deg,#17263b,#101c2d);border:1px solid var(--line);border-radius:20px;padding:24px;box-shadow:0 12px 30px #0002}.compact{padding:20px}.section-title,.dialog-head{justify-content:space-between}.section-title h2{margin:0;font-size:17px}label{display:block;font-size:13px;font-weight:650;color:#c6d4e7;margin:16px 0 7px}input,select{display:block;width:100%;background:#0b1627;color:var(--text);border:1px solid #36465c;border-radius:10px;padding:11px 12px;font:inherit;min-height:44px}label input,label select{margin-top:7px}input:focus,select:focus,button:focus-visible{outline:2px solid var(--accent);outline-offset:2px}button{font:inherit;font-size:13px;font-weight:700;border:1px solid transparent;border-radius:10px;padding:11px 14px;cursor:pointer;min-height:42px;white-space:normal}.primary{background:var(--accent);color:#09211e}.secondary{background:#203048;color:var(--text);border-color:#34455b}button:hover{filter:brightness(1.12)}button:disabled{opacity:.55;cursor:wait}select:disabled{opacity:.75}.wide{width:100%;margin-top:20px}.small{padding:6px 10px;min-height:34px;font-size:12px}.hint,.muted{color:var(--muted);font-size:13px}.hint:empty,.form-error:empty{display:none}.inline>input,.inline>div{min-width:0;flex:1}.location-actions{margin-top:12px}.location-label{font-size:12px;color:var(--accent);padding-top:30px;overflow-wrap:anywhere}.empty{min-height:320px;padding-top:36px}.empty h2{font-size:26px;margin:16px 0}.empty p{max-width:520px;color:var(--muted)}.tags{display:flex;flex-wrap:wrap;gap:8px;margin-top:20px}.tags span,.badge{font-size:11px;background:#23374a;color:#cee5e5;padding:5px 9px;border-radius:7px}.badge{display:inline-block;margin:0 6px 6px 0}.badge.brand{background:#1d4a44;color:#a7f3e3;font-weight:700}.station-cards{display:grid;grid-template-columns:repeat(auto-fill,minmax(190px,1fr));gap:12px;margin:14px 0}.station-card{background:#0d192a;border:1px solid #25364b;border-radius:12px;padding:12px}.station-head{display:flex;justify-content:space-between;align-items:baseline;gap:8px}.station-head strong{font-size:14px;overflow-wrap:anywhere}.station-head span{font-size:17px;font-weight:750;color:var(--accent);white-space:nowrap}.station-head small{font-size:10px;color:var(--muted)}.station-card p{margin:4px 0}.job-head{display:flex;justify-content:space-between;align-items:baseline;gap:10px}.nav-actions{display:flex;gap:8px;margin-top:10px}.nav-btn{font-size:12px;font-weight:700;color:#09211e;background:var(--accent);border-radius:8px;padding:7px 11px;text-decoration:none;white-space:nowrap}.nav-btn+.nav-btn{background:#2f4a68;color:var(--text)}.pressure{display:flex;flex-wrap:wrap;align-items:center;gap:10px;padding:14px 16px;border-radius:12px;background:#0d192a;border:1px solid #25364b;margin-bottom:14px}.pressure strong{font-size:17px}.pressure-up{border-color:#8a6a3c;background:#2c2317}.pressure-down{border-color:#2f6a5c;background:#12261f}.factors{display:grid;gap:10px}.factor{display:grid;grid-template-columns:34px minmax(0,1fr);gap:12px;align-items:start;border-top:1px solid var(--line);padding-top:10px}.factor:first-child{border-top:0}.factor-arrow{font-size:20px;text-align:center}.arrow-up{color:var(--warn)}.arrow-down{color:var(--accent)}.arrow-flat{color:var(--muted)}.arrow-unknown{color:#8894a6}.factor p{margin:2px 0}.factor-levels{display:flex;flex-wrap:wrap;gap:8px;margin:6px 0}.lvl{font-size:11px;font-weight:750;padding:4px 8px;border-radius:7px;background:#2c2317;color:#f9cb72}.lvl-EXTRÊME{background:#4a1f1f;color:#ffb4a8}.factor-chain{display:flex;flex-wrap:wrap;align-items:baseline;gap:8px;margin:6px 0}.measured{color:#dbe7f5;font-weight:600}.chain-arrow{color:var(--muted)}.effect{font-weight:750;white-space:nowrap}.effect-up{color:var(--warn)}.effect-down{color:var(--accent)}.effect-flat{color:var(--muted)}.effect-unknown{color:#8894a6}.mini{width:100%;height:52px;display:block;margin:8px 0}.mini polyline{stroke:var(--accent);stroke-width:2;fill:none;vector-effect:non-scaling-stroke}.mini circle{fill:var(--accent)}.verdict{font-size:clamp(24px,3vw,34px);line-height:1.2;margin:12px 0 20px}.tone-refuel,.tone-topup{color:var(--warn)}.tone-wait,.tone-none{color:var(--accent)}.metrics{display:grid;grid-template-columns:repeat(3,1fr);gap:10px;margin:18px 0}.metric{background:#0d192a;border:1px solid #25364b;border-radius:12px;padding:14px}.metric strong{display:block;font-size:22px;line-height:1.4}.metric span{font-size:11px;color:var(--muted)}.reasons{padding-left:19px;color:#c1cee0;font-size:13px}.reasons li{margin:8px 0}.notice{padding:12px;border:1px solid #78603c;background:#382d1e;color:#f3d9ac;border-radius:10px;font-size:13px}.station{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:10px;align-items:center;border-top:1px solid var(--line);padding:15px 0}.station:first-child{border-top:0}.station strong{font-size:14px;overflow-wrap:anywhere}.station .price{font-size:23px;font-weight:750;color:var(--accent);white-space:nowrap}.station .price small{font-size:11px}.station p{margin:2px 0}.buckets{display:flex;gap:6px;flex-wrap:wrap;max-height:110px;overflow:auto;margin:12px 0}.bucket{font-size:11px;padding:4px 7px;background:#203048;border-radius:6px}.chart{width:100%;height:170px;display:block;margin-top:16px}.chart polyline{stroke:var(--accent);stroke-width:2.5;fill:none;vector-effect:non-scaling-stroke}.chart circle{fill:var(--accent)}.chart text{fill:var(--muted);font-size:10px}.chart line{stroke:var(--line)}.error,.form-error{color:var(--bad);font-size:13px}.loading{color:var(--muted);padding:32px}.two{display:grid;grid-template-columns:1fr 1fr;gap:14px}dialog{border:1px solid #35465b;border-radius:20px;background:var(--panel);color:var(--text);width:min(560px,calc(100% - 24px));max-height:90vh;padding:24px;box-shadow:0 30px 100px #0009}dialog::backdrop{background:#030a16b8}dialog h2{margin:0}.close{font-size:24px;padding:0 12px}form h3{border-top:1px solid var(--line);padding-top:18px}form button[type=submit]{margin-top:20px}.item{padding:14px 0;border-bottom:1px solid var(--line)}.item-actions{margin-top:8px}.items{margin-bottom:16px}footer{font-size:11px;color:#8a9bb1;margin-top:30px;max-width:950px}details{margin-top:16px}summary{cursor:pointer;color:#cbd8e8;font-size:13px}[hidden]{display:none!important}@media(max-width:850px){main{padding:22px 16px}.layout{grid-template-columns:1fr}header{align-items:flex-start;flex-direction:column;gap:14px}.header-actions{width:100%}.header-actions button{flex:1}.card{padding:20px}.empty{min-height:240px}.metrics{gap:6px}.metric{padding:11px}.metric strong{font-size:19px}.two{gap:10px}.station .price{font-size:20px}} diff --git a/synthesis.py b/synthesis.py index dc633df..f3ca1f1 100644 --- a/synthesis.py +++ b/synthesis.py @@ -216,32 +216,91 @@ def _trend_factor( ) -def factor_brut(days=7): - """Pétrole brut : baril en euros. Une hausse du brut pousse les prix à la pompe (avec retard).""" - factor = _trend_factor( - ["brent_eur_daily", "brent_usd_daily", "dgec_brent_usd"], - days, - threshold=1.5, - window_days=400, - fresh_days=45, - source="Brent (cotation quotidienne, DGEC en mensuel)", +DAILY_MAX_GAP_DAYS = 4 # au-delà, la série n'a plus une cadence quotidienne +DAILY_FRESH_DAYS = 5 # au-delà, la cotation quotidienne n'est plus « actuelle » + + +def _is_daily(rows): + """Cadence quotidienne : aucun trou de plus de quelques jours entre deux points.""" + if len(rows) < 2: + return False + days = [date.fromisoformat(str(row["day"])) for row in rows] + return max((b - a).days for a, b in zip(days, days[1:], strict=False)) <= DAILY_MAX_GAP_DAYS + + +def _monthly_context(fuel_series="dgec_brent_usd", unit="USD/baril"): + """Contexte historique mensuel (DGEC). Jamais présenté comme le cours actuel.""" + rows = _series(fuel_series, 400) + if not rows: + return None + last = _last(rows) + return dict( + value=last["value"], + day=str(last["day"]), + unit=unit, + series=fuel_series, + source=last.get("source"), + label="moyenne mensuelle DGEC (contexte historique)", ) - if not factor: + + +def factor_brut(days=7): + """Pétrole brut : priorité absolue à une cotation **quotidienne fraîche**. + + Ordre de priorité : Brent quotidien frais > autre série quotidienne fraîche > rien. La moyenne + mensuelle DGEC n'est **jamais** utilisée comme cours du jour ni pour piloter la pression + quotidienne : elle est exposée à part comme contexte historique. Sans quotidien frais, le + facteur dit « cours quotidien indisponible » au lieu de présenter une moyenne mensuelle. + """ + daily, daily_series, age_days = None, None, None + for name in ("brent_eur_daily", "brent_usd_daily", "eia_brent_daily"): + rows = _series(name, max(days * 3, 60)) + if rows: + daily, daily_series = rows, name + break + context = _monthly_context() + unit = "EUR/baril" if daily_series == "brent_eur_daily" else "USD/baril" + if daily: + age_days = (datetime.now(timezone.utc).date() - date.fromisoformat(str(_last(daily)["day"]))).days + if not daily or not _is_daily(daily) or age_days is None or age_days > DAILY_FRESH_DAYS: + if daily and age_days is not None and age_days <= DAILY_FRESH_DAYS: + reason = "la série disponible n’a pas une cadence quotidienne" + elif daily: + reason = f"dernière cotation quotidienne le {_last(daily)['day']}, soit {age_days} jours" + else: + reason = "aucune cotation quotidienne enregistrée" return _decorate( dict( key="brut", label="Pétrole brut", direction=UNKNOWN, weight=FACTOR_WEIGHTS["brut"], - observation="Aucune cotation récente exploitable du baril.", - relation="Sans cotation, l’effet du brut ne peut pas être évalué.", + daily_available=False, + historical_context=context, + observation=f"Cours quotidien du brut indisponible ({reason}).", + observation_change=( + f"Contexte historique : moyenne mensuelle DGEC à " + f"{context['value']:.2f} {context['unit']} pour {context['day']} " + f"— donnée mensuelle, pas un cours du jour." + if context + else "" + ), + relation=( + "Sans cotation quotidienne fraîche, l’effet du brut sur les prix de la semaine " + "ne peut pas être évalué. Une moyenne mensuelle décrirait le mois écoulé, pas " + "la situation actuelle." + ), ) ) - unit = "EUR/baril" if factor["series"] == "brent_eur_daily" else "USD/baril" + factor = _trend_factor( + [daily_series], days, threshold=1.5, fresh_days=DAILY_FRESH_DAYS, source="Brent, cotation quotidienne" + ) factor.update( key="brut", label="Pétrole brut", weight=FACTOR_WEIGHTS["brut"], + daily_available=True, + historical_context=context, observation=f"Baril à {factor['value']:.2f} {unit}", observation_change=_format_changes(factor["changes"], ("d1", "d7")), relation=( @@ -249,7 +308,8 @@ def factor_brut(days=7): "la pompe, une baisse avec au moins autant de retard." ), explanation=f"Baril à {factor['value']:.2f} {unit}, {factor['effect_change_pct']:+.1f} % " - f"sur la période observée ({factor['reference_day']} → {factor['observed_at']}).", + f"sur la période observée ({factor['reference_day']} → {factor['observed_at']}, " + f"cotation quotidienne).", ) return factor @@ -291,17 +351,22 @@ def factor_change(days=7): "euros (effet baissier) ; un euro plus faible le renchérit (effet haussier). " "Le signe de ce facteur est donc l’inverse de celui du taux affiché." ), - explanation=f"1 € = {factor['value']:.4f} $ ({factor['change_pct']:+.2f} % sur la période) : " - + ( - "l’euro s’est renforcé face au dollar, ce qui allège la facture en euros." - if stronger - else "l’euro s’est affaibli face au dollar, ce qui renchérit le baril en euros." + explanation=( + f"1 € = {factor['value']:.4f} $ : variation de {factor['change_pct']:+.2f} % sur la " + "période, trop faible pour conclure à elle seule." + if factor["direction"] == FLAT + else f"1 € = {factor['value']:.4f} $ ({factor['change_pct']:+.2f} % sur la période) : " + + ( + "l’euro s’est renforcé face au dollar, ce qui allège la facture en euros." + if stronger + else "l’euro s’est affaibli face au dollar, ce qui renchérit le baril en euros." + ) ), ) return factor -def factor_raffinage(days=35): +def factor_raffinage(days=30): """Marge de raffinage : transformer le brut coûte plus ou moins cher. Même sens que la marge.""" factor = _trend_factor( ["dgec_margin_eur_per_tonne"], @@ -379,22 +444,70 @@ def factor_produits(fuel="Gazole", days=28): return factor -# Un trafic de quelques navires par jour est trop bruité pour établir une normale : la mesure -# PortWatch du détroit d'Ormuz tombe régulièrement à 0–2 pétroliers par jour, ce qui produirait -# des variations de ±100 % sans signification. En dessous de ces seuils, on ne conclut pas. -MIN_TANKERS_PER_DAY = 5 -MIN_OBSERVATIONS = 4 +# Seuils de niveau (écart à la référence pré-crise) et de dynamique (évolution récente). +# Aucune règle ne déclare un faible trafic « impossible » : un effondrement mesuré est un signal, +# dont la confiance dépend de la qualité de mesure ET de sa corroboration par l'actualité. +LEVEL_THRESHOLDS = ((-70, "EXTRÊME"), (-40, "FORTE"), (-15, "MODÉRÉE"), (15, "NORMALE")) +DYNAMICS_THRESHOLDS = ( + (15, "nette amélioration"), + (5, "légère amélioration"), + (-5, "stable"), + (-15, "légère dégradation"), +) +CHOKEPOINT_KEYWORDS = { + "Strait of Hormuz": ("ormuz", "hormuz"), + "Bab el-Mandeb Strait": ("bab el mandeb", "bab-el-mandeb", "mer rouge", "red sea"), + "Suez Canal": ("suez",), + "Malacca Strait": ("malacca",), +} + + +def _level_label(level_pct): + if level_pct is None: + return None + for threshold, label in LEVEL_THRESHOLDS: + if level_pct <= threshold: + return label + return "SUPÉRIEURE" + + +def _dynamics_label(dynamics_pct): + if dynamics_pct is None: + return None + for threshold, label in DYNAMICS_THRESHOLDS: + if dynamics_pct >= threshold: + return label + return "nette dégradation" + + +def _corroboration(name, events): + """Événements d'actualité qui parlent de ce détroit (source et date conservées).""" + keywords = CHOKEPOINT_KEYWORDS.get(name, ()) + matches = [] + for event in events: + haystack = " ".join( + str(event.get(key) or "") for key in ("zone", "event_type", "summary", "title") + ).lower() + if any(keyword in haystack for keyword in keywords): + matches.append(event) + return matches def factor_logistique(days=30): - """Détroits : moins de pétroliers en circulation = approvisionnement plus tendu (effet haussier). + """Détroits : deux dimensions distinctes, jamais mélangées. - La variation mesurée porte sur le trafic ; la flèche affichée porte sur l'**effet prix**, qui est - l'inverse : un trafic en baisse est haussier, un trafic en reprise est baissier. + 1. **Niveau de perturbation** : valeur du jour comparée à la référence pré-crise, mesurée avec + la **même métrique** (pétroliers avec pétroliers). Un trafic effondré est un signal fort. + 2. **Dynamique récente** : évolution sur les derniers jours (J-1, J-7, moyenne 10 jours). + + Un trafic « 6 contre 5 habituellement » n'est pas une détente si les 5 sont déjà un niveau de + crise : c'est pourquoi la référence est pré-crise et non la médiane locale. """ per_chokepoint = { name: entries for name, entries in storage.chokepoint_daily(days=days).items() if entries } + references = storage.chokepoint_reference() + events = storage.news_events(days=21) if not per_chokepoint: return _decorate( dict( @@ -406,48 +519,119 @@ def factor_logistique(days=30): relation="Sans mesure de trafic, la tension logistique ne peut pas être évaluée.", ) ) - details, changes, newest, samples, unusable = [], [], None, {}, [] + + details, samples, unusable, notes = [], {}, [], [] + effects, corroborated, recent_moves = [], [], [] + newest = None for name, entries in per_chokepoint.items(): entries.sort(key=lambda item: item["day"]) values = [ - (entry["day"], entry["transit_tankers"]) + (str(entry["day"]), entry["transit_tankers"]) for entry in entries if entry.get("transit_tankers") is not None ] - if len(values) < MIN_OBSERVATIONS: - unusable.append(f"{name} : historique trop court ({len(values)} observation(s))") - continue - median_volume = sorted(value for _day, value in values)[len(values) // 2] - if median_volume < MIN_TANKERS_PER_DAY: - unusable.append( - f"{name} : trafic mesuré trop faible " - f"({median_volume} pétrolier(s)/jour en médiane) pour établir une normale" - ) + if len(values) < 2: + unusable.append(f"{name} : {len(values)} observation(s) seulement") continue + reference = references.get(name) today, latest = values[-1] - normal = sorted(value for _day, value in values)[len(values) // 2] - week_ago = next( - ( - value - for day, value in reversed(values) - if date.fromisoformat(str(day)) <= date.fromisoformat(str(today)) - timedelta(days=7) - ), - None, + newest = max(newest or "", today) + + def _before(offset, today=today, values=values): + """Dernière valeur connue au moins ``offset`` jours avant la dernière observation.""" + limit = (date.fromisoformat(today) - timedelta(days=offset)).isoformat() + earlier = [(day, value) for day, value in values if day <= limit] + return earlier[-1][1] if earlier else None + + window = [ + value + for day, value in values + if date.fromisoformat(day) >= date.fromisoformat(today) - timedelta(days=10) + ] + mean10 = round(sum(window) / len(window), 1) if window else None + level_pct = ( + round((latest - reference["tankers_median"]) / reference["tankers_median"] * 100, 1) + if reference and reference.get("tankers_median") + else None + ) + d1, d7 = _before(1), _before(7) + # Référence la plus robuste d'abord (moyenne 10 jours), puis J-7, puis J-1. + dynamics_pct, dynamics_basis, dynamics_note = None, None, None + minimum_move = max(3.0, (reference["tankers_median"] or 0) * 0.05) if reference else 3.0 + for label, candidate in (("moyenne 10 jours", mean10), ("J-7", d7), ("J-1", d1)): + if candidate is None: + continue + move = latest - candidate + if abs(move) < minimum_move: + dynamics_note = ( + f"variations de {abs(move):.0f} navire(s)/jour : trop faibles pour " + f"être interprétées (seuil {minimum_move:.0f})" + ) + break + dynamics_pct, dynamics_basis = round(move / candidate * 100, 1), label + break + # Qualité de mesure : volume observé, régularité, fraîcheur de la publication. + volume = sorted(value for _day, value in values)[len(values) // 2] + mean = sum(value for _day, value in values) / len(values) + spread = ( + (max(value for _day, value in values) - min(value for _day, value in values)) / mean + if mean + else 0 + ) + publication_age = (datetime.now(timezone.utc).date() - date.fromisoformat(today)).days + measurement = 0.35 + min(0.25, reference["observations"] / 4000) if reference else 0.15 + measurement += 0.15 if volume >= 10 else (0.08 if volume >= 3 else 0.0) + measurement -= min(0.2, spread) + measurement -= min(0.2, publication_age / 60) + measurement = round(max(0.1, min(0.9, measurement)), 2) + matches = _corroboration(name, events) + if dynamics_note: + notes.append(f"{name} : {dynamics_note}") + details.append( + f"{name} : {latest:.0f} pétroliers/jour" + + ( + f" (référence pré-crise {reference['tankers_median']:.0f}, {level_pct:+.0f} %, " + f"{reference['window_start']} → {reference['window_end']})" + if level_pct is not None + else " (référence pré-crise indisponible)" + ) + + ( + f", dynamique {dynamics_pct:+.0f} % sur les derniers jours" + if dynamics_pct is not None + else "" + ) ) - if not normal: - continue - vs_normal = round((latest - normal) / normal * 100, 1) - vs_week = round((latest - week_ago) / week_ago * 100, 1) if week_ago else None - # La donnée observée est le trafic ; l'effet prix est son inverse. - changes.append(-vs_normal) - details.append(f"{name} : {latest} pétroliers contre {normal} habituellement ({vs_normal:+.0f} %)") - if vs_week is not None: - details.append(f"{name} sur 7 jours : {vs_week:+.0f} %") - newest = max(newest or "", str(today)) samples[name] = dict( - transit=latest, normal=normal, vs_normal_pct=vs_normal, vs_week_pct=vs_week, day=str(today) + transit=latest, + day=today, + level_pct=level_pct, + dynamics_pct=dynamics_pct, + dynamics_basis=dynamics_basis, + dynamics_note=dynamics_note, + mean10=mean10, + d1=d1, + d7=d7, + reference_median=reference["tankers_median"] if reference else None, + reference_window=( + f"{reference['window_start']} → {reference['window_end']}" if reference else None + ), + measurement_confidence=measurement, + corroboration=len(matches), + corroboration_sources=[event.get("url") for event in matches[:3]], ) - if not changes: + if level_pct is not None: + effects.append(level_pct) + if matches and level_pct is not None and level_pct <= -15: + corroborated.append(name) + if dynamics_pct is not None: + recent_moves.append(dynamics_pct) + if not reference: + notes.append( + f"{name} : référence pré-crise indisponible, historique local utilisé avec " + "prudence (il peut avoir commencé pendant la perturbation)" + ) + + if not samples: return _decorate( dict( key="logistique", @@ -455,53 +639,115 @@ def factor_logistique(days=30): direction=UNKNOWN, weight=FACTOR_WEIGHTS["logistique"], observation=( - "Mesure du trafic non exploitable : " + " ; ".join(unusable[:3]) + "Mesure du trafic insuffisante : " + " ; ".join(unusable[:3]) if unusable - else "Historique des détroits trop court pour comparer à une normale." - ), - relation=( - "Un trafic trop faible ou trop irrégulier ne permet pas de définir une normale " - "fiable : aucune flèche n’est affichée plutôt que d’en tirer un signal " - "trompeur." + else "Historique des détroits trop court." ), + relation="Sans comparaison possible, aucune conclusion n’est tirée.", ) ) - average_effect = sum(changes) / len(changes) - direction = _direction(average_effect, 10) - first_day, first_sample = next(iter(samples.items())) - traffic_move = -average_effect - if traffic_move <= -10: - tension = "en baisse, ce qui tend l’approvisionnement mondial" - elif traffic_move >= 10: - tension = "en reprise, ce qui détend l’approvisionnement" + + worst = min( + samples.items(), key=lambda item: item[1]["level_pct"] if item[1]["level_pct"] is not None else 0 + ) + key_name, sample = worst + level_pct, dynamics_pct = sample["level_pct"], sample["dynamics_pct"] + level_label = _level_label(level_pct) + dynamics_label = _dynamics_label(dynamics_pct) + # L'effet suit le niveau (pression persistante) ; la dynamique module le message. + if level_pct is None: + direction = UNKNOWN + elif level_pct <= -15: + direction = UP + elif level_pct >= 15: + direction = DOWN + elif dynamics_pct is not None and dynamics_pct >= 5: + direction = DOWN + elif dynamics_pct is not None and dynamics_pct <= -5: + direction = UP else: - tension = "globalement stable" + direction = FLAT + confidence = sample["measurement_confidence"] + if corroborated: + notes.append( + "mesure AIS imparfaite (brouillage, AIS coupé ou spoofing possibles) mais " + "corroborée par l’actualité : le signal est conservé avec une confiance réduite" + ) + elif level_pct is not None and level_pct <= -15: + confidence = round(max(0.1, confidence - 0.15), 2) + notes.append( + "effondrement mesuré mais non corroboré par les articles suivis : confiance " + "réduite, aucune conclusion ferme" + ) + if level_pct is None: + conclusion = ( + "Détroit fortement mesuré, mais sans référence pré-crise : impossible de dire " + "ce qui relève de la perturbation et ce qui relève de la normale." + ) + else: + pressure = ( + "forte pression haussière" + if level_pct <= -40 + else "pression haussière" + if level_pct <= -15 + else "pression baissière" + if level_pct >= 15 + else "pression neutre" + ) + conclusion = ( + f"{level_label} — trafic {level_pct:+.0f} % par rapport à la référence " + f"pré-crise ({key_name}) : {pressure}" + ) + if dynamics_label and dynamics_pct is not None: + conclusion += f" ; dynamique récente : {dynamics_label} ({dynamics_pct:+.0f} %)" return _decorate( dict( key="logistique", label="Ormuz et détroits", direction=direction, weight=FACTOR_WEIGHTS["logistique"], - change_pct=round(traffic_move, 2), - effect_change_pct=round(average_effect, 2), + level_label=level_label, + level_pct=level_pct, + dynamics_label=dynamics_label, + dynamics_pct=dynamics_pct, + change_pct=dynamics_pct, + effect_change_pct=(-level_pct if level_pct is not None else None), inverted=True, - observation=f"Trafic de pétroliers : {first_sample['transit']} contre " - f"{first_sample['normal']} habituellement " - f"({first_sample['vs_normal_pct']:+.0f} % vs normale 30 jours)" - + (f" · mesure jugée non exploitable pour : {' ; '.join(unusable[:2])}" if unusable else ""), - observation_change=" · ".join(details[:4]), - observed_at=newest, - source="IMF PortWatch (base du moniteur IEA)", - age_days=None, - fresh=True, + data_confidence=confidence, + corroboration_count=sum(item["corroboration"] for item in samples.values()), + corroborated_chokepoints=corroborated, + daily_available=True, samples=samples, + unusable=unusable, + notes=notes, + observed_at=newest, + source="IMF PortWatch – Daily Chokepoints Data (transits AIS)", + age_days=(datetime.now(timezone.utc).date() - date.fromisoformat(newest)).days + if newest + else None, + fresh=True, + observation=( + f"Perturbation {level_label} : {key_name} à {sample['transit']:.0f} pétroliers/jour" + + ( + f", soit {level_pct:+.0f} % par rapport à la référence pré-crise " + f"({sample['reference_window']})" + if level_pct is not None + else "" + ) + if level_pct is not None + else f"{key_name} à {sample['transit']:.0f} pétroliers/jour, référence pré-crise indisponible" + ), + observation_change=" · ".join(details[:3]), evidence_text=" · ".join(details[:3]), relation=( - "La donnée observée est le trafic de pétroliers ; l’effet sur les prix est son " - "inverse : moins de trafic disponible (détournement, blocage, risque) tend " - "l’approvisionnement et pousse à la hausse, une reprise du trafic détend les prix." + "Deux dimensions distinctes comptent : le niveau par rapport à une normale " + "pré-crise (mesuré avec la même métrique) et la dynamique des derniers jours. " + "Un trafic très bas reste haussier même s’il remonte légèrement : la détente " + "récente ne remet pas en cause la tension. Les comptages sont issus de l’AIS, " + "donc imparfaits (navires à AIS coupé, brouillage, spoofing) : une valeur " + "extrême est recoupée avec l’actualité avant d’en tirer une conclusion." ), - explanation=f"Trafic de pétroliers dans les détroits surveillés : {tension}.", + explanation=conclusion, ) ) diff --git a/tests/test_factor_signs.py b/tests/test_factor_signs.py index 3302c57..326703c 100644 --- a/tests/test_factor_signs.py +++ b/tests/test_factor_signs.py @@ -1,8 +1,10 @@ -"""Sens des facteurs : chaque flèche doit être justifiable, et les écarts chiffrés présents. +"""Sens des facteurs et sémantique des détroits. -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**. +Deux exigences verrouillées ici : +- un facteur distingue la **donnée observée** de son **effet** sur les prix, et les signes + inverses (euro/dollar, trafic de pétroliers) ne doivent jamais être retournés ; +- un trafic effondré est un **signal**, pas une mesure impossible : la référence est pré-crise, + le niveau et la dynamique sont séparés, la confiance dépend de la mesure ET de l'actualité. """ from datetime import date, timedelta @@ -19,87 +21,223 @@ 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, - ), +def seed_reference(median=47.0, chokepoint="Strait of Hormuz", total_median=95.0): + storage.save_chokepoint_reference( + [ + dict( + chokepoint=chokepoint, + window_start="2022-09-12", + window_end="2025-09-12", + observations=1000, + tankers_median=median, + tankers_mean=median + 1, + tankers_p10=median - 20, + tankers_p90=median + 20, + total_median=total_median, + capacity_tanker_median=2_500_000, + source="test", ) + ] + ) + + +def seed_transits(values, chokepoint="Strait of Hormuz", step=1): + """values : du plus ancien au plus récent, un point tous les ``step`` jours.""" + pairs = [((len(values) - 1 - index) * step, value) for index, value in enumerate(values)] + seed_transits_at(pairs, chokepoint) + + +def seed_transits_at(pairs, chokepoint="Strait of Hormuz"): + """pairs : (jours dans le passé, nombre de pétroliers). Permet de simuler un historique ancien.""" + rows = [ + ( + chokepoint, + dict( + day=days_ago(offset), + transit_tankers=value, + transit_total=value * 2, + capacity_tankers=value * 1000, + capacity_total=value * 2000, + ), ) + for offset, value in pairs + ] storage.save_chokepoints(rows, "IMF PortWatch") -def test_ormuz_traffic_drop_pushes_prices_up(store): - seed_hormuz([40, 40, 40, 40, 40, 40, 22]) +def seed_event(zone, direction="hausse", confidence=0.7, days=3): + storage.save_news_event( + dict( + url_hash=f"hash-{zone}", + topic="geo", + event_type="chokepoint", + direction=direction, + magnitude="", + fuels=[], + zone=zone, + horizon_days=10, + confidence=confidence, + valid_from=days_ago(days), + valid_until=days_ago(days - 20), + observed_at=days_ago(days), + published_at=days_ago(days), + source_url=f"https://exemple.local/{zone}", + extracted_by="gemma4:12b", + ) + ) + + +def test_collapse_is_kept_as_a_signal_when_corroborated(store): + """Un trafic de quelques navires par jour n'est pas « impossible » : c'est un signal.""" + seed_reference(median=47.0) + seed_transits([45, 44, 3, 2, 2, 1, 2]) + seed_event("détroit d'Ormuz", "hausse", 0.9) 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"] + assert factor["direction"] == synthesis.UP, "effondrement du trafic = pression haussière" + assert factor["level_label"] == "EXTRÊME" + assert factor["level_pct"] <= -90 + assert factor["corroboration_count"] >= 1 + assert factor["data_confidence"] < 0.7, "mesure AIS imparfaite : confiance réduite" + assert any("corroborée" in note for note in factor["notes"]) + assert "AIS" in factor["relation"] -def test_ormuz_traffic_recovery_pushes_prices_down(store): - seed_hormuz([30, 30, 30, 30, 30, 30, 45]) +def test_collapse_without_news_keeps_signal_with_lower_confidence(store): + seed_reference(median=47.0) + seed_transits([45, 44, 3, 2, 2, 1, 2]) + alone = synthesis.factor_logistique() + assert alone["direction"] == synthesis.UP, "aucune règle absolue ne neutralise le signal" + assert alone["corroboration_count"] == 0 + assert any("non corroboré" in note for note in alone["notes"]) + seed_event("détroit d'Ormuz", "hausse", 0.9) + corroborated = synthesis.factor_logistique() + assert corroborated["data_confidence"] > alone["data_confidence"] + + +def test_level_and_dynamics_are_separate_dimensions(store): + """Niveau de crise + légère amélioration récente : les deux doivent apparaître.""" + seed_reference(median=50.0) + # Niveau pré-crise il y a plusieurs mois, puis effondrement et reprise partielle récente. + seed_transits_at([(600, 50), (500, 49), (4, 2), (3, 2), (2, 3), (1, 6), (0, 10)]) 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"] + assert factor["level_label"] == "EXTRÊME" + assert factor["level_pct"] <= -75 + assert factor["dynamics_pct"] > 50 + assert factor["dynamics_label"] == "nette amélioration" + assert factor["direction"] == synthesis.UP, "la tension reste, la détente récente ne l’annule pas" + assert "EXTRÊME" in factor["explanation"] and "amélioration" in factor["explanation"] + assert "pré-crise" in factor["observation"] -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]) +def test_tiny_moves_are_not_presented_as_dynamics(store): + """0–2 pétroliers/jour : une variation d'un navire n'est pas une tendance.""" + seed_reference(median=54.0) + seed_transits([1, 0, 1, 2, 0, 1, 2]) + factor = synthesis.factor_logistique() + assert factor["level_label"] == "EXTRÊME" + assert factor["dynamics_pct"] is None + assert factor["dynamics_label"] is None + assert any("trop faibles pour" in note for note in factor["notes"]) + assert factor["direction"] == synthesis.UP, "la tension reste le message principal" + + +def test_reference_and_current_use_the_same_metric(store): + """Pétroliers avec pétroliers : la référence « tous navires » ne doit pas servir de norme.""" + seed_reference(median=47.0, total_median=95.0) + seed_transits([45, 45, 2, 2, 2, 2, 2]) + factor = synthesis.factor_logistique() + sample = factor["samples"]["Strait of Hormuz"] + assert sample["reference_median"] == 47.0 + assert sample["level_pct"] == round((2 - 47) / 47 * 100, 1) + assert "pré-crise 47" in factor["observation_change"] + + +def test_missing_pre_crisis_reference_no_conclusion(store): + """Sans référence pré-crise, on ne conclut pas : l'historique local peut être né dans la crise.""" + seed_transits([2, 2, 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 + assert factor["level_label"] is None + assert "référence pré-crise indisponible" in factor["observation"] or any( + "référence pré-crise indisponible" in note for note in factor["notes"] + ) + assert "impossible de dire" in factor["explanation"] -def test_chokepoint_with_usable_volume_still_concludes(store): - seed_hormuz([40, 41, 39, 42, 40, 41, 22]) +def test_recent_recovery_from_a_normal_level_eases_pressure(store): + seed_reference(median=50.0) + seed_transits([100, 100, 120, 130, 130, 130, 140]) factor = synthesis.factor_logistique() + assert factor["level_label"] == "SUPÉRIEURE" + assert factor["direction"] == synthesis.DOWN + + +def test_brut_never_uses_the_monthly_average_as_current_price(store): + seed( + "dgec_brent_usd", + "USD/baril", + [dict(day=days_ago(31), value=95.0), dict(day=days_ago(1), value=91.08)], + ) + factor = synthesis.factor_brut() + assert factor["direction"] == synthesis.UNKNOWN, "pas de direction depuis une moyenne mensuelle" + assert factor["daily_available"] is False + assert "Cours quotidien du brut indisponible" in factor["observation"] + assert factor["historical_context"]["value"] == 91.08 + assert "contexte historique" in factor["observation_change"].lower() + assert "pas un cours du jour" in factor["observation_change"] + + +def test_brut_uses_a_fresh_daily_quote(store): + rows = [dict(day=days_ago(offset), value=88.0 + (5 - offset) * 1.2) for offset in range(5, 0, -1)] + seed("brent_usd_daily", "USD/baril", rows) + seed( + "dgec_brent_usd", + "USD/baril", + [dict(day=days_ago(31), value=95.0), dict(day=days_ago(1), value=91.08)], + ) + factor = synthesis.factor_brut() + assert factor["daily_available"] is True assert factor["direction"] == synthesis.UP - assert factor["change_pct"] < 0 + assert factor["series"] == "brent_usd_daily" + assert "USD/baril" in factor["observation"] + assert factor["historical_context"]["value"] == 91.08, "le mensuel reste exposé comme contexte" + + +def test_stale_daily_quote_is_declared_unavailable(store): + seed( + "brent_usd_daily", + "USD/baril", + [ + dict(day=days_ago(14), value=88.0), + dict(day=days_ago(12), value=89.0), + dict(day=days_ago(10), value=90.0), + ], + ) + factor = synthesis.factor_brut() + assert factor["direction"] == synthesis.UNKNOWN + assert "indisponible" in factor["observation"] + assert "jours" in factor["observation"] 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)] - ) + rows = [dict(day=days_ago(offset), value=80.0 + (5 - offset) * 2) for offset in range(5, 0, -1)] + seed("brent_usd_daily", "USD/baril", rows) seed( "dgec_margin_eur_per_tonne", "EUR/tonne", @@ -114,7 +252,6 @@ def test_brut_raffinage_and_products_keep_same_sign(store): 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"] @@ -122,19 +259,18 @@ def test_brut_raffinage_and_products_keep_same_sign(store): 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) + seed("brent_usd_daily", "USD/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): + seed_reference() + seed_transits([40, 40, 40, 40, 40, 40, 40]) built = synthesis.build("Gazole") assert len(built["factors"]) == 6 for factor in built["factors"]: @@ -144,20 +280,18 @@ def test_every_factor_explains_observation_and_effect(store): 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]) + """Le trafic s'effondre (donnée en baisse) : l'effet est haussier.""" + seed_reference(median=47.0) + seed_transits([45, 45, 2, 2, 2, 2, 2]) seed( - "brent_eur_daily", "EUR/baril", [dict(day=days_ago(9), value=80.0), dict(day=days_ago(1), value=90.0)] + "brent_usd_daily", + "USD/baril", + [dict(day=days_ago(offset), value=80.0 + (5 - offset) * 2) for offset in range(5, 0, -1)], ) 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 + assert logistique["direction"] == "up" and logistique["level_pct"] < 0 diff --git a/tests/test_synthesis.py b/tests/test_synthesis.py index 9352a28..0892e6a 100644 --- a/tests/test_synthesis.py +++ b/tests/test_synthesis.py @@ -28,85 +28,6 @@ def test_factors_report_unknown_without_data(store): 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", @@ -158,8 +79,11 @@ def test_evenements_factor_weighs_confidence_and_expiry(store): def test_pressure_aggregates_weights_and_confidence(store): + # Cotation quotidienne fraîche : le brut n'accepte plus une série mensuelle comme cours du jour. seed( - "brent_eur_daily", "EUR/baril", [dict(day=days_ago(9), value=80.0), dict(day=days_ago(1), value=92.0)] + "brent_eur_daily", + "EUR/baril", + [dict(day=days_ago(off), value=80.0 + (5 - off) * 2.4) for off in range(5, 0, -1)], ) seed( "dgec_margin_eur_per_tonne", @@ -170,7 +94,7 @@ def test_pressure_aggregates_weights_and_confidence(store): 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"] + up = [factor["label"] for factor in built["factors"] if factor["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"] diff --git a/ui.js b/ui.js index 7f98683..3d8af9d 100644 --- a/ui.js +++ b/ui.js @@ -135,6 +135,9 @@ function synthesisBlock(s){

${esc(f.observation||'—')}→${esc(f.effect||'')}

${f.observation_change?`

${esc(f.observation_change)}

`:''}

${esc(f.relation||'')}

+ ${(f.level_label||f.dynamics_label)?`

${f.level_label?`Perturbation : ${esc(f.level_label)}`:''}${f.dynamics_label?`Dynamique : ${esc(f.dynamics_label)}`:''}${f.data_confidence!==undefined&&f.data_confidence!==null?`confiance donnée ${num(f.data_confidence*100,0)} %`:''}${f.level_label?`${f.corroboration_count?`corroborée par ${f.corroboration_count} article(s)`:'non corroborée par l’actualité'}`:''}

`:''} + ${(f.notes||[]).map(n=>`

${esc(n)}

`).join('')} + ${f.historical_context?`

Contexte historique : moyenne mensuelle DGEC à ${num(f.historical_context.value,2)} ${esc(f.historical_context.unit)} (${esc(f.historical_context.day)}) — donnée mensuelle, pas un cours du jour.

`:''} ${f.evidence_text?`

${esc(f.evidence_text)}

`:''}

Donnée du ${esc(String(f.observed_at||'—'))}${f.age_days!==null&&f.age_days!==undefined?` (${f.age_days} j)`:''} · source : ${esc(f.source||'—')}

`).join(''); return `
Pression sur les prix : ${esc(s.pressure)}${conf}
${factors?`
${factors}
`:''}

En clair

${esc(s.plain||'')}

${esc(s.disclaimer||'')}

`; diff --git a/upstream.py b/upstream.py index 892902b..b773810 100644 --- a/upstream.py +++ b/upstream.py @@ -9,6 +9,7 @@ from __future__ import annotations import io import json import re +import statistics import urllib.parse import urllib.request import zipfile @@ -299,6 +300,63 @@ def fetch_chokepoint_window(days=12, today=None): return pairs +def fetch_chokepoint_reference(days_back=365, window_years=3, today=None): + """Référence « normale » des détroits, mesurée **avant** la période récente. + + Le jeu PortWatch remonte à 2019 : on peut donc établir une normale pré-crise (médiane + journalière sur plusieurs années calmes) au lieu de prendre l'historique local comme référence. + Sans cela, un historique commencé pendant une perturbation ferait passer un trafic effondré + pour normal. + + Même métrique pour la référence et pour la valeur du jour : pétroliers avec pétroliers + (``n_tanker``), tous navires avec tous navires (``n_total``), capacité avec capacité + (``capacity_tanker``). + """ + today = today or datetime.now(timezone.utc).date() + end = today - timedelta(days=days_back) + start = end - timedelta(days=int(365.25 * window_years)) + out = {} + for name in WATCHED_CHOKEPOINTS: + query = urllib.parse.urlencode( + { + "where": ( + f"portname = '{name}' AND date >= DATE '{start.isoformat()}' " + f"AND date <= DATE '{end.isoformat()}'" + ), + "outFields": "date,n_tanker,n_total,capacity_tanker", + "returnGeometry": "false", + "orderByFields": "date DESC", + "resultRecordCount": "1000", + "f": "json", + } + ) + payload = fetch_bytes(f"{PORTWATCH_QUERY}?{query}", timeout=45) + try: + features = json.loads(payload)["features"] + except (KeyError, TypeError, ValueError): + continue + rows = [feature.get("attributes") or {} for feature in features] + tankers = sorted(row["n_tanker"] for row in rows if row.get("n_tanker") is not None) + totals = sorted(row["n_total"] for row in rows if row.get("n_total") is not None) + capacities = sorted(row["capacity_tanker"] for row in rows if row.get("capacity_tanker") is not None) + if not tankers: + continue + out[name] = dict( + chokepoint=name, + window_start=start.isoformat(), + window_end=end.isoformat(), + observations=len(rows), + tankers_median=statistics.median(tankers), + tankers_mean=round(statistics.fmean(tankers), 1), + tankers_p10=tankers[int(len(tankers) * 0.1)], + tankers_p90=tankers[int(len(tankers) * 0.9)], + total_median=statistics.median(totals) if totals else None, + capacity_tanker_median=statistics.median(capacities) if capacities else None, + source="IMF PortWatch – Daily Chokepoints Data (transits AIS)", + ) + return out + + def fetch_chokepoints(days=6, today=None): """Détroits surveillés : quelques jours suffisent, la source a du retard.""" today = today or datetime.now(timezone.utc).date()