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,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
|
||||
|
||||
Reference in New Issue
Block a user