Cinq modeles sont compares sur des previsions directes par horizon (naive, tendance locale, autoregressif pompe, ridge marche, k-NN borne), sans bibliotheque scientifique et avec une selection faite sur une fin d apprentissage chronologique, jamais sur le test. Les cibles sont exprimees en centimes par litre sur le panel comparable, avec intervalle et probabilites. La serie BZ=F est reconnue comme un future Brent : renommee, jamais utilisee en niveau absolu, avec detection des changements de contrat et conservation de la reference mensuelle DGEC a cote. Une date available_at explicite separe desormais periode decrite, publication reelle et disponibilite, avec des hypotheses conservatrices marquees comme estimees. Le backtest rend les performances par carburant, par horizon et par regime (Covid, 2022, periode calme, crise actuelle), refuse une forte confiance pendant un choc, et teste la strategie sur quatre profils d usage.
131 lines
7.0 KiB
Python
131 lines
7.0 KiB
Python
"""Événements prix (changement uniquement), actualités structurées et opérations commerciales."""
|
||
from datetime import datetime, timedelta, timezone
|
||
|
||
import pytest
|
||
|
||
import collector
|
||
import llm
|
||
import news
|
||
import promotions
|
||
import storage
|
||
|
||
|
||
def flux_row(price=1.9, declared='2026-09-12 08:00:00', station='S1', fuel='Gazole'):
|
||
return {'id': station, 'name': 'RUE TEST', 'city': 'Nantes', 'lat': 48.8, 'lon': 2.3,
|
||
'prices': {fuel: price}, 'updates': {fuel: declared}}
|
||
|
||
|
||
def test_price_events_only_on_change(store):
|
||
now = datetime(2026, 9, 12, 10, 0, tzinfo=timezone.utc)
|
||
assert storage.record_price_events([flux_row()], now) == 1, 'première observation'
|
||
assert storage.record_price_events([flux_row()], now + timedelta(hours=1)) == 0, 'identique'
|
||
assert storage.record_price_events([flux_row(price=1.87)], now + timedelta(hours=2)) == 1
|
||
assert storage.record_price_events([flux_row(price=1.87)], now + timedelta(hours=3)) == 0
|
||
assert storage.record_price_events(
|
||
[flux_row(price=1.87, declared='2026-09-12 12:00:00')], now + timedelta(hours=4)) == 1, \
|
||
'nouvel horodatage déclaré par la station'
|
||
events = storage.price_events(days=30)
|
||
assert len(events) == 3, 'pas de doublon pour un prix identique'
|
||
baisse = [event for event in events if event['price'] == 1.87 and event['previous_price'] == 1.9]
|
||
assert len(baisse) == 1, 'baisse de 3 c€ enregistrée'
|
||
redeclared = [event for event in events if event['declared_at'] == '2026-09-12 12:00:00'][0]
|
||
assert redeclared['price'] == 1.87 and redeclared['previous_price'] == 1.87, \
|
||
'même prix mais nouvel horodatage déclaré'
|
||
assert redeclared['fetched_at'] and redeclared['fetched_at'] != redeclared['declared_at'], \
|
||
'la date de téléchargement ne remplace pas la date d’observation'
|
||
assert redeclared['source'].startswith('prix-carburants.gouv.fr')
|
||
|
||
|
||
def test_local_prices_job_needs_favorites_and_records_events(store):
|
||
assert collector.job_local_prices(load=lambda: [flux_row()])['status'] == 'unchanged'
|
||
store.save_entity('favorites', dict(name='Maison', lat=48.8, lon=2.3, radius_km=5))
|
||
out = collector.job_local_prices(load=lambda: [flux_row()])
|
||
assert out['status'] == 'ok' and out['events'] == 1
|
||
assert out['last_observation_at'] == '2026-09-12 08:00:00'
|
||
assert collector.job_local_prices(load=lambda: [flux_row()])['events'] == 0
|
||
|
||
|
||
def test_rss_articles_keep_publication_date_and_source():
|
||
xml = b"""<?xml version="1.0"?><rss version="2.0"><channel>
|
||
<item><title>Attaque en mer Rouge sur un pétrolier</title>
|
||
<link>https://exemple.fr/a1</link><pubDate>Fri, 11 Sep 2026 09:30:00 GMT</pubDate>
|
||
<source>Agence Test</source><description><p>Un pétrolier visé.</p></description></item>
|
||
</channel></rss>"""
|
||
articles = news.parse_rss(xml, 'Google News', 'suez_babelmandeb')
|
||
assert len(articles) == 1
|
||
article = articles[0]
|
||
assert article['published_at'] == '2026-09-11', 'date de publication conservée'
|
||
assert article['observed_at'] == '2026-09-11'
|
||
assert article['source'] == 'Agence Test'
|
||
assert '<' not in article['title'] and 'pétrolier' in article['title']
|
||
assert len(article['hash']) == 32
|
||
|
||
|
||
def test_news_only_calls_llm_for_new_articles(store, monkeypatch):
|
||
article = dict(hash='h1', url='https://exemple.fr/a1', title='Ormuz bloqué', topic='ormuz',
|
||
source='Test', published_at='2026-09-11', observed_at='2026-09-11', summary='Détroit fermé.')
|
||
monkeypatch.setattr(news, 'gather', lambda *a, **k: ([article], []))
|
||
calls = []
|
||
|
||
def fake_extract(prompt, models=None):
|
||
calls.append(prompt)
|
||
return {'pertinent': True, 'evenements': [
|
||
{'type': 'chokepoint', 'direction': 'hausse', 'magnitude': 'forte',
|
||
'carburants': ['gazole'], 'zone': 'Ormuz', 'horizon_jours': 12,
|
||
'confiance': 0.7, 'debut': '2026-09-11', 'fin': None}]}, 'mistral-small3.2:24b'
|
||
|
||
monkeypatch.setattr(llm, 'extract', fake_extract)
|
||
first = news.collect()
|
||
assert first['analysed'] == 1 and first['events'] == 1
|
||
assert len(calls) == 1
|
||
second = news.collect()
|
||
assert second['analysed'] == 0, 'aucun nouvel article, aucun appel au modèle'
|
||
assert len(calls) == 1
|
||
events = storage.news_events()
|
||
assert events[0]['direction'] == 'hausse'
|
||
assert events[0]['valid_from'] == '2026-09-11' and events[0]['valid_until'] == '2026-09-23'
|
||
assert events[0]['source_url'] == 'https://exemple.fr/a1', 'aucun signal sans source'
|
||
assert events[0]['extracted_by'] == 'mistral-small3.2:24b'
|
||
|
||
|
||
def test_news_rejects_unrelated_article(store, monkeypatch):
|
||
article = dict(hash='h2', url='https://exemple.fr/a2', title='Recette de cuisine', topic='ormuz',
|
||
source='Test', published_at='2026-09-11', observed_at='2026-09-11', summary='Gâteau.')
|
||
monkeypatch.setattr(news, 'gather', lambda *a, **k: ([article], []))
|
||
monkeypatch.setattr(llm, 'extract', lambda prompt, models=None: ({'pertinent': False}, 'm'))
|
||
out = news.collect()
|
||
assert out['events'] == 0 and storage.news_events() == []
|
||
|
||
|
||
def test_promotions_extraction_keeps_only_sourced_and_known_brands(store, monkeypatch):
|
||
article = dict(hash='p1', url='https://exemple.fr/promo', title='Carburant à prix coûtant chez E.Leclerc',
|
||
topic='_general', source='Test', published_at='2026-09-12',
|
||
observed_at='2026-09-12', summary='Ce week-end, E.Leclerc vend le gazole à prix coûtant.')
|
||
monkeypatch.setattr(promotions, 'gather', lambda use_gdelt=True: ([article], []))
|
||
monkeypatch.setattr(llm, 'extract', lambda prompt, models=None: ({'operations': [
|
||
{'enseigne': 'E.Leclerc', 'nature': 'prix_coutant', 'remise_par_litre': None,
|
||
'carburants': ['gazole'], 'zone': 'France', 'debut': '2026-09-13', 'fin': '2026-09-14',
|
||
'confiance': 0.9},
|
||
{'enseigne': 'Enseigne Inventée', 'nature': 'remise_litre', 'debut': '2026-09-13'},
|
||
]}, 'mistral-small3.2:24b'))
|
||
out = promotions.collect()
|
||
assert out['promotions'] == 1, 'enseigne absente du texte rejetée'
|
||
rows = storage.promotions(today=datetime(2026, 9, 13, tzinfo=timezone.utc).date())
|
||
assert rows[0]['brand'] == 'E.Leclerc'
|
||
assert rows[0]['valid_from'] == '2026-09-13' and rows[0]['valid_until'] == '2026-09-14'
|
||
assert rows[0]['confidence'] == pytest.approx(0.9)
|
||
assert rows[0]['source_url'] == 'https://exemple.fr/promo'
|
||
assert rows[0]['observed_at'] == '2026-09-12'
|
||
active = promotions.active(today=datetime(2026, 9, 13, tzinfo=timezone.utc).date())
|
||
assert active[0]['state'] == 'en cours'
|
||
announced = promotions.active(today=datetime(2026, 9, 12, tzinfo=timezone.utc).date())
|
||
assert announced[0]['state'] == 'annoncée'
|
||
|
||
|
||
def test_llm_json_parsing_tolerates_wrapping():
|
||
data, _ = llm.parse_json('```json\n{"pertinent": true, "evenements": []}\n```'), None
|
||
assert data['pertinent'] is True
|
||
assert llm.parse_json('Voici : {"a": 1} voilà') == {'a': 1}
|
||
with pytest.raises(ValueError):
|
||
llm.parse_json('aucun json ici')
|