diff --git a/README.md b/README.md index e16bee1..91cd2b9 100644 --- a/README.md +++ b/README.md @@ -120,6 +120,63 @@ 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. +## Modèle J+0→J+21 : benchmarks simples, unités décisionnelles, régimes séparés + +### Brent futures ≠ Brent spot + +`BZ=F` (Yahoo) est un **future** Brent, enchaînement d'échéances : un changement de contrat (*roll*) +ressemble à un mouvement du pétrole. Trois conséquences appliquées dans le code : + +- la série est nommée `brent_futures_usd` avec sa source réelle, et le **niveau absolu n'est jamais + une feature** : seules les **variations logarithmiques** (1, 7, 14 jours) sont utilisées, ce qui est + insensible au roll par construction ; +- `market.detect_rolls()` signale les jours suspects : un saut d'un jour **partiellement annulé** les + jours suivants (signature d'un roll), signalé comme suspicion documentée, jamais retiré en silence ; +- la référence officielle **DGEC mensuelle** est conservée à côté (`brent_spot_reference`) : les deux + séries se comparent par leur valeur prédictive, l'une ne remplace pas l'autre. + +### `available_at` : ce qui était utilisable, pas ce qui est décrit + +Trois dates distinctes pour chaque donnée : `observed_at` (période décrite), `published_at` +(publication réelle si connue), `available_at` (premier instant où l'information était utilisable). +Quand la publication réelle existe, c'est elle. Sinon un décalage **estimé par source** est appliqué, +explicitement marqué `estimated: true`, avec des hypothèses **conservatrices** (DGEC mensuelle +45 j, +bulletin hebdomadaire +7 j, PortWatch +10 j) : mieux vaut une information disponible trop tard dans le +backtest qu'une fuite de futur. + +### Cibles en centimes par litre + +La variation est calculée sur le **panel comparable** (stations présentes aux deux dates), en deux +unités : un **ratio** (tendance indépendante du niveau de prix) et un **delta en c€/L** +(`delta_cents`, avec quartiles pour la fourchette). C'est le delta en c€/L qui permet de chiffrer +directement un gain sur 10, 20 ou 40 litres. Sortie du modèle par horizon : variation prévue, +intervalle 80 %, probabilité de hausse et de baisse. + +### Cinq modèles comparés, sélection sans fuite + +1. **naïve** — le prix ne bouge pas (la référence à battre) ; +2. **tendance locale** — prolongation de la pente récente ; +3. **autorégressif pompe** — ridge sur 5 décalages de variation quotidienne ; +4. **ridge marché** — ridge sur les décalages des variables de marché (variations) ; +5. **k-NN** — seule candidate non linéaire, à coût borné. + +Chaque horizon a son modèle (une prévision directe) et le choix se fait sur une **fin +d'apprentissage chronologique**, jamais sur la période de test. Aucune bibliothèque scientifique n'est +disponible sur la VM : régression, normalisation (ajustée sur le train seul) et voisinage sont écrits +en Python standard. + +### Validation par régimes et couverture réelle par carburant + +Le backtest est chronologique et rend les performances **séparées** : crise Covid 2020, choc +énergétique 2022, période plus calme 2023-2024, crise actuelle 2026 — plus une expérience où la crise +actuelle reste **entièrement hors entraînement**. Un modèle perdu pendant un choc **ne doit pas +afficher une forte confiance** pendant ce choc : au-delà de 75 % de confiance annoncée pour une +justesse de sens ≤ 55 % pendant un choc, le verdict est refusé. + +La couverture est par carburant, car elle n'est pas la même : Gazole et SP95 depuis 2007, E85 depuis +2007-05, **E10 seulement depuis 2009-05**, **SP98 seulement depuis 2013-06**, GPLc depuis 2007-11. +Chaque modèle n'est entraîné que sur la couverture réelle de son carburant. + ## Reconstruction du marché : journal d'événements, pas médiane des lignes du jour Les archives ne contiennent **que les changements** : une ligne existe le jour où une station diff --git a/asof.py b/asof.py index dca3db9..8cfdcd4 100644 --- a/asof.py +++ b/asof.py @@ -16,17 +16,23 @@ Trois pièges évités ici : from datetime import date, timedelta # Décalages de publication estimés, en jours, quand la source ne fournit pas de date de publication. +# Hypothèses **conservatrices** : en cas de doute, l'information arrive trop tard plutôt que +# trop tôt. Un décalage surestimé coûte un peu de réactivité ; un décalage sous-estimé crée une +# fuite de futur et rend le backtest menteur. PUBLICATION_LAG_DAYS = { - "instantane": 0, # prix locaux : déclarés en temps réel par les stations + "instantane": 0, # prix locaux : déclarés le jour même par les stations "archive": 0, # archives officielles : date déclarée par la station "usd_per_eur": 0, # BCE : publiée le jour même (jours ouvrés, ~16 h) - "brent": 0, # cotation du brut : disponible le jour même - "eia": 0, - "dgec": 31, # DGEC mensuelle : publiée le mois suivant - "fr_htt": 4, # produits raffinés : bulletin hebdomadaire du jeudi - "fr_ttc": 4, - "eu_bulletin": 4, - "portwatch": 7, # trafic des détroits : publication différée + "brent_futures": 0, # cotation disponible le jour même en soirée + "brent_spot": 0, + "brent": 0, + "eia": 7, # publication hebdomadaire américaine, décalée + "dgec_brent": 45, # DGEC mensuelle : contexte du mois précédent, publiée bien plus tard + "dgec": 45, + "fr_htt": 10, # série mensuelle DGEC : publiée le mois suivant + "fr_ttc": 10, + "eu_bulletin": 7, # bulletin hebdomadaire : jeudi pour la semaine écoulée + "portwatch": 10, # trafic des détroits : publication différée de plusieurs jours "news": 0, # un article est disponible à sa date de publication "promotions": 0, } @@ -56,16 +62,51 @@ def source_family(name): return "instantane" -def availability_day(row, family=None): - """Jour à partir duquel une donnée est réellement disponible (publication, pas observation).""" - published = row.get("published_at") or row.get("published") - if published: - return str(published)[:10] +def available_at(row, family=None): + """Premier instant où Fuel Advisor pouvait raisonnablement utiliser l'information. + + Trois dates distinctes : + + - ``observed_at`` : la période **décrite** par la donnée (ce qui s'est passé) ; + - ``published_at`` : la publication **réelle** si la source la fournit ; + - ``available_at`` : ce qui est utilisable pour décider — ``published_at`` quand elle existe, + sinon ``observed_at`` + un décalage **estimé par source**, explicitement signalé comme tel. + """ observed = str(row.get("observed_at") or row.get("day") or "")[:10] if not observed: - return None - lag = PUBLICATION_LAG_DAYS.get(family or source_family(row.get("series") or row.get("source")), 0) - return (date.fromisoformat(observed) + timedelta(days=lag)).isoformat() + return dict( + available_at=None, + observed_at=None, + published_at=None, + basis="inconnue", + estimated=True, + lag_days=None, + ) + published = row.get("published_at") or row.get("published") + if published: + return dict( + available_at=str(published)[:10], + observed_at=observed, + published_at=str(published)[:10], + basis="publication réelle", + estimated=False, + lag_days=(date.fromisoformat(str(published)[:10]) - date.fromisoformat(observed)).days, + ) + family = family or source_family(row.get("series") or row.get("source")) + lag = PUBLICATION_LAG_DAYS.get(family, 0) + return dict( + available_at=(date.fromisoformat(observed) + timedelta(days=lag)).isoformat(), + observed_at=observed, + published_at=None, + basis=f"estimée par source ({family}, +{lag} j)", + estimated=True, + lag_days=lag, + ) + + +def availability_day(row, family=None): + """Jour à partir duquel une donnée est réellement disponible (publication, pas observation).""" + return available_at(row, family)["available_at"] def available_rows(rows, as_of, family=None): diff --git a/backfill.py b/backfill.py index f9b64e8..17bf4af 100644 --- a/backfill.py +++ b/backfill.py @@ -189,7 +189,7 @@ def targets(margin_deg=0.15, fuel=None): return bbox, ids -def backfill(years=None, fuels=DEFAULT_FUELS, progress=None, refresh_current=True): +def backfill(years=None, fuels=DEFAULT_FUELS, progress=None, refresh_current=True, force=False): """Importe les archives annuelles. Idempotent et reprenable année par année.""" progress = progress or (lambda message: None) bbox, ids = targets() @@ -199,7 +199,7 @@ def backfill(years=None, fuels=DEFAULT_FUELS, progress=None, refresh_current=Tru summary = dict(years=[], stations=0, imported=0, skipped=0, failures=[]) for year in years: state = done.get(year) - if state and state["status"] == "ok" and year < current_year: + if state and state["status"] == "ok" and year < current_year and not force: summary["skipped"] += 1 continue if year == current_year and not refresh_current and state: @@ -245,6 +245,11 @@ if __name__ == "__main__": parser.add_argument("--to-year", type=int, default=datetime.now(timezone.utc).year) parser.add_argument("--fuels", default=",".join(DEFAULT_FUELS)) parser.add_argument("--summary", action="store_true", help="état des imports par année") + parser.add_argument( + "--force", + action="store_true", + help="ré-analyser les années déjà importées (nouveau carburant par ex.)", + ) args = parser.parse_args() if args.summary: print( @@ -260,6 +265,7 @@ if __name__ == "__main__": else: result = backfill( years=list(range(args.from_year, args.to_year + 1)), + force=args.force, fuels=tuple(fuel.strip() for fuel in args.fuels.split(",") if fuel.strip()), progress=print, ) diff --git a/backtest.py b/backtest.py new file mode 100644 index 0000000..2b6b342 --- /dev/null +++ b/backtest.py @@ -0,0 +1,332 @@ +"""Backtest J+0→J+21 : modèles simples, régimes séparés, résultats par carburant et par horizon. + +Aucune prévision n'est branchée au conseil réel par ce module : il mesure et rend un verdict. +Le rapport produit répond, pour chaque carburant et chaque horizon, aux questions posées : +période d'apprentissage et de test, nombre de prévisions, MAE naïve et modèle, amélioration, +justesse du sens, calibration, amplitude moyenne prévue et réelle, et résultat économique simulé. +""" +import statistics +from datetime import datetime + +import features +import models +import validation + +# Périodes atypiques : on veut savoir ce que le modèle fait **pendant** les chocs, pas seulement +# en moyenne. Un modèle perdu pendant un choc ne doit pas afficher une forte confiance. +REGIMES = { + 'covid_2020': ('2020-02-01', '2020-09-30', 'crise Covid'), + 'choc_2022': ('2022-02-01', '2022-10-31', 'choc énergétique'), + 'calme_2023': ('2023-06-01', '2024-06-30', 'période plus calme'), + 'crise_2026': ('2026-01-01', '2026-12-31', 'crise actuelle'), +} +HOLDOUT_CURRENT = '2026-01-01' # la crise actuelle reste entièrement hors entraînement +MIN_REGIME_PREDICTIONS = 20 +SHOCK_REGIMES = ('covid_2020', 'choc_2022', 'crise_2026') +SHOCK_CONFIDENCE_LIMIT = 0.75 +SHOCK_ACCURACY_FLOOR = 0.55 +FUEL_HORIZONS = models.HORIZONS + + +def metrics_in_cents(metrics): + """Les métriques de ``validation`` sont en euros : on les rend en centimes par litre.""" + out = dict(metrics) + for key in ('mae', 'rmse', 'bias', 'amplitude_mae'): + if out.get(key) is not None: + out[f'{key}_cents'] = round(out[key] * 100, 4) + if out.get('naive'): + out['naive'] = metrics_in_cents(out['naive']) + if out.get('skill_vs_naive') is not None: + out['improvement_pct'] = round(out['skill_vs_naive'] * 100, 2) + return out + + +def _predictions(fitted, samples, horizon, trained_until): + """Prédictions au format attendu par le banc de validation (prix en euros, variation en c€).""" + rows = [] + for sample in samples: + actual = sample['targets'].get(horizon) + if actual is None or fitted is None: + continue + forecast = models.predict(fitted, sample) + rows.append(dict( + day=sample['day'], horizon=horizon, trained_until=trained_until, + last_known_price=sample['price'], + predicted_price=round(sample['price'] + forecast['mu_cents'] / 100, 5), + actual_price=round(sample['price'] + actual / 100, 5), + predicted_change=forecast['mu_cents'], actual_change=actual, + confidence=forecast['confidence'], model=fitted['name'], + interval=forecast['interval'], p_up=forecast['p_up'], sigma_cents=forecast['sigma_cents'])) + return rows + + +def amplitude(rows): + """Amplitude moyenne prévue et réelle, en centimes par litre.""" + if not rows: + return dict(predicted_cents=None, actual_cents=None) + return dict( + predicted_cents=round(statistics.fmean(abs(row['predicted_change']) for row in rows), 3), + actual_cents=round(statistics.fmean(abs(row['actual_change']) for row in rows), 3)) + + +def regime_report(predictions): + """Performance séparée par régime, avec la confiance annoncée pendant les chocs.""" + out = {} + for key, (start, end, label) in REGIMES.items(): + scoped = [row for row in predictions if start <= row['day'] <= end] + if not scoped: + out[key] = dict(label=label, period=f'{start} → {end}', count=0) + continue + metrics = metrics_in_cents(validation.evaluate(scoped, horizon=scoped[0]['horizon'], + naive_mae=None)) + confidences = [row['confidence'] for row in scoped if row.get('confidence') is not None] + out[key] = dict(label=label, period=f'{start} → {end}', count=metrics['count'], + mae_cents=metrics['mae_cents'], improvement_pct=metrics.get('improvement_pct'), + direction=(metrics['direction'] or {}).get('accuracy'), + calibration=(metrics['calibration'] or {}).get('calibration_quality'), + mean_confidence=round(statistics.fmean(confidences), 3) if confidences else None, + amplitude=amplitude(scoped)) + return out + + +def shock_verdict(regimes): + """Un modèle perdu pendant un choc ne doit pas afficher une forte confiance pendant ce choc.""" + problems = [] + for key in SHOCK_REGIMES: + entry = regimes.get(key) or {} + if (entry.get('count') or 0) < MIN_REGIME_PREDICTIONS: + continue + confidence = entry.get('mean_confidence') + accuracy = entry.get('direction') + if confidence is None or accuracy is None: + continue + if confidence >= SHOCK_CONFIDENCE_LIMIT and accuracy <= SHOCK_ACCURACY_FLOOR: + problems.append(f"{entry['label']} : confiance {confidence:.0%} pour une justesse de " + f"sens {accuracy:.0%} sur {entry['count']} prévisions") + return dict(passed=not problems, problems=problems) + + +def economics(predictions, levels, vehicle, horizon, min_change_cents=1.0, min_confidence=0.6): + """Résultat économique simulé : stratégie naïve contre stratégie guidée par les prévisions.""" + forecast_by_day = {} + for row in predictions: + if row['horizon'] != horizon: + continue + if abs(row['predicted_change']) < min_change_cents or row['confidence'] < min_confidence: + continue + forecast_by_day[row['day']] = dict( + direction='up' if row['predicted_change'] > 0 else 'down', + change_cents=row['predicted_change'], confidence=row['confidence']) + price_series = [dict(day=point['day'], price=point['median']) for point in levels + if point['median']] + if predictions: + start, end = min(row['day'] for row in predictions), max(row['day'] for row in predictions) + price_series = [point for point in price_series if start <= point['day'] <= end] + if len(price_series) < 30: + return dict(reason='période trop courte pour une simulation économique') + comparison = validation.compare_strategies(price_series, vehicle, forecasts=forecast_by_day) + comparison['forecast_days'] = len(forecast_by_day) + comparison['period'] = (price_series[0]['day'], price_series[-1]['day']) + return comparison + + +def run_variant(fuel, variant_key, lat, lon, radius, train_ratio=0.7, days=4000, + holdout_start=None, horizons=FUEL_HORIZONS, vehicle=None, verbose=False): + """Un couple (carburant, variante) : entraînement, test chronologique, régimes, verdict.""" + variant = {item['key']: item for item in features.VARIANTS}[variant_key] + market = variant_key != 'local_long' + built = models.build_samples(lat, lon, radius, fuel, horizons=horizons, days=days, + market=market) + samples = built.get('samples') or [] + result = dict(fuel=fuel, variant=variant_key, label=variant['label'], + coverage=models.fuel_coverage(fuel), samples=len(samples), + reason=built.get('reason'), reconstruction=built.get('reconstructed', {}).get( + 'basis')) + if not samples: + result['reason'] = result['reason'] or 'aucun échantillon exploitable' + return result + ordered = sorted(samples, key=lambda item: item['day']) + if holdout_start: + train = [row for row in ordered if row['day'] < holdout_start] + test = [row for row in ordered if row['day'] >= holdout_start] + else: + train, test = validation.split_chronologically(ordered, ratio=train_ratio) + if len(train) < models.MIN_TRAIN_SAMPLES or len(test) < 30: + result['reason'] = (f"{len(train)} échantillons d’apprentissage, {len(test)} de test : " + 'trop peu pour conclure') + return result + trained_until = max(row['day'] for row in train) + validation.assert_no_leakage([dict(day=row['day'], trained_until=trained_until) + for row in test]) + result['train'] = (min(row['day'] for row in train), trained_until) + result['test'] = (min(row['day'] for row in test), max(row['day'] for row in test)) + result['train_samples'] = len(train) + result['test_samples'] = len(test) + per_horizon, selections, all_predictions = {}, {}, [] + for horizon in horizons: + fitted, selection = models.select_model(train, horizon) + selections[str(horizon)] = dict(selection, fitted_model=(fitted or {}).get('name')) + rows = _predictions(fitted, test, horizon, trained_until) + all_predictions.extend(rows) + metrics = metrics_in_cents(validation.evaluate(all_predictions, horizon=horizon)) + metrics['amplitude'] = amplitude(rows) + metrics['model'] = (fitted or {}).get('name') + metrics['interval_coverage'] = _interval_coverage(rows) + metrics['probability_up_calibration'] = _probability_calibration(rows) + per_horizon[str(horizon)] = metrics + result['horizons'] = per_horizon + result['selection'] = selections + result['regimes'] = regime_report(all_predictions) + result['shock'] = shock_verdict(result['regimes']) + horizon_for_economics = str(validation.DEFAULT_HORIZON) + chosen = per_horizon.get(horizon_for_economics) or {} + if vehicle: + result['economics'] = economics(all_predictions, built['levels'], vehicle, + validation.DEFAULT_HORIZON) + result['profiles'] = {} + for key, profile in validation.VEHICLE_PROFILES.items(): + simulation = economics(all_predictions, built['levels'], profile, + validation.DEFAULT_HORIZON) + if simulation.get('advisor'): + result['profiles'][key] = dict( + label=profile.get('label', key), fuel=profile.get('fuel'), + naive_cost=simulation['naive']['cost_eur'], + advisor_cost=simulation['advisor']['cost_eur'], + naive_refuels=simulation['naive']['refuels'], + advisor_refuels=simulation['advisor']['refuels'], + net_saving_eur=simulation['value']['net_saving_eur'], + comfortable=simulation['comfort']['comfortable']) + main = per_horizon.get(horizon_for_economics) or {} + if vehicle and result.get('economics') and 'advisor' in result['economics']: + result['verdict'] = validation.verdict({horizon_for_economics: _verdict_view(main)}, + result['economics']) + if not result['shock']['passed']: + result['verdict']['passed'] = False + result['verdict']['failures'].extend(result['shock']['problems']) + else: + result['verdict'] = dict(passed=False, + failures=['simulation économique indisponible'], + reasons=[], criteria=validation.CRITERIA) + result['main_horizon'] = horizon_for_economics + result['main_model'] = chosen.get('model') + return result + + +def _verdict_view(metrics): + """Vue attendue par ``validation.verdict`` (clés du banc d'essai).""" + return dict(count=metrics.get('count'), + direction=dict(accuracy=(metrics.get('direction') or {}).get('accuracy')), + calibration=dict(calibration_quality=(metrics.get('calibration') or {}).get( + 'calibration_quality')), + skill_vs_naive=metrics.get('skill_vs_naive')) + + +def _interval_coverage(rows): + """Part des variations réelles effectivement couvertes par la fourchette annoncée (80 % visés).""" + scoped = [row for row in rows if row.get('interval')] + if not scoped: + return None + inside = sum(1 for row in scoped if row['interval'][0] <= row['actual_change'] <= row['interval'][1]) + return round(inside / len(scoped), 4) + + +def _probability_calibration(rows): + """Probabilité de hausse annoncée contre fréquence réelle de hausse (écart moyen).""" + scoped = [row for row in rows if row.get('p_up') is not None] + if len(scoped) < 30: + return None + ups = sum(1 for row in scoped if row['actual_change'] > 0) + return dict(forecast_mean=round(statistics.fmean(row['p_up'] for row in scoped), 4), + observed=round(ups / len(scoped), 4), count=len(scoped)) + + +def run_all(fuels=('Gazole', 'E10'), variants=('local_long', 'market', 'enriched'), lat=44.7737872, + lon=-0.5595029, radius=15, profiles=None, verbose=True): + """Lance les variantes sur les carburants couverts, puis rend un rapport lisible.""" + profiles = profiles or validation.VEHICLE_PROFILES + vehicle = profiles['gros_rouleur_diesel'] if 'gros_rouleur_diesel' in profiles else None + results, report = [], [] + for fuel in fuels: + coverage = models.fuel_coverage(fuel) + report.append(f"\n## {fuel} — couverture réelle : {coverage['first']} → {coverage['last']} " + f"({coverage['points']} points, {coverage['stations']} stations, " + f"{coverage['archived']} importés d’archives)") + for variant in variants: + entry = run_variant(fuel, variant, lat, lon, radius, vehicle=vehicle) + results.append(entry) + report.append(render_variant(entry)) + if verbose: + print(f" {fuel} · {variant} : " + f"{'ok' if entry.get('verdict', {}).get('passed') else 'refusé'} " + f"(modèle {entry.get('main_model')}, " + f"{entry.get('horizons', {}).get(str(validation.DEFAULT_HORIZON), {}).get('count', 0)} " + 'prévisions)', flush=True) + return dict(results=results, report='\n'.join(report), + generated_at=datetime.now().isoformat(timespec='seconds')) + + +def render_variant(entry): + """Rendu lisible d'un couple (carburant, variante), horizon par horizon.""" + if entry.get('reason'): + return f"\n### {entry['label']}\n- non exploitable : {entry['reason']}" + lines = [f"\n### {entry['label']}", + f"- apprentissage : {entry['train'][0]} → {entry['train'][1]} " + f"({entry['train_samples']} échantillons)", + f"- test : {entry['test'][0]} → {entry['test'][1]} ({entry['test_samples']} échantillons)", + f"- modèle retenu à J+{validation.DEFAULT_HORIZON} : {entry.get('main_model')}", + '', + '- par horizon : horizon · modèle · n · MAE naïve → modèle (c€/L) · amélioration · ' + 'sens · calibration · amplitude prévue/réelle · couverture de fourchette'] + for horizon, metrics in sorted(entry.get('horizons', {}).items(), key=lambda item: int(item[0])): + naive = (metrics.get('naive') or {}).get('mae_cents') + lines.append( + f" - J+{horizon} · {metrics.get('model')} · n={metrics.get('count')} · " + f"{_fmt(naive)} → {_fmt(metrics.get('mae_cents'))} · " + f"{_pct(metrics.get('improvement_pct'))} · " + f"sens {_pct((metrics.get('direction') or {}).get('accuracy'), scale=100)} · " + f"calib {_fmt((metrics.get('calibration') or {}).get('calibration_quality'), 2)} · " + f"amplitude {_fmt((metrics.get('amplitude') or {}).get('predicted_cents'))}/" + f"{_fmt((metrics.get('amplitude') or {}).get('actual_cents'))} · " + f"fourchette {_pct(metrics.get('interval_coverage'), scale=100)}") + lines.append('- régimes :') + for _key, regime in (entry.get('regimes') or {}).items(): + if not regime.get('count'): + lines.append(f" - {regime['label']} ({regime['period']}) : aucune prévision") + continue + lines.append(f" - {regime['label']} ({regime['period']}) : n={regime['count']} · " + f"MAE {_fmt(regime.get('mae_cents'))} c€/L · " + f"amélioration {_pct(regime.get('improvement_pct'))} · " + f"sens {_pct(regime.get('direction'), scale=100)} · " + f"confiance annoncée {_pct(regime.get('mean_confidence'), scale=100)}") + economics = entry.get('economics') or {} + if economics.get('advisor'): + naive, advisor = economics['naive'], economics['advisor'] + lines.append(f"- économie simulée ({economics.get('period', ('', ''))[0]} → " + f"{economics.get('period', ('', ''))[1]}) : coût {advisor['cost_eur']} € contre " + f"{naive['cost_eur']} € · passages {advisor['refuels']} contre {naive['refuels']} " + f"· gain net {economics['value']['net_saving_eur']} € · confort " + f"{'ok' if economics['comfort']['comfortable'] else 'refusé'}") + if entry.get('profiles'): + lines.append('- profils d’usage (même carburant, même période) :') + for profile in entry['profiles'].values(): + lines.append(f" - {profile['label']} : coût {profile['advisor_cost']} € contre " + f"{profile['naive_cost']} € · passages {profile['advisor_refuels']} contre " + f"{profile['naive_refuels']} · gain net {profile['net_saving_eur']} € · " + f"confort {'ok' if profile['comfortable'] else 'refusé'}") + verdict = entry.get('verdict') or {} + lines.append(f"- verdict : {'PASSÉ' if verdict.get('passed') else 'REFUSÉ'}") + for failure in verdict.get('failures') or []: + lines.append(f" - motif : {failure}") + for reason in verdict.get('reasons') or []: + lines.append(f" - {reason}") + return '\n'.join(lines) + + +def _fmt(value, digits=3): + return '—' if value is None else f'{value:.{digits}f}' + + +def _pct(value, scale=1): + if value is None: + return '—' + return f'{value * scale:+.1f} %' if scale == 1 else f'{value * scale:.0f} %' diff --git a/collector.py b/collector.py index f46468b..a9d2167 100644 --- a/collector.py +++ b/collector.py @@ -489,7 +489,10 @@ def job_brent_history(force=False): if not series: raise RuntimeError("aucune cotation récupérée") stored = storage.save_upstream( - "brent_usd_daily", series, "USD/baril", "Yahoo Finance (BZ=F, historique quotidien)" + "brent_futures_usd", + series, + "USD/baril", + "Brent futures BZ=F (Yahoo Finance) – contrat à échéance enchaîné, à n’utiliser qu’en variations", ) return dict( status="ok", diff --git a/features.py b/features.py index 79694bf..5b6d044 100644 --- a/features.py +++ b/features.py @@ -25,19 +25,29 @@ FEATURES = ( ), dict( key="local_matched_change", - label="Évolution à panel comparable", + label="Évolution à panel comparable (c€/L)", family="archive", cadence="quotidien", expected_from="2007-01-01", note="stations présentes aux deux dates : insensible aux ouvertures et fermetures", ), dict( - key="brent_eur", - label="Brent en euros (quotidien)", - family="brent", + key="brent_futures", + label="Brent futures (BZ=F) – variations uniquement", + family="brent_futures", cadence="quotidien", + expected_from="2016-01-01", + note="contrat à échéance enchaîné : le niveau absolu est proscrit (rolls), seules les " + "variations logarithmiques sont utilisées", + ), + dict( + key="brent_spot_reference", + label="Brent spot mensuel (DGEC) – contexte", + family="dgec_brent", + cadence="mensuel", expected_from="2015-01-01", - note="cotation quotidienne ; repli mensuel DGEC en contexte", + note="référence officielle mensuelle, conservée à côté des futures pour comparer leur " + "valeur prédictive au lieu de remplacer l’une par l’autre", ), dict( key="usd_per_eur", @@ -56,12 +66,20 @@ FEATURES = ( note="publiée le mois suivant", ), dict( - key="refined_products", - label="Produits raffinés hors taxes (hebdomadaire)", - family="fr_htt", + key="eu_refined_products", + label="Produits raffinés France hors taxes (bulletin UE)", + family="eu_bulletin", cadence="hebdomadaire", - expected_from="2015-01-01", - note="bulletin hebdomadaire du jeudi", + expected_from="2005-01-01", + note="bulletin hebdomadaire de la Commission : la plus longue série de marché disponible", + ), + dict( + key="dgec_retail_htt", + label="Prix de détail hors taxes par carburant (DGEC, mensuel)", + family="fr_htt", + cadence="mensuel", + expected_from="2020-01-01", + note="publiée le mois suivant", ), dict( key="portwatch_traffic", @@ -69,7 +87,7 @@ FEATURES = ( family="portwatch", cadence="quotidien", expected_from="2019-01-01", - note="publication différée de plusieurs jours ; historique disponible depuis 2019", + note="transits AIS ; publication différée de plusieurs jours", ), dict( key="news_events", @@ -102,12 +120,14 @@ VARIANTS = ( features=( "local_price_level", "local_matched_change", - "brent_eur", + "brent_futures", + "brent_spot_reference", "usd_per_eur", "dgec_margin", - "refined_products", + "eu_refined_products", + "dgec_retail_htt", ), - rationale="variables de marché : période limitée par la plus jeune d’entre elles", + rationale="variables de marché en variations, période limitée par la plus jeune d’entre elles", ), dict( key="enriched", @@ -115,10 +135,12 @@ VARIANTS = ( features=( "local_price_level", "local_matched_change", - "brent_eur", + "brent_futures", + "brent_spot_reference", "usd_per_eur", "dgec_margin", - "refined_products", + "eu_refined_products", + "dgec_retail_htt", "portwatch_traffic", ), rationale="ajoute le trafic des détroits (disponible depuis 2019)", @@ -266,10 +288,12 @@ def availability_matrix(fuel="Gazole"): def _series_prefix(key): return { - "brent_eur": "brent", + "brent_futures": "brent_futures", + "brent_spot_reference": "dgec_brent", "usd_per_eur": "usd_per_eur", - "dgec_margin": "dgec", - "refined_products": "fr_htt", + "dgec_margin": "dgec_margin", + "eu_refined_products": "eu_fr_", + "dgec_retail_htt": "fr_htt", }.get(key, key) diff --git a/market.py b/market.py index 458d1d6..a0c4251 100644 --- a/market.py +++ b/market.py @@ -249,6 +249,51 @@ def fetch(providers=None, force=False): return out +def detect_rolls(series, threshold_sigma=4.0, revert_window=2, revert_ratio=0.5): + """Jours suspects de changement de contrat (roll) sur une série continue de futures. + + Yahoo ne publie pas le contrat sous-jacent : BZ=F enchaîne les échéances. Un roll apparaît comme + un saut d'un jour qui **ne se prolonge pas** (le prix revient partiellement ensuite), là où un + vrai mouvement de marché se poursuit. Renvoie une suspicion documentée, pas un verdict : ces + jours ne sont jamais retirés en silence. + """ + import math + + values = [row for row in series if row.get("value")] + if len(values) < 30: + return dict(count=0, days=[], basis="série trop courte") + returns = [ + math.log(newer["value"] / older["value"]) if older["value"] > 0 else 0.0 + for older, newer in zip(values, values[1:], strict=False) + ] + absolute = sorted(abs(value) for value in returns) + sigma = 1.4826 * absolute[len(absolute) // 2] or 1e-9 + flagged = [] + for index, value in enumerate(returns): + if abs(value) <= threshold_sigma * sigma: + continue + following = returns[index + 1 : index + 1 + revert_window] + if not following: + continue + reversal = -sum(following) + if value and reversal / abs(value) >= revert_ratio: + flagged.append( + dict( + day=values[index + 1]["day"], + move_pct=round(value * 100, 3), + reversal_pct=round(reversal * 100, 3), + ) + ) + return dict( + count=len(flagged), + days=flagged, + threshold_sigma=threshold_sigma, + robust_sigma=round(sigma, 5), + observations=len(values), + basis="saut d’un jour partiellement annulé les jours suivants : signature d’un roll", + ) + + def fetch_brent_history(years=10, timeout=90): """Brent quotidien sur plusieurs années (API publique, sans clé). diff --git a/models.py b/models.py new file mode 100644 index 0000000..53035d1 --- /dev/null +++ b/models.py @@ -0,0 +1,468 @@ +"""Modèles de prévision J+0→J+21 : benchmarks simples d'abord, mesurés hors échantillon. + +Aucune bibliothèque scientifique n'est disponible sur la VM (Python standard + SQLite) : la +régression, la normalisation et le voisinage sont donc écrits à la main. C'est suffisant, ces +modèles sont volontairement petits. + +Règles de conception : + +- **le niveau absolu du Brent futures n'est jamais une feature** : la série BZ=F est un contrat à + échéance enchaîné, et un changement de contrat (roll) ressemble à un mouvement du pétrole. On + n'utilise que des **variations** (rendements logarithmiques), insensibles au roll par construction. +- **deux séries de brut sont conservées** (futures BZ=F et référence mensuelle DGEC) : leur valeur + prédictive se compare, elle ne se remplace pas aveuglément. +- **features as-of** : chaque valeur est prise à la première date où elle était réellement + disponible (`asof.available_at`), jamais à la date qu'elle décrit. +- **une prédiction par horizon** : la relation à J+3 n'est pas celle à J+14, chaque horizon a son + propre modèle et ses propres cibles en **centimes par litre**. +- **sélection sans fuite** : le modèle et ses hyper-paramètres sont choisis sur une fin + d'apprentissage, jamais sur la période de test. + +Sortie destinée au moteur véhicule : ``mu_cents`` (variation prévue), ``interval`` (fourchette +80 %), ``p_up`` / ``p_down`` (probabilités) et ``confidence``. +""" +import math +import statistics +from datetime import date, timedelta + +import asof +import series as series_module +import storage + +HORIZONS = (1, 3, 7, 14, 21) +MIN_TRAIN_SAMPLES = 120 +FEATURE_NAMES = ( + 'local_delta_1', 'local_delta_3', 'local_delta_7', 'local_delta_14', 'local_slope_7', + 'local_vol_14', 'local_percentile_90', 'local_matched_7', 'brent_fut_ret_1', + 'brent_fut_ret_7', 'brent_fut_ret_14', 'usd_ret_7', 'dgec_brent_change', 'dgec_margin_change', + 'eu_diesel_htt_ret_14', 'eu_diesel_htt_ret_28', 'portwatch_change_14', +) +MARKET_FEATURES = ('brent_fut_ret_1', 'brent_fut_ret_7', 'brent_fut_ret_14', 'usd_ret_7', + 'dgec_brent_change', 'dgec_margin_change', 'eu_diesel_htt_ret_14', + 'eu_diesel_htt_ret_28') +LOGISTIC_SCALE = 1.7 # approximation logistique de la fonction de répartition normale + + +# --------------------------------------------------------------------------- données + +def _series_points(names): + """Séries amont avec leur date de disponibilité réelle (``available_at``).""" + out = {} + with storage.connect() as db: + for name in names: + rows = db.execute('SELECT day, value, observed_at, published_at FROM upstream_series ' + 'WHERE series=? ORDER BY day', (name,)).fetchall() + points = [] + for row in rows: + info = asof.available_at(dict(row, series=name)) + if info['available_at']: + points.append(dict(available_from=info['available_at'], day=row['day'], + value=row['value'], estimated=info['estimated'], + basis=info['basis'])) + points.sort(key=lambda item: item['available_from']) + out[name] = points + return out + + +def _asof_value(points, day, max_age_days=60): + """Dernière valeur disponible à ``day``, ou None si elle est trop ancienne.""" + usable = [point for point in points if point['available_from'] <= day] + if not usable: + return None + newest = usable[-1] + if (date.fromisoformat(day) - date.fromisoformat(newest['available_from'])).days > max_age_days: + return None + return newest + + +def _log_return(points, day, window, max_age_days=60): + """Rendement logarithmique en % sur ``window`` jours, à partir des seules valeurs disponibles.""" + newest = _asof_value(points, day, max_age_days) + if not newest or not newest['value']: + return None + target = (date.fromisoformat(newest['available_from']) - timedelta(days=window)).isoformat() + older = _asof_value(points, target, max_age_days) + if not older or not older['value'] or older['value'] <= 0 or newest['value'] <= 0: + return None + return round(math.log(newest['value'] / older['value']) * 100, 4) + + +def detect_rolls(points, threshold=4.0, revert_window=2, revert_ratio=0.5): + """Jours suspects de **changement de contrat** sur une série continue de futures. + + Yahoo ne publie pas le contrat sous-jacent : BZ=F est un enchaînement d'échéances. Un roll + apparaît comme un saut d'un jour qui **ne se prolonge pas** (le prix revient partiellement les + jours suivants), là où un vrai mouvement de marché se poursuit. On signale ces jours au lieu de + les retirer : c'est une suspicion, pas une certitude. + """ + values = [point for point in points if point.get('value')] + if len(values) < 30: + return dict(count=0, days=[], threshold_sigma=threshold, basis='série trop courte') + returns = [] + for older, newer in zip(values, values[1:], strict=False): + returns.append(math.log(newer['value'] / older['value']) if older['value'] > 0 else 0.0) + absolute = sorted(abs(value) for value in returns) + median = absolute[len(absolute) // 2] + sigma = 1.4826 * median or 1e-9 + flagged = [] + for index, value in enumerate(returns): + if abs(value) <= threshold * sigma: + continue + following = returns[index + 1:index + 1 + revert_window] + if not following: + continue + reversal = -sum(following) + if value and reversal / abs(value) >= revert_ratio: + flagged.append(dict(day=values[index + 1]['day'], move_pct=round(value * 100, 3), + reversal_pct=round(reversal * 100, 3))) + return dict(count=len(flagged), days=flagged, threshold_sigma=threshold, + robust_sigma=round(sigma, 5), + basis='saut d’un jour partiellement annulé : signature d’un roll de contrat') + + +def fuel_coverage(fuel): + """Couverture réelle d'un carburant : premier jour exploitable, volume, stations.""" + with storage.connect() as db: + row = db.execute('SELECT min(day) AS first, max(day) AS last, count(*) AS points, ' + 'count(DISTINCT station_id) AS stations FROM observations WHERE fuel=?', + (fuel,)).fetchone() + archived = db.execute("SELECT count(*) FROM observations WHERE fuel=? AND origin LIKE " + "'archive:%'", (fuel,)).fetchone()[0] + return dict(fuel=fuel, first=row['first'], last=row['last'], points=row['points'], + stations=row['stations'], archived=archived) + + +def build_samples(lat, lon, radius, fuel, horizons=HORIZONS, days=4000, market=True, now=None): + """Échantillons jour par jour : features as-of en entrée, variations en c€/L en cible.""" + reconstructed = series_module.active_series(lat, lon, radius, fuel, days=days, now=now) + levels = series_module.median_series(reconstructed) + if len(levels) < MIN_TRAIN_SAMPLES: + return dict(samples=[], reason=f"seulement {len(levels)} jours de marché reconstruits") + targets = {} + for horizon in horizons: + for item in series_module.matched_variation(reconstructed, horizon=horizon): + if item['comparable']: + targets.setdefault(horizon, {})[item['day']] = item + upstream = _series_points(('brent_futures_usd', 'brent_spot_usd', 'dgec_brent_usd', + 'usd_per_eur', 'dgec_margin_usd_per_bbl', 'eu_fr_diesel_htt', + 'portwatch')) if market else {} + chokepoints = _chokepoint_points() if market else [] + samples = [] + for index, point in enumerate(levels): + if index < 20: + continue + day, level = point['day'], point['median'] + window = [item for item in levels[max(0, index - 30):index + 1] if item['median']] + deltas = [round((later['median'] - older['median']) * 100, 3) + for older, later in zip(window, window[1:], strict=False)] + if len(deltas) < 14: + continue + features = dict( + local_delta_1=deltas[-1], + local_delta_3=round(sum(deltas[-3:]), 3), + local_delta_7=round(sum(deltas[-7:]), 3), + local_delta_14=round(sum(deltas[-14:]), 3), + local_slope_7=round(statistics.median(deltas[-7:]), 3), + local_vol_14=round(statistics.median(abs(value) for value in deltas[-14:]), 3), + local_percentile_90=_asof_percentile(levels, index, + [item['median'] for item in levels[max(0, index - 90):index + 1]]), + # Déjà calculée une seule fois avant la boucle : la recalculer ici serait un O(n²). + local_matched_7=(targets.get(7, {}).get(day) or {}).get('delta_cents'), + days_since_change=point['declared_today'], + ) + if market: + futures = upstream.get('brent_futures_usd') or [] + spot = upstream.get('brent_spot_usd') or [] + brent_series = futures or spot + features.update( + brent_fut_ret_1=_log_return(brent_series, day, 1), + brent_fut_ret_7=_log_return(brent_series, day, 7), + brent_fut_ret_14=_log_return(brent_series, day, 14), + usd_ret_7=_log_return(upstream.get('usd_per_eur') or [], day, 7), + dgec_brent_change=_log_return(upstream.get('dgec_brent_usd') or [], day, 30), + dgec_margin_change=_log_return(upstream.get('dgec_margin_usd_per_bbl') or [], day, 30), + eu_diesel_htt_ret_14=_log_return(upstream.get('eu_fr_diesel_htt') or [], day, 14), + eu_diesel_htt_ret_28=_log_return(upstream.get('eu_fr_diesel_htt') or [], day, 28), + portwatch_change_14=_chokepoint_change(chokepoints, day), + ) + row = dict(day=day, price=level, features=features, + targets={horizon: (targets.get(horizon, {}).get(day) or {}).get('delta_cents') + for horizon in horizons}, + target_meta={horizon: targets.get(horizon, {}).get(day) for horizon in horizons}, + declared_today=point['declared_today'], active_stations=point['stations']) + samples.append(row) + usable = [row for row in samples if any(value is not None for value in row['targets'].values())] + return dict(samples=usable, levels=levels, reconstructed=reconstructed, + basis='features as-of, cibles en centimes par litre sur panel comparable') + + +def _asof_percentile(levels, index, window_values): + """Percentile du niveau courant parmi les seuls jours antérieurs (aucune fuite).""" + sample = sorted(value for value in window_values if value) + if not sample: + return None + rank = sum(1 for value in sample if value <= levels[index]['median']) + return round(rank / len(sample) * 100, 2) + + +def _chokepoint_points(): + with storage.connect() as db: + rows = db.execute('SELECT day, sum(transit_tankers) AS tankers FROM chokepoint_daily ' + 'GROUP BY day ORDER BY day').fetchall() + return [dict(day=row['day'], value=row['tankers'], + available_from=(date.fromisoformat(row['day']) + + timedelta(days=asof.PUBLICATION_LAG_DAYS['portwatch'])).isoformat()) + for row in rows if row['tankers']] + + +def _chokepoint_change(points, day): + newest = _asof_value(points, day, max_age_days=21) + if not newest or not newest['value']: + return None + target = (date.fromisoformat(newest['available_from']) - timedelta(days=14)).isoformat() + older = _asof_value(points, target, max_age_days=21) + if not older or not older['value']: + return None + return round((newest['value'] - older['value']) / older['value'] * 100, 4) + + +# --------------------------------------------------------------------------- algèbre + +def _standardise(rows, names): + columns = {name: [row[name] for row in rows] for name in names} + stats = {} + for name, values in columns.items(): + clean = [value for value in values if value is not None] + mean = statistics.fmean(clean) if clean else 0.0 + sigma = statistics.pstdev(clean) if len(clean) > 1 else 1.0 + stats[name] = (mean, sigma or 1.0) + return stats + + +def _design(rows, names, stats, fill=0.0): + matrix = [] + for row in rows: + line = [1.0] + for name in names: + value = row.get(name) + mean, sigma = stats[name] + line.append(fill if value is None else (value - mean) / sigma) + matrix.append(line) + return matrix + + +def _solve(matrix, vector): + """Résolution d'un système linéaire (Gauss, pivot partiel) — dimension minuscule.""" + size = len(matrix) + augmented = [row[:] + [vector[index]] for index, row in enumerate(matrix)] + for column in range(size): + pivot = max(range(column, size), key=lambda row: abs(augmented[row][column])) + if abs(augmented[pivot][column]) < 1e-12: + continue + augmented[column], augmented[pivot] = augmented[pivot], augmented[column] + for row in range(column + 1, size): + factor = augmented[row][column] / augmented[column][column] + if factor: + for item in range(column, size + 1): + augmented[row][item] -= factor * augmented[column][item] + solution = [0.0] * size + for row in range(size - 1, -1, -1): + if abs(augmented[row][row]) < 1e-12: + continue + total = augmented[row][size] - sum(augmented[row][column] * solution[column] + for column in range(row + 1, size)) + solution[row] = total / augmented[row][row] + return solution + + +def _ridge(rows, names, targets, lam=1.0): + stats = _standardise(rows, names) + design = _design(rows, names, stats) + width = len(names) + 1 + gram = [[0.0] * width for _ in range(width)] + moment = [0.0] * width + for line, target in zip(design, targets, strict=False): + for first in range(width): + moment[first] += line[first] * target + for second in range(first, width): + gram[first][second] += line[first] * line[second] + for first in range(width): + for second in range(first): + gram[first][second] = gram[second][first] + for index in range(1, width): # l'intercepte n'est pas pénalisé + gram[index][index] += lam + coefficients = _solve(gram, moment) + return dict(names=names, stats=stats, coefficients=coefficients) + + +def _ridge_predict(model, row): + line = [1.0] + [0.0 if row.get(name) is None + else (row[name] - model['stats'][name][0]) / model['stats'][name][1] + for name in model['names']] + return sum(coefficient * value for coefficient, value in zip(model['coefficients'], line, + strict=False)) + + +# --------------------------------------------------------------------------- modèles + +def _fit_pairs(samples, horizon): + return [(row, row['targets'][horizon]) for row in samples + if row['targets'].get(horizon) is not None] + + +def model_naive_unchanged(train, horizon): + """« Le prix ne bouge pas » : la référence à battre.""" + pairs = _fit_pairs(train, horizon) + values = [target for _row, target in pairs] + sigma = statistics.pstdev(values) if len(values) > 1 else 0.0 + return dict(name='naive_unchanged', sigma_cents=round(sigma, 3), mean_cents=0.0, + predict=lambda row: 0.0) + + +def model_local_trend(train, horizon): + """Prolongation de la tendance locale récente (momentum simple).""" + pairs = _fit_pairs(train, horizon) + values = [target for _row, target in pairs] + sigma = statistics.pstdev(values) if len(values) > 1 else 0.0 + + def predict(row): + slope = row['features'].get('local_slope_7') + if slope is None: + return 0.0 + return round(slope * horizon, 3) + + residuals = [abs(predict(row) - target) for row, target in pairs] + return dict(name='local_trend', sigma_cents=round(sigma, 3), + residual_mae=round(statistics.fmean(residuals), 3) if residuals else None, + mean_cents=statistics.fmean([predict(row) for row, _t in pairs]) if pairs else 0.0, + predict=predict) + + +def model_autoregressive(train, horizon): + """Autorégressif sur le seul historique pompe (5 décalages de variation quotidienne).""" + names = ('local_delta_1', 'local_delta_3', 'local_delta_7', 'local_delta_14', 'local_slope_7') + return _linear_model('ar_pump', train, horizon, names, default_lambda=0.5) + + +def model_ridge_market(train, horizon, names=None): + """Ridge sur les décalages des variables de marché et du marché local.""" + names = names or [name for name in FEATURE_NAMES if name in MARKET_FEATURES] + \ + ['local_delta_7', 'local_delta_14', 'local_slope_7', 'local_vol_14', 'local_percentile_90'] + return _linear_model('ridge_market', train, horizon, tuple(names), default_lambda=1.0) + + +def _linear_model(name, train, horizon, names, default_lambda=1.0): + pairs = _fit_pairs(train, horizon) + if len(pairs) < 30: + return None + rows = [{key: row['features'].get(key) for key in names} for row, _target in pairs] + targets = [target for _row, target in pairs] + model = _ridge(rows, list(names), targets, default_lambda) + fitted = [_ridge_predict(model, row) for row in rows] + sigma = statistics.pstdev([predicted - actual + for predicted, actual in zip(fitted, targets, strict=False)]) + return dict(name=name, sigma_cents=round(sigma, 3), names=tuple(names), + default_lambda=default_lambda, ridge=model, + predict=lambda row: round(_ridge_predict( + model, {key: (row.get('features') or row).get(key) for key in names}), 3)) + + +def model_knn(train, horizon, neighbours=20, subset=300): + """Voisinage : seule candidate non linéaire, coût explicitement borné. + + Le sous-échantillon et la dispersion (écart-type des cibles) évitent une boucle in-sample qui + dominerait le temps de calcul sans rien apporter à la décision. + """ + pairs = _fit_pairs(train, horizon) + if len(pairs) < 60: + return None + names = ('local_delta_7', 'local_delta_14', 'local_slope_7', 'local_vol_14', + 'local_matched_7', 'brent_fut_ret_7', 'eu_diesel_htt_ret_14') + rows = [{key: row['features'].get(key) for key in names} for row, _target in pairs] + targets = [target for _row, target in pairs] + stats = _standardise(rows, list(names)) + step = max(1, len(rows) // subset) + kept_rows, kept_targets = rows[::step], targets[::step] + + def predict(row): + flat = row.get('features') or row + vector = [0.0 if flat.get(name) is None + else (flat[name] - stats[name][0]) / stats[name][1] for name in names] + distances = [] + for index, candidate in enumerate(kept_rows): + total = 0.0 + for position, name in enumerate(names): + value = candidate.get(name) + delta = vector[position] - (0.0 if value is None + else (value - stats[name][0]) / stats[name][1]) + total += delta * delta + distances.append((total, kept_targets[index])) + distances.sort(key=lambda item: item[0]) + chosen = [target for _distance, target in distances[:neighbours]] + return round(statistics.median(chosen), 3) + + sigma = statistics.pstdev(targets) if len(targets) > 1 else 0.0 + return dict(name='knn', sigma_cents=round(sigma, 3), names=names, neighbours=neighbours, + subset=len(kept_rows), predict=predict) + + +CANDIDATES = (model_naive_unchanged, model_local_trend, model_autoregressive, + model_ridge_market, model_knn) + + +def probability_up(mu_cents, sigma_cents): + """Probabilité de hausse à partir de la variation prévue et de la dispersion observée.""" + if not sigma_cents: + return 0.5 if not mu_cents else (1.0 if mu_cents > 0 else 0.0) + exponent = max(-30.0, min(30.0, LOGISTIC_SCALE * mu_cents / sigma_cents)) + return round(1 / (1 + math.exp(-exponent)), 4) + + +def predict(fitted, row): + """Sortie destinée au moteur véhicule : variation, fourchette, probabilités, confiance.""" + mu = fitted['predict'](row) if fitted['name'] != 'naive_unchanged' else 0.0 + sigma = fitted.get('sigma_cents') or 0.0 + up = probability_up(mu, sigma) + return dict(mu_cents=round(mu, 3), sigma_cents=round(sigma, 3), + interval=(round(mu - 1.28 * sigma, 3), round(mu + 1.28 * sigma, 3)), + p_up=up, p_down=round(1 - up, 4), confidence=round(max(up, 1 - up), 4), + direction=('up' if mu > 0 else 'down' if mu < 0 else 'flat'), + model=fitted['name']) + + +def select_model(train, horizon, candidates=CANDIDATES, validation_share=0.2, verbose=False): + """Choix du modèle **sur une fin d'apprentissage**, jamais sur la période de test.""" + ordered = sorted(_fit_pairs(train, horizon), key=lambda item: item[0]['day']) + if len(ordered) < 60: + return None, dict(reason=f'{len(ordered)} échantillons : trop peu pour sélectionner') + cut = max(30, int(len(ordered) * (1 - validation_share))) + inner_train = [row for row, _target in ordered[:cut]] + inner_valid = [row for row, _target in ordered[cut:]] + if len(inner_valid) < 10: + inner_valid = [row for row, _target in ordered[-10:]] + inner_train = [row for row, _target in ordered[:-10]] + scores = {} + for candidate in candidates: + fitted = candidate(inner_train, horizon) + if not fitted: + continue + errors = [] + for row in inner_valid: + target = row['targets'].get(horizon) + if target is None: + continue + predicted = 0.0 if fitted['name'] == 'naive_unchanged' else fitted['predict'](row) + errors.append(abs(predicted - target)) + if not errors: + continue + scores[fitted['name']] = round(statistics.fmean(errors), 4) + if not scores: + return None, dict(reason='aucun candidat évaluable') + winner = min(scores, key=scores.get) + for candidate in candidates: + fitted = candidate(train, horizon) + if fitted and fitted['name'] == winner: + return fitted, dict(candidate_scores=scores, winner=winner, + validation_samples=len(inner_valid), + validation='fin d’apprentissage (chronologique)') + return None, dict(reason='candidat retenu non réentraînable', candidate_scores=scores) diff --git a/run_backtest.py b/run_backtest.py new file mode 100644 index 0000000..3861cfc --- /dev/null +++ b/run_backtest.py @@ -0,0 +1,115 @@ +"""Campagne complète J+0→J+21 : couverture par carburant, trois variantes, régimes, profils. + +Sortie : rapport Markdown + résultats JSON, plus l'expérience où la crise actuelle reste +entièrement hors entraînement. +""" +import json +import os +import sys +import time + +sys.path.insert(0, '/opt/fuel-advisor') +os.environ.setdefault('FUEL_ADVISOR_DATA_DIR', '/var/lib/fuel-advisor') + +import backtest # noqa: E402 +import features # noqa: E402 +import market # noqa: E402 +import models # noqa: E402 +import storage # noqa: E402 +import validation # noqa: E402 + +LAT, LON, RADIUS = 44.7737872, -0.5595029, 15 +FUELS = ('Gazole', 'SP95', 'SP98', 'E10', 'E85', 'GPLc') +VARIANTS = ('local_long', 'market', 'enriched') +OUT = '/tmp/backtest-report.md' +JSON_OUT = '/tmp/backtest-results.json' + + +def header(): + lines = ['# Backtest J+0→J+21 — Fuel Advisor', + '', + f"*Généré le {time.strftime('%Y-%m-%d %H:%M')} · " + f"favori Villenave-d'Ornon ({LAT}, {LON}), rayon {RADIUS} km*", + '', + '## Couverture réelle par carburant (aucune hypothèse de 2007 à 2026)', + ''] + for fuel in FUELS: + coverage = models.fuel_coverage(fuel) + period = (f"{coverage['first']} → {coverage['last']}" if coverage['first'] else '—') + lines.append(f"- **{fuel}** : {period} · {coverage['points']} points · " + f"{coverage['stations']} stations · {coverage['archived']} lignes d’archives") + lines.append('') + lines.append('## Variables disponibles et variantes réellement entraînables') + lines.append('') + for variant in features.variant_periods(features.availability_matrix('Gazole')): + lines.append(f"- **{variant['key']}** : {variant['start']} → {variant['end']} · " + f"entraînable : {'oui' if variant['trainable'] else 'non'} · " + f"bloquants : {variant['blockers'] or '—'}") + lines.append('') + lines.append('## Contrôle du Brent futures (BZ=F)') + lines.append('') + with storage.connect() as db: + rows = [dict(row) for row in db.execute( + 'SELECT day, value FROM upstream_series WHERE series=? ORDER BY day', + ('brent_futures_usd',))] + rolls = market.detect_rolls(rows) + lines.append(f"- {rolls.get('observations')} cotations quotidiennes ; " + f"**{rolls['count']} jours suspects de changement de contrat** " + f"(seuil {rolls.get('threshold_sigma')} σ robuste, σ = {rolls.get('robust_sigma')})") + lines.append(f"- méthode : {rolls['basis']}") + if rolls['days']: + lines.append('- jours signalés : ' + ', '.join( + f"{item['day']} ({item['move_pct']:+.1f} % → annulation {item['reversal_pct']:+.1f} %)" + for item in rolls['days'][:8])) + lines.append('- conséquence : **aucun niveau absolu** de la série n’est utilisé comme variable ' + '(seules les variations logarithmiques le sont), et les deux séries de brut ' + '(futures et référence mensuelle DGEC) sont conservées côte à côte.') + lines.append('') + return lines + + +def main(): + lines = header() + results = [] + for fuel in FUELS: + lines.append(f"\n---\n\n# {fuel}\n") + coverage = models.fuel_coverage(fuel) + if coverage['points'] < 1000: + lines.append(f"- couverture insuffisante ({coverage['points']} points) : " + 'aucun entraînement, pour ne pas extrapoler un historique qui n’existe pas') + continue + for variant in VARIANTS: + started = time.time() + entry = backtest.run_variant( + fuel, variant, LAT, LON, RADIUS, days=4200, + vehicle=validation.VEHICLE_PROFILES.get( + 'gros_rouleur_diesel' if fuel in ('Gazole', 'E85', 'GPLc') + else 'petit_rouleur_essence')) + results.append(entry) + lines.append(backtest.render_variant(entry)) + print(f"[{time.strftime('%H:%M:%S')}] {fuel} · {variant} : " + f"{'PASSÉ' if (entry.get('verdict') or {}).get('passed') else 'refusé'} " + f"({round(time.time() - started, 1)} s)", flush=True) + lines.append('') + lines.append('\n---\n\n# Expérience : crise actuelle entièrement hors entraînement') + lines.append('') + lines.append('Apprentissage arrêté au 2025-12-31, évaluation sur 2026 : le modèle n’a jamais vu ' + 'la période actuelle.') + lines.append('') + for fuel in ('Gazole', 'E10'): + entry = backtest.run_variant(fuel, 'enriched', LAT, LON, RADIUS, days=4200, + holdout_start=backtest.HOLDOUT_CURRENT, + vehicle=validation.VEHICLE_PROFILES['gros_rouleur_diesel']) + entry['label'] = f"Enrichi, hors échantillon 2026 — {fuel}" + entry['variant'] = 'enriched_holdout_2026' + results.append(entry) + lines.append(backtest.render_variant(entry)) + with open(OUT, 'w', encoding='utf-8') as handle: + handle.write('\n'.join(lines)) + with open(JSON_OUT, 'w', encoding='utf-8') as handle: + json.dump(results, handle, ensure_ascii=False, default=str, indent=1) + print('rapport écrit :', OUT, '|', JSON_OUT, flush=True) + + +if __name__ == '__main__': + main() diff --git a/series.py b/series.py index d9f884e..0f91aa4 100644 --- a/series.py +++ b/series.py @@ -158,6 +158,10 @@ def matched_variation(series, horizon=7, min_pairs=3): day=point["day"], horizon=horizon, change_pct=None, + delta_cents=None, + delta_cents_p25=None, + delta_cents_p75=None, + delta_cents_spread=None, matched_stations=len(shared), comparable=False, basis="panel comparable insuffisant", @@ -165,12 +169,20 @@ def matched_variation(series, horizon=7, min_pairs=3): ) continue ratios = sorted(after[station] / before[station] - 1 for station in shared) + deltas = sorted((after[station] - before[station]) * 100 for station in shared) middle = ratios[len(ratios) // 2] out.append( dict( day=point["day"], horizon=horizon, change_pct=round(middle * 100, 3), + # Unité décisionnelle : la variation en centimes par litre, sur les mêmes + # stations. Le ratio sert à lire une tendance indépendamment du niveau de + # prix ; le delta en c€/L sert à chiffrer directement un gain sur N litres. + delta_cents=round(deltas[len(deltas) // 2], 3), + delta_cents_p25=round(deltas[len(deltas) // 4], 3), + delta_cents_p75=round(deltas[(len(deltas) * 3) // 4], 3), + delta_cents_spread=round(deltas[(len(deltas) * 3) // 4] - deltas[len(deltas) // 4], 3), matched_stations=len(shared), available_stations=min(point["stations"], later["stations"]), comparable=True, diff --git a/tests/conftest.py b/tests/conftest.py index 1ccec50..0309be8 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -20,16 +20,14 @@ def isolated_environment(tmp_path, monkeypatch): monkeypatch.setattr(module, "DB_PATH", tmp_path / f"{module.__name__}.sqlite3") monkeypatch.setattr(brands, "fetch_candidates", lambda *args, **kwargs: []) monkeypatch.setattr(market, "PROVIDERS", {}) - monkeypatch.setattr(routing, "PROVIDERS", {"osrm": lambda *a, **k: {}, "google": lambda *a, **k: {}}) + monkeypatch.setattr(routing, "PROVIDERS", {"osrm": lambda *a, **k: {}, + "google": lambda *a, **k: {}}) monkeypatch.delenv("FUEL_ROUTING_PROVIDERS", raising=False) monkeypatch.delenv("FUEL_GOOGLE_MAPS_API_KEY", raising=False) monkeypatch.setattr(news, "gather", lambda *args, **kwargs: ([], [])) monkeypatch.setattr(promotions, "gather", lambda *args, **kwargs: ([], [])) - monkeypatch.setattr( - llm, - "extract", - lambda *args, **kwargs: (_ for _ in ()).throw(RuntimeError("Ollama non appelé pendant les tests")), - ) + monkeypatch.setattr(llm, "extract", lambda *args, **kwargs: (_ for _ in ()).throw( + RuntimeError("Ollama non appelé pendant les tests"))) monkeypatch.setattr(llm, "available", lambda *args, **kwargs: []) collector = importlib.import_module("collector") monkeypatch.setattr(collector, "UPSTREAM_SOURCES", {}) diff --git a/tests/test_asof.py b/tests/test_asof.py index 4e8fba4..7efe209 100644 --- a/tests/test_asof.py +++ b/tests/test_asof.py @@ -1,5 +1,4 @@ """Discipline as-of : aucune information future, publications différées respectées.""" - from datetime import date, timedelta import pytest @@ -9,173 +8,122 @@ import features def test_publication_lag_depends_on_the_source(): - assert ( - asof.availability_day(dict(observed_at="2026-09-06", series="chokepoint_daily"), "portwatch") - == "2026-09-13" - ) - assert ( - asof.availability_day(dict(observed_at="2026-08-01", series="dgec_brent_usd"), "dgec") == "2026-09-01" - ) - assert ( - asof.availability_day(dict(observed_at="2026-09-11", series="usd_per_eur"), "usd_per_eur") - == "2026-09-11" - ) - assert asof.availability_day(dict(day="2026-09-12", origin="live"), "instantane") == "2026-09-12" + assert asof.availability_day(dict(observed_at='2026-09-06', series='chokepoint_daily'), + 'portwatch') == '2026-09-16' + assert asof.availability_day(dict(observed_at='2026-08-01', series='dgec_brent_usd'), + 'dgec_brent') == '2026-09-15' + assert asof.availability_day(dict(observed_at='2026-09-11', series='usd_per_eur'), + 'usd_per_eur') == '2026-09-11' + assert asof.availability_day(dict(day='2026-09-12', origin='live'), 'instantane') == '2026-09-12' def test_explicit_publication_date_wins_over_the_lag(): - row = dict(observed_at="2026-09-06", published_at="2026-09-11", series="chokepoint_daily") - assert asof.availability_day(row) == "2026-09-11" + row = dict(observed_at='2026-09-06', published_at='2026-09-11', series='chokepoint_daily') + assert asof.availability_day(row) == '2026-09-11' def test_a_delayed_publication_is_not_visible_before_its_date(): """PortWatch décrit le 6 septembre mais n'est publié que le 11 : invisible le 8.""" - rows = [dict(day="2026-09-06", observed_at="2026-09-06", value=42)] - assert asof.available_rows(rows, "2026-09-08", family="portwatch") == [] - assert len(asof.available_rows(rows, "2026-09-13", family="portwatch")) == 1 - assert asof.latest_available(rows, "2026-09-08", family="portwatch") is None - frame = asof.asof_frame(rows, "2026-09-08", family="portwatch") - assert frame["last"] is None and frame["stale_days"] is None + rows = [dict(day='2026-09-06', observed_at='2026-09-06', value=42)] + assert asof.available_rows(rows, '2026-09-10', family='portwatch') == [] + assert len(asof.available_rows(rows, '2026-09-16', family='portwatch')) == 1 + assert asof.latest_available(rows, '2026-09-08', family='portwatch') is None + frame = asof.asof_frame(rows, '2026-09-08', family='portwatch') + assert frame['last'] is None and frame['stale_days'] is None def test_stale_features_are_absent_rather_than_eternal(): - rows = [dict(day="2026-01-01", observed_at="2026-01-01", value=1.5)] - assert asof.latest_available(rows, "2026-03-15", family="brent") is None - assert asof.latest_available(rows, "2026-01-20", family="brent")["stale_days"] == 19 + rows = [dict(day='2026-01-01', observed_at='2026-01-01', value=1.5)] + assert asof.latest_available(rows, '2026-03-15', family='brent') is None + assert asof.latest_available(rows, '2026-01-20', family='brent')['stale_days'] == 19 def test_asof_percentile_ignores_the_future(): - points = [dict(day=f"2026-01-{day:02d}", value=2.00) for day in range(1, 11)] - points += [dict(day="2026-02-01", value=1.00), dict(day="2026-02-02", value=1.00)] - early = asof.asof_percentile(points, "2026-01-05", value=2.00) - assert early["count"] == 5, "rien après le 5 janvier" - assert early["percentile"] == 1.0 - late = asof.asof_percentile(points, "2026-02-02", value=1.00) - assert late["count"] == 12 - assert late["percentile"] < 0.5 + points = [dict(day=f'2026-01-{day:02d}', value=2.00) for day in range(1, 11)] + points += [dict(day='2026-02-01', value=1.00), dict(day='2026-02-02', value=1.00)] + early = asof.asof_percentile(points, '2026-01-05', value=2.00) + assert early['count'] == 5, 'rien après le 5 janvier' + assert early['percentile'] == 1.0 + late = asof.asof_percentile(points, '2026-02-02', value=1.00) + assert late['count'] == 12 + assert late['percentile'] < 0.5 def test_moving_average_only_looks_backwards(): - points = [dict(day=f"2026-01-{day:02d}", value=float(day)) for day in range(1, 11)] - assert asof.moving_average(points, "2026-01-03", window=10) == 2.0 - assert asof.moving_average(points, "2026-01-10", window=3) == 9.0 - assert asof.moving_average(points, "2025-12-31", window=3) is None + points = [dict(day=f'2026-01-{day:02d}', value=float(day)) for day in range(1, 11)] + assert asof.moving_average(points, '2026-01-03', window=10) == 2.0 + assert asof.moving_average(points, '2026-01-10', window=3) == 9.0 + assert asof.moving_average(points, '2025-12-31', window=3) is None def test_scaler_is_fitted_on_train_only(): - train = [dict(day=f"2026-01-{day:02d}", value=float(day)) for day in range(1, 11)] - scaler = asof.fit_scaler( - [point["value"] for point in train], fitted_until=max(point["day"] for point in train) - ) - assert scaler["fitted_until"] == "2026-01-10" - asof.assert_scaler_uses_only_train(scaler, [point["day"] for point in train], ["2026-02-01"]) + train = [dict(day=f'2026-01-{day:02d}', value=float(day)) for day in range(1, 11)] + scaler = asof.fit_scaler([point['value'] for point in train], + fitted_until=max(point['day'] for point in train)) + assert scaler['fitted_until'] == '2026-01-10' + asof.assert_scaler_uses_only_train(scaler, [point['day'] for point in train], ['2026-02-01']) with pytest.raises(ValueError) as error: - asof.assert_scaler_uses_only_train( - dict(scaler, fitted_until="2026-03-01"), [point["day"] for point in train], ["2026-02-01"] - ) - assert "fuite de données" in str(error.value) + asof.assert_scaler_uses_only_train(dict(scaler, fitted_until='2026-03-01'), + [point['day'] for point in train], ['2026-02-01']) + assert 'fuite de données' in str(error.value) def test_feature_matrix_reports_real_periods_not_wishful_ones(store): - store.save_upstream( - "dgec_brent_usd", - [dict(day="2015-06-01", value=60.0), dict(day="2015-07-01", value=62.0)], - "USD/baril", - "DGEC", - ) - store.save_chokepoints( - [ - ( - "Strait of Hormuz", - dict( - day="2019-03-01", - transit_tankers=40, - transit_total=90, - capacity_tankers=1, - capacity_total=2, - ), - ), - ( - "Strait of Hormuz", - dict( - day="2019-03-02", - transit_tankers=41, - transit_total=91, - capacity_tankers=1, - capacity_total=2, - ), - ), - ], - "IMF PortWatch", - ) - matrix = {item["key"]: item for item in features.availability_matrix("Gazole")} - assert matrix["dgec_margin"]["first"] == "2015-06-01" - assert matrix["dgec_margin"]["points"] == 2 - assert matrix["portwatch_traffic"]["first"] == "2019-03-01" - assert matrix["brent_eur"]["status"] == "absent", "aucune cotation quotidienne en base" - assert matrix["news_events"]["status"] == "absent" + store.save_upstream('dgec_brent_usd', [dict(day='2015-06-01', value=60.0), + dict(day='2015-07-01', value=62.0)], + 'USD/baril', 'DGEC') + store.save_chokepoints([('Strait of Hormuz', dict(day='2019-03-01', transit_tankers=40, + transit_total=90, capacity_tankers=1, + capacity_total=2)), + ('Strait of Hormuz', dict(day='2019-03-02', transit_tankers=41, + transit_total=91, capacity_tankers=1, + capacity_total=2))], + 'IMF PortWatch') + matrix = {item['key']: item for item in features.availability_matrix('Gazole')} + assert matrix['brent_spot_reference']['first'] == '2015-06-01' + assert matrix['brent_spot_reference']['points'] == 2 + assert matrix['portwatch_traffic']['first'] == '2019-03-01' + assert matrix['brent_futures']['status'] == 'absent', 'aucune cotation quotidienne en base' + assert matrix['news_events']['status'] == 'absent' def test_portwatch_history_is_never_projected_back_to_2007(store): store.save_chokepoints( - [ - ( - "Strait of Hormuz", - dict( - day=(date(2019, 1, 1) + timedelta(days=offset)).isoformat(), - transit_tankers=40, - transit_total=90, - capacity_tankers=1, - capacity_total=2, - ), - ) - for offset in range(60) - ], - "IMF PortWatch", - ) - matrix = {item["key"]: item for item in features.availability_matrix("Gazole")} - assert matrix["portwatch_traffic"]["first"] == "2019-01-01" - assert matrix["portwatch_traffic"]["expected_from"] == "2019-01-01" - periods = {item["key"]: item for item in features.variant_periods(list(matrix.values()))} - enriched = periods["enriched"] - assert "portwatch_traffic" in enriched["members"], "le trafic est exploitable sur cette période" - assert enriched["start"] is not None and enriched["start"] >= "2019-01-01" - assert "news_events" not in enriched["features"], ( - "les événements, disponibles depuis 2026 seulement, ne sont jamais recopiés sur 2019" - ) - assert enriched["trainable"] is False, "le niveau local manque dans cette base de test" - assert "local_price_level" in enriched["blockers"] + [('Strait of Hormuz', dict(day=(date(2019, 1, 1) + timedelta(days=offset)).isoformat(), + transit_tankers=40, transit_total=90, capacity_tankers=1, + capacity_total=2)) for offset in range(60)], 'IMF PortWatch') + matrix = {item['key']: item for item in features.availability_matrix('Gazole')} + assert matrix['portwatch_traffic']['first'] == '2019-01-01' + assert matrix['portwatch_traffic']['expected_from'] == '2019-01-01' + periods = {item['key']: item for item in features.variant_periods( + list(matrix.values()))} + enriched = periods['enriched'] + assert 'portwatch_traffic' in enriched['members'], 'le trafic est exploitable sur cette période' + assert 'brent_futures' not in enriched['members'], 'le Brent futures manque dans cette base' + assert enriched['start'] is not None and enriched['start'] >= '2019-01-01' + assert 'news_events' not in enriched['features'], \ + 'les événements, disponibles depuis 2026 seulement, ne sont jamais recopiés sur 2019' + assert enriched['trainable'] is False, 'le niveau local manque dans cette base de test' + assert 'local_price_level' in enriched['blockers'] def test_variant_start_is_the_youngest_member(store): - store.save_upstream( - "dgec_brent_usd", - [ - dict(day=(date(2015, 6, 1) + timedelta(days=offset)).isoformat(), value=60.0) - for offset in range(120) - ], - "USD/baril", - "DGEC", - ) - store.save_upstream( - "usd_per_eur", - [ - dict(day=(date(2018, 5, 1) + timedelta(days=offset)).isoformat(), value=1.18) - for offset in range(120) - ], - "USD/EUR", - "BCE", - ) - matrix = {item["key"]: item for item in features.availability_matrix("Gazole")} - periods = {item["key"]: item for item in features.variant_periods(list(matrix.values()))} - start = periods["market"]["start"] - assert start == "2018-05-01", "la variante commence quand toutes ses variables existent" + store.save_upstream('dgec_brent_usd', + [dict(day=(date(2015, 6, 1) + timedelta(days=offset)).isoformat(), + value=60.0) for offset in range(120)], 'USD/baril', 'DGEC') + store.save_upstream('usd_per_eur', + [dict(day=(date(2018, 5, 1) + timedelta(days=offset)).isoformat(), + value=1.18) for offset in range(120)], 'USD/EUR', 'BCE') + matrix = {item['key']: item for item in features.availability_matrix('Gazole')} + periods = {item['key']: item for item in features.variant_periods(list(matrix.values()))} + start = periods['market']['start'] + assert start == '2018-05-01', 'la variante commence quand toutes ses variables existent' def test_report_states_periods_and_statuses(store): - store.save_upstream( - "usd_per_eur", [dict(day=f"2026-08-{day:02d}", value=1.17) for day in range(1, 31)], "USD/EUR", "BCE" - ) - text = features.report(features.availability_matrix("Gazole")) - assert "Taux BCE USD/EUR" in text and "disponible" in text - assert "aucune donnée en base" in text or "absent" in text + store.save_upstream('usd_per_eur', + [dict(day=f'2026-08-{day:02d}', value=1.17) for day in range(1, 31)], + 'USD/EUR', 'BCE') + text = features.report(features.availability_matrix('Gazole')) + assert 'Taux BCE USD/EUR' in text and 'disponible' in text + assert 'aucune donnée en base' in text or 'absent' in text diff --git a/tests/test_backfill.py b/tests/test_backfill.py index f81b355..5144c05 100644 --- a/tests/test_backfill.py +++ b/tests/test_backfill.py @@ -1,5 +1,4 @@ """Archives officielles : formats, sélection, dates réelles, et aucune continuité inventée.""" - import io import zipfile @@ -27,105 +26,102 @@ XML = """ """ -BBOX = (44.5, 45.0, -0.9, -0.2) # Gironde +BBOX = (44.5, 45.0, -0.9, -0.2) # Gironde def archive_bytes(xml=XML): buffer = io.BytesIO() - with zipfile.ZipFile(buffer, "w") as archive: - archive.writestr("PrixCarburants_annuel_2007.xml", xml.encode("iso-8859-1")) + with zipfile.ZipFile(buffer, 'w') as archive: + archive.writestr('PrixCarburants_annuel_2007.xml', xml.encode('iso-8859-1')) return buffer.getvalue() def test_price_formats_both_eras_are_accepted(): - assert backfill.parse_price("999") == 0.999, "millièmes d’euro (premières années)" - assert backfill.parse_price("1.707") == 1.707, "euros décimaux (années récentes)" - assert backfill.parse_price("1,707") == 1.707 - assert backfill.parse_price("") is None + assert backfill.parse_price('999') == 0.999, 'millièmes d’euro (premières années)' + assert backfill.parse_price('1.707') == 1.707, 'euros décimaux (années récentes)' + assert backfill.parse_price('1,707') == 1.707 + assert backfill.parse_price('') is None assert backfill.parse_price(None) is None - assert backfill.parse_price("0") is None, "valeur nulle : pas un prix" - assert backfill.parse_price("99") is None, "0,099 €/L : implausible" - assert backfill.parse_price("20000") is None, "20 €/L : implausible" + assert backfill.parse_price('0') is None, 'valeur nulle : pas un prix' + assert backfill.parse_price('99') is None, '0,099 €/L : implausible' + assert backfill.parse_price('20000') is None, '20 €/L : implausible' def test_declared_dates_both_formats(): - assert backfill.parse_declared("2007-01-04 18:43:38.841521") == "2007-01-04T18:43:38" - assert backfill.parse_declared("2025-01-02T00:37:00") == "2025-01-02T00:37:00" - assert backfill.parse_declared("0000-00-00 00:00:00") is None - assert backfill.parse_declared("") is None + assert backfill.parse_declared('2007-01-04 18:43:38.841521') == '2007-01-04T18:43:38' + assert backfill.parse_declared('2025-01-02T00:37:00') == '2025-01-02T00:37:00' + assert backfill.parse_declared('0000-00-00 00:00:00') is None + assert backfill.parse_declared('') is None assert backfill.parse_declared(None) is None def test_fuel_names_are_normalised(): - assert backfill.normalize_fuel("Gazole") == "Gazole" - assert backfill.normalize_fuel("SP95-E10") == "E10" - assert backfill.normalize_fuel("e10") == "E10" - assert backfill.normalize_fuel("GPLc") == "GPLc" - assert backfill.normalize_fuel("SP95") == "SP95" - assert backfill.normalize_fuel("inconnu") is None + assert backfill.normalize_fuel('Gazole') == 'Gazole' + assert backfill.normalize_fuel('SP95-E10') == 'E10' + assert backfill.normalize_fuel('e10') == 'E10' + assert backfill.normalize_fuel('GPLc') == 'GPLc' + assert backfill.normalize_fuel('SP95') == 'SP95' + assert backfill.normalize_fuel('inconnu') is None def test_scan_keeps_only_the_target_box_and_the_declared_dates(): - rows, stations = backfill.scan_archive(archive_bytes(), bbox=BBOX, fuels=("Gazole", "E10")) - assert set(stations) == {"1111111", "3333333"}, "Paris est hors zone" - by_key = {(row["station_id"], row["fuel"], row["day"]): row for row in rows} - assert ("1111111", "Gazole", "2007-01-04") in by_key, "la date est celle déclarée" - assert by_key[("1111111", "Gazole", "2007-01-04")]["price"] == 1.005, "dernière valeur du jour" - assert by_key[("1111111", "Gazole", "2007-01-04")]["declared_at"] == "2007-01-04T21:10:00" - assert by_key[("1111111", "Gazole", "2007-03-13")]["price"] == 1.009 - assert by_key[("1111111", "E10", "2007-03-13")]["price"] == 1.052 - assert ("1111111", "E85", "2007-03-13") not in by_key, "carburant non demandé" - assert not any(row["price"] in (0.0, 1.111, 20.0) for row in rows), "valeurs invalides écartées" - assert stations["1111111"]["first_day"] == "2007-01-04" - assert stations["1111111"]["last_day"] == "2007-03-13" - assert stations["1111111"]["days"] == 2 + rows, stations = backfill.scan_archive(archive_bytes(), bbox=BBOX, fuels=('Gazole', 'E10')) + assert set(stations) == {'1111111', '3333333'}, 'Paris est hors zone' + by_key = {(row['station_id'], row['fuel'], row['day']): row for row in rows} + assert ('1111111', 'Gazole', '2007-01-04') in by_key, 'la date est celle déclarée' + assert by_key[('1111111', 'Gazole', '2007-01-04')]['price'] == 1.005, 'dernière valeur du jour' + assert by_key[('1111111', 'Gazole', '2007-01-04')]['declared_at'] == '2007-01-04T21:10:00' + assert by_key[('1111111', 'Gazole', '2007-03-13')]['price'] == 1.009 + assert by_key[('1111111', 'E10', '2007-03-13')]['price'] == 1.052 + assert ('1111111', 'E85', '2007-03-13') not in by_key, 'carburant non demandé' + assert not any(row['price'] in (0.0, 1.111, 20.0) for row in rows), 'valeurs invalides écartées' + assert stations['1111111']['first_day'] == '2007-01-04' + assert stations['1111111']['last_day'] == '2007-03-13' + assert stations['1111111']['days'] == 2 def test_stations_outside_the_box_are_ignored_even_when_targeted_by_id(): - rows, stations = backfill.scan_archive( - archive_bytes(), bbox=BBOX, fuels=("Gazole",), station_ids={"2222222"} - ) - assert "2222222" in stations, "un identifiant suivi est repris même hors zone" - assert "1111111" in stations, "et la zone reste prise en compte" - assert any( - row["station_id"] == "2222222" and row["day"] == "2007-02-02" and row["price"] == 1.05 for row in rows - ) + rows, stations = backfill.scan_archive(archive_bytes(), bbox=BBOX, fuels=('Gazole',), + station_ids={'2222222'}) + assert '2222222' in stations, 'un identifiant suivi est repris même hors zone' + assert '1111111' in stations, 'et la zone reste prise en compte' + assert any(row['station_id'] == '2222222' and row['day'] == '2007-02-02' + and row['price'] == 1.05 for row in rows) def test_no_price_is_ever_invented_for_an_absent_year(): """Une archive sans la station ne produit aucune ligne : aucune continuité fabriquée.""" - empty = XML.split('" - rows, stations = backfill.scan_archive(archive_bytes(empty), bbox=BBOX, fuels=("Gazole",)) - assert "3333333" not in stations - assert {row["station_id"] for row in rows} == {"1111111"} + empty = XML.split('' + rows, stations = backfill.scan_archive(archive_bytes(empty), bbox=BBOX, fuels=('Gazole',)) + assert '3333333' not in stations + assert {row['station_id'] for row in rows} == {'1111111'} def test_import_marks_origin_and_keeps_declared_dates(store): - rows, _stations = backfill.scan_archive(archive_bytes(), bbox=BBOX, fuels=("Gazole", "E10")) - imported = store.save_archive_observations(rows, "archive:2007") + rows, _stations = backfill.scan_archive(archive_bytes(), bbox=BBOX, fuels=('Gazole', 'E10')) + imported = store.save_archive_observations(rows, 'archive:2007') assert imported == len(rows) > 0 with store.connect() as db: - sample = db.execute("SELECT * FROM observations ORDER BY station_id, day LIMIT 1").fetchone() - assert sample["origin"] == "archive:2007" - assert sample["day"] == "2007-01-04" and sample["source_updated"].startswith("2007-01-04T21:10") - assert sample["fetched_at"] and not sample["fetched_at"].startswith("2007"), ( - "l’heure d’import est distincte de la date déclarée" - ) - assert store.save_archive_observations(rows, "archive:2007") == 0, "import idempotent" + sample = db.execute('SELECT * FROM observations ORDER BY station_id, day LIMIT 1').fetchone() + assert sample['origin'] == 'archive:2007' + assert sample['day'] == '2007-01-04' and sample['source_updated'].startswith('2007-01-04T21:10') + assert sample['fetched_at'] and not sample['fetched_at'].startswith('2007'), \ + 'l’heure d’import est distincte de la date déclarée' + assert store.save_archive_observations(rows, 'archive:2007') == 0, 'import idempotent' def test_archived_rows_never_pass_as_todays_prices(store): """Un import historique ne doit jamais être présenté comme un prix du jour.""" - rows, _stations = backfill.scan_archive(archive_bytes(), bbox=BBOX, fuels=("Gazole",)) - store.save_archive_observations(rows, "archive:2007") - history = store.history(44.7737872, -0.5595029, 15, "Gazole") - assert history["days"] == 0, "les lignes importées ne comptent pas comme relevés récents" - assert store.fresh_price(rows[0]["declared_at"]) is False + rows, _stations = backfill.scan_archive(archive_bytes(), bbox=BBOX, fuels=('Gazole',)) + store.save_archive_observations(rows, 'archive:2007') + history = store.history(44.7737872, -0.5595029, 15, 'Gazole') + assert history['days'] == 0, 'les lignes importées ne comptent pas comme relevés récents' + assert store.fresh_price(rows[0]['declared_at']) is False def test_backfill_runs_are_recorded_per_year(store): - store.save_backfill_run(2007, "ok", 3, 42, "détail") - store.save_backfill_run(2008, "error", 0, 0, "HTTP 404") + store.save_backfill_run(2007, 'ok', 3, 42, 'détail') + store.save_backfill_run(2008, 'error', 0, 0, 'HTTP 404') runs = store.backfill_runs() - assert runs[2007]["status"] == "ok" and runs[2007]["prices"] == 42 - assert runs[2008]["status"] == "error" + assert runs[2007]['status'] == 'ok' and runs[2007]['prices'] == 42 + assert runs[2008]['status'] == 'error' diff --git a/tests/test_backtest.py b/tests/test_backtest.py new file mode 100644 index 0000000..b404824 --- /dev/null +++ b/tests/test_backtest.py @@ -0,0 +1,132 @@ +"""Backtest : unités en c€/L, régimes séparés, confiance tenue pendant les chocs.""" +import backtest +import validation + + +def prediction(day, horizon=7, mu=2.0, actual=2.5, confidence=0.7, price=2.0, + trained_until='2019-12-31'): + """Prédiction de test : jamais entraînée après la date prédite (sinon fuite détectée).""" + return dict(day=day, horizon=horizon, predicted_price=price + mu / 100, + actual_price=price + actual / 100, last_known_price=price, + predicted_change=mu, actual_change=actual, confidence=confidence, + interval=(mu - 1.0, mu + 1.0), p_up=confidence, trained_until=trained_until) + + +def test_metrics_are_converted_to_cents(): + rows = [prediction('2026-01-01', mu=2.0, actual=3.0), prediction('2026-01-02', mu=-1.0, + actual=-2.0)] + metrics = backtest.metrics_in_cents(validation.evaluate(rows, horizon=7)) + assert metrics['mae_cents'] == 1.0, '1 c€/L d’erreur moyenne, exprimée en centimes' + assert metrics['improvement_pct'] is not None + assert metrics['naive']['mae_cents'] is not None + + +def test_amplitude_reports_predicted_and_actual(): + rows = [prediction('2026-01-01', mu=2.0, actual=-4.0), prediction('2026-01-02', mu=-2.0, + actual=2.0)] + out = backtest.amplitude(rows) + assert out['predicted_cents'] == 2.0 + assert out['actual_cents'] == 3.0 + + +def test_regimes_split_predictions_by_period(): + rows = [prediction('2020-03-15'), prediction('2022-05-15'), prediction('2023-09-15'), + prediction('2026-03-01'), prediction('2021-01-01')] + regimes = backtest.regime_report(rows) + assert regimes['covid_2020']['count'] == 1 + assert regimes['choc_2022']['count'] == 1 + assert regimes['calme_2023']['count'] == 1 + assert regimes['crise_2026']['count'] == 1 + assert '2021' not in str([regime['count'] for regime in regimes.values()]) + + +def test_confidence_must_be_earned_during_a_shock(): + """Forte confiance pendant un choc + sens proche du hasard = refus.""" + rows = [] + for index in range(40): + rows.append(prediction(f'2026-01-{index % 28 + 1:02d}', mu=5.0, + actual=(-5.0 if index % 2 else 5.0), confidence=0.93)) + regimes = backtest.regime_report(rows) + verdict = backtest.shock_verdict(regimes) + assert verdict['passed'] is False + assert any('confiance' in problem for problem in verdict['problems']) + + +def test_a_prudent_model_during_a_shock_is_accepted(): + rows = [prediction(f'2026-02-{index % 28 + 1:02d}', mu=2.0, + actual=(2.0 if index % 4 else -2.0), confidence=0.55) + for index in range(40)] + verdict = backtest.shock_verdict(backtest.regime_report(rows)) + assert verdict['passed'] is True + + +def test_shock_verdict_ignores_a_thin_regime(): + rows = [prediction('2022-03-01', mu=6.0, actual=-6.0, confidence=0.95) for _ in range(5)] + verdict = backtest.shock_verdict(backtest.regime_report(rows)) + assert verdict['passed'] is True, 'cinq prévisions ne permettent pas de conclure' + + +def test_interval_coverage_and_probability_calibration(): + rows = [prediction('2026-01-01', mu=2.0, actual=2.5), + prediction('2026-01-02', mu=2.0, actual=9.0)] + assert backtest._interval_coverage(rows) == 0.5 + assert backtest._probability_calibration(rows) is None, 'échantillon trop mince' + many = [prediction(f'2026-02-{index % 28 + 1:02d}', mu=2.0, + actual=(2.0 if index < 35 else -2.0), confidence=0.7) + for index in range(70)] + calibration = backtest._probability_calibration(many) + assert calibration['count'] == 70 + assert calibration['observed'] == 0.5 + + +def test_render_reports_every_required_item(): + entry = dict(fuel='Gazole', variant='local_long', label='Modèle local long historique', + train=('2007-01-01', '2024-12-31'), test=('2025-01-01', '2026-09-12'), + train_samples=5000, test_samples=600, main_model='ridge_market', + horizons={'7': backtest.metrics_in_cents( + validation.evaluate([prediction(f'2026-01-{index % 28 + 1:02d}') + for index in range(40)], horizon=7)) + | dict(model='ridge_market', interval_coverage=0.8, + amplitude=dict(predicted_cents=2.4, actual_cents=2.8))}, + regimes={'crise_2026': dict(label='crise actuelle', period='2026-01-01 → 2026-12-31', + count=40, mae_cents=1.2, improvement_pct=12.0, + direction=0.6, mean_confidence=0.62)}, + economics=dict(naive=dict(cost_eur=100.0, refuels=10), advisor=dict( + cost_eur=95.0, refuels=11), value=dict(net_saving_eur=3.5), + comfort=dict(comfortable=True), period=('2025-01-01', '2026-09-12')), + verdict=dict(passed=True, failures=[], reasons=['coût simulé'])) + text = backtest.render_variant(entry) + for needle in ('apprentissage', 'test', 'MAE', 'amélioration', 'sens', 'calib', 'amplitude', + 'régimes', 'économie simulée', 'verdict'): + assert needle in text, needle + + +def test_render_explains_a_refusal(): + text = backtest.render_variant(dict(label='Modèle marché', fuel='SP95', variant='market', + reason='12 échantillons : trop peu pour conclure')) + assert 'non exploitable' in text and 'trop peu' in text + + +def test_run_variant_without_data_returns_a_reason(store): + entry = backtest.run_variant('Gazole', 'local_long', 44.77, -0.55, 15, days=60) + assert entry['reason'] + assert entry.get('verdict') is None + + +def test_holdout_keeps_the_current_crisis_out_of_training(store, monkeypatch): + """La période actuelle peut rester totalement hors entraînement.""" + rows = [] + from datetime import date, timedelta + base = date(2024, 1, 1) + for index in range(900): + day = (base + timedelta(days=index)).isoformat() + for station in range(5): + rows.append(dict(station_id=f's{station}', fuel='Gazole', day=day, + price=round(2.0 + index * 0.0005 + station * 0.004, 4), + declared_at=f'{day}T09:00:00', lat=44.7737872, lon=-0.5595029)) + store.save_archive_observations(rows, 'archive:test') + entry = backtest.run_variant('Gazole', 'local_long', 44.7737872, -0.5595029, 15, days=900, + holdout_start='2026-06-01') + if entry.get('train'): + assert entry['train'][1] < '2026-06-01' + assert entry['test'][0] >= '2026-06-01' diff --git a/tests/test_collector.py b/tests/test_collector.py index c98f2a4..e00d2f7 100644 --- a/tests/test_collector.py +++ b/tests/test_collector.py @@ -24,7 +24,7 @@ def test_collect_overlapping_favorites_once_daily(store, collector): assert out["status"] == "ok" assert out["count"] == 1 assert len(calls) == 1 - assert collector.collect(load, force=False)["status"] == "skipped" + assert collector.collect(load, force=False)['status'] == 'skipped' assert len(calls) == 1 with store.connect() as db: assert db.execute("select count(*) from observations").fetchone()[0] == 1 @@ -36,7 +36,7 @@ def test_failed_collection_logged_and_retryable(store, collector): def fail(): raise OSError("source inaccessible") - assert collector.collect(fail, force=True)["status"] == "error" + assert collector.collect(fail, force=True)['status'] == 'error' out = collector.collect(lambda: [sample(datetime.now(timezone.utc))], force=False) assert out["status"] == "ok" diff --git a/tests/test_collectors.py b/tests/test_collectors.py index 5650412..d3875da 100644 --- a/tests/test_collectors.py +++ b/tests/test_collectors.py @@ -1,5 +1,4 @@ """Événements prix (changement uniquement), actualités structurées et opérations commerciales.""" - from datetime import datetime, timedelta, timezone import pytest @@ -11,51 +10,39 @@ 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 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()], 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" + 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") + 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)) + 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 + 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(): @@ -64,131 +51,80 @@ def test_rss_articles_keep_publication_date_and_source(): https://exemple.fr/a1Fri, 11 Sep 2026 09:30:00 GMT Agence Test<p>Un pétrolier visé.</p> """ - articles = news.parse_rss(xml, "Google News", "suez_babelmandeb") + 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 + 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], [])) + 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" + 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) + monkeypatch.setattr(llm, 'extract', fake_extract) first = news.collect() - assert first["analysed"] == 1 and first["events"] == 1 + 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 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" + 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")) + 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() == [] + 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", - ), - ) + 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" + 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" + 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" + assert active[0]['state'] == 'en cours' announced = promotions.active(today=datetime(2026, 9, 12, tzinfo=timezone.utc).date()) - assert announced[0]["state"] == "annoncée" + 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} + 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") + llm.parse_json('aucun json ici') diff --git a/tests/test_factor_signs.py b/tests/test_factor_signs.py index 326703c..d12c21b 100644 --- a/tests/test_factor_signs.py +++ b/tests/test_factor_signs.py @@ -6,7 +6,6 @@ Deux exigences verrouillées ici : - 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 @@ -18,100 +17,66 @@ def days_ago(n): def seed(series, unit, rows): - return storage.save_upstream(series, rows, unit, "test") + 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_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): +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"): +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") + 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 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) + 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"] + 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) + 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"] + assert corroborated['data_confidence'] > alone['data_confidence'] def test_level_and_dynamics_are_separate_dimensions(store): @@ -120,13 +85,13 @@ def test_level_and_dynamics_are_separate_dimensions(store): # 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"] + 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): @@ -134,11 +99,11 @@ def test_tiny_moves_are_not_presented_as_dynamics(store): 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" + 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): @@ -146,152 +111,133 @@ def test_reference_and_current_use_the_same_metric(store): 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"] + 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"] + 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 + 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)], - ) + 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"] + 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)], - ) + 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" + 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), - ], - ) + 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"] + 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)]) + 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 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)]) + 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"] + 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"] + 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) + 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"] + 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é" + 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 + 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 diff --git a/tests/test_http.py b/tests/test_http.py index dae6a6b..c81a02b 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -136,35 +136,18 @@ def test_http_jobs_inventory_exposes_sources_and_schedules(server): def test_http_advice_reports_refresh_and_promotions(server, store, monkeypatch): - monkeypatch.setattr( - app.collector, - "ensure_fresh_local", - lambda max_age_seconds=900: dict(refreshed=True, age_seconds=1200.0), - ) - monkeypatch.setattr( - app.promotions, - "active", - lambda: [ - dict( - brand="E.Leclerc", - nature="prix_coutant", - fuels="Gazole", - state="en cours", - valid_from="2026-09-12", - valid_until="2026-09-13", - stations="", - source_url="https://exemple.fr/promo", - confidence=0.9, - discount_per_liter=None, - ) - ], - ) + monkeypatch.setattr(app.collector, "ensure_fresh_local", + lambda max_age_seconds=900: dict(refreshed=True, age_seconds=1200.0)) + monkeypatch.setattr(app.promotions, "active", + lambda: [dict(brand="E.Leclerc", nature="prix_coutant", fuels="Gazole", + state="en cours", valid_from="2026-09-12", valid_until="2026-09-13", + stations="", source_url="https://exemple.fr/promo", confidence=0.9, + discount_per_liter=None)]) row = sample(datetime.now(timezone.utc)) row.update(name="A", city="Paris", address="Rue") monkeypatch.setattr(app, "load_fuel_data", lambda **kwargs: [row]) - code, out = request( - server, "POST", "/api/advice", {"lat": 48.8, "lon": 2.3, "radius_km": 15, "fuel": "Gazole"} - ) + code, out = request(server, "POST", "/api/advice", + {"lat": 48.8, "lon": 2.3, "radius_km": 15, "fuel": "Gazole"}) assert code == 200 assert out["local_refresh"]["refreshed"] is True assert out["promotions"][0]["brand"] == "E.Leclerc" diff --git a/tests/test_market.py b/tests/test_market.py index 6ca36ff..27e93f2 100644 --- a/tests/test_market.py +++ b/tests/test_market.py @@ -1,5 +1,5 @@ import importlib -from datetime import date, timedelta +from datetime import date, datetime, timedelta, timezone import pytest @@ -12,7 +12,9 @@ def market(monkeypatch, tmp_path): return module -TODAY = date.today() +# Le module raisonne en UTC : le test doit utiliser la même horloge, sinon il casse au passage +# de minuit en heure locale (décalage Paris/UTC). +TODAY = datetime.now(timezone.utc).date() STOOQ_OK = f"Symbol,Date,Open,Close\nCL.F,{TODAY},80.0,82.4\n" TE_ROW = ( ' Brent' @@ -24,7 +26,7 @@ TE_ROW = ( def test_stooq_parsing_accepts_fresh_quote(market): out = market.parse_stooq(STOOQ_OK) assert out["price_usd"] == pytest.approx(82.4) - assert out["date"] == date.today() + assert out["date"] == TODAY assert out["change_pct"] == pytest.approx(3.0) diff --git a/tests/test_models.py b/tests/test_models.py new file mode 100644 index 0000000..e1261de --- /dev/null +++ b/tests/test_models.py @@ -0,0 +1,171 @@ +"""Modèles : algèbre vérifiable, rolls détectés, sélection sans fuite, sorties en c€/L.""" +import math +from datetime import date, timedelta + +import pytest + +import market +import models +import storage + + +def sample(day, delta_7=0.0, target_7=0.0, slope=0.0, vol=1.0, **extra): + features = dict(local_delta_1=delta_7 / 7, local_delta_3=delta_7, local_delta_7=delta_7, + local_delta_14=delta_7 * 2, local_slope_7=slope, local_vol_14=vol, + local_percentile_90=50.0, local_matched_7=delta_7) + features.update(extra) + return dict(day=day, price=2.0, features=features, targets={1: target_7, 3: target_7, + 7: target_7, 14: target_7, + 21: target_7}, + target_meta={}, declared_today=3, active_stations=40) + + +def history(count=200, relation=lambda index: (index % 3) - 1): + out = [] + for index in range(count): + day = (date(2024, 1, 1) + timedelta(days=index)).isoformat() + delta = (index % 5) - 2.0 + out.append(sample(day, delta_7=delta, slope=delta / 7, target_7=2.0 * delta, + local_delta_1=delta / 5, local_delta_14=delta * 2)) + return out + + +def test_probability_up_is_monotonic_and_bounded(): + assert models.probability_up(5, 2) > 0.5 + assert models.probability_up(-5, 2) < 0.5 + assert models.probability_up(0, 2) == 0.5 + assert 0.9 < models.probability_up(50, 1) <= 1.0 + assert models.probability_up(3, 0) == 1.0 + + +def test_ridge_recovers_a_simple_linear_relation(): + train = [sample((date(2024, 1, 1) + timedelta(days=index)).isoformat(), + delta_7=float(index), target_7=0.0) for index in range(40)] + for row in train: + row['targets'][7] = 2.0 * row['features']['local_delta_7'] + fitted = models.model_autoregressive(train, 7) + assert fitted is not None + predicted = fitted['predict'](sample('2024-02-01', delta_7=10.0)) + assert predicted == pytest.approx(20.0, abs=3.0) + + +def test_naive_model_predicts_no_change(): + train = history(120) + fitted = models.model_naive_unchanged(train, 7) + assert fitted['predict'](train[0]) == 0.0 + out = models.predict(fitted, train[0]) + assert out['mu_cents'] == 0.0 and out['direction'] == 'flat' + + +def test_predict_exposes_the_decision_making_output(): + fitted = models.model_local_trend(history(120), 7) + out = models.predict(fitted, sample('2024-05-01', slope=0.5)) + assert out['mu_cents'] == pytest.approx(3.5, abs=0.01) + assert out['interval'][0] < out['mu_cents'] <= out['interval'][1] + assert 0 <= out['p_up'] <= 1 and 0.5 <= out['confidence'] <= 1 + assert out['direction'] == 'up' + + +def test_selection_uses_a_chronological_tail_and_never_the_test_set(): + train = history(200) + fitted, selection = models.select_model(train, 7, validation_share=0.2) + assert fitted is not None + assert selection['validation'].startswith('fin d’apprentissage') + assert selection['validation_samples'] >= 10 + assert selection['winner'] in selection['candidate_scores'] + # Le meilleur score interne est bien celui retenu + assert selection['candidate_scores'][selection['winner']] == min( + selection['candidate_scores'].values()) + + +def test_selection_refuses_a_too_small_sample(): + fitted, selection = models.select_model(history(20), 7) + assert fitted is None + assert 'trop peu' in selection['reason'] + + +def test_roll_detection_flags_a_reverted_jump_only(): + """Un saut annulé = changement de contrat ; une vraie tendance = mouvement de marché.""" + values = [dict(day=(date(2024, 1, 1) + timedelta(days=index)).isoformat(), + value=80.0 + index * 0.01) for index in range(40)] + clean = market.detect_rolls(values) + assert clean['count'] == 0 + rolled = [dict(point) for point in values] + rolled[20]['value'] = rolled[19]['value'] * 1.12 # saut de 12 % + for index in range(21, 23): # annulé dans les 2 jours + rolled[index]['value'] = rolled[19]['value'] * (1 + (index - 19) * 0.001) + flagged = market.detect_rolls(rolled) + assert flagged['count'] >= 1 + assert flagged['days'][0]['day'] == rolled[20]['day'] + assert 'roll' in flagged['basis'] + + +def test_log_return_respects_publication_dates(): + """Une valeur publiée plus tard n'est pas utilisable avant sa publication.""" + points = [dict(available_from='2026-07-01', day='2026-07-01', value=80.0), + dict(available_from='2026-08-15', day='2026-07-01', value=88.0)] + assert models._log_return(points, '2026-08-02', 30) is None, 'pas encore publiée' + assert models._log_return(points, '2026-08-20', 30) is not None + + +def test_samples_carry_cent_targets_and_no_future_feature(store): + """La cible est en centimes ; la feature « matched » est connue au jour du calcul.""" + import series as series_module + lat, lon = 44.7737872, -0.5595029 + base = storage.datetime.now(storage.PARIS).date() - timedelta(days=200) + rows = [] + for index in range(150): + day = (base + timedelta(days=index)).isoformat() + for station in range(6): + rows.append(dict(station_id=f's{station}', fuel='Gazole', day=day, + price=round(2.0 + index * 0.001 + station * 0.005, 4), + declared_at=f'{day}T09:00:00', lat=lat, lon=lon)) + store.save_archive_observations(rows, 'archive:test') + built = models.build_samples(lat, lon, 15, 'Gazole', days=200, market=False) + samples = built['samples'] + assert samples, built.get('reason') + row = [item for item in samples if item['targets'][7] is not None][-1] + assert isinstance(row['targets'][7], float) + assert abs(row['targets'][7]) < 100, 'cible en centimes par litre' + expected = None + for item in series_module.matched_variation(built['reconstructed'], horizon=7): + if item['day'] == row['day']: + expected = item['delta_cents'] + assert row['features']['local_matched_7'] == expected, 'feature connue au jour J' + assert row['targets'][7] == expected, 'cible au jour J+7' + + +def test_samples_are_empty_without_enough_market_history(store): + built = models.build_samples(44.77, -0.55, 15, 'Gazole', days=30, market=False) + assert built['samples'] == [] + assert 'jours de marché reconstruits' in built['reason'] + + +def test_every_candidate_is_reentrainable_on_enough_data(): + train = history(160) + for candidate in models.CANDIDATES: + fitted = candidate(train, 7) + assert fitted is not None, candidate.__name__ + out = models.predict(fitted, train[0]) + assert isinstance(out['mu_cents'], float) + + +def test_fuel_coverage_reports_the_real_period(store): + store.save_archive_observations( + [dict(station_id='a', fuel='E10', day='2009-05-05', price=1.2, + declared_at='2009-05-05T09:00:00', lat=44.77, lon=-0.55), + dict(station_id='b', fuel='E10', day='2026-01-01', price=1.9, + declared_at='2026-01-01T09:00:00', lat=44.77, lon=-0.55)], 'archive:test') + coverage = models.fuel_coverage('E10') + assert coverage['first'] == '2009-05-05' + assert coverage['points'] == 2 + assert coverage['archived'] == 2 + assert models.fuel_coverage('GPLc')['points'] == 0 + + +def test_standardisation_survives_missing_values(): + rows = [dict(a=1.0, b=None), dict(a=3.0, b=5.0), dict(a=None, b=7.0)] + stats = models._standardise(rows, ['a', 'b']) + design = models._design(rows, ['a', 'b'], stats) + assert len(design[0]) == 3 and design[0][0] == 1.0 + assert all(math.isfinite(value) for line in design for value in line) diff --git a/tests/test_positions.py b/tests/test_positions.py index 0975f7c..e06e6d3 100644 --- a/tests/test_positions.py +++ b/tests/test_positions.py @@ -1,96 +1,84 @@ """Deux indicateurs distincts : position dans l'espace (aujourd'hui) et dans le temps (historique).""" +from datetime import timedelta -from datetime import date, timedelta +import storage def days_ago(n): - return (date.today() - timedelta(days=n)).isoformat() + return (storage.datetime.now(storage.PARIS).date() - timedelta(days=n)).isoformat() def seed_observation(store, station_id, fuel, day, price, lat=44.7737872, lon=-0.5595029): store.save_archive_observations( - [ - dict( - station_id=station_id, - fuel=fuel, - day=day, - price=price, - declared_at=f"{day}T10:00:00", - lat=lat, - lon=lon, - ) - ], - "archive:test", - ) + [dict(station_id=station_id, fuel=fuel, day=day, price=price, + declared_at=f'{day}T10:00:00', lat=lat, lon=lon)], 'archive:test') def test_local_position_ranks_stations_today(store): for index, price in enumerate((2.30, 2.10, 1.99, 2.20)): - seed_observation(store, f"station{index}", "E10", days_ago(0), price) - local = store.local_position(44.7737872, -0.5595029, 15, "E10") - assert local["kind"] == "local" - assert local["stations"] == 4 - assert local["percentile"] == 0.25, "le meilleur prix est le 1ᵉʳ des 4" - assert local["best"] == 1.99 - assert "dans l’espace" in local["summary"] and "pas dans le temps" in local["summary"] + seed_observation(store, f'station{index}', 'E10', days_ago(0), price) + local = store.local_position(44.7737872, -0.5595029, 15, 'E10') + assert local['kind'] == 'local' + assert local['stations'] == 4 + assert local['percentile'] == 0.25, 'le meilleur prix est le 1ᵉʳ des 4' + assert local['best'] == 1.99 + assert 'dans l’espace' in local['summary'] and 'pas dans le temps' in local['summary'] def test_historical_position_uses_daily_medians_over_windows(store): """Un jour = un point (médiane du panel), pour que les jours chargés ne pèsent pas plus.""" for offset in range(40, 0, -1): day = days_ago(offset) - seed_observation(store, "a", "E10", day, 2.20 + (offset - 40) * 0.01) - seed_observation(store, "b", "E10", day, 2.30 + (offset - 40) * 0.01) - seed_observation(store, "a", "E10", days_ago(39), 2.19) - seed_observation(store, "b", "E10", days_ago(39), 2.29) - seed_observation(store, "c", "E10", days_ago(39), 2.39) + seed_observation(store, 'a', 'E10', day, 2.20 + (offset - 40) * 0.01) + seed_observation(store, 'b', 'E10', day, 2.30 + (offset - 40) * 0.01) + seed_observation(store, 'a', 'E10', days_ago(39), 2.19) + seed_observation(store, 'b', 'E10', days_ago(39), 2.29) + seed_observation(store, 'c', 'E10', days_ago(39), 2.39) for index, price in enumerate((1.95, 2.05, 2.15)): - seed_observation(store, f"today{index}", "E10", days_ago(0), price) - position = store.historical_position(44.7737872, -0.5595029, 15, "E10", windows=(30, 90, 365)) - assert position["kind"] == "historique" + seed_observation(store, f'today{index}', 'E10', days_ago(0), price) + position = store.historical_position(44.7737872, -0.5595029, 15, 'E10', + windows=(30, 90, 365)) + assert position['kind'] == 'historique' # Reconstruction : les stations qui n'ont pas déclaré aujourd'hui comptent encore, avec leur # dernière valeur connue. La médiane n'est donc pas celle des seules déclarations du jour. - assert position["daily_series"][1]["stations"] == 3, "les 3 stations déclarées la veille" - assert position["current"] == 1.95, "a et b comptent encore (≈1,81 et ≈1,91), d’où 1,95" - assert "aucune interpolation" in position["basis"] - assert position["windows"]["30"]["percentile"] is not None - assert position["windows"]["30"]["days"] <= 31 - assert position["windows"]["365"]["percentile"] is None, ( - "40 jours d’historique ne suffisent pas pour un percentile à 365 jours" - ) - assert ( - "Historique" in position["windows"]["365"]["summary"] - or "insuffisant" in position["windows"]["365"]["summary"] - ) + assert position['daily_series'][1]['stations'] == 3, 'les 3 stations déclarées la veille' + assert position['current'] == 1.95, 'a et b comptent encore (≈1,81 et ≈1,91), d’où 1,95' + assert 'aucune interpolation' in position['basis'] + assert position['windows']['30']['percentile'] is not None + assert position['windows']['30']['days'] <= 31 + assert position['windows']['365']['percentile'] is None, \ + '40 jours d’historique ne suffisent pas pour un percentile à 365 jours' + assert 'Historique' in position['windows']['365']['summary'] or \ + 'insuffisant' in position['windows']['365']['summary'] def test_historical_position_is_insufficient_without_history(store): for index, price in enumerate((2.0, 2.1, 2.2)): - seed_observation(store, f"today{index}", "E10", days_ago(0), price) - position = store.historical_position(44.7737872, -0.5595029, 15, "E10") - assert position["percentile"] is None - assert position["windows"]["30"]["percentile"] is None - assert "insuffisant" in position["windows"]["30"]["summary"] + seed_observation(store, f'today{index}', 'E10', days_ago(0), price) + position = store.historical_position(44.7737872, -0.5595029, 15, 'E10') + assert position['percentile'] is None + assert position['windows']['30']['percentile'] is None + assert 'insuffisant' in position['windows']['30']['summary'] def test_positions_are_two_different_distributions(store): """Le même jour peut être excellent localement et cher dans le temps.""" for offset in range(25, 0, -1): for index, base in enumerate((1.70, 1.75, 1.80)): - seed_observation(store, f"old{index}", "E10", days_ago(offset), base) + seed_observation(store, f'old{index}', 'E10', days_ago(offset), base) for index, price in enumerate((2.40, 2.45, 2.50)): - seed_observation(store, f"today{index}", "E10", days_ago(0), price) - local = store.local_position(44.7737872, -0.5595029, 15, "E10") - historical = store.historical_position(44.7737872, -0.5595029, 15, "E10") - assert local["percentile"] == round(1 / 3, 3), "meilleur prix du jour" - assert historical["percentile"] >= 0.9, "mais cher par rapport à son propre passé" - assert local["percentile"] < 0.5 < historical["percentile"] + seed_observation(store, f'today{index}', 'E10', days_ago(0), price) + local = store.local_position(44.7737872, -0.5595029, 15, 'E10') + historical = store.historical_position(44.7737872, -0.5595029, 15, 'E10') + assert local['percentile'] == round(1 / 3, 3), 'meilleur prix du jour' + assert historical['percentile'] >= 0.9, 'mais cher par rapport à son propre passé' + assert local['percentile'] < 0.5 < historical['percentile'] def test_stations_outside_the_radius_are_excluded(store): - seed_observation(store, "loin", "E10", days_ago(0), 1.50, lat=48.8566, lon=2.3522) - seed_observation(store, "proche", "E10", days_ago(1), 2.00) - seed_observation(store, "proche", "E10", days_ago(0), 2.05) - local = store.local_position(44.7737872, -0.5595029, 15, "E10") - assert local["stations"] == 1, "la station parisienne est hors rayon" - assert local["best"] == 2.05 + seed_observation(store, 'loin', 'E10', days_ago(0), 1.50, lat=48.8566, lon=2.3522) + seed_observation(store, 'proche', 'E10', days_ago(1), 2.00) + seed_observation(store, 'proche', 'E10', days_ago(0), 2.05) + local = store.local_position(44.7737872, -0.5595029, 15, 'E10') + assert local['stations'] == 1, 'la station parisienne est hors rayon' + assert local['best'] == 2.05 diff --git a/tests/test_quantity.py b/tests/test_quantity.py index 061b4f5..1171a37 100644 --- a/tests/test_quantity.py +++ b/tests/test_quantity.py @@ -4,88 +4,39 @@ Scénarios repris de l'usage réel : appoint minimal pour atteindre une baisse a anticipé justifié par un prix favorable **et** une hausse fiable, véhicule occasionnel basé sur le prochain trajet, et refus d'un passage supplémentaire pour quelques centimes. """ - import pytest import quantity import storage -REGULAR = dict( - name="Prius", - fuel="Gazole", - usage="regular", - consumption=5.0, - min_range_km=80.0, - monthly_km=1100.0, - tank_liters=43.0, - min_topup_liters=10.0, - min_gain_eur=1.5, -) -VAN = dict( - name="Van", - fuel="Gazole", - usage="occasional", - consumption=8.0, - min_range_km=80.0, - monthly_km=0.0, - tank_liters=70.0, - min_topup_liters=10.0, - min_gain_eur=1.5, -) +REGULAR = dict(name='Prius', fuel='Gazole', usage='regular', consumption=5.0, min_range_km=80.0, + monthly_km=1100.0, tank_liters=43.0, min_topup_liters=10.0, min_gain_eur=1.5) +VAN = dict(name='Van', fuel='Gazole', usage='occasional', consumption=8.0, min_range_km=80.0, + monthly_km=0.0, tank_liters=70.0, min_topup_liters=10.0, min_gain_eur=1.5) def outlook_down(confidence=0.72, days_min=3, days_max=5, low=0.04, high=0.07): - return dict( - status="ok", - direction="down", - change_low=low, - change_high=high, - days_min=days_min, - days_max=days_max, - confidence=confidence, - model="test-v1", - ) + return dict(status='ok', direction='down', change_low=low, change_high=high, + days_min=days_min, days_max=days_max, confidence=confidence, model='test-v1') def outlook_up(confidence=0.81, days_max=7, low=0.05, high=0.08): - return dict( - status="ok", - direction="up", - change_low=low, - change_high=high, - days_min=2, - days_max=days_max, - confidence=confidence, - model="test-v1", - ) + return dict(status='ok', direction='up', change_low=low, change_high=high, + days_min=2, days_max=days_max, confidence=confidence, model='test-v1') def historical_position(percentile, current=1.62, days=120): """Position **historique** (fenêtres 30/90/365 jours). Seule utilisée pour anticiper.""" - return dict( - kind="historique", - percentile=percentile, - current=current, - days=days, - windows={ - str(window): dict(percentile=percentile, days=days, current=current, median=1.60, summary="test") - for window in (30, 90, 365) - }, - summary="1.620 €/L se situe au test.", - ) + return dict(kind='historique', percentile=percentile, current=current, days=days, + windows={str(window): dict(percentile=percentile, days=days, current=current, + median=1.60, summary='test') for window in (30, 90, 365)}, + summary='1.620 €/L se situe au test.') def local_position(percentile, stations=36): """Position **locale** du jour : classement dans l'espace, jamais dans le temps.""" - return dict( - kind="local", - percentile=percentile, - stations=stations, - day="2026-09-12", - best=1.99, - median=2.11, - summary="test local", - ) + return dict(kind='local', percentile=percentile, stations=stations, day='2026-09-12', + best=1.99, median=2.11, summary='test local') def test_bands_refuse_false_precision(): @@ -101,218 +52,151 @@ def test_daily_km_never_assumes_an_average_for_occasional_use(): def test_wait_plan_buys_the_minimum_and_respects_comfort_floor(): """Baisse annoncée : appoint minimal, jamais 4 L qui obligeraient à revenir demain.""" - out = quantity.plan( - REGULAR, - remaining_km=150, - price_now=1.62, - historical_position=historical_position(0.5), - outlook=outlook_down(), - ) - assert out["action"] == "topup" - assert out["usable_km"] == 70.0 - assert out["daily_km"] == pytest.approx(36.1, abs=0.1) - assert out["litres_low"] >= 10.0, "plancher de confort appliqué" - assert out["horizon"]["direction"] == "down" - assert out["horizon"]["days_min"] == 3 - assert out["economy"]["reference"].startswith("litres dont") - assert any("baisse de 4.0–7.0 c€/L" in reason for reason in out["reasons"]) - assert any("confiance 72%" in reason for reason in out["reasons"]) - assert out["forecast_note"] is None + out = quantity.plan(REGULAR, remaining_km=150, price_now=1.62, historical_position=historical_position(0.5), + outlook=outlook_down()) + assert out['action'] == 'topup' + assert out['usable_km'] == 70.0 + assert out['daily_km'] == pytest.approx(36.1, abs=0.1) + assert out['litres_low'] >= 10.0, 'plancher de confort appliqué' + assert out['horizon']['direction'] == 'down' + assert out['horizon']['days_min'] == 3 + assert out['economy']['reference'].startswith('litres dont') + assert any('baisse de 4.0–7.0 c€/L' in reason for reason in out['reasons']) + assert any('confiance 72%' in reason for reason in out['reasons']) + assert out['forecast_note'] is None def test_wait_plan_buys_nothing_when_the_autonomy_already_covers_the_window(): - out = quantity.plan( - REGULAR, - remaining_km=195, - price_now=1.62, - historical_position=historical_position(0.5), - outlook=outlook_down(), - ) - assert out["action"] == "wait" - assert out["litres_low"] is None - assert any("couvre déjà" in reason for reason in out["reasons"]) + out = quantity.plan(REGULAR, remaining_km=195, price_now=1.62, historical_position=historical_position(0.5), + outlook=outlook_down()) + assert out['action'] == 'wait' + assert out['litres_low'] is None + assert any('couvre déjà' in reason for reason in out['reasons']) def test_wait_plan_warns_when_the_tank_cannot_reach_the_window(): """Réservoir trop petit pour tenir jusqu'à la baisse : le dire au lieu de promettre.""" small_tank = dict(REGULAR, tank_liters=20.0) - out = quantity.plan( - small_tank, - remaining_km=95, - price_now=1.62, - historical_position=historical_position(0.5), - outlook=outlook_down(days_min=14, days_max=17), - ) - assert out["action"] == "topup" - assert out["litres_target"] == pytest.approx(15.3, abs=0.4), "plafonné au réservoir" - assert any("second ravitaillement" in caveat for caveat in out["caveats"]) - assert any("plafonnée" in caveat for caveat in out["caveats"]) + out = quantity.plan(small_tank, remaining_km=95, price_now=1.62, historical_position=historical_position(0.5), + outlook=outlook_down(days_min=14, days_max=17)) + assert out['action'] == 'topup' + assert out['litres_target'] == pytest.approx(15.3, abs=0.4), 'plafonné au réservoir' + assert any('second ravitaillement' in caveat for caveat in out['caveats']) + assert any('plafonnée' in caveat for caveat in out['caveats']) def test_full_tank_requires_both_favourable_price_and_upward_forecast(): - out = quantity.plan( - REGULAR, - remaining_km=195, - price_now=1.55, - historical_position=historical_position(0.10), - outlook=outlook_up(), - ) - assert out["action"] == "refill" - assert out["litres_low"] == 30.0 and out["litres_high"] == 35.0 - assert out["economy"]["gain_low"] > 0 and out["economy"]["worth_it"] is True - joined = " ".join(out["reasons"]) - assert "centile des prix journaliers" in joined - assert "plancher garanti" in joined, "un bon prix n’est jamais présenté comme un plancher certain" + out = quantity.plan(REGULAR, remaining_km=195, price_now=1.55, historical_position=historical_position(0.10), + outlook=outlook_up()) + assert out['action'] == 'refill' + assert out['litres_low'] == 30.0 and out['litres_high'] == 35.0 + assert out['economy']['gain_low'] > 0 and out['economy']['worth_it'] is True + joined = ' '.join(out['reasons']) + assert 'centile des prix journaliers' in joined + assert 'plancher garanti' in joined, 'un bon prix n’est jamais présenté comme un plancher certain' def test_upward_forecast_with_ordinary_price_does_not_justify_a_full_tank(): - out = quantity.plan( - REGULAR, - remaining_km=195, - price_now=1.72, - historical_position=historical_position(0.70), - outlook=outlook_up(), - ) - assert out["action"] == "topup" - assert out["action"] != "refill" - assert any("n'est pas historiquement favorable" in reason for reason in out["reasons"]) + out = quantity.plan(REGULAR, remaining_km=195, price_now=1.72, historical_position=historical_position(0.70), + outlook=outlook_up()) + assert out['action'] == 'topup' + assert out['action'] != 'refill' + assert any("n'est pas historiquement favorable" in reason for reason in out['reasons']) def test_small_gain_is_rejected_to_avoid_a_pointless_stop(): - out = quantity.plan( - REGULAR, - remaining_km=195, - price_now=1.55, - historical_position=historical_position(0.10), - outlook=outlook_up(low=0.004, high=0.006), - ) - assert out["economy"]["worth_it"] is False - assert any( - "ne multipliez pas les passages" in caveat - or "Gain net faible" in caveat - or "inutile de multiplier" in caveat - for caveat in out["caveats"] - ) + out = quantity.plan(REGULAR, remaining_km=195, price_now=1.55, historical_position=historical_position(0.10), + outlook=outlook_up(low=0.004, high=0.006)) + assert out['economy']['worth_it'] is False + assert any('ne multipliez pas les passages' in caveat + or 'Gain net faible' in caveat or 'inutile de multiplier' in caveat + for caveat in out['caveats']) def test_no_validated_forecast_means_no_anticipation(store): """Autonomie confortable : sans prévision validée, on n'anticipe pas du tout.""" - out = quantity.plan( - REGULAR, - remaining_km=420, - price_now=1.55, - historical_position=historical_position(0.10), - local_position=local_position(0.16), - outlook=dict(status="insufficient", reason="modèle non entraîné"), - ) - assert out["action"] == "wait" - assert out["litres_low"] is None - assert out["forecast_note"] == "modèle non entraîné" - assert any("Position historique" in reason for reason in out["reasons"]) - assert any("Position locale" in reason for reason in out["reasons"]) + out = quantity.plan(REGULAR, remaining_km=420, price_now=1.55, + historical_position=historical_position(0.10), + local_position=local_position(0.16), + outlook=dict(status='insufficient', reason='modèle non entraîné')) + assert out['action'] == 'wait' + assert out['litres_low'] is None + assert out['forecast_note'] == 'modèle non entraîné' + assert any('Position historique' in reason for reason in out['reasons']) + assert any('Position locale' in reason for reason in out['reasons']) def test_without_forecast_a_short_runway_still_buys_the_need_only(store): """Sans prévision, le besoin réel reste couvert — sans argument de prix.""" - out = quantity.plan( - REGULAR, - remaining_km=150, - price_now=1.55, - historical_position=historical_position(0.10), - outlook=dict(status="insufficient", reason="modèle non entraîné"), - ) - assert out["action"] == "topup" - assert out["horizon"] is None - assert out["forecast_note"] == "modèle non entraîné" - assert out["economy"].get("gain_high") is None + out = quantity.plan(REGULAR, remaining_km=150, price_now=1.55, historical_position=historical_position(0.10), + outlook=dict(status='insufficient', reason='modèle non entraîné')) + assert out['action'] == 'topup' + assert out['horizon'] is None + assert out['forecast_note'] == 'modèle non entraîné' + assert out['economy'].get('gain_high') is None def test_low_confidence_forecast_does_not_drive_the_quantity(): - out = quantity.plan( - REGULAR, - remaining_km=150, - price_now=1.55, - historical_position=historical_position(0.10), - outlook=outlook_down(confidence=0.40), - ) - assert out["horizon"] is None, "la prévision ne pilote pas la quantité sous le seuil" - assert out["action"] == "topup", "le besoin réel reste couvert" - assert "confiance 40%" in out["forecast_note"] - assert "seuil" in out["forecast_note"] + out = quantity.plan(REGULAR, remaining_km=150, price_now=1.55, historical_position=historical_position(0.10), + outlook=outlook_down(confidence=0.40)) + assert out['horizon'] is None, 'la prévision ne pilote pas la quantité sous le seuil' + assert out['action'] == 'topup', 'le besoin réel reste couvert' + assert 'confiance 40%' in out['forecast_note'] + assert 'seuil' in out['forecast_note'] def test_no_forecast_but_immediate_need_still_buys_what_is_needed(): - out = quantity.plan( - REGULAR, - remaining_km=110, - price_now=1.62, - historical_position=None, - outlook=dict(status="insufficient", reason="modèle non entraîné"), - ) - assert out["action"] == "topup" - assert out["litres_low"] >= 10.0 - assert any("Besoin de déplacement estimé" in reason for reason in out["reasons"]) + out = quantity.plan(REGULAR, remaining_km=110, price_now=1.62, historical_position=None, + outlook=dict(status='insufficient', reason='modèle non entraîné')) + assert out['action'] == 'topup' + assert out['litres_low'] >= 10.0 + assert any('Besoin de déplacement estimé' in reason for reason in out['reasons']) def test_margin_reached_recommends_refuelling_without_waiting(): - out = quantity.plan( - REGULAR, remaining_km=80, price_now=1.62, historical_position=None, outlook=outlook_down() - ) - assert out["action"] == "refuel" - assert any("marge minimale est atteinte" in reason for reason in out["reasons"]) + out = quantity.plan(REGULAR, remaining_km=80, price_now=1.62, historical_position=None, + outlook=outlook_down()) + assert out['action'] == 'refuel' + assert any('marge minimale est atteinte' in reason for reason in out['reasons']) def test_occasional_vehicle_uses_the_next_trip_only(store): - out = quantity.plan( - VAN, - remaining_km=280, - trip=dict(km=600, date="2026-10-01"), - outlook=dict(status="insufficient", reason="modèle non entraîné"), - ) - assert out["daily_km"] is None, "aucune moyenne mensuelle supposée" - assert out["action"] == "topup" - assert out["litres_low"] == 30.0 and out["litres_high"] == 35.0 - assert any("jamais sur une moyenne mensuelle" in caveat for caveat in out["caveats"]) - assert out["trip_km"] == 600 + out = quantity.plan(VAN, remaining_km=280, trip=dict(km=600, date='2026-10-01'), + outlook=dict(status='insufficient', reason='modèle non entraîné')) + assert out['daily_km'] is None, 'aucune moyenne mensuelle supposée' + assert out['action'] == 'topup' + assert out['litres_low'] == 30.0 and out['litres_high'] == 35.0 + assert any('jamais sur une moyenne mensuelle' in caveat for caveat in out['caveats']) + assert out['trip_km'] == 600 def test_occasional_vehicle_without_trip_asks_for_one(store): - out = quantity.plan( - VAN, remaining_km=280, trip=None, outlook=dict(status="insufficient", reason="modèle non entraîné") - ) - assert out["action"] == "none" - assert out["litres_low"] is None - assert any("prochain trajet" in reason for reason in out["reasons"]) + out = quantity.plan(VAN, remaining_km=280, trip=None, + outlook=dict(status='insufficient', reason='modèle non entraîné')) + assert out['action'] == 'none' + assert out['litres_low'] is None + assert any('prochain trajet' in reason for reason in out['reasons']) def test_occasional_vehicle_anticipates_before_a_rise_during_the_trip(store): - out = quantity.plan(VAN, remaining_km=280, trip=dict(km=600, date="2026-10-01"), outlook=outlook_up()) - assert any("anticiper le plein avant le départ" in caveat for caveat in out["caveats"]) + out = quantity.plan(VAN, remaining_km=280, trip=dict(km=600, date='2026-10-01'), + outlook=outlook_up()) + assert any('anticiper le plein avant le départ' in caveat for caveat in out['caveats']) def test_declared_tank_caps_the_quantity(store): - out = quantity.plan( - REGULAR, - remaining_km=780, - price_now=1.55, - historical_position=historical_position(0.10), - outlook=outlook_up(), - ) - assert out["action"] == "refill" - assert out["litres_target"] == pytest.approx(4.0, abs=0.5), "réservoir presque plein" + out = quantity.plan(REGULAR, remaining_km=780, price_now=1.55, historical_position=historical_position(0.10), + outlook=outlook_up()) + assert out['action'] == 'refill' + assert out['litres_target'] == pytest.approx(4.0, abs=0.5), 'réservoir presque plein' def test_missing_tank_is_declared_not_invented(store): vehicle = dict(REGULAR, tank_liters=None) - out = quantity.plan( - vehicle, - remaining_km=150, - price_now=1.62, - historical_position=historical_position(0.5), - outlook=outlook_down(), - ) - assert out["litres_target"] is not None - assert any("Capacité du réservoir non déclarée" in caveat for caveat in out["caveats"]) + out = quantity.plan(vehicle, remaining_km=150, price_now=1.62, historical_position=historical_position(0.5), + outlook=outlook_down()) + assert out['litres_target'] is not None + assert any('Capacité du réservoir non déclarée' in caveat for caveat in out['caveats']) def test_quantity_module_never_calls_a_language_model(): @@ -320,135 +204,89 @@ def test_quantity_module_never_calls_a_language_model(): Le module ne peut pas atteindre un modèle sans importer le client : c'est ce qu'on verrouille. """ - source = storage.__file__.rsplit("/", 1)[0] + "/quantity.py" - text = open(source, encoding="utf-8").read() - assert "import llm" not in text - assert "llm.extract" not in text and "llm.run" not in text + source = (storage.__file__.rsplit('/', 1)[0] + '/quantity.py') + text = open(source, encoding='utf-8').read() + assert 'import llm' not in text + assert 'llm.extract' not in text and 'llm.run' not in text def test_forecast_is_ignored_until_it_beats_the_naive_rule(store): import forecast - - storage.save_forecast( - dict( - fuel="Gazole", - direction="down", - change_low=-0.05, - change_high=-0.08, - days_min=3, - days_max=5, - confidence=0.8, - model="test-v1", - skill_vs_naive=0.001, - ) - ) - out = forecast.outlook("Gazole") - assert out["status"] == "insufficient" - assert "règle naïve" in out["reason"] - storage.save_forecast( - dict( - fuel="Gazole", - direction="down", - change_low=-0.05, - change_high=-0.08, - days_min=3, - days_max=5, - confidence=0.8, - model="test-v2", - skill_vs_naive=0.15, - ) - ) - out = forecast.outlook("Gazole") - assert out["status"] == "ok" and out["direction"] == "down" and out["model"] == "test-v2" + storage.save_forecast(dict(fuel='Gazole', direction='down', change_low=-0.05, + change_high=-0.08, days_min=3, days_max=5, confidence=0.8, + model='test-v1', skill_vs_naive=0.001)) + out = forecast.outlook('Gazole') + assert out['status'] == 'insufficient' + assert 'règle naïve' in out['reason'] + storage.save_forecast(dict(fuel='Gazole', direction='down', change_low=-0.05, + change_high=-0.08, days_min=3, days_max=5, confidence=0.8, + model='test-v2', skill_vs_naive=0.15)) + out = forecast.outlook('Gazole') + assert out['status'] == 'ok' and out['direction'] == 'down' and out['model'] == 'test-v2' def test_absent_model_is_declared_absent(store): import forecast - - out = forecast.outlook("Gazole") - assert out["status"] == "insufficient" - assert "pas encore entraîné" in out["reason"] + out = forecast.outlook('Gazole') + assert out['status'] == 'insufficient' + assert 'pas encore entraîné' in out['reason'] def test_local_rank_never_triggers_a_full_tank(store): """Excellent localement mais cher dans le temps : aucune anticipation autorisée.""" - out = quantity.plan( - REGULAR, - remaining_km=200, - historical_position=historical_position(0.72), - local_position=local_position(0.01), - outlook=outlook_up(), - ) - assert out["action"] == "topup" - assert out["action"] != "refill" - assert any("n'est pas historiquement favorable" in reason for reason in out["reasons"]) - assert any("36 stations" in reason for reason in out["reasons"]) + out = quantity.plan(REGULAR, remaining_km=200, + historical_position=historical_position(0.72), + local_position=local_position(0.01), outlook=outlook_up()) + assert out['action'] == 'topup' + assert out['action'] != 'refill' + assert any("n'est pas historiquement favorable" in reason for reason in out['reasons']) + assert any('36 stations' in reason for reason in out['reasons']) def test_historical_rank_is_the_only_anticipation_trigger(store): - out = quantity.plan( - REGULAR, - remaining_km=200, - historical_position=historical_position(0.05), - local_position=local_position(0.90), - outlook=outlook_up(), - ) - assert out["action"] == "refill" - assert any("Position historique favorable" in reason for reason in out["reasons"]) - assert any("ne participe pas à cette décision" in caveat for caveat in out["caveats"]) + out = quantity.plan(REGULAR, remaining_km=200, + historical_position=historical_position(0.05), + local_position=local_position(0.90), outlook=outlook_up()) + assert out['action'] == 'refill' + assert any('Position historique favorable' in reason for reason in out['reasons']) + assert any('ne participe pas à cette décision' in caveat for caveat in out['caveats']) def test_detour_fuel_is_deducted_from_the_net_gain(store): """Un détour peut annuler une économie : le gain net doit le montrer.""" from quantity import detour_cost - detour = dict(extra_km=40.0, nearest_km=3.0, chosen_km=43.0) - detour["cost_eur"] = detour_cost(detour, REGULAR, 1.55) - assert detour["cost_eur"] == round(40 * 5 / 100 * 1.55, 2), "km × consommation × prix" - out = quantity.plan( - REGULAR, - remaining_km=200, - price_now=1.55, - historical_position=historical_position(0.05), - local_position=local_position(0.9), - outlook=outlook_up(), - detour=detour, - ) - assert out["economy"]["detour_eur"] == detour["cost_eur"] - assert out["economy"]["net_high"] == round(out["economy"]["gain_high"] - detour["cost_eur"], 2) - assert out["economy"]["worth_it"] is False, "gain net sous le seuil : pas un passage de plus" - assert any("Gain net faible" in caveat for caveat in out["caveats"]) + detour['cost_eur'] = detour_cost(detour, REGULAR, 1.55) + assert detour['cost_eur'] == round(40 * 5 / 100 * 1.55, 2), 'km × consommation × prix' + out = quantity.plan(REGULAR, remaining_km=200, price_now=1.55, + historical_position=historical_position(0.05), + local_position=local_position(0.9), outlook=outlook_up(), detour=detour) + assert out['economy']['detour_eur'] == detour['cost_eur'] + assert out['economy']['net_high'] == round(out['economy']['gain_high'] - detour['cost_eur'], 2) + assert out['economy']['worth_it'] is False, 'gain net sous le seuil : pas un passage de plus' + assert any('Gain net faible' in caveat for caveat in out['caveats']) def test_a_small_detour_can_be_absorbed_by_the_expected_gain(store): from quantity import detour_cost - detour = dict(extra_km=2.0, nearest_km=3.0, chosen_km=5.0) - detour["cost_eur"] = detour_cost(detour, REGULAR, 1.55) - out = quantity.plan( - REGULAR, - remaining_km=200, - price_now=1.55, - historical_position=historical_position(0.05), - local_position=local_position(0.9), - outlook=outlook_up(), - detour=detour, - ) - assert out["economy"]["worth_it"] is True - assert out["economy"]["net_high"] > out["economy"]["gain_high"] - 1.0 + detour['cost_eur'] = detour_cost(detour, REGULAR, 1.55) + out = quantity.plan(REGULAR, remaining_km=200, price_now=1.55, + historical_position=historical_position(0.05), + local_position=local_position(0.9), outlook=outlook_up(), detour=detour) + assert out['economy']['worth_it'] is True + assert out['economy']['net_high'] > out['economy']['gain_high'] - 1.0 def test_detour_cost_is_computed_by_the_engine(store): from quantity import detour_cost - assert detour_cost(None, REGULAR, 2.0) is None assert detour_cost(dict(extra_km=0.0), REGULAR, 2.0) == 0.0 - assert detour_cost(dict(extra_km=10.0), REGULAR, 2.0) == 1.0, "10 km × 5 L/100 × 2 €/L" + assert detour_cost(dict(extra_km=10.0), REGULAR, 2.0) == 1.0, '10 km × 5 L/100 × 2 €/L' def test_tank_content_is_always_an_estimate(store): - out = quantity.plan( - REGULAR, remaining_km=150, historical_position=historical_position(0.5), outlook=outlook_down() - ) - assert out["estimated_in_tank_liters"] == 7.5, "estimation issue de l’autonomie affichée" - assert any("estimé" in caveat or "estimation" in caveat for caveat in out["caveats"]) + out = quantity.plan(REGULAR, remaining_km=150, historical_position=historical_position(0.5), + outlook=outlook_down()) + assert out['estimated_in_tank_liters'] == 7.5, 'estimation issue de l’autonomie affichée' + assert any('estimé' in caveat or 'estimation' in caveat for caveat in out['caveats']) diff --git a/tests/test_routes_cache.py b/tests/test_routes_cache.py index c374f65..354516e 100644 --- a/tests/test_routes_cache.py +++ b/tests/test_routes_cache.py @@ -1,5 +1,4 @@ """Cache de routes : origine normalisée, rattachement au favori, séparation statique / trafic.""" - from datetime import datetime, timedelta, timezone import pytest @@ -15,11 +14,11 @@ def meters_between(origin, other): def test_gps_jitter_of_a_few_dozens_of_meters_shares_one_cache_key(store): target = (44.795280, -0.604509) first = (44.78060, -0.57060) - second = (44.78063, -0.57064) # ~5 m plus loin : bruit normal d'une mesure téléphone - third = (44.78110, -0.57110) # ~70 m plus loin + second = (44.78063, -0.57064) # ~5 m plus loin : bruit normal d'une mesure téléphone + third = (44.78110, -0.57110) # ~70 m plus loin assert meters_between(first, second) < 10 keys = {storage.route_key(point, target) for point in (first, second, third)} - assert len(keys) == 1, f"positions quasi identiques, clés distinctes : {keys}" + assert len(keys) == 1, f'positions quasi identiques, clés distinctes : {keys}' def test_two_positions_hundreds_of_meters_apart_use_distinct_keys(store): @@ -38,89 +37,77 @@ def test_distinct_stations_never_share_a_key(store): def test_favourite_tag_replaces_raw_coordinates(store): target = (44.795280, -0.604509) - key = storage.route_key((44.78055, -0.57051), target, origin_tag="fav:3") - assert key.startswith("fav:3|") - assert storage.route_key((44.79999, -0.57051), target, origin_tag="fav:3") == key + key = storage.route_key((44.78055, -0.57051), target, origin_tag='fav:3') + assert key.startswith('fav:3|') + assert storage.route_key((44.79999, -0.57051), target, origin_tag='fav:3') == key def test_match_favorite_absorbs_gps_jitter(store): - storage.save_entity("favorites", dict(name="Villenave", lat=44.78060, lon=-0.57060, radius_km=10)) + storage.save_entity('favorites', dict(name='Villenave', lat=44.78060, lon=-0.57060, radius_km=10)) favorite = storage.match_favorite(44.78068, -0.57070) - assert favorite and favorite["name"] == "Villenave" - assert favorite["distance_km"] <= 0.15 + assert favorite and favorite['name'] == 'Villenave' + assert favorite['distance_km'] <= 0.15 assert storage.match_favorite(44.90000, -0.57070) is None def test_osrm_duration_is_static_and_never_an_eta(store, monkeypatch): - monkeypatch.setitem( - routing.PROVIDERS, - "osrm", - lambda origin, targets: { - t[0]: dict(distance_m=5000.0, duration_s=600.0, duration_kind=routing.STATIC) for t in targets - }, - ) - monkeypatch.setenv("FUEL_ROUTING_PROVIDERS", "osrm") - routes, info = routing.routes((44.78, -0.57), [("A", 44.79, -0.60)]) - assert routes["A"]["duration_kind"] == routing.STATIC - assert routes["A"]["duration_label"] == "hors trafic" - assert routes["A"]["eta_min"] is None - assert info["eta_count"] == 0 - assert "hors trafic" in info["eta_note"] + monkeypatch.setitem(routing.PROVIDERS, 'osrm', + lambda origin, targets: {t[0]: dict(distance_m=5000.0, duration_s=600.0, + duration_kind=routing.STATIC) + for t in targets}) + monkeypatch.setenv('FUEL_ROUTING_PROVIDERS', 'osrm') + routes, info = routing.routes((44.78, -0.57), [('A', 44.79, -0.60)]) + assert routes['A']['duration_kind'] == routing.STATIC + assert routes['A']['duration_label'] == 'hors trafic' + assert routes['A']['eta_min'] is None + assert info['eta_count'] == 0 + assert 'hors trafic' in info['eta_note'] assert store.eta_lookup([storage.route_key((44.78, -0.57), (44.79, -0.60))]) == {} def test_google_traffic_duration_goes_to_short_cache_only(store, monkeypatch): - monkeypatch.setattr(routing, "GOOGLE_KEY", "clé-de-test") - monkeypatch.setitem( - routing.PROVIDERS, - "google", - lambda origin, targets: { - t[0]: dict(distance_m=8000.0, duration_s=900.0, duration_kind=routing.TRAFFIC) for t in targets - }, - ) - monkeypatch.setenv("FUEL_ROUTING_PROVIDERS", "google") - routes, info = routing.routes((44.78, -0.57), [("A", 44.79, -0.60)]) - assert routes["A"]["distance_km"] == pytest.approx(8.0) - assert routes["A"]["duration_min"] is None, "une durée de trafic n’est pas une durée statique" - assert routes["A"]["eta_min"] == pytest.approx(15.0) - assert routes["A"]["eta_age_seconds"] is not None - assert info["eta_count"] == 1 and info["eta_provider"] == "google" + monkeypatch.setattr(routing, 'GOOGLE_KEY', 'clé-de-test') + monkeypatch.setitem(routing.PROVIDERS, 'google', + lambda origin, targets: {t[0]: dict(distance_m=8000.0, duration_s=900.0, + duration_kind=routing.TRAFFIC) + for t in targets}) + monkeypatch.setenv('FUEL_ROUTING_PROVIDERS', 'google') + routes, info = routing.routes((44.78, -0.57), [('A', 44.79, -0.60)]) + assert routes['A']['distance_km'] == pytest.approx(8.0) + assert routes['A']['duration_min'] is None, 'une durée de trafic n’est pas une durée statique' + assert routes['A']['eta_min'] == pytest.approx(15.0) + assert routes['A']['eta_age_seconds'] is not None + assert info['eta_count'] == 1 and info['eta_provider'] == 'google' cached = store.route_lookup([storage.route_key((44.78, -0.57), (44.79, -0.60))]) - assert list(cached.values())[0]["duration_s"] is None, "pas de durée trafic dans le cache long" + assert list(cached.values())[0]['duration_s'] is None, 'pas de durée trafic dans le cache long' def test_stale_eta_is_ignored_and_static_duration_is_used(store, monkeypatch): - monkeypatch.setattr(routing, "GOOGLE_KEY", "clé-de-test") - monkeypatch.setitem( - routing.PROVIDERS, - "google", - lambda origin, targets: { - t[0]: dict(distance_m=8000.0, duration_s=900.0, duration_kind=routing.TRAFFIC) for t in targets - }, - ) - monkeypatch.setenv("FUEL_ROUTING_PROVIDERS", "google") - routing.routes((44.78, -0.57), [("A", 44.79, -0.60)]) + monkeypatch.setattr(routing, 'GOOGLE_KEY', 'clé-de-test') + monkeypatch.setitem(routing.PROVIDERS, 'google', + lambda origin, targets: {t[0]: dict(distance_m=8000.0, duration_s=900.0, + duration_kind=routing.TRAFFIC) + for t in targets}) + monkeypatch.setenv('FUEL_ROUTING_PROVIDERS', 'google') + routing.routes((44.78, -0.57), [('A', 44.79, -0.60)]) key = storage.route_key((44.78, -0.57), (44.79, -0.60)) stale = (datetime.now(timezone.utc) - timedelta(hours=3)).isoformat() - store.eta_save([dict(key=key, duration_s=1800.0, provider="google")]) + store.eta_save([dict(key=key, duration_s=1800.0, provider='google')]) with store.connect() as db: - db.execute("UPDATE route_eta SET computed_at=? WHERE key=?", (stale, key)) - routes, info = routing.routes((44.78, -0.57), [("A", 44.79, -0.60)], eta_ttl=900) - assert routes["A"]["eta_min"] is None, "une ETA de 3 heures n’est pas une ETA actuelle" - assert info["eta_count"] == 0 - assert "Aucune ETA de trafic" in info["eta_note"] + db.execute('UPDATE route_eta SET computed_at=? WHERE key=?', (stale, key)) + routes, info = routing.routes((44.78, -0.57), [('A', 44.79, -0.60)], eta_ttl=900) + assert routes['A']['eta_min'] is None, 'une ETA de 3 heures n’est pas une ETA actuelle' + assert info['eta_count'] == 0 + assert 'Aucune ETA de trafic' in info['eta_note'] def test_eta_key_is_separate_for_tagged_origin(store, monkeypatch): - monkeypatch.setattr(routing, "GOOGLE_KEY", "clé-de-test") - monkeypatch.setitem( - routing.PROVIDERS, - "google", - lambda origin, targets: { - t[0]: dict(distance_m=4000.0, duration_s=600.0, duration_kind=routing.TRAFFIC) for t in targets - }, - ) - monkeypatch.setenv("FUEL_ROUTING_PROVIDERS", "google") - _, info = routing.routes((44.78, -0.57), [("A", 44.79, -0.60)], origin_tag="fav:7") - assert info["eta_count"] == 1 - assert store.eta_lookup(["fav:7|44.7900|-0.6000"]) != {} + monkeypatch.setattr(routing, 'GOOGLE_KEY', 'clé-de-test') + monkeypatch.setitem(routing.PROVIDERS, 'google', + lambda origin, targets: {t[0]: dict(distance_m=4000.0, duration_s=600.0, + duration_kind=routing.TRAFFIC) + for t in targets}) + monkeypatch.setenv('FUEL_ROUTING_PROVIDERS', 'google') + _, info = routing.routes((44.78, -0.57), [('A', 44.79, -0.60)], origin_tag='fav:7') + assert info['eta_count'] == 1 + assert store.eta_lookup(['fav:7|44.7900|-0.6000']) != {} diff --git a/tests/test_routing.py b/tests/test_routing.py index 43627cf..deefb83 100644 --- a/tests/test_routing.py +++ b/tests/test_routing.py @@ -1,5 +1,4 @@ """Distances routières : fournisseurs, cache, application du rayon, liens de navigation.""" - import json import pytest @@ -9,69 +8,55 @@ import routing import storage -def station_row(station_id, lat, lon, price=1.9, fuel="Gazole"): - return dict( - id=station_id, - name=f"Station {station_id}", - address="Rue", - city="Nantes", - lat=lat, - lon=lon, - prices={fuel: price}, - updates={fuel: "2026-09-12 08:00:00"}, - road="", - ) +def station_row(station_id, lat, lon, price=1.9, fuel='Gazole'): + return dict(id=station_id, name=f'Station {station_id}', address='Rue', city='Nantes', + lat=lat, lon=lon, prices={fuel: price}, updates={fuel: '2026-09-12 08:00:00'}, + road='') def test_provider_order_skips_google_without_key(monkeypatch): - monkeypatch.delenv("FUEL_GOOGLE_MAPS_API_KEY", raising=False) - monkeypatch.setattr(routing, "GOOGLE_KEY", "") - assert routing.provider_order() == ["osrm"] - monkeypatch.setenv("FUEL_ROUTING_PROVIDERS", "google,osrm") - assert routing.provider_order() == ["osrm"], "Google sans clé ne doit jamais être tenté" - monkeypatch.setattr(routing, "GOOGLE_KEY", "clé-de-test") - assert routing.provider_order() == ["google", "osrm"] + monkeypatch.delenv('FUEL_GOOGLE_MAPS_API_KEY', raising=False) + monkeypatch.setattr(routing, 'GOOGLE_KEY', '') + assert routing.provider_order() == ['osrm'] + monkeypatch.setenv('FUEL_ROUTING_PROVIDERS', 'google,osrm') + assert routing.provider_order() == ['osrm'], 'Google sans clé ne doit jamais être tenté' + monkeypatch.setattr(routing, 'GOOGLE_KEY', 'clé-de-test') + assert routing.provider_order() == ['google', 'osrm'] def test_provider_osrm_parses_table_and_drops_unreachable(monkeypatch): - payload = json.dumps( - {"code": "Ok", "distances": [[0, 3699.3, None]], "durations": [[0, 580.3, None]]} - ).encode() - monkeypatch.setattr(routing, "_get", lambda *args, **kwargs: payload) - found = routing.provider_osrm((48.85, 2.35), [("A", 48.86, 2.30), ("B", 48.90, 2.25)]) - assert found["A"]["distance_m"] == pytest.approx(3699.3) - assert found["A"]["duration_s"] == pytest.approx(580.3) - assert "B" not in found, "aucune route : la station n’est pas estimée" + payload = json.dumps({'code': 'Ok', 'distances': [[0, 3699.3, None]], + 'durations': [[0, 580.3, None]]}).encode() + monkeypatch.setattr(routing, '_get', lambda *args, **kwargs: payload) + found = routing.provider_osrm((48.85, 2.35), [('A', 48.86, 2.30), ('B', 48.90, 2.25)]) + assert found['A']['distance_m'] == pytest.approx(3699.3) + assert found['A']['duration_s'] == pytest.approx(580.3) + assert 'B' not in found, 'aucune route : la station n’est pas estimée' def test_provider_google_requires_key_and_parses_matrix(monkeypatch): - monkeypatch.setattr(routing, "GOOGLE_KEY", "") + monkeypatch.setattr(routing, 'GOOGLE_KEY', '') with pytest.raises(ValueError): - routing.provider_google((48.85, 2.35), [("A", 48.86, 2.30)]) + routing.provider_google((48.85, 2.35), [('A', 48.86, 2.30)]) captured = {} def fake_get(url, timeout=None, data=None, headers=None): - captured["url"], captured["body"] = url, json.loads(data or b"{}") - return json.dumps( - [ - { - "destinationIndex": 0, - "condition": "ROUTE_EXISTS", - "distanceMeters": 4200, - "duration": "720s", - }, - {"destinationIndex": 1, "condition": "ROUTE_NOT_FOUND"}, - ] - ).encode() + captured['url'], captured['body'] = url, json.loads(data or b'{}') + return json.dumps([ + {'destinationIndex': 0, 'condition': 'ROUTE_EXISTS', 'distanceMeters': 4200, + 'duration': '720s'}, + {'destinationIndex': 1, 'condition': 'ROUTE_NOT_FOUND'}, + ]).encode() - monkeypatch.setattr(routing, "GOOGLE_KEY", "clé-de-test") - monkeypatch.setattr(routing, "_get", fake_get) - found = routing.provider_google((48.85, 2.35), [("A", 48.86, 2.30), ("B", 48.90, 2.25)]) - assert "computeRouteMatrix" in captured["url"] - assert captured["url"] == "https://routes.googleapis.com/distanceMatrix/v2:computeRouteMatrix" - assert len(captured["body"]["destinations"]) == 2 - assert captured["body"]["travelMode"] == "DRIVE" - assert found == {"A": dict(distance_m=4200.0, duration_s=720.0, duration_kind=routing.TRAFFIC)} + monkeypatch.setattr(routing, 'GOOGLE_KEY', 'clé-de-test') + monkeypatch.setattr(routing, '_get', fake_get) + found = routing.provider_google((48.85, 2.35), [('A', 48.86, 2.30), ('B', 48.90, 2.25)]) + assert 'computeRouteMatrix' in captured['url'] + assert captured['url'] == 'https://routes.googleapis.com/distanceMatrix/v2:computeRouteMatrix' + assert len(captured['body']['destinations']) == 2 + assert captured['body']['travelMode'] == 'DRIVE' + assert found == {'A': dict(distance_m=4200.0, duration_s=720.0, + duration_kind=routing.TRAFFIC)} def test_routes_uses_cache_then_provider(store, monkeypatch): @@ -81,105 +66,83 @@ def test_routes_uses_cache_then_provider(store, monkeypatch): calls.append(targets) return {station_id: dict(distance_m=5000.0, duration_s=600.0) for station_id, _a, _b in targets} - monkeypatch.setitem(routing.PROVIDERS, "osrm", fake_provider) - monkeypatch.setenv("FUEL_ROUTING_PROVIDERS", "osrm") + monkeypatch.setitem(routing.PROVIDERS, 'osrm', fake_provider) + monkeypatch.setenv('FUEL_ROUTING_PROVIDERS', 'osrm') origin = (48.85, 2.35) - targets = [("A", 48.86, 2.30)] + targets = [('A', 48.86, 2.30)] first, info = routing.routes(origin, targets) - assert first["A"]["distance_km"] == pytest.approx(5.0) - assert first["A"]["duration_min"] == pytest.approx(10.0) - assert info["provider"] == "osrm" and info["computed"] == 1 and info["from_cache"] == 0 + assert first['A']['distance_km'] == pytest.approx(5.0) + assert first['A']['duration_min'] == pytest.approx(10.0) + assert info['provider'] == 'osrm' and info['computed'] == 1 and info['from_cache'] == 0 second, info2 = routing.routes(origin, targets) - assert info2["from_cache"] == 1 and info2["computed"] == 0 - assert len(calls) == 1, "la seconde demande ne doit pas rappeler le fournisseur" + assert info2['from_cache'] == 1 and info2['computed'] == 0 + assert len(calls) == 1, 'la seconde demande ne doit pas rappeler le fournisseur' assert store.route_lookup([storage.route_key(origin, (48.86, 2.30))], max_age_days=1) def test_routes_without_provider_says_so_and_invents_nothing(store, monkeypatch): - monkeypatch.setattr(routing, "PROVIDERS", {}) - monkeypatch.setenv("FUEL_ROUTING_PROVIDERS", "google") - monkeypatch.setattr(routing, "GOOGLE_KEY", "") - routes, info = routing.routes((48.85, 2.35), [("A", 48.86, 2.30)]) + monkeypatch.setattr(routing, 'PROVIDERS', {}) + monkeypatch.setenv('FUEL_ROUTING_PROVIDERS', 'google') + monkeypatch.setattr(routing, 'GOOGLE_KEY', '') + routes, info = routing.routes((48.85, 2.35), [('A', 48.86, 2.30)]) assert routes == {} - assert info["provider"] == "none" - assert "à vol d’oiseau" in info["note"] + assert info['provider'] == 'none' + assert 'à vol d’oiseau' in info['note'] def test_nearest_stations_applies_radius_on_road_distance(store, monkeypatch): - rows = [ - station_row("proche", 48.8610, 2.3010, price=1.95), - station_row("loin", 48.9000, 2.2500, price=1.80), - station_row("hors", 49.2000, 2.6000, price=1.70), - ] - monkeypatch.setattr(app, "load_fuel_data", lambda **kwargs: rows) + rows = [station_row('proche', 48.8610, 2.3010, price=1.95), + station_row('loin', 48.9000, 2.2500, price=1.80), + station_row('hors', 49.2000, 2.6000, price=1.70)] + monkeypatch.setattr(app, 'load_fuel_data', lambda **kwargs: rows) def fake_routes(origin, targets, origin_tag=None, **kwargs): - distances = {"proche": 1200.0, "loin": 18500.0, "hors": 40000.0} - return ( - { - station_id: dict( - distance_km=distances[station_id] / 1000, - duration_min=5.0, - duration_label="hors trafic", - provider="osrm", - cached=False, - ) - for station_id, _lat, _lon in targets - }, - dict(provider="osrm", computed=len(targets), from_cache=0, failures=[], note=""), - ) + distances = {'proche': 1200.0, 'loin': 18500.0, 'hors': 40000.0} + return ({station_id: dict(distance_km=distances[station_id] / 1000, duration_min=5.0, + duration_label='hors trafic', provider='osrm', cached=False) + for station_id, _lat, _lon in targets}, + dict(provider='osrm', computed=len(targets), from_cache=0, failures=[], note='')) - monkeypatch.setattr(routing, "routes", fake_routes) - stations, info = app.nearest_stations(48.86, 2.30, "Gazole", 15) - assert [s.id for s in stations] == ["proche"], "rayon de 15 km appliqué à la distance routière" + monkeypatch.setattr(routing, 'routes', fake_routes) + stations, info = app.nearest_stations(48.86, 2.30, 'Gazole', 15) + assert [s.id for s in stations] == ['proche'], 'rayon de 15 km appliqué à la distance routière' assert stations[0].route_distance_km == pytest.approx(1.2) assert stations[0].route_duration_min == pytest.approx(5.0) - assert stations[0].distance_km < 1, "le vol d’oiseau reste disponible en interne" - assert info["provider"] == "osrm" + assert stations[0].distance_km < 1, 'le vol d’oiseau reste disponible en interne' + assert info['provider'] == 'osrm' def test_nearest_stations_without_routing_falls_back_and_says_it(store, monkeypatch): - rows = [station_row("proche", 48.8610, 2.3010), station_row("hors", 49.1000, 2.5000)] - monkeypatch.setattr(app, "load_fuel_data", lambda **kwargs: rows) - monkeypatch.setattr( - routing, - "routes", - lambda *args, **kwargs: ( - {}, - dict(provider="none", computed=0, from_cache=0, failures=["TimeoutError"], note="indispo"), - ), - ) - stations, info = app.nearest_stations(48.86, 2.30, "Gazole", 5) - assert [s.id for s in stations] == ["proche"] + rows = [station_row('proche', 48.8610, 2.3010), station_row('hors', 49.1000, 2.5000)] + monkeypatch.setattr(app, 'load_fuel_data', lambda **kwargs: rows) + monkeypatch.setattr(routing, 'routes', lambda *args, **kwargs: ( + {}, dict(provider='none', computed=0, from_cache=0, failures=['TimeoutError'], note='indispo'))) + stations, info = app.nearest_stations(48.86, 2.30, 'Gazole', 5) + assert [s.id for s in stations] == ['proche'] assert stations[0].route_distance_km is None - assert info["provider"] == "none" + assert info['provider'] == 'none' def test_navigation_links_use_exact_coordinates(): links = app.navigation_links(48.861012, 2.301045) - assert links["coordinates"] == "48.861012,2.301045" - assert links["google_maps"].startswith("https://www.google.com/maps/dir/?api=1&destination=") - assert "48.861012,2.301045" in links["google_maps"] and "travelmode=driving" in links["google_maps"] - assert links["waze"].startswith("https://waze.com/ul?ll=48.861012,2.301045") + assert links['coordinates'] == '48.861012,2.301045' + assert links['google_maps'].startswith('https://www.google.com/maps/dir/?api=1&destination=') + assert '48.861012,2.301045' in links['google_maps'] and 'travelmode=driving' in links['google_maps'] + assert links['waze'].startswith('https://waze.com/ul?ll=48.861012,2.301045') def test_station_payload_carries_detour_ready_fields(store, monkeypatch): - monkeypatch.setattr(app, "load_fuel_data", lambda **kwargs: [station_row("A", 48.861, 2.301)]) - monkeypatch.setattr( - routing, - "routes", - lambda *args, **kwargs: ( - {"A": dict(distance_km=3.4, duration_min=8.0, provider="osrm", cached=False)}, - dict(provider="osrm", computed=1, from_cache=0, failures=[], note=""), - ), - ) - monkeypatch.setattr(app.collector, "ensure_fresh_local", lambda **kwargs: dict(refreshed=False)) - monkeypatch.setattr(app.promotions, "active", lambda: []) - monkeypatch.setattr(app, "load_fuel_data", lambda **kwargs: [station_row("A", 48.861, 2.301)]) - out = app.advice(48.86, 2.30, "Gazole", 15) - station = out["stations"][0] - assert station["route_distance_km"] == pytest.approx(3.4) - assert station["route_duration_min"] == pytest.approx(8.0) - assert station["navigation"]["waze"] - assert out["detour_prep"]["available"] is True - assert out["routing"]["provider"] == "osrm" + monkeypatch.setattr(app, 'load_fuel_data', lambda **kwargs: [station_row('A', 48.861, 2.301)]) + monkeypatch.setattr(routing, 'routes', lambda *args, **kwargs: ( + {'A': dict(distance_km=3.4, duration_min=8.0, provider='osrm', cached=False)}, + dict(provider='osrm', computed=1, from_cache=0, failures=[], note=''))) + monkeypatch.setattr(app.collector, 'ensure_fresh_local', lambda **kwargs: dict(refreshed=False)) + monkeypatch.setattr(app.promotions, 'active', lambda: []) + monkeypatch.setattr(app, 'load_fuel_data', lambda **kwargs: [station_row('A', 48.861, 2.301)]) + out = app.advice(48.86, 2.30, 'Gazole', 15) + station = out['stations'][0] + assert station['route_distance_km'] == pytest.approx(3.4) + assert station['route_duration_min'] == pytest.approx(8.0) + assert station['navigation']['waze'] + assert out['detour_prep']['available'] is True + assert out['routing']['provider'] == 'osrm' diff --git a/tests/test_scheduler.py b/tests/test_scheduler.py index e94583f..a0bb30a 100644 --- a/tests/test_scheduler.py +++ b/tests/test_scheduler.py @@ -1,5 +1,4 @@ """Ordonnanceur : cadences propres à chaque source, fenêtres, supervision, résilience.""" - from datetime import datetime, timedelta, timezone import collector @@ -8,91 +7,80 @@ import storage def test_registry_covers_every_source_with_its_own_cadence(): - expected = { - "local_prices", - "market_daily", - "ecb_fx", - "eu_bulletin", - "dgec_monthly", - "portwatch", - "news_geo", - "promotions", - } + expected = {'local_prices', 'market_daily', 'ecb_fx', 'eu_bulletin', 'dgec_monthly', + 'portwatch', 'news_geo', 'promotions'} assert expected <= set(scheduler.JOBS) for name, job in scheduler.JOBS.items(): - assert job["source"] and job["frequency"], name - assert job["cadence_seconds"] > 0, name - assert callable(job["window"]), name - assert hasattr(collector, job["func"]), name - assert scheduler.JOBS["local_prices"]["cadence_seconds"] == 3600, "prix locaux : toutes les heures" - assert scheduler.JOBS["news_geo"]["cadence_seconds"] == 7200, "actualités : toutes les 2 heures" + assert job['source'] and job['frequency'], name + assert job['cadence_seconds'] > 0, name + assert callable(job['window']), name + assert hasattr(collector, job['func']), name + assert scheduler.JOBS['local_prices']['cadence_seconds'] == 3600, 'prix locaux : toutes les heures' + assert scheduler.JOBS['news_geo']['cadence_seconds'] == 7200, 'actualités : toutes les 2 heures' def test_job_is_due_only_within_its_window(store, monkeypatch): - monkeypatch.setattr(scheduler, "JOBS", dict(scheduler.JOBS, ecb_fx=dict(scheduler.JOBS["ecb_fx"]))) + monkeypatch.setattr(scheduler, 'JOBS', dict( + scheduler.JOBS, ecb_fx=dict(scheduler.JOBS['ecb_fx']))) saturday = datetime(2026, 9, 12, 17, 0, tzinfo=timezone.utc) # samedi 19 h à Paris monday_morning = datetime(2026, 9, 14, 8, 0, tzinfo=timezone.utc) # lundi 10 h monday_evening = datetime(2026, 9, 14, 14, 30, tzinfo=timezone.utc) # lundi 16 h 30 - assert scheduler.is_due("ecb_fx", now=monday_evening) is True - assert scheduler.is_due("ecb_fx", now=saturday) is False - assert scheduler.is_due("ecb_fx", now=monday_morning) is False - assert scheduler.is_due("local_prices", now=saturday) is True + assert scheduler.is_due('ecb_fx', now=monday_evening) is True + assert scheduler.is_due('ecb_fx', now=saturday) is False + assert scheduler.is_due('ecb_fx', now=monday_morning) is False + assert scheduler.is_due('local_prices', now=saturday) is True def test_cadence_and_retry_after_failure(store): now = datetime(2026, 9, 14, 12, 0, tzinfo=timezone.utc) - storage.job_record("news_geo", "src", "freq", 7200, "ok", now=now) - assert scheduler.is_due("news_geo", now=now + timedelta(minutes=30)) is False - assert scheduler.is_due("news_geo", now=now + timedelta(hours=2)) is True - storage.job_record("news_geo", "src", "freq", 7200, "error", now=now) - assert scheduler.is_due("news_geo", now=now + timedelta(minutes=31)) is True, "réessai après échec" + storage.job_record('news_geo', 'src', 'freq', 7200, 'ok', now=now) + assert scheduler.is_due('news_geo', now=now + timedelta(minutes=30)) is False + assert scheduler.is_due('news_geo', now=now + timedelta(hours=2)) is True + storage.job_record('news_geo', 'src', 'freq', 7200, 'error', now=now) + assert scheduler.is_due('news_geo', now=now + timedelta(minutes=31)) is True, 'réessai après échec' def test_next_run_respects_window(store): sunday = datetime(2026, 9, 13, 10, 0, tzinfo=timezone.utc) # dimanche - upcoming = scheduler.next_run("eu_bulletin", now=sunday) - assert datetime.fromisoformat(upcoming).astimezone(storage.PARIS).weekday() == 3, "jeudi" + upcoming = scheduler.next_run('eu_bulletin', now=sunday) + assert datetime.fromisoformat(upcoming).astimezone(storage.PARIS).weekday() == 3, 'jeudi' def test_run_records_supervision_and_survives_failures(store, monkeypatch): calls = [] def good(force=False): - calls.append("local_prices") - return dict(status="ok", stored=3, last_observation_at="2026-09-12T18:00:00", detail="3 changements") + calls.append('local_prices') + return dict(status='ok', stored=3, last_observation_at='2026-09-12T18:00:00', + detail='3 changements') def broken(force=False): - calls.append("portwatch") - raise OSError("source hors ligne") + calls.append('portwatch') + raise OSError('source hors ligne') - monkeypatch.setattr(collector, "job_local_prices", good) - monkeypatch.setattr(collector, "job_portwatch", broken) - monkeypatch.setattr( - scheduler, - "JOBS", - { - name: dict(scheduler.JOBS[name], window=lambda now=None: True) - for name in ("local_prices", "portwatch") - }, - ) - outcome = scheduler.run(names=["local_prices", "portwatch"], force=True) - assert outcome["status"] == "ok" - assert outcome["results"]["local_prices"]["status"] == "ok" - assert outcome["results"]["portwatch"]["status"] == "error" - assert "job_local_prices" not in str(outcome) - state = storage.job_get("local_prices") - assert state["status"] == "ok" and state["stored"] == 3 - assert state["last_observation_at"] == "2026-09-12T18:00:00" - assert state["last_success_at"] and state["next_run_at"] - failed = storage.job_get("portwatch") - assert failed["status"] == "error" and failed["fail_count"] == 1 - assert "OSError" in failed["detail"] + monkeypatch.setattr(collector, 'job_local_prices', good) + monkeypatch.setattr(collector, 'job_portwatch', broken) + monkeypatch.setattr(scheduler, 'JOBS', { + name: dict(scheduler.JOBS[name], window=lambda now=None: True) + for name in ('local_prices', 'portwatch')}) + outcome = scheduler.run(names=['local_prices', 'portwatch'], force=True) + assert outcome['status'] == 'ok' + assert outcome['results']['local_prices']['status'] == 'ok' + assert outcome['results']['portwatch']['status'] == 'error' + assert 'job_local_prices' not in str(outcome) + state = storage.job_get('local_prices') + assert state['status'] == 'ok' and state['stored'] == 3 + assert state['last_observation_at'] == '2026-09-12T18:00:00' + assert state['last_success_at'] and state['next_run_at'] + failed = storage.job_get('portwatch') + assert failed['status'] == 'error' and failed['fail_count'] == 1 + assert 'OSError' in failed['detail'] def test_inventory_exposes_source_frequency_state_and_next_run(store): - rows = {row["name"]: row for row in scheduler.inventory()} - assert rows["local_prices"]["source"].startswith("prix-carburants.gouv.fr") - assert rows["eu_bulletin"]["frequency"].startswith("le jeudi") - assert rows["promotions"]["status"] == "never" - assert rows["dgec_monthly"]["next_run_at"] - assert "n’historise un événement" in rows["local_prices"]["note"] + rows = {row['name']: row for row in scheduler.inventory()} + assert rows['local_prices']['source'].startswith('prix-carburants.gouv.fr') + assert rows['eu_bulletin']['frequency'].startswith('le jeudi') + assert rows['promotions']['status'] == 'never' + assert rows['dgec_monthly']['next_run_at'] + assert 'n’historise un événement' in rows['local_prices']['note'] diff --git a/tests/test_series.py b/tests/test_series.py index 88702f3..4de899e 100644 --- a/tests/test_series.py +++ b/tests/test_series.py @@ -1,6 +1,5 @@ """Reconstruction du marché : la médiane ne doit pas basculer quand seules 3 stations déclarent.""" - -from datetime import date, timedelta +from datetime import timedelta import series import storage @@ -9,80 +8,70 @@ LAT, LON = 44.7737872, -0.5595029 def days_ago(n): - return (date.today() - timedelta(days=n)).isoformat() + """Même horloge que ``series`` (Paris) : un test ne doit pas dépendre du fuseau de la VM.""" + return (storage.datetime.now(storage.PARIS).date() - timedelta(days=n)).isoformat() def declare(store, station_id, fuel, day, price, lat=LAT, lon=LON): store.save_archive_observations( - [ - dict( - station_id=station_id, - fuel=fuel, - day=day, - price=price, - declared_at=f"{day}T09:00:00", - lat=lat, - lon=lon, - ) - ], - "archive:test", - ) + [dict(station_id=station_id, fuel=fuel, day=day, price=price, + declared_at=f'{day}T09:00:00', lat=lat, lon=lon)], 'archive:test') def test_median_uses_the_last_declared_price_not_only_today_s_changes(store): """30 stations à 1,90 € et 3 changements à 1,95 € : la médiane reste 1,90 €.""" for index in range(30): - declare(store, f"stable{index}", "Gazole", days_ago(10), 1.90) + declare(store, f'stable{index}', 'Gazole', days_ago(10), 1.90) for index in range(3): - declare(store, f"stable{index}", "Gazole", days_ago(0), 1.95) - reconstructed = series.active_series(LAT, LON, 15, "Gazole", days=15) - today = reconstructed["days"][-1] - assert len(today["active"]) == 30, "une seule entrée active par station" - assert today["declared_today"] == 3, "seules 3 stations ont déclaré aujourd’hui" - assert today["median"] == 1.90, "la médiane du marché ne doit pas devenir 1,95 €" - journal = store.price_journal("Gazole", days_ago(1), days_ago(0)) - naive = sorted(row["price"] for row in journal) - assert naive[len(naive) // 2] == 1.95, "calcul naïf (lignes du jour) : 1,95 € — c’est le piège" + declare(store, f'stable{index}', 'Gazole', days_ago(0), 1.95) + reconstructed = series.active_series(LAT, LON, 15, 'Gazole', days=15) + today = reconstructed['days'][-1] + assert len(today['active']) == 30, 'une seule entrée active par station' + assert today['declared_today'] == 3, 'seules 3 stations ont déclaré aujourd’hui' + assert today['median'] == 1.90, 'la médiane du marché ne doit pas devenir 1,95 €' + journal = store.price_journal('Gazole', days_ago(1), days_ago(0)) + naive = sorted(row['price'] for row in journal) + assert naive[len(naive) // 2] == 1.95, 'calcul naïf (lignes du jour) : 1,95 € — c’est le piège' def test_a_price_stays_active_until_the_next_declaration(store): - declare(store, "a", "Gazole", days_ago(5), 2.00) - declare(store, "b", "Gazole", days_ago(5), 2.10) - declare(store, "c", "Gazole", days_ago(5), 2.20) - declare(store, "a", "Gazole", days_ago(1), 2.50) - reconstructed = series.active_series(LAT, LON, 15, "Gazole", days=15) - by_day = {item["day"]: item for item in reconstructed["days"]} - assert by_day[days_ago(3)]["median"] == 2.10, "a est encore à 2,00 € avant sa nouvelle déclaration" - assert by_day[days_ago(0)]["median"] == 2.20, "après la déclaration de a à 2,50 €" + declare(store, 'a', 'Gazole', days_ago(5), 2.00) + declare(store, 'b', 'Gazole', days_ago(5), 2.10) + declare(store, 'c', 'Gazole', days_ago(5), 2.20) + declare(store, 'a', 'Gazole', days_ago(1), 2.50) + reconstructed = series.active_series(LAT, LON, 15, 'Gazole', days=15) + by_day = {item['day']: item for item in reconstructed['days']} + assert by_day[days_ago(3)]['median'] == 2.10, 'a est encore à 2,00 € avant sa nouvelle déclaration' + assert by_day[days_ago(0)]['median'] == 2.20, 'après la déclaration de a à 2,50 €' def test_stations_that_stopped_declaring_are_dropped(store): - declare(store, "muette", "Gazole", days_ago(45), 1.50) - declare(store, "actives1", "Gazole", days_ago(1), 2.00) - declare(store, "actives2", "Gazole", days_ago(1), 2.20) - declare(store, "actives3", "Gazole", days_ago(1), 2.10) - reconstructed = series.active_series(LAT, LON, 15, "Gazole", days=15, max_stale_days=30) - today = reconstructed["days"][-1] - assert {item["station_id"] for item in today["active"]} == {"actives1", "actives2", "actives3"} - assert today["median"] == 2.10 - assert reconstructed["stale_dropped"] > 0 - permissive = series.active_series(LAT, LON, 15, "Gazole", days=15, max_stale_days=90) - assert permissive["days"][-1]["stations"] == 4, "un seuil plus large la conserve" + declare(store, 'muette', 'Gazole', days_ago(45), 1.50) + declare(store, 'actives1', 'Gazole', days_ago(1), 2.00) + declare(store, 'actives2', 'Gazole', days_ago(1), 2.20) + declare(store, 'actives3', 'Gazole', days_ago(1), 2.10) + reconstructed = series.active_series(LAT, LON, 15, 'Gazole', days=15, max_stale_days=30) + today = reconstructed['days'][-1] + assert {item['station_id'] for item in today['active']} == {'actives1', 'actives2', 'actives3'} + assert today['median'] == 2.10 + assert reconstructed['stale_dropped'] > 0 + permissive = series.active_series(LAT, LON, 15, 'Gazole', days=15, max_stale_days=90) + assert permissive['days'][-1]['stations'] == 4, 'un seuil plus large la conserve' def test_matched_panel_ignores_opening_stations(store): """Six stations qui ouvrent à 1,00 € font chuter le niveau, pas l'indice comparable.""" - for name in ("a", "b", "c"): - declare(store, name, "Gazole", days_ago(7), 2.00) - declare(store, name, "Gazole", days_ago(0), 2.00) + for name in ('a', 'b', 'c'): + declare(store, name, 'Gazole', days_ago(7), 2.00) + declare(store, name, 'Gazole', days_ago(0), 2.00) for index in range(6): - declare(store, f"nouvelle{index}", "Gazole", days_ago(0), 1.00) - reconstructed = series.active_series(LAT, LON, 15, "Gazole", days=15) + declare(store, f'nouvelle{index}', 'Gazole', days_ago(0), 1.00) + reconstructed = series.active_series(LAT, LON, 15, 'Gazole', days=15) matched = series.matched_variation(reconstructed, horizon=7, min_pairs=3) - entry = [item for item in matched if item["day"] == days_ago(7)][0] - assert entry["matched_stations"] == 3, "seules les stations présentes aux deux dates" - assert entry["change_pct"] == 0.0, "aucune variation réelle : l’ouverture ne compte pas" - levels = {item["day"]: item["median"] for item in series.median_series(reconstructed)} + entry = [item for item in matched if item['day'] == days_ago(7)][0] + assert entry['matched_stations'] == 3, 'seules les stations présentes aux deux dates' + assert entry['change_pct'] == 0.0, 'aucune variation réelle : l’ouverture ne compte pas' + levels = {item['day']: item['median'] for item in series.median_series(reconstructed)} # Le niveau du marché, lui, bouge : six stations pas chères ont ouvert. C'est pourquoi les # variations utilisées par le modèle reposent sur le panel comparable, pas sur ce niveau. assert levels[days_ago(0)] == 1.00 @@ -90,58 +79,55 @@ def test_matched_panel_ignores_opening_stations(store): def test_matched_panel_detects_a_real_move(store): for index, (before, after) in enumerate(((2.00, 2.20), (2.00, 2.20), (2.00, 1.80))): - declare(store, f"station{index}", "Gazole", days_ago(7), before) - declare(store, f"station{index}", "Gazole", days_ago(0), after) - reconstructed = series.active_series(LAT, LON, 15, "Gazole", days=15) - entry = [ - item - for item in series.matched_variation(reconstructed, horizon=7, min_pairs=3) - if item["day"] == days_ago(7) - ][0] - assert entry["comparable"] is True - assert entry["change_pct"] == 10.0, "médiane des rapports : +10 %" + declare(store, f'station{index}', 'Gazole', days_ago(7), before) + declare(store, f'station{index}', 'Gazole', days_ago(0), after) + reconstructed = series.active_series(LAT, LON, 15, 'Gazole', days=15) + entry = [item for item in series.matched_variation(reconstructed, horizon=7, min_pairs=3) + if item['day'] == days_ago(7)][0] + assert entry['comparable'] is True + assert entry['change_pct'] == 10.0, 'médiane des rapports : +10 %' def test_matched_panel_refuses_a_thin_sample(store): - declare(store, "only", "Gazole", days_ago(7), 2.00) - declare(store, "only", "Gazole", days_ago(0), 2.20) - reconstructed = series.active_series(LAT, LON, 15, "Gazole", days=15) + declare(store, 'only', 'Gazole', days_ago(7), 2.00) + declare(store, 'only', 'Gazole', days_ago(0), 2.20) + reconstructed = series.active_series(LAT, LON, 15, 'Gazole', days=15) entry = series.matched_variation(reconstructed, horizon=7, min_pairs=3)[0] - assert entry["comparable"] is False - assert entry["change_pct"] is None + assert entry['comparable'] is False + assert entry['change_pct'] is None def test_reconstructed_series_is_what_the_percentiles_use(store): """Le percentile doit porter sur la série reconstruite, pas sur les seules lignes du jour.""" for index in range(10): - declare(store, f"stable{index}", "Gazole", days_ago(20), 1.90) + declare(store, f'stable{index}', 'Gazole', days_ago(20), 1.90) for offset in range(19, 0, -1): - declare(store, f"stable{offset % 10}", "Gazole", days_ago(offset), 1.95) + declare(store, f'stable{offset % 10}', 'Gazole', days_ago(offset), 1.95) for index in range(2): - declare(store, f"stable{index}", "Gazole", days_ago(0), 2.20) - position = storage.historical_position(LAT, LON, 15, "Gazole", windows=(30,)) - assert position["current"] == 1.95, "médiane reconstruite, pas les 2,20 € du jour" - assert position["windows"]["30"]["percentile"] is not None - assert "aucune interpolation" in position["basis"] - assert position["reconstruction"]["max_stale_days"] == series.MAX_STALE_DAYS + declare(store, f'stable{index}', 'Gazole', days_ago(0), 2.20) + position = storage.historical_position(LAT, LON, 15, 'Gazole', windows=(30,)) + assert position['current'] == 1.95, 'médiane reconstruite, pas les 2,20 € du jour' + assert position['windows']['30']['percentile'] is not None + assert 'aucune interpolation' in position['basis'] + assert position['reconstruction']['max_stale_days'] == series.MAX_STALE_DAYS def test_targets_are_built_on_the_matched_panel(store): for index in range(4): - declare(store, f"station{index}", "Gazole", days_ago(20), 2.00) - declare(store, f"station{index}", "Gazole", days_ago(13), 2.10) - declare(store, "nouvelle", "Gazole", days_ago(13), 1.00) - out = series.targets(LAT, LON, 15, "Gazole", horizons=(7,), days=30) - entries = {item["day"]: item for item in out[7]} - assert entries[days_ago(20)]["change_pct"] == 5.0 - assert entries[days_ago(20)]["matched_stations"] == 4 + declare(store, f'station{index}', 'Gazole', days_ago(20), 2.00) + declare(store, f'station{index}', 'Gazole', days_ago(13), 2.10) + declare(store, 'nouvelle', 'Gazole', days_ago(13), 1.00) + out = series.targets(LAT, LON, 15, 'Gazole', horizons=(7,), days=30) + entries = {item['day']: item for item in out[7]} + assert entries[days_ago(20)]['change_pct'] == 5.0 + assert entries[days_ago(20)]['matched_stations'] == 4 def test_freshness_report_summarises_the_reconstruction(store): for index in range(5): - declare(store, f"station{index}", "Gazole", days_ago(1), 2.00) - reconstructed = series.active_series(LAT, LON, 15, "Gazole", days=15) + declare(store, f'station{index}', 'Gazole', days_ago(1), 2.00) + reconstructed = series.active_series(LAT, LON, 15, 'Gazole', days=15) report = series.freshness_report(reconstructed) - assert report["days"] == 16 - assert report["median_stations"] == 5 - assert report["share_declaring"] is not None + assert report['days'] == 16 + assert report['median_stations'] == 5 + assert report['share_declaring'] is not None diff --git a/tests/test_station_names.py b/tests/test_station_names.py index d9e9cd8..c689694 100644 --- a/tests/test_station_names.py +++ b/tests/test_station_names.py @@ -2,72 +2,28 @@ def test_sync_fills_missing_station_names(store): - assert hasattr(store, "sync_station_names"), "Backfill des noms absent" + assert hasattr(store, 'sync_station_names'), 'Backfill des noms absent' from datetime import datetime, timezone - now = datetime.now(timezone.utc) - store.record_observations( - [ - { - "id": "X1", - "lat": 44.77, - "lon": -0.55, - "prices": {"Gazole": 1.9}, - "updates": {"Gazole": now.isoformat()}, - } - ], - now, - ) - assert store.history(44.77, -0.55, 5, "Gazole", now)["stations_series"][0]["name"] == "Station X1" - filled = store.sync_station_names( - [ - { - "id": "X1", - "name": "12 RUE DES VIGNES", - "city": "Villenave", - "road": "", - "lat": 44.77, - "lon": -0.55, - }, - { - "id": "X2", - "name": "AUTRE STATION", - "city": "Ailleurs", - "road": "autoroute", - "lat": 44.80, - "lon": -0.60, - }, - ], - now, - ) - assert filled == 1, "seules les stations observées doivent être complétées" - entry = store.history(44.77, -0.55, 5, "Gazole", now)["stations_series"][0] - assert entry["name"] == "12 RUE DES VIGNES" - assert entry["city"] == "Villenave" + store.record_observations([{'id': 'X1', 'lat': 44.77, 'lon': -0.55, + 'prices': {'Gazole': 1.9}, 'updates': {'Gazole': now.isoformat()}}], now) + assert store.history(44.77, -0.55, 5, 'Gazole', now)['stations_series'][0]['name'] == 'Station X1' + filled = store.sync_station_names([ + {'id': 'X1', 'name': '12 RUE DES VIGNES', 'city': 'Villenave', 'road': '', 'lat': 44.77, 'lon': -0.55}, + {'id': 'X2', 'name': 'AUTRE STATION', 'city': 'Ailleurs', 'road': 'autoroute', 'lat': 44.80, 'lon': -0.60}, + ], now) + assert filled == 1, 'seules les stations observées doivent être complétées' + entry = store.history(44.77, -0.55, 5, 'Gazole', now)['stations_series'][0] + assert entry['name'] == '12 RUE DES VIGNES' + assert entry['city'] == 'Villenave' # Un second passage ne reécrit rien. - assert ( - store.sync_station_names( - [{"id": "X1", "name": "AUTRE NOM", "city": "Villenave", "road": "", "lat": 44.77, "lon": -0.55}], - now, - ) - == 0 - ) + assert store.sync_station_names([{'id': 'X1', 'name': 'AUTRE NOM', 'city': 'Villenave', 'road': '', + 'lat': 44.77, 'lon': -0.55}], now) == 0 def test_sync_ignores_unknown_and_malformed_rows(store): from datetime import datetime, timezone - now = datetime.now(timezone.utc) - store.record_observations( - [ - { - "id": "Y1", - "lat": 44.7, - "lon": -0.5, - "prices": {"Gazole": 1.9}, - "updates": {"Gazole": now.isoformat()}, - } - ], - now, - ) - assert store.sync_station_names([{"name": "SANS ID"}, {"id": "Y1", "name": ""}], now) == 0 + store.record_observations([{'id': 'Y1', 'lat': 44.7, 'lon': -0.5, + 'prices': {'Gazole': 1.9}, 'updates': {'Gazole': now.isoformat()}}], now) + assert store.sync_station_names([{'name': 'SANS ID'}, {'id': 'Y1', 'name': ''}], now) == 0 diff --git a/tests/test_synthesis.py b/tests/test_synthesis.py index 0892e6a..254c501 100644 --- a/tests/test_synthesis.py +++ b/tests/test_synthesis.py @@ -1,5 +1,4 @@ """Synthèse amont : pression, facteurs en langage courant, « En clair » et prudence.""" - from datetime import date, timedelta import pytest @@ -11,7 +10,7 @@ import synthesis def seed(series, unit, rows): - return storage.save_upstream(series, rows, unit, "test") + return storage.save_upstream(series, rows, unit, 'test') def days_ago(n): @@ -19,159 +18,88 @@ def days_ago(n): 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"] + 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_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), - ) - ) + 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) + 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 + 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): # 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(off), value=80.0 + (5 - off) * 2.4) for off in range(5, 0, -1)], - ) - 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 = [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"] - assert "délai de transmission" in built["plain"] + seed('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', '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 = [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'] + 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"] + 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" + 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") + 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" + 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' diff --git a/tests/test_upstream.py b/tests/test_upstream.py index fb3fe2a..a73e779 100644 --- a/tests/test_upstream.py +++ b/tests/test_upstream.py @@ -1,5 +1,4 @@ """Parseurs des sources amont officielles (DGEC, bulletin UE, PortWatch).""" - import io import json import zipfile @@ -23,139 +22,89 @@ def make_xlsx(sheet_name, cells, strings=None): sheet_rows = {} for ref in list(numeric) + list(text_values): - row = "".join(ch for ch in ref if ch.isdigit()) + row = ''.join(ch for ch in ref if ch.isdigit()) sheet_rows.setdefault(int(row), []).append(cell_xml(ref, {**numeric, **text_values}[ref])) - body = "".join( - f'{"".join(cells_xml)}' for number, cells_xml in sorted(sheet_rows.items()) - ) - shared_xml = ( - '' - + "".join(f"{value}" for value in shared) - + "" - ) - workbook = ( - '' - f'' - ) - rels = ( - '' - '' - ) - sheet = ( - '' - f"{body}" - ) + body = ''.join(f'{"".join(cells_xml)}' for number, cells_xml in sorted(sheet_rows.items())) + shared_xml = ('' + + ''.join(f'{value}' for value in shared) + '') + workbook = ('' + f'') + rels = ('' + '') + sheet = ('' + f'{body}') buffer = io.BytesIO() - with zipfile.ZipFile(buffer, "w") as archive: - archive.writestr("xl/workbook.xml", workbook) - archive.writestr("xl/_rels/workbook.xml.rels", rels) - archive.writestr("xl/sharedStrings.xml", shared_xml) - archive.writestr("xl/worksheets/sheet1.xml", sheet) + with zipfile.ZipFile(buffer, 'w') as archive: + archive.writestr('xl/workbook.xml', workbook) + archive.writestr('xl/_rels/workbook.xml.rels', rels) + archive.writestr('xl/sharedStrings.xml', shared_xml) + archive.writestr('xl/worksheets/sheet1.xml', sheet) return buffer.getvalue() def test_excel_date_conversion_and_rejection(): - assert upstream.excel_date(42005) == "2015-01-01" - assert upstream.excel_date(46272) == "2026-09-07" - assert upstream.excel_date("2025") is None + assert upstream.excel_date(42005) == '2015-01-01' + assert upstream.excel_date(46272) == '2026-09-07' + assert upstream.excel_date('2025') is None assert upstream.excel_date(None) is None def test_parse_dgec_brent_keeps_monthly_rows_only(): - raw = make_xlsx( - "Cours du Brent", - {"A3": 42005, "B3": 47.708, "A4": 42036, "B4": 58.0955, "A157": "2025", "B157": 69.1}, - ) + raw = make_xlsx('Cours du Brent', {'A3': 42005, 'B3': 47.708, 'A4': 42036, 'B4': 58.0955, 'A157': '2025', 'B157': 69.1}) out = upstream.parse_dgec_brent(raw) - assert out == [{"day": "2015-01-01", "value": 47.71}, {"day": "2015-02-01", "value": 58.1}] + assert out == [{'day': '2015-01-01', 'value': 47.71}, {'day': '2015-02-01', 'value': 58.1}] def test_parse_dgec_brent_rejects_garbage(): with pytest.raises(ValueError): - upstream.parse_dgec_brent(make_xlsx("Cours du Brent", {"B1": "rien"})) + upstream.parse_dgec_brent(make_xlsx('Cours du Brent', {'B1': 'rien'})) def test_parse_dgec_margin_keeps_both_units(): - raw = make_xlsx("Marge brute raffinage sur Brent", {"A3": 42005, "B3": 6.9877, "C3": 45.253}) - assert upstream.parse_dgec_margin(raw) == [ - {"day": "2015-01-01", "usd_per_bbl": 6.99, "eur_per_tonne": 45.25} - ] + raw = make_xlsx('Marge brute raffinage sur Brent', {'A3': 42005, 'B3': 6.9877, 'C3': 45.253}) + assert upstream.parse_dgec_margin(raw) == [{'day': '2015-01-01', 'usd_per_bbl': 6.99, 'eur_per_tonne': 45.25}] def test_parse_dgec_prices_splits_htt_and_ttc(): - cells = {"A3": 46272, "B2": "Gazole", "H2": "Gazole", "B3": 1.653, "H3": 1.99} - out = upstream.parse_dgec_prices(make_xlsx("Carburants routiers", cells)) - assert out == [{"day": "2026-09-07", "htt": {"Gazole": 1.653}, "ttc": {"Gazole": 1.99}}] + cells = {'A3': 46272, 'B2': 'Gazole', 'H2': 'Gazole', 'B3': 1.653, 'H3': 1.99} + out = upstream.parse_dgec_prices(make_xlsx('Carburants routiers', cells)) + assert out == [{'day': '2026-09-07', 'htt': {'Gazole': 1.653}, 'ttc': {'Gazole': 1.99}}] def test_parse_eu_bulletin_converts_thousands_of_litres(): - cells = { - "A3": "Date", - "A4": 46272, - "CN1": "FR_price_with_tax_diesel", - "CN4": 2041.66, - "CO1": "FR_price_with_tax_euro95", - "CO4": 1899.99, - } - out = upstream.parse_eu_bulletin(make_xlsx("Prices with taxes", cells)) - assert out == [{"day": "2026-09-07", "prices": {"diesel": 2.042, "euro95": 1.9}}] + cells = {'A3': 'Date', 'A4': 46272, 'CN1': 'FR_price_with_tax_diesel', 'CN4': 2041.66, + 'CO1': 'FR_price_with_tax_euro95', 'CO4': 1899.99} + out = upstream.parse_eu_bulletin(make_xlsx('Prices with taxes', cells)) + assert out == [{'day': '2026-09-07', 'prices': {'diesel': 2.042, 'euro95': 1.9}}] def test_parse_eu_bulletin_accepts_without_tax_sheet(): # Le bulletin nomme le second onglet « Prices wo taxes » : les en-têtes diffèrent. - cells = {"A3": "Date", "A4": 46272, "CN1": "FR_price_wo_tax_diesel", "CN4": 1500.0} - out = upstream.parse_eu_bulletin(make_xlsx("Prices wo taxes", cells), "FR", "Prices wo taxes") - assert out == [{"day": "2026-09-07", "prices": {"diesel": 1.5}}] + cells = {'A3': 'Date', 'A4': 46272, 'CN1': 'FR_price_wo_tax_diesel', 'CN4': 1500.0} + out = upstream.parse_eu_bulletin(make_xlsx('Prices wo taxes', cells), 'FR', 'Prices wo taxes') + assert out == [{'day': '2026-09-07', 'prices': {'diesel': 1.5}}] def test_parse_eu_bulletin_rejects_missing_country(): - raw = make_xlsx( - "Prices with taxes", {"A3": "Date", "A4": 46272, "CN1": "BE_price_with_tax_diesel", "CN4": 1500} - ) + raw = make_xlsx('Prices with taxes', {'A3': 'Date', 'A4': 46272, 'CN1': 'BE_price_with_tax_diesel', 'CN4': 1500}) with pytest.raises(ValueError): upstream.parse_eu_bulletin(raw) def test_parse_chokepoints_keeps_latest_per_watched_strait(): - payload = json.dumps( - { - "features": [ - { - "attributes": { - "date": "2026-08-30", - "portname": "Strait of Hormuz", - "n_tanker": 40, - "n_total": 90, - } - }, - { - "attributes": { - "date": "2026-09-06", - "portname": "Strait of Hormuz", - "n_tanker": 2, - "n_total": 6, - "capacity_tanker": 60280, - "capacity": 150000, - } - }, - { - "attributes": { - "date": "2026-09-06", - "portname": "Bab el-Mandeb Strait", - "n_tanker": 6, - "n_total": 23, - } - }, - {"attributes": {"date": "2026-09-06", "portname": "Port of Nantes", "n_tanker": 99}}, - ] - } - ).encode() + payload = json.dumps({'features': [ + {'attributes': {'date': '2026-08-30', 'portname': 'Strait of Hormuz', 'n_tanker': 40, 'n_total': 90}}, + {'attributes': {'date': '2026-09-06', 'portname': 'Strait of Hormuz', 'n_tanker': 2, 'n_total': 6, + 'capacity_tanker': 60280, 'capacity': 150000}}, + {'attributes': {'date': '2026-09-06', 'portname': 'Bab el-Mandeb Strait', 'n_tanker': 6, 'n_total': 23}}, + {'attributes': {'date': '2026-09-06', 'portname': 'Port of Nantes', 'n_tanker': 99}}, + ]}).encode() out = upstream.parse_chokepoints(payload) - assert set(out) == {"Strait of Hormuz", "Bab el-Mandeb Strait"} - assert out["Strait of Hormuz"]["day"] == "2026-09-06" - assert out["Strait of Hormuz"]["transit_tankers"] == 2 - assert out["Strait of Hormuz"]["capacity_total"] == 150000 + assert set(out) == {'Strait of Hormuz', 'Bab el-Mandeb Strait'} + assert out['Strait of Hormuz']['day'] == '2026-09-06' + assert out['Strait of Hormuz']['transit_tankers'] == 2 + assert out['Strait of Hormuz']['capacity_total'] == 150000 def test_parse_chokepoints_rejects_garbage(): @@ -164,11 +113,7 @@ def test_parse_chokepoints_rejects_garbage(): def test_freshness_never_assumes_current(): - assert upstream.freshness("2026-09-10", today=__import__("datetime").date(2026, 9, 12)) == { - "state": "fresh", - "age_days": 2, - } - assert ( - upstream.freshness("2026-07-01", today=__import__("datetime").date(2026, 9, 12))["state"] == "stale" - ) - assert upstream.freshness(None) == {"state": "unknown", "age_days": None} + assert upstream.freshness('2026-09-10', today=__import__('datetime').date(2026, 9, 12)) == { + 'state': 'fresh', 'age_days': 2} + assert upstream.freshness('2026-07-01', today=__import__('datetime').date(2026, 9, 12))['state'] == 'stale' + assert upstream.freshness(None) == {'state': 'unknown', 'age_days': None} diff --git a/tests/test_upstream_store.py b/tests/test_upstream_store.py index 7da3081..9ba19a4 100644 --- a/tests/test_upstream_store.py +++ b/tests/test_upstream_store.py @@ -1,5 +1,4 @@ """Historisation des séries amont et orchestration de la collecte amont.""" - from datetime import datetime, timezone import collector @@ -7,91 +6,72 @@ import storage def test_upstream_series_roundtrip_and_deduplication(store): - rows = [dict(day="2026-01-01", value=80.0), dict(day="2026-02-01", value=82.5)] - assert storage.save_upstream("dgec_brent_usd", rows, "USD/baril", "DGEC", datetime.now(timezone.utc)) == 2 - assert [r["value"] for r in storage.upstream_series("dgec_brent_usd")] == [80.0, 82.5] - storage.save_upstream("dgec_brent_usd", [dict(day="2026-02-01", value=83.0)], "USD/baril", "DGEC") - assert [r["value"] for r in storage.upstream_series("dgec_brent_usd")] == [80.0, 83.0] + rows = [dict(day='2026-01-01', value=80.0), dict(day='2026-02-01', value=82.5)] + assert storage.save_upstream('dgec_brent_usd', rows, 'USD/baril', 'DGEC', datetime.now(timezone.utc)) == 2 + assert [r['value'] for r in storage.upstream_series('dgec_brent_usd')] == [80.0, 82.5] + storage.save_upstream('dgec_brent_usd', [dict(day='2026-02-01', value=83.0)], 'USD/baril', 'DGEC') + assert [r['value'] for r in storage.upstream_series('dgec_brent_usd')] == [80.0, 83.0] def test_save_upstream_ignores_invalid_values(store): - assert ( - storage.save_upstream( - "x", - [ - dict(day="2026-01-01", value=float("nan")), - dict(day=None, value=1.0), - dict(day="2026-01-02", value="n/a"), - ], - "unit", - "src", - ) - == 0 - ) - assert storage.upstream_series("x") == [] + assert storage.save_upstream('x', [dict(day='2026-01-01', value=float('nan')), + dict(day=None, value=1.0), dict(day='2026-01-02', value='n/a')], + 'unit', 'src') == 0 + assert storage.upstream_series('x') == [] def test_latest_upstream_reports_real_freshness(store): today = datetime.now(timezone.utc).date() - store.save_upstream("s1", [dict(day=today.isoformat(), value=1.0)], "EUR/L", "src") - store.save_upstream("s2", [dict(day="2015-01-01", value=2.0)], "EUR/L", "src") + store.save_upstream('s1', [dict(day=today.isoformat(), value=1.0)], 'EUR/L', 'src') + store.save_upstream('s2', [dict(day='2015-01-01', value=2.0)], 'EUR/L', 'src') latest = store.latest_upstream() - assert latest["s1"]["freshness"] == "fresh" - assert latest["s2"]["freshness"] == "stale" - assert latest["s2"]["age_days"] > 1000 + assert latest['s1']['freshness'] == 'fresh' + assert latest['s2']['freshness'] == 'stale' + assert latest['s2']['age_days'] > 1000 def test_chokepoints_history_keeps_days(store): - entries = { - "Strait of Hormuz": dict( - day="2026-09-06", - transit_tankers=2, - transit_total=6, - capacity_tankers=60280, - capacity_total=150000, - ) - } - assert store.save_chokepoints(entries, "IMF PortWatch") == 1 - store.save_chokepoints(entries, "IMF PortWatch") + entries = {'Strait of Hormuz': dict(day='2026-09-06', transit_tankers=2, transit_total=6, + capacity_tankers=60280, capacity_total=150000)} + assert store.save_chokepoints(entries, 'IMF PortWatch') == 1 + store.save_chokepoints(entries, 'IMF PortWatch') history = store.chokepoint_daily(60) - assert list(history) == ["Strait of Hormuz"] - assert len(history["Strait of Hormuz"]) == 1 - assert history["Strait of Hormuz"][0]["transit_tankers"] == 2 + assert list(history) == ['Strait of Hormuz'] + assert len(history['Strait of Hormuz']) == 1 + assert history['Strait of Hormuz'][0]['transit_tankers'] == 2 def test_collect_upstream_runs_once_per_day_and_lists_failures(store, monkeypatch): calls = [] def good(): - calls.append("good") - return [ - dict(series="test_series", unit="EUR/L", source="test", rows=[dict(day="2026-09-01", value=1.5)]) - ] + calls.append('good') + return [dict(series='test_series', unit='EUR/L', source='test', rows=[dict(day='2026-09-01', value=1.5)])] def broken(): - calls.append("broken") - raise OSError("source en panne") + calls.append('broken') + raise OSError('source en panne') - assert collector.collect_upstream(force=True, sources={"good": good})["status"] == "ok" - assert collector.collect_upstream(sources={"good": good})["status"] == "skipped" - assert calls.count("good") == 1 + assert collector.collect_upstream(force=True, sources={'good': good})['status'] == 'ok' + assert collector.collect_upstream(sources={'good': good})['status'] == 'skipped' + assert calls.count('good') == 1 # Un échec partiel ne doit pas empêcher une nouvelle tentative le même jour. - out = collector.collect_upstream(force=True, sources={"good": good, "broken": broken}) - assert out["status"] == "partial" - assert "broken" in out["detail"] and "OSError" in out["detail"] - assert store.upstream_series("test_series")[0]["value"] == 1.5 + out = collector.collect_upstream(force=True, sources={'good': good, 'broken': broken}) + assert out['status'] == 'partial' + assert 'broken' in out['detail'] and 'OSError' in out['detail'] + assert store.upstream_series('test_series')[0]['value'] == 1.5 def test_collect_upstream_reports_total_failure(store): def broken(): - raise OSError("hors ligne") + raise OSError('hors ligne') - out = collector.collect_upstream(force=True, sources={"broken": broken}) - assert out["status"] == "error" + out = collector.collect_upstream(force=True, sources={'broken': broken}) + assert out['status'] == 'error' assert store.latest_upstream() == {} def test_collect_still_returns_no_favorites_with_upstream(store, monkeypatch): out = collector.collect(lambda: [], force=True) - assert out["status"] == "no_favorites" - assert "upstream" in out + assert out['status'] == 'no_favorites' + assert 'upstream' in out diff --git a/tests/test_validation.py b/tests/test_validation.py index 47aa02c..4259fc7 100644 --- a/tests/test_validation.py +++ b/tests/test_validation.py @@ -1,302 +1,235 @@ """Banc de validation : aucune fuite, métriques exigées, et verdict économique.""" - from datetime import date, timedelta import pytest import validation -VEHICLE = dict( - name="Fictif", fuel="E10", consumption=6.0, tank_liters=45.0, min_range_km=80.0, monthly_km=1000.0 -) +VEHICLE = dict(name='Fictif', fuel='E10', consumption=6.0, tank_liters=45.0, + min_range_km=80.0, monthly_km=1000.0) def series(prices, step_days=1, start_day=1): origin = date(2026, 1, start_day) - return [ - dict(day=(origin + timedelta(days=index * step_days)).isoformat(), price=price) - for index, price in enumerate(prices) - ] + return [dict(day=(origin + timedelta(days=index * step_days)).isoformat(), price=price) + for index, price in enumerate(prices)] -def prediction( - day, horizon=7, predicted=None, actual=None, reference=None, confidence=0.8, trained_until=None -): - return dict( - day=day, - horizon=horizon, - predicted_change=predicted, - actual_change=actual, - predicted_price=(reference or 0) + (predicted or 0), - actual_price=(reference or 0) + (actual or 0), - last_known_price=reference, - confidence=confidence, - trained_until=trained_until or day, - ) +def prediction(day, horizon=7, predicted=None, actual=None, reference=None, confidence=0.8, + trained_until=None): + return dict(day=day, horizon=horizon, predicted_change=predicted, actual_change=actual, + predicted_price=(reference or 0) + (predicted or 0), actual_price=(reference or 0) + (actual or 0), + last_known_price=reference, confidence=confidence, + trained_until=trained_until or day) def test_chronological_split_never_trains_on_the_future(): - samples = [dict(day=f"2026-01-{day:02d}") for day in range(1, 11)] + samples = [dict(day=f'2026-01-{day:02d}') for day in range(1, 11)] train, test = validation.split_chronologically(samples, ratio=0.6) assert len(train) == 6 and len(test) == 4 - assert max(item["day"] for item in train) < min(item["day"] for item in test) + assert max(item['day'] for item in train) < min(item['day'] for item in test) def test_leakage_is_refused_outright(): - leaky = [prediction("2026-03-01", trained_until="2026-03-05")] + leaky = [prediction('2026-03-01', trained_until='2026-03-05')] with pytest.raises(ValueError) as error: validation.assert_no_leakage(leaky) - assert "fuite de données" in str(error.value) - validation.assert_no_leakage([prediction("2026-03-05", trained_until="2026-03-01")]) + assert 'fuite de données' in str(error.value) + validation.assert_no_leakage([prediction('2026-03-05', trained_until='2026-03-01')]) def test_perfect_model_beats_the_naive_rule(): - predictions = [ - prediction(f"2026-0{month}-15", predicted=delta, actual=delta, reference=2.0) - for month in (1, 2) - for delta in (0.05, -0.03, 0.02) - ] + predictions = [prediction(f'2026-0{month}-15', predicted=delta, actual=delta, reference=2.0) + for month in (1, 2) for delta in (0.05, -0.03, 0.02)] metrics = validation.evaluate(predictions, horizon=7) - assert metrics["count"] == 6 - assert metrics["mae"] == 0 - assert metrics["skill_vs_naive"] == 1.0 - assert metrics["direction"]["accuracy"] == 1.0 + assert metrics['count'] == 6 + assert metrics['mae'] == 0 + assert metrics['skill_vs_naive'] == 1.0 + assert metrics['direction']['accuracy'] == 1.0 def test_a_useless_model_scores_no_better_than_the_naive_rule(): - predictions = [ - prediction(f"2026-01-{day:02d}", predicted=0.01, actual=-0.02, reference=2.0, confidence=0.9) - for day in range(1, 11) - ] + predictions = [prediction(f'2026-01-{day:02d}', predicted=0.01, actual=-0.02, reference=2.0, + confidence=0.9) for day in range(1, 11)] metrics = validation.evaluate(predictions, horizon=7) - assert metrics["skill_vs_naive"] <= 0.1, "aucun progrès sur la règle « prix identique »" - assert metrics["direction"]["accuracy"] == 0.0 + assert metrics['skill_vs_naive'] <= 0.1, 'aucun progrès sur la règle « prix identique »' + assert metrics['direction']['accuracy'] == 0.0 def test_direction_accuracy_counts_only_real_moves(): predictions = [ - prediction("2026-01-01", predicted=0.05, actual=0.04, reference=2.0), - prediction("2026-01-02", predicted=-0.05, actual=0.04, reference=2.0), - prediction("2026-01-03", predicted=0.0, actual=0.04, reference=2.0), + prediction('2026-01-01', predicted=0.05, actual=0.04, reference=2.0), + prediction('2026-01-02', predicted=-0.05, actual=0.04, reference=2.0), + prediction('2026-01-03', predicted=0.0, actual=0.04, reference=2.0), ] scored = validation.direction_accuracy(predictions) - assert scored["count"] == 2, "un « stable » annoncé n’est pas compté comme un sens juste" - assert scored["accuracy"] == 0.5 - assert scored["flat_predicted"] == 1 + assert scored['count'] == 2, 'un « stable » annoncé n’est pas compté comme un sens juste' + assert scored['accuracy'] == 0.5 + assert scored['flat_predicted'] == 1 def test_confidence_calibration_penalises_overconfidence(): """Confiance annoncée contre réussite réelle : une surconfiance doit coûter cher.""" honest, confident = [], [] for day in range(1, 11): - sign = 1 if day % 2 else -1 # une fois sur deux le sens est faux + sign = 1 if day % 2 else -1 # une fois sur deux le sens est faux hit = dict(predicted=0.02, actual=0.02 * sign, reference=2.0) - honest.append(prediction(f"2026-01-{day:02d}", confidence=0.55, **hit)) - confident.append(prediction(f"2026-01-{day:02d}", confidence=0.95, **hit)) - assert ( - validation.confidence_calibration(honest)["calibration_quality"] - > validation.confidence_calibration(confident)["calibration_quality"] - ) - assert validation.confidence_calibration([])["expected_calibration_error"] is None + honest.append(prediction(f'2026-01-{day:02d}', confidence=0.55, **hit)) + confident.append(prediction(f'2026-01-{day:02d}', confidence=0.95, **hit)) + assert (validation.confidence_calibration(honest)['calibration_quality'] > + validation.confidence_calibration(confident)['calibration_quality']) + assert validation.confidence_calibration([])['expected_calibration_error'] is None def test_every_horizon_is_measured_separately(): predictions = [] for horizon in validation.HORIZONS: for day in range(1, 6): - predictions.append( - prediction( - f"2026-01-{day:02d}", - horizon=horizon, - predicted=0.03 * horizon / 10, - actual=0.02, - reference=2.0, - ) - ) + predictions.append(prediction(f'2026-01-{day:02d}', horizon=horizon, + predicted=0.03 * horizon / 10, actual=0.02, reference=2.0)) metrics = validation.evaluate_all_horizons(predictions) assert set(metrics) == {str(horizon) for horizon in validation.HORIZONS} - assert metrics["21"]["count"] == 5 + assert metrics['21']['count'] == 5 def test_naive_strategy_refuels_only_when_needed(): prices = series([2.00] * 40) - result = validation.simulate(prices, VEHICLE, strategy="naive") - assert result["refuels"] >= 1 - assert result["cost_eur"] > 0 - assert result["cost_per_liter"] == pytest.approx(2.0, abs=0.01) + result = validation.simulate(prices, VEHICLE, strategy='naive') + assert result['refuels'] >= 1 + assert result['cost_eur'] > 0 + assert result['cost_per_liter'] == pytest.approx(2.0, abs=0.01) def test_advisor_strategy_can_wait_for_a_falling_price(): """Prix qui baisse : attendre coûte moins cher que remplir au début.""" prices = series([2.00] * 5 + [1.80] * 20 + [2.00] * 15) - forecasts = {point["day"]: dict(direction="down") for point in prices[:6]} + forecasts = {point['day']: dict(direction='down') for point in prices[:6]} comparison = validation.compare_strategies(prices, VEHICLE, forecasts=forecasts) - assert comparison["advisor"]["cost_eur"] <= comparison["naive"]["cost_eur"] + assert comparison['advisor']['cost_eur'] <= comparison['naive']['cost_eur'] def test_strategy_comparison_reports_cost_refuels_and_detour(): prices = series([1.95] * 30) - forecasts = {point["day"]: dict(direction="up") for point in prices} - comparison = validation.compare_strategies(prices, VEHICLE, forecasts=forecasts, detour_km_per_stop=4.0) - assert {"naive", "advisor", "value", "comfort"} <= set(comparison) - for side in (comparison["naive"], comparison["advisor"]): - assert {"cost_eur", "refuels", "detour_km", "litres"} <= set(side) - assert comparison["advisor"]["detour_km"] == 4.0 * comparison["advisor"]["refuels"] + forecasts = {point['day']: dict(direction='up') for point in prices} + comparison = validation.compare_strategies(prices, VEHICLE, forecasts=forecasts, + detour_km_per_stop=4.0) + assert {'naive', 'advisor', 'value', 'comfort'} <= set(comparison) + for side in (comparison['naive'], comparison['advisor']): + assert {'cost_eur', 'refuels', 'detour_km', 'litres'} <= set(side) + assert comparison['advisor']['detour_km'] == 4.0 * comparison['advisor']['refuels'] def _metrics(count=500, accuracy=0.62, calibration=0.9, skill=0.05): - return { - str(validation.DEFAULT_HORIZON): dict( - count=count, - direction=dict(accuracy=accuracy), - calibration=dict(calibration_quality=calibration), - skill_vs_naive=skill, - ) - } + return {str(validation.DEFAULT_HORIZON): dict( + count=count, direction=dict(accuracy=accuracy), + calibration=dict(calibration_quality=calibration), skill_vs_naive=skill)} -def _economics( - naive_cost=100.0, advisor_cost=100.0, naive_refuels=10, advisor_refuels=10, penalty=1.5, refuel_days=None -): - days = refuel_days or [ - (date(2026, 1, 1) + timedelta(days=index * 3)).isoformat() for index in range(advisor_refuels) - ] - naive = dict( - cost_eur=naive_cost, - refuels=naive_refuels, - detour_km=0.0, - median_interval_days=9.0, - min_interval_days=3.0, - refuels_per_month=naive_refuels / 3, - ) - advisor = dict( - cost_eur=advisor_cost, - refuels=advisor_refuels, - detour_km=8.0, - refuel_days=days, - median_interval_days=9.0 if advisor_refuels < 2 else 3.0, - min_interval_days=3.0 if advisor_refuels < 2 else 3.0, - refuels_per_month=advisor_refuels / 3, - ) +def _economics(naive_cost=100.0, advisor_cost=100.0, naive_refuels=10, advisor_refuels=10, + penalty=1.5, refuel_days=None): + days = refuel_days or [(date(2026, 1, 1) + timedelta(days=index * 3)).isoformat() + for index in range(advisor_refuels)] + naive = dict(cost_eur=naive_cost, refuels=naive_refuels, detour_km=0.0, + median_interval_days=9.0, min_interval_days=3.0, + refuels_per_month=naive_refuels / 3) + advisor = dict(cost_eur=advisor_cost, refuels=advisor_refuels, detour_km=8.0, + refuel_days=days, + median_interval_days=9.0 if advisor_refuels < 2 else 3.0, + min_interval_days=3.0 if advisor_refuels < 2 else 3.0, + refuels_per_month=advisor_refuels / 3) value = validation.net_value(naive, advisor, penalty) - advisor.update( - saving_eur=value["fuel_saving_eur"], - net_saving_eur=value["net_saving_eur"], - penalty_eur=value["penalty_eur"], - cost_ratio=advisor_cost / naive_cost if naive_cost else None, - ) - return dict( - naive=naive, - advisor=advisor, - value=value, - comfort=validation.comfort_check(advisor), - penalty_per_extra_refuel=penalty, - ) + advisor.update(saving_eur=value['fuel_saving_eur'], net_saving_eur=value['net_saving_eur'], + penalty_eur=value['penalty_eur'], + cost_ratio=advisor_cost / naive_cost if naive_cost else None) + return dict(naive=naive, advisor=advisor, value=value, + comfort=validation.comfort_check(advisor), penalty_per_extra_refuel=penalty) def test_verdict_refuses_a_model_that_saves_nothing(): verdict = validation.verdict(_metrics(), _economics(100.0, 100.0)) - assert verdict["passed"] is False - assert any("gain net simulé" in failure for failure in verdict["failures"]) + assert verdict['passed'] is False + assert any('gain net simulé' in failure for failure in verdict['failures']) def test_one_extra_refuel_is_fine_if_it_pays_for_itself(): """Un passage supplémentaire sur trois mois est acceptable s'il économise réellement.""" - verdict = validation.verdict( - _metrics(), - _economics(naive_cost=120.0, advisor_cost=99.0, naive_refuels=10, advisor_refuels=11, penalty=1.5), - ) - assert verdict["passed"] is True, verdict["failures"] - assert verdict["net_saving_eur"] == pytest.approx(19.5, abs=0.1) + verdict = validation.verdict(_metrics(), + _economics(naive_cost=120.0, advisor_cost=99.0, + naive_refuels=10, advisor_refuels=11, penalty=1.5)) + assert verdict['passed'] is True, verdict['failures'] + assert verdict['net_saving_eur'] == pytest.approx(19.5, abs=0.1) def test_extra_refuels_that_do_not_pay_are_refused(): - verdict = validation.verdict( - _metrics(), - _economics(naive_cost=100.0, advisor_cost=96.0, naive_refuels=10, advisor_refuels=13, penalty=2.5), - ) - assert verdict["passed"] is False - assert any("passage(s) supplémentaire(s)" in failure for failure in verdict["failures"]) + verdict = validation.verdict(_metrics(), + _economics(naive_cost=100.0, advisor_cost=96.0, + naive_refuels=10, advisor_refuels=13, penalty=2.5)) + assert verdict['passed'] is False + assert any('passage(s) supplémentaire(s)' in failure for failure in verdict['failures']) def test_comfort_blocks_daily_refuelling_patterns(): """Gagner de l'argent en ravitaillant tous les jours n'est pas un conseil acceptable.""" - economics = _economics( - naive_cost=120.0, - advisor_cost=90.0, - naive_refuels=6, - advisor_refuels=8, - penalty=1.0, - refuel_days=[ - "2026-01-01", - "2026-01-02", - "2026-01-03", - "2026-01-04", - "2026-01-20", - "2026-01-21", - "2026-02-01", - "2026-02-02", - ], - ) + economics = _economics(naive_cost=120.0, advisor_cost=90.0, naive_refuels=6, + advisor_refuels=8, penalty=1.0, + refuel_days=['2026-01-01', '2026-01-02', '2026-01-03', '2026-01-04', + '2026-01-20', '2026-01-21', '2026-02-01', '2026-02-02']) verdict = validation.verdict(_metrics(), economics) - assert verdict["passed"] is False - assert any("confort" in failure for failure in verdict["failures"]) + assert verdict['passed'] is False + assert any('confort' in failure for failure in verdict['failures']) def test_verdict_refuses_a_small_sample_or_a_leaky_score(): - verdict = validation.verdict(_metrics(count=12, accuracy=0.9, skill=0.2), _economics(100.0, 90.0, 10, 9)) - assert verdict["passed"] is False - assert any("pour conclure" in failure for failure in verdict["failures"]) + verdict = validation.verdict(_metrics(count=12, accuracy=0.9, skill=0.2), + _economics(100.0, 90.0, 10, 9)) + assert verdict['passed'] is False + assert any('pour conclure' in failure for failure in verdict['failures']) def test_verdict_accepts_a_genuinely_useful_model(): - verdict = validation.verdict( - _metrics(count=800, accuracy=0.64, calibration=0.88, skill=0.12), _economics(100.0, 92.5, 10, 9) - ) - assert verdict["passed"] is True, verdict["failures"] - assert verdict["failures"] == [] + verdict = validation.verdict(_metrics(count=800, accuracy=0.64, calibration=0.88, skill=0.12), + _economics(100.0, 92.5, 10, 9)) + assert verdict['passed'] is True, verdict['failures'] + assert verdict['failures'] == [] def test_comfort_check_flags_abnormally_short_intervals(): - simulation = dict( - refuels=3, - refuel_days=["2026-01-01", "2026-01-02", "2026-01-10"], - min_interval_days=1, - refuels_per_month=30.0, - ) + simulation = dict(refuels=3, refuel_days=['2026-01-01', '2026-01-02', '2026-01-10'], + min_interval_days=1, refuels_per_month=30.0) check = validation.comfort_check(simulation) - assert check["comfortable"] is False - assert any("1 jour" in problem for problem in check["problems"]) - ok = validation.comfort_check(dict(refuels=3, refuel_days=[], min_interval_days=9, refuels_per_month=1.0)) - assert ok["comfortable"] is True + assert check['comfortable'] is False + assert any('1 jour' in problem for problem in check['problems']) + ok = validation.comfort_check(dict(refuels=3, refuel_days=[], min_interval_days=9, + refuels_per_month=1.0)) + assert ok['comfortable'] is True def test_van_profile_uses_discrete_trips(): """Le van ne consomme pas tous les jours : la simulation suit des trajets.""" prices = series([2.00] * 60) - van = validation.VEHICLE_PROFILES["van_occasionnel"] - result = validation.simulate(prices, van, strategy="naive") - assert result["km_per_day"] < 30, "des trajets discrets, pas une moyenne quotidienne" - assert result["refuels"] >= 1 - assert result["refuels"] <= 6, "quatre trajets par mois ne demandent pas un plein par jour" + van = validation.VEHICLE_PROFILES['van_occasionnel'] + result = validation.simulate(prices, van, strategy='naive') + assert result['km_per_day'] < 30, 'des trajets discrets, pas une moyenne quotidienne' + assert result['refuels'] >= 1 + assert result['refuels'] <= 6, 'quatre trajets par mois ne demandent pas un plein par jour' def test_every_requested_profile_is_simulated(): prices = series([2.00] * 10, step_days=3, start_day=1) - forecasts = {point["day"]: dict(direction="down") for point in prices} + forecasts = {point['day']: dict(direction='down') for point in prices} out = validation.validate_profiles(prices, forecasts) - assert set(out) == {"petit_rouleur_essence", "gros_rouleur_diesel", "petit_reservoir", "van_occasionnel"} + assert set(out) == {'petit_rouleur_essence', 'gros_rouleur_diesel', 'petit_reservoir', + 'van_occasionnel'} for entry in out.values(): - assert "value" in entry and "comfort" in entry - assert entry["naive"]["cost_eur"] is not None + assert 'value' in entry and 'comfort' in entry + assert entry['naive']['cost_eur'] is not None def test_model_quality_is_vehicle_independent(): """Les métriques statistiques ne dépendent pas du véhicule : elles se valident à part.""" - predictions = [ - prediction(f"2026-01-{day:02d}", predicted=0.02, actual=0.02, reference=2.0) for day in range(1, 11) - ] + predictions = [prediction(f'2026-01-{day:02d}', predicted=0.02, actual=0.02, reference=2.0) + for day in range(1, 11)] first = validation.evaluate(predictions, horizon=7) second = validation.evaluate(predictions, horizon=7) assert first == second - assert "vehicle" not in first + assert 'vehicle' not in first