Files
Fuel-Advisor/tests/test_upstream.py
root ad46a08d64 Modele J+0 vers J+21 : benchmarks simples, unites en centimes, regimes et couverture par carburant
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.
2026-09-13 00:32:37 +02:00

120 lines
5.9 KiB
Python

"""Parseurs des sources amont officielles (DGEC, bulletin UE, PortWatch)."""
import io
import json
import zipfile
import pytest
import upstream
def make_xlsx(sheet_name, cells, strings=None):
"""Construit un classeur minimal respectant la structure réelle lue sur la VM."""
text_values = {ref: value for ref, value in cells.items() if isinstance(value, str)}
numeric = {ref: value for ref, value in cells.items() if not isinstance(value, str)}
shared = list(dict.fromkeys(text_values.values()))
index = {value: position for position, value in enumerate(shared)}
def cell_xml(ref, value):
if isinstance(value, str):
return f'<c r="{ref}" t="s"><v>{index[value]}</v></c>'
return f'<c r="{ref}"><v>{value}</v></c>'
sheet_rows = {}
for ref in list(numeric) + list(text_values):
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'<row r="{number}">{"".join(cells_xml)}</row>' for number, cells_xml in sorted(sheet_rows.items()))
shared_xml = ('<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">'
+ ''.join(f'<si><t>{value}</t></si>' for value in shared) + '</sst>')
workbook = ('<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" '
'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">'
f'<sheets><sheet name="{sheet_name}" sheetId="1" r:id="rId1"/></sheets></workbook>')
rels = ('<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
'<Relationship Id="rId1" Target="worksheets/sheet1.xml"/></Relationships>')
sheet = ('<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">'
f'<sheetData>{body}</sheetData></worksheet>')
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)
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(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})
out = upstream.parse_dgec_brent(raw)
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'}))
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}]
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}}]
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}}]
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}}]
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})
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()
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
def test_parse_chokepoints_rejects_garbage():
with pytest.raises(ValueError):
upstream.parse_chokepoints(b'{"error": "bad query"}')
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}