Le conseiller du backtest raisonne desormais comme le moteur de decision : besoin d abord, anticipation seulement si le gain depasse le seuil du vehicule, et plancher d appoint qui interdit de repasser a la pompe pour quelques litres. La campagne precedente le montrait : sans ce plancher, la strategie multipliait les passages quotidiens et le verdict la refusait a juste titre. Ajout de la validation par regimes : chaque periode atypique est evaluee avec un apprentissage arrete la veille de son debut, plus l experience ou la crise actuelle reste entierement hors entrainement.
298 lines
12 KiB
Python
298 lines
12 KiB
Python
"""Sens des facteurs et sémantique des détroits.
|
||
|
||
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
|
||
|
||
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_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 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["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_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["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_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["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_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["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):
|
||
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"]
|
||
|
||
|
||
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["direction"] == synthesis.UP
|
||
assert "affaibli" in factor["explanation"]
|
||
|
||
|
||
def test_brut_raffinage_and_products_keep_same_sign(store):
|
||
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",
|
||
[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 "€/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_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 "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"]:
|
||
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é"
|
||
|
||
|
||
def test_pressure_uses_effect_not_observed_move(store):
|
||
"""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_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["level_pct"] < 0
|