Conseil simule aligne sur le moteur reel et validation par regimes
Le conseiller du backtest raisonne desormais comme le moteur de decision : besoin d abord, anticipation seulement si le gain depasse le seuil du vehicule, et plancher d appoint qui interdit de repasser a la pompe pour quelques litres. La campagne precedente le montrait : sans ce plancher, la strategie multipliait les passages quotidiens et le verdict la refusait a juste titre. Ajout de la validation par regimes : chaque periode atypique est evaluee avec un apprentissage arrete la veille de son debut, plus l experience ou la crise actuelle reste entierement hors entrainement.
This commit is contained in:
@@ -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"
|
||||
|
||||
Reference in New Issue
Block a user