"""Comblement des trous d'historique : EUR/USD (BCE, API officielle) et Brent quotidien si possible.""" import csv import io import json import sys import urllib.request sys.path.insert(0, "/opt/fuel-advisor") import features # noqa: E402 import storage # noqa: E402 UA = {"User-Agent": "CortexFuelAdvisor/0.6 (interne)"} def fetch(url, timeout=90): request = urllib.request.Request(url, headers=UA) with urllib.request.urlopen(request, timeout=timeout) as response: return response.read() print("=== BCE : historique quotidien USD/EUR (API officielle) ===") try: payload = fetch( "https://data-api.ecb.europa.eu/service/data/EXR/" "D.USD.EUR.SP00.A?startPeriod=1999-01-04&format=csvdata" ) rows = list(csv.DictReader(io.StringIO(payload.decode("utf-8")))) series = [ dict(day=row["TIME_PERIOD"], value=float(row["OBS_VALUE"])) for row in rows if row.get("OBS_VALUE") ] stored = storage.save_upstream("usd_per_eur", series, "USD/EUR", "BCE (EXR, API officielle)") print(f" {len(series)} jours récupérés, {stored} valeurs enregistrées") print(f" période : {series[0]['day']} → {series[-1]['day']}") except Exception as exc: print(" échec :", type(exc).__name__, exc) print() print("=== Brent quotidien : tentatives de source ===") for label, url, parser in ( ( "Yahoo Finance (BZ=F)", "https://query1.finance.yahoo.com/v8/finance/chart/BZ=F?range=10y&interval=1d", "yahoo", ), ("Stooq (brent.f)", "https://stooq.com/q/d/l/?s=brent.f&i=d", "stooq"), ): try: payload = fetch(url) if parser == "yahoo": data = json.loads(payload) result = data["chart"]["result"][0] stamps = result["timestamp"] closes = result["indicators"]["quote"][0]["close"] series = [ dict( day=storage.datetime.fromtimestamp(stamp, storage.timezone.utc).date().isoformat(), value=round(close, 3), ) for stamp, close in zip(stamps, closes, strict=False) if close ] source = "Yahoo Finance (BZ=F)" else: text = payload.decode("utf-8", "replace") lines = [line.split(",") for line in text.strip().splitlines()[1:] if line.count(",") >= 4] series = [ dict(day=line[0], value=round(float(line[4]), 3)) for line in lines if line[0][:4].isdigit() and float(line[4]) > 0 ] source = "Stooq (brent.f)" stored = storage.save_upstream("brent_usd_daily", series, "USD/baril", source) print( f" {label} : {len(series)} jours ({series[0]['day']} → {series[-1]['day']}), " f"{stored} enregistrés" ) break except Exception as exc: print(f" {label} : échec {type(exc).__name__} {str(exc)[:80]}") print() print("=== MATRICE APRÈS COMBLEMENT ===") matrix = features.availability_matrix("Gazole") for item in matrix: period = f"{item['first']} → {item['last']}" if item["first"] else "—" print(f" {item['label']:<52} {period:<26} {item['points']:>7} {item['status']}") print() for variant in features.variant_periods(matrix): print( f" {variant['key']:<12} {variant['start']} → {variant['end']} · " f"entraînable : {'oui' if variant['trainable'] else 'non'} " f"· bloquants : {variant['blockers'] or '—'}" )