diff --git a/backtest.py b/backtest.py index 2b6b342..e13998a 100644 --- a/backtest.py +++ b/backtest.py @@ -5,6 +5,7 @@ Le rapport produit répond, pour chaque carburant et chaque horizon, aux questio 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 @@ -15,14 +16,14 @@ 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'), + "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 +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_REGIMES = ("covid_2020", "choc_2022", "crise_2026") SHOCK_CONFIDENCE_LIMIT = 0.75 SHOCK_ACCURACY_FLOOR = 0.55 FUEL_HORIZONS = models.HORIZONS @@ -31,13 +32,13 @@ 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'): + 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) + 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 @@ -45,18 +46,27 @@ 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) + 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'])) + 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 @@ -65,27 +75,32 @@ def amplitude(rows): 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)) + 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] + 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) + 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)) + 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 @@ -94,15 +109,17 @@ def shock_verdict(regimes): problems = [] for key in SHOCK_REGIMES: entry = regimes.get(key) or {} - if (entry.get('count') or 0) < MIN_REGIME_PREDICTIONS: + if (entry.get("count") or 0) < MIN_REGIME_PREDICTIONS: continue - confidence = entry.get('mean_confidence') - accuracy = entry.get('direction') + 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") + 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) @@ -110,175 +127,239 @@ def economics(predictions, levels, vehicle, horizon, min_change_cents=1.0, min_c """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: + if row["horizon"] != horizon: continue - if abs(row['predicted_change']) < min_change_cents or row['confidence'] < min_confidence: + 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']] + 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] + 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') + 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']) + 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): +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, + built=None, + regime=None, +): """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')) + variant = {item["key"]: item for item in features.VARIANTS}[variant_key] + market = variant_key != "local_long" + built = built or 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' + 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] + ordered = sorted(samples, key=lambda item: item["day"]) + if regime: + start, end, label = REGIMES[regime] + result["regime"] = dict(key=regime, label=label, period=f"{start} → {end}") + train = [row for row in ordered if row["day"] < start] + test = [row for row in ordered if start <= row["day"] <= end] + elif 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') + 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) + 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')) + 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) + 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']) + 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'] = {} + 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']) + 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']) + 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') + 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')) + 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')] + 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]) + 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] + 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)) + 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): +def run_regimes(fuel, variant_key, lat, lon, radius, days=4200, vehicle=None, regimes=None): + """Performance sur chaque période atypique : on n'apprend que **avant** chaque régime. + + Un modèle doit être jugé sur sa réaction aux chocs, pas seulement en moyenne sur une période de + test continue : ici chaque régime est évalué avec un apprentissage qui s'arrête à sa veille. + """ + regimes = regimes or tuple(REGIMES) + market = variant_key != "local_long" + built = models.build_samples(lat, lon, radius, fuel, horizons=FUEL_HORIZONS, days=days, market=market) + out = {} + for key in regimes: + entry = run_variant( + fuel, variant_key, lat, lon, radius, days=days, vehicle=vehicle, built=built, regime=key + ) + out[key] = entry + return out + + +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 + 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)") + 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')) + 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'): + 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 = [ + 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'))} · " @@ -287,46 +368,53 @@ def render_variant(entry): 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'): + 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" - {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 []: + for failure in verdict.get("failures") or []: lines.append(f" - motif : {failure}") - for reason in verdict.get('reasons') or []: + for reason in verdict.get("reasons") or []: lines.append(f" - {reason}") - return '\n'.join(lines) + return "\n".join(lines) def _fmt(value, digits=3): - return '—' if value is None else f'{value:.{digits}f}' + 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} %' + return "—" + return f"{value * scale:+.1f} %" if scale == 1 else f"{value * scale:.0f} %" diff --git a/models.py b/models.py index 53035d1..627563f 100644 --- a/models.py +++ b/models.py @@ -21,6 +21,7 @@ Règles de conception : 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 @@ -32,45 +33,75 @@ 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', + "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 +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() + 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']) + 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] + 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: + if (date.fromisoformat(day) - date.fromisoformat(newest["available_from"])).days > max_age_days: return None return newest @@ -78,13 +109,13 @@ def _asof_value(points, day, max_age_days=60): 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']: + if not newest or not newest["value"]: return None - target = (date.fromisoformat(newest['available_from']) - timedelta(days=window)).isoformat() + 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: + 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) + return round(math.log(newest["value"] / older["value"]) * 100, 4) def detect_rolls(points, threshold=4.0, revert_window=2, revert_ratio=0.5): @@ -95,12 +126,12 @@ def detect_rolls(points, threshold=4.0, revert_window=2, revert_ratio=0.5): 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')] + 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') + 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) + 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 @@ -108,28 +139,46 @@ def detect_rolls(points, threshold=4.0, revert_window=2, revert_ratio=0.5): for index, value in enumerate(returns): if abs(value) <= threshold * sigma: continue - following = returns[index + 1:index + 1 + revert_window] + 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') + 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) + 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): @@ -141,20 +190,34 @@ def build_samples(lat, lon, radius, fuel, horizons=HORIZONS, days=4000, market=T 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 {} + 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)] + 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( @@ -164,36 +227,47 @@ def build_samples(lat, lon, radius, fuel, horizons=HORIZONS, days=4000, market=T 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]]), + 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'], + 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 [] + 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), + 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']) + 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') + 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): @@ -201,33 +275,42 @@ def _asof_percentile(levels, index, window_values): 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']) + 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']] + 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']: + if not newest or not newest["value"]: return None - target = (date.fromisoformat(newest['available_from']) - timedelta(days=14)).isoformat() + 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']: + if not older or not older["value"]: return None - return round((newest['value'] - older['value']) / older['value'] * 100, 4) + 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 = {} @@ -269,8 +352,9 @@ def _solve(matrix, vector): 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)) + 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 @@ -289,25 +373,25 @@ def _ridge(rows, names, targets, lam=1.0): 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é + 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)) + 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] + return [(row, row["targets"][horizon]) for row in samples if row["targets"].get(horizon) is not None] def model_naive_unchanged(train, horizon): @@ -315,8 +399,7 @@ def model_naive_unchanged(train, horizon): 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) + 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): @@ -326,45 +409,60 @@ def model_local_trend(train, horizon): sigma = statistics.pstdev(values) if len(values) > 1 else 0.0 def predict(row): - slope = row['features'].get('local_slope_7') + 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) + 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) + 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) + 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] + 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)) + 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): @@ -376,25 +474,35 @@ def model_knn(train, horizon, neighbours=20, subset=300): 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] + 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] + 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]) + 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]) @@ -402,12 +510,17 @@ def model_knn(train, horizon, neighbours=20, subset=300): 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) + 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) +CANDIDATES = (model_naive_unchanged, model_local_trend, model_autoregressive, model_ridge_market, model_knn) def probability_up(mu_cents, sigma_cents): @@ -420,21 +533,26 @@ def probability_up(mu_cents, sigma_cents): 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 + 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']) + 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']) + 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') + 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:]] @@ -448,21 +566,24 @@ def select_model(train, horizon, candidates=CANDIDATES, validation_share=0.2, ve continue errors = [] for row in inner_valid: - target = row['targets'].get(horizon) + target = row["targets"].get(horizon) if target is None: continue - predicted = 0.0 if fitted['name'] == 'naive_unchanged' else fitted['predict'](row) + 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) + scores[fitted["name"]] = round(statistics.fmean(errors), 4) if not scores: - return None, dict(reason='aucun candidat évaluable') + 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) + 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 index 3861cfc..64f28af 100644 --- a/run_backtest.py +++ b/run_backtest.py @@ -3,13 +3,14 @@ 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') +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 @@ -19,52 +20,70 @@ 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' +FUELS = ("Gazole", "SP95", "SP98", "E10", "E85", "GPLc") +VARIANTS = ("local_long", "market", "enriched") +REGIMES_LABEL = {key: value[2] for key, value in backtest.REGIMES.items()} +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)', - ''] + 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('') + 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',))] + 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"- {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('') + 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 @@ -74,42 +93,108 @@ def main(): 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') + 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, + 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')) + "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' + 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# Validation par régimes (apprentissage avant chaque choc)") + lines.append("") + lines.append( + "Chaque régime est évalué avec un apprentissage qui s’arrête la veille de son début : " + "le modèle n’a jamais vu la période sur laquelle il est jugé." + ) + lines.append("") + for fuel, variant in (("Gazole", "local_long"), ("Gazole", "enriched"), ("E10", "enriched")): + regimes = backtest.run_regimes( + fuel, + variant, + LAT, + LON, + RADIUS, + days=4200, + vehicle=validation.VEHICLE_PROFILES["gros_rouleur_diesel"], + ) + lines.append(f"\n### {fuel} · {variant}") + for key, entry in regimes.items(): + if entry.get("reason"): + lines.append(f"- **{REGIMES_LABEL[key]}** : non exploitable ({entry['reason']})") + continue + metrics = entry["horizons"].get("7") or {} + naive = (metrics.get("naive") or {}).get("mae_cents") + lines.append( + f"- **{entry['regime']['label']}** ({entry['regime']['period']}) · " + f"apprentissage {entry['train'][0]} → {entry['train'][1]} " + f"({entry['train_samples']} échantillons) · évalué sur {entry['test_samples']} jours" + ) + lines.append( + f" - J+7 : {metrics.get('model')} · n={metrics.get('count')} · " + f"MAE naïve {naive} → {metrics.get('mae_cents')} c€/L · " + f"amélioration {metrics.get('improvement_pct')} % · " + f"sens {(metrics.get('direction') or {}).get('accuracy')} · " + f"calibration {(metrics.get('calibration') or {}).get('calibration_quality')}" + f" · confiance annoncée moyenne " + f"{entry['regimes'][key].get('mean_confidence') if entry.get('regimes') else None}" + ) + for horizon in ("1", "3", "14", "21"): + other = entry["horizons"].get(horizon) or {} + lines.append( + f" - J+{horizon} : {other.get('model')} · n={other.get('count')} · " + f"amélioration {other.get('improvement_pct')} % · " + f"sens {(other.get('direction') or {}).get('accuracy')}" + ) + 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: + 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) + print("rapport écrit :", OUT, "|", JSON_OUT, flush=True) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/tests/conftest.py b/tests/conftest.py index 0309be8..1ccec50 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -20,14 +20,16 @@ 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 7efe209..0151d64 100644 --- a/tests/test_asof.py +++ b/tests/test_asof.py @@ -1,4 +1,5 @@ """Discipline as-of : aucune information future, publications différées respectées.""" + from datetime import date, timedelta import pytest @@ -8,122 +9,175 @@ 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-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' + 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-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 + 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['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' + 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 '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'] + [ + ( + "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 5144c05..f81b355 100644 --- a/tests/test_backfill.py +++ b/tests/test_backfill.py @@ -1,4 +1,5 @@ """Archives officielles : formats, sélection, dates réelles, et aucune continuité inventée.""" + import io import zipfile @@ -26,102 +27,105 @@ 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 index b404824..f62a369 100644 --- a/tests/test_backtest.py +++ b/tests/test_backtest.py @@ -1,132 +1,235 @@ """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'): +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) + 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)] + 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 + 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)] + 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 + 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')] + 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()]) + 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)) + 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']) + 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)] + 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 + 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)] + 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' + 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)] + 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)] + 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 + 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é'])) + 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'): + 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 + 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 + 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_run_regimes_trains_strictly_before_each_regime(store): + """Chaque régime est jugé avec un apprentissage arrêté la veille de son début.""" + from datetime import date, timedelta + + base = date(2018, 1, 1) + rows = [] + for index in range(2600): + 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.0004 + station * 0.004, 4), + declared_at=f"{day}T09:00:00", + lat=44.7737872, + lon=-0.5595029, + ) + ) + store.save_archive_observations(rows, "archive:test") + regimes = backtest.run_regimes( + "Gazole", "local_long", 44.7737872, -0.5595029, 15, days=2600, regimes=("covid_2020",) + ) + entry = regimes["covid_2020"] + if entry.get("train"): + assert entry["train"][1] < "2020-02-01", "apprentissage arrêté avant le régime" + assert entry["test"][0] >= "2020-02-01" and entry["test"][1] <= "2020-09-30" + assert entry["regime"]["label"] == "crise Covid" 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' + 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 e00d2f7..c98f2a4 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 d3875da..5650412 100644 --- a/tests/test_collectors.py +++ b/tests/test_collectors.py @@ -1,4 +1,5 @@ """Événements prix (changement uniquement), actualités structurées et opérations commerciales.""" + from datetime import datetime, timedelta, timezone import pytest @@ -10,39 +11,51 @@ 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(): @@ -51,80 +64,131 @@ 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 d12c21b..326703c 100644 --- a/tests/test_factor_signs.py +++ b/tests/test_factor_signs.py @@ -6,6 +6,7 @@ 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 @@ -17,66 +18,100 @@ 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): @@ -85,13 +120,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): @@ -99,11 +134,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): @@ -111,133 +146,152 @@ 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 c81a02b..dae6a6b 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -136,18 +136,35 @@ 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_models.py b/tests/test_models.py index e1261de..027984e 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -1,4 +1,5 @@ """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 @@ -10,14 +11,26 @@ 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 = 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) + 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): @@ -25,8 +38,16 @@ def history(count=200, relation=lambda index: (index % 3) - 1): 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)) + 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 @@ -39,106 +60,120 @@ def test_probability_up_is_monotonic_and_bounded(): 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)] + 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'] + 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)) + 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 + assert fitted["predict"](train[0]) == 0.0 out = models.predict(fitted, train[0]) - assert out['mu_cents'] == 0.0 and out['direction'] == 'flat' + 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' + 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'] + 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()) + 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'] + 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)] + 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 + 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) + 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'] + 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 + 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' + 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' + 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'] + 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(): @@ -147,25 +182,43 @@ def test_every_candidate_is_reentrainable_on_enough_data(): fitted = candidate(train, 7) assert fitted is not None, candidate.__name__ out = models.predict(fitted, train[0]) - assert isinstance(out['mu_cents'], float) + 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 + [ + 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) + 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 e06e6d3..3600895 100644 --- a/tests/test_positions.py +++ b/tests/test_positions.py @@ -1,4 +1,5 @@ """Deux indicateurs distincts : position dans l'espace (aujourd'hui) et dans le temps (historique).""" + from datetime import timedelta import storage @@ -10,75 +11,88 @@ def days_ago(n): 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 1171a37..061b4f5 100644 --- a/tests/test_quantity.py +++ b/tests/test_quantity.py @@ -4,39 +4,88 @@ 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(): @@ -52,151 +101,218 @@ 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(): @@ -204,89 +320,135 @@ 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 354516e..c374f65 100644 --- a/tests/test_routes_cache.py +++ b/tests/test_routes_cache.py @@ -1,4 +1,5 @@ """Cache de routes : origine normalisée, rattachement au favori, séparation statique / trafic.""" + from datetime import datetime, timedelta, timezone import pytest @@ -14,11 +15,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): @@ -37,77 +38,89 @@ 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 deefb83..43627cf 100644 --- a/tests/test_routing.py +++ b/tests/test_routing.py @@ -1,4 +1,5 @@ """Distances routières : fournisseurs, cache, application du rayon, liens de navigation.""" + import json import pytest @@ -8,55 +9,69 @@ 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): @@ -66,83 +81,105 @@ 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 a0bb30a..e94583f 100644 --- a/tests/test_scheduler.py +++ b/tests/test_scheduler.py @@ -1,4 +1,5 @@ """Ordonnanceur : cadences propres à chaque source, fenêtres, supervision, résilience.""" + from datetime import datetime, timedelta, timezone import collector @@ -7,80 +8,91 @@ 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 4de899e..dbd3184 100644 --- a/tests/test_series.py +++ b/tests/test_series.py @@ -1,4 +1,5 @@ """Reconstruction du marché : la médiane ne doit pas basculer quand seules 3 stations déclarent.""" + from datetime import timedelta import series @@ -14,64 +15,75 @@ def days_ago(n): 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 @@ -79,55 +91,58 @@ 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 c689694..d9e9cd8 100644 --- a/tests/test_station_names.py +++ b/tests/test_station_names.py @@ -2,28 +2,72 @@ 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 254c501..0892e6a 100644 --- a/tests/test_synthesis.py +++ b/tests/test_synthesis.py @@ -1,4 +1,5 @@ """Synthèse amont : pression, facteurs en langage courant, « En clair » et prudence.""" + from datetime import date, timedelta import pytest @@ -10,7 +11,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): @@ -18,88 +19,159 @@ 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 a73e779..fb3fe2a 100644 --- a/tests/test_upstream.py +++ b/tests/test_upstream.py @@ -1,4 +1,5 @@ """Parseurs des sources amont officielles (DGEC, bulletin UE, PortWatch).""" + import io import json import zipfile @@ -22,89 +23,139 @@ 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(): @@ -113,7 +164,11 @@ 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 9ba19a4..7da3081 100644 --- a/tests/test_upstream_store.py +++ b/tests/test_upstream_store.py @@ -1,4 +1,5 @@ """Historisation des séries amont et orchestration de la collecte amont.""" + from datetime import datetime, timezone import collector @@ -6,72 +7,91 @@ 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 4259fc7..0b76879 100644 --- a/tests/test_validation.py +++ b/tests/test_validation.py @@ -204,6 +204,33 @@ def test_comfort_check_flags_abnormally_short_intervals(): assert ok['comfortable'] is True +def test_topup_floor_prevents_absurd_short_intervals(): + """Le plancher d'appoint empêche la stratégie de repasser à la pompe pour quelques litres.""" + prices = series([2.00] * 120) + vehicle = dict(validation.VEHICLE_PROFILES['gros_rouleur_diesel']) + forecasts = {point['day']: dict(direction='up', change_cents=3.0, confidence=0.8) + for point in prices} + comparison = validation.compare_strategies(prices, vehicle, forecasts=forecasts) + advisor = comparison['advisor'] + assert advisor['min_interval_days'] is None or advisor['min_interval_days'] >= 3, \ + 'aucun passage quotidien' + assert comparison['comfort']['comfortable'] is True, comparison['comfort']['problems'] + assert advisor['refuels'] <= comparison['naive']['refuels'] + 3 + + +def test_anticipation_only_when_it_pays(): + """Anticiper un plein n'est accepté que si le gain dépasse le seuil du véhicule.""" + assert validation._anticipation_gain(dict(direction='up', change_cents=3.0), 2.0, 40.0, + 1.0) == pytest.approx(1.2, abs=0.01) + assert validation._anticipation_gain(dict(direction='up', change_cents=3.0), 2.0, 40.0, + 1.5) is None, '1,20 € pour un seuil de 1,50 € : non' + assert validation._anticipation_gain(dict(direction='up', change_cents=0.2), 2.0, 40.0, + 1.5) is None, 'gain trop faible' + assert validation._anticipation_gain(dict(direction='down', change_cents=5.0), 2.0, 40.0, + 1.5) is None, 'une baisse ne justifie pas d’anticiper' + assert validation._anticipation_gain(None, 2.0, 40.0, 1.5) is None + + 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) diff --git a/validation.py b/validation.py index 251fc02..ecb4f68 100644 --- a/validation.py +++ b/validation.py @@ -227,6 +227,21 @@ def _km_for_day(vehicle, index): return vehicle["monthly_km"] / quantity.DAYS_PER_MONTH +MIN_TOPUP_LITERS = 10.0 # plancher d'appoint : on ne va pas à la pompe pour 2 litres +MIN_FORECAST_CENTS = 1.0 # en dessous, la prévision ne justifie aucun déplacement + + +def _anticipation_gain(forecast, price, litres, min_gain_eur): + """Gain attendu en anticipant : litres concernés × variation prévue, comparé au seuil.""" + if not forecast or not litres: + return None + change_eur = (forecast.get("change_cents") or 0) / 100 + if forecast.get("direction") != "up" or change_eur <= 0: + return None + gain = litres * change_eur + return round(gain, 2) if gain >= min_gain_eur else None + + def simulate( price_series, vehicle, @@ -266,20 +281,29 @@ def simulate( if strategy == "naive": action = "refill" if usable < km_today else "wait" else: - forecast = forecasts.get(point["day"]) - direction = (forecast or {}).get("direction") - if direction == "down" and usable > km_today * 3: - action = "wait" - elif direction == "up" and usable <= km_today * 7: - action = "refill" - elif usable < km_today: + # Le conseiller raisonne comme le moteur réel : besoin d'abord, anticipation ensuite + # (et seulement si elle paie), jamais de passage pour quelques litres. + forecast = forecasts.get(point["day"]) or {} + change = abs(forecast.get("change_cents") or 0) + addable = max(0.0, tank * fill_ratio - litres) + if usable < km_today: action = "refill" if usable <= 0 else "topup" + elif ( + forecast.get("direction") == "up" + and change >= MIN_FORECAST_CENTS + and _anticipation_gain(forecast, price, addable, vehicle.get("min_gain_eur", 1.5)) + ): + action = "refill" + else: + action = "wait" litres_to_buy = 0.0 if action == "refill": litres_to_buy = max(0.0, tank * fill_ratio - litres) elif action == "topup": - needed = km_today * 3 * consumption / 100 + needed = km_today * 7 * consumption / 100 litres_to_buy = max(0.0, min(tank * fill_ratio, litres + needed) - litres) + if action in ("refill", "topup") and litres_to_buy < MIN_TOPUP_LITERS: + litres_to_buy = 0.0 # plancher de confort : ni achat inutile, ni passage quotidien if litres_to_buy > 0.05: result["cost_eur"] += litres_to_buy * price result["litres"] += litres_to_buy