Cinq modeles sont compares sur des previsions directes par horizon (naive, tendance locale, autoregressif pompe, ridge marche, k-NN borne), sans bibliotheque scientifique et avec une selection faite sur une fin d apprentissage chronologique, jamais sur le test. Les cibles sont exprimees en centimes par litre sur le panel comparable, avec intervalle et probabilites. La serie BZ=F est reconnue comme un future Brent : renommee, jamais utilisee en niveau absolu, avec detection des changements de contrat et conservation de la reference mensuelle DGEC a cote. Une date available_at explicite separe desormais periode decrite, publication reelle et disponibilite, avec des hypotheses conservatrices marquees comme estimees. Le backtest rend les performances par carburant, par horizon et par regime (Covid, 2022, periode calme, crise actuelle), refuse une forte confiance pendant un choc, et teste la strategie sur quatre profils d usage.
133 lines
6.7 KiB
Python
133 lines
6.7 KiB
Python
"""Backtest : unités en c€/L, régimes séparés, confiance tenue pendant les chocs."""
|
||
import backtest
|
||
import validation
|
||
|
||
|
||
def prediction(day, horizon=7, mu=2.0, actual=2.5, confidence=0.7, price=2.0,
|
||
trained_until='2019-12-31'):
|
||
"""Prédiction de test : jamais entraînée après la date prédite (sinon fuite détectée)."""
|
||
return dict(day=day, horizon=horizon, predicted_price=price + mu / 100,
|
||
actual_price=price + actual / 100, last_known_price=price,
|
||
predicted_change=mu, actual_change=actual, confidence=confidence,
|
||
interval=(mu - 1.0, mu + 1.0), p_up=confidence, trained_until=trained_until)
|
||
|
||
|
||
def test_metrics_are_converted_to_cents():
|
||
rows = [prediction('2026-01-01', mu=2.0, actual=3.0), prediction('2026-01-02', mu=-1.0,
|
||
actual=-2.0)]
|
||
metrics = backtest.metrics_in_cents(validation.evaluate(rows, horizon=7))
|
||
assert metrics['mae_cents'] == 1.0, '1 c€/L d’erreur moyenne, exprimée en centimes'
|
||
assert metrics['improvement_pct'] is not None
|
||
assert metrics['naive']['mae_cents'] is not None
|
||
|
||
|
||
def test_amplitude_reports_predicted_and_actual():
|
||
rows = [prediction('2026-01-01', mu=2.0, actual=-4.0), prediction('2026-01-02', mu=-2.0,
|
||
actual=2.0)]
|
||
out = backtest.amplitude(rows)
|
||
assert out['predicted_cents'] == 2.0
|
||
assert out['actual_cents'] == 3.0
|
||
|
||
|
||
def test_regimes_split_predictions_by_period():
|
||
rows = [prediction('2020-03-15'), prediction('2022-05-15'), prediction('2023-09-15'),
|
||
prediction('2026-03-01'), prediction('2021-01-01')]
|
||
regimes = backtest.regime_report(rows)
|
||
assert regimes['covid_2020']['count'] == 1
|
||
assert regimes['choc_2022']['count'] == 1
|
||
assert regimes['calme_2023']['count'] == 1
|
||
assert regimes['crise_2026']['count'] == 1
|
||
assert '2021' not in str([regime['count'] for regime in regimes.values()])
|
||
|
||
|
||
def test_confidence_must_be_earned_during_a_shock():
|
||
"""Forte confiance pendant un choc + sens proche du hasard = refus."""
|
||
rows = []
|
||
for index in range(40):
|
||
rows.append(prediction(f'2026-01-{index % 28 + 1:02d}', mu=5.0,
|
||
actual=(-5.0 if index % 2 else 5.0), confidence=0.93))
|
||
regimes = backtest.regime_report(rows)
|
||
verdict = backtest.shock_verdict(regimes)
|
||
assert verdict['passed'] is False
|
||
assert any('confiance' in problem for problem in verdict['problems'])
|
||
|
||
|
||
def test_a_prudent_model_during_a_shock_is_accepted():
|
||
rows = [prediction(f'2026-02-{index % 28 + 1:02d}', mu=2.0,
|
||
actual=(2.0 if index % 4 else -2.0), confidence=0.55)
|
||
for index in range(40)]
|
||
verdict = backtest.shock_verdict(backtest.regime_report(rows))
|
||
assert verdict['passed'] is True
|
||
|
||
|
||
def test_shock_verdict_ignores_a_thin_regime():
|
||
rows = [prediction('2022-03-01', mu=6.0, actual=-6.0, confidence=0.95) for _ in range(5)]
|
||
verdict = backtest.shock_verdict(backtest.regime_report(rows))
|
||
assert verdict['passed'] is True, 'cinq prévisions ne permettent pas de conclure'
|
||
|
||
|
||
def test_interval_coverage_and_probability_calibration():
|
||
rows = [prediction('2026-01-01', mu=2.0, actual=2.5),
|
||
prediction('2026-01-02', mu=2.0, actual=9.0)]
|
||
assert backtest._interval_coverage(rows) == 0.5
|
||
assert backtest._probability_calibration(rows) is None, 'échantillon trop mince'
|
||
many = [prediction(f'2026-02-{index % 28 + 1:02d}', mu=2.0,
|
||
actual=(2.0 if index < 35 else -2.0), confidence=0.7)
|
||
for index in range(70)]
|
||
calibration = backtest._probability_calibration(many)
|
||
assert calibration['count'] == 70
|
||
assert calibration['observed'] == 0.5
|
||
|
||
|
||
def test_render_reports_every_required_item():
|
||
entry = dict(fuel='Gazole', variant='local_long', label='Modèle local long historique',
|
||
train=('2007-01-01', '2024-12-31'), test=('2025-01-01', '2026-09-12'),
|
||
train_samples=5000, test_samples=600, main_model='ridge_market',
|
||
horizons={'7': backtest.metrics_in_cents(
|
||
validation.evaluate([prediction(f'2026-01-{index % 28 + 1:02d}')
|
||
for index in range(40)], horizon=7))
|
||
| dict(model='ridge_market', interval_coverage=0.8,
|
||
amplitude=dict(predicted_cents=2.4, actual_cents=2.8))},
|
||
regimes={'crise_2026': dict(label='crise actuelle', period='2026-01-01 → 2026-12-31',
|
||
count=40, mae_cents=1.2, improvement_pct=12.0,
|
||
direction=0.6, mean_confidence=0.62)},
|
||
economics=dict(naive=dict(cost_eur=100.0, refuels=10), advisor=dict(
|
||
cost_eur=95.0, refuels=11), value=dict(net_saving_eur=3.5),
|
||
comfort=dict(comfortable=True), period=('2025-01-01', '2026-09-12')),
|
||
verdict=dict(passed=True, failures=[], reasons=['coût simulé']))
|
||
text = backtest.render_variant(entry)
|
||
for needle in ('apprentissage', 'test', 'MAE', 'amélioration', 'sens', 'calib', 'amplitude',
|
||
'régimes', 'économie simulée', 'verdict'):
|
||
assert needle in text, needle
|
||
|
||
|
||
def test_render_explains_a_refusal():
|
||
text = backtest.render_variant(dict(label='Modèle marché', fuel='SP95', variant='market',
|
||
reason='12 échantillons : trop peu pour conclure'))
|
||
assert 'non exploitable' in text and 'trop peu' in text
|
||
|
||
|
||
def test_run_variant_without_data_returns_a_reason(store):
|
||
entry = backtest.run_variant('Gazole', 'local_long', 44.77, -0.55, 15, days=60)
|
||
assert entry['reason']
|
||
assert entry.get('verdict') is None
|
||
|
||
|
||
def test_holdout_keeps_the_current_crisis_out_of_training(store, monkeypatch):
|
||
"""La période actuelle peut rester totalement hors entraînement."""
|
||
rows = []
|
||
from datetime import date, timedelta
|
||
base = date(2024, 1, 1)
|
||
for index in range(900):
|
||
day = (base + timedelta(days=index)).isoformat()
|
||
for station in range(5):
|
||
rows.append(dict(station_id=f's{station}', fuel='Gazole', day=day,
|
||
price=round(2.0 + index * 0.0005 + station * 0.004, 4),
|
||
declared_at=f'{day}T09:00:00', lat=44.7737872, lon=-0.5595029))
|
||
store.save_archive_observations(rows, 'archive:test')
|
||
entry = backtest.run_variant('Gazole', 'local_long', 44.7737872, -0.5595029, 15, days=900,
|
||
holdout_start='2026-06-01')
|
||
if entry.get('train'):
|
||
assert entry['train'][1] < '2026-06-01'
|
||
assert entry['test'][0] >= '2026-06-01'
|