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.
130 lines
7.1 KiB
Python
130 lines
7.1 KiB
Python
"""Discipline as-of : aucune information future, publications différées respectées."""
|
|
from datetime import date, timedelta
|
|
|
|
import pytest
|
|
|
|
import asof
|
|
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'
|
|
|
|
|
|
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'
|
|
|
|
|
|
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
|
|
|
|
|
|
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
|
|
|
|
|
|
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
|
|
|
|
|
|
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
|
|
|
|
|
|
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'])
|
|
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)
|
|
|
|
|
|
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'
|
|
|
|
|
|
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']
|
|
|
|
|
|
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'
|
|
|
|
|
|
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
|