"""Brent quotidien — série FRED DCOILBRENTEU (source d'origine EIA). « Crude Oil Prices: Brent - Europe », U.S. Energy Information Administration, diffusée quotidiennement par FRED en USD par baril. Contrairement au future BZ=F, il s'agit d'un prix au comptant : aucun roll de contrat à gérer. Ce module est **informatif**. Il n'alimente ni le score, ni le conseil, ni la quantité. Règles tenues ici : - aucune interpolation, aucun report : une journée sans observation n'existe pas ; - `observed_at` (jour de l'observation) reste distinct de `available_at` (jour à partir duquel la donnée est publiable, délai de publication retenu) et de `fetched_at` (notre téléchargement) ; - une série périmée est annoncée comme périmée, jamais présentée comme le cours du jour. """ from __future__ import annotations import csv import io import logging import urllib.request from contextlib import contextmanager from datetime import date, datetime, timedelta, timezone from pathlib import Path LOG = logging.getLogger("fuel-advisor.brent") SOURCE = "EIA via FRED" SERIES = "DCOILBRENTEU" URL = f"https://fred.stlouisfed.org/graph/fredgraph.csv?id={SERIES}" # Délai de publication retenu : une observation n'est utilisable que le lendemain. PUBLICATION_LAG_DAYS = 1 # Au-delà, on ne parle plus de « Brent du jour » mais de la dernière observation connue. STALE_AFTER_DAYS = 5 SCHEMA = """ CREATE TABLE IF NOT EXISTS brent_daily ( observed_at TEXT PRIMARY KEY, usd_per_barrel REAL NOT NULL, available_at TEXT NOT NULL, fetched_at TEXT NOT NULL, source TEXT NOT NULL ) """ def _storage(): import storage return storage @contextmanager def _connection(db=None): """Connexion fournie par l'appelant, ou ouverte via la couche stockage de l'application.""" if db is not None: yield db return with _storage().connect() as connection: yield connection def ensure_schema(db): db.execute(SCHEMA) db.commit() def parse(text): """Extrait (jour, valeur) en ignorant les valeurs manquantes de FRED (« . »).""" rows = [] reader = csv.DictReader(io.StringIO(text)) for line in reader: day = (line.get("observation_date") or "").strip() raw = (line.get(SERIES) or line.get("value") or "").strip() if not day or raw in ("", "."): continue try: value = float(raw) except ValueError: continue if value <= 0: # un baril à zéro ou négatif n'est pas une observation exploitable continue rows.append((day, value)) return rows def refresh(url=URL, db=None, fetched_at=None, text=None): """Télécharge la série complète et enregistre les observations absentes. Les observations déjà connues ne sont jamais réécrites : une donnée révisée par la source doit être traitée comme une nouvelle publication, pas comme un écrasement silencieux. """ with _connection(db) as db: ensure_schema(db) if text is None: request = urllib.request.Request(url, headers={"User-Agent": "fuel-advisor/1.0"}) with urllib.request.urlopen(request, timeout=60) as response: payload = response.read().decode("utf-8", "replace") else: payload = text rows = parse(payload) if not rows: raise ValueError("série Brent vide") stamp = fetched_at or datetime.now(timezone.utc).isoformat(timespec="seconds") before = db.execute("SELECT COUNT(*) FROM brent_daily").fetchone()[0] for day, value in rows: measured = date.fromisoformat(day) db.execute( "INSERT OR IGNORE INTO brent_daily" " (observed_at, usd_per_barrel, available_at, fetched_at, source)" " VALUES (?, ?, ?, ?, ?)", ( day, value, (measured + timedelta(days=PUBLICATION_LAG_DAYS)).isoformat(), stamp, SOURCE, ), ) db.commit() after = db.execute("SELECT COUNT(*) FROM brent_daily").fetchone()[0] return dict(stored=after - before, total=after, fetched_at=stamp, source=SOURCE) def latest(db=None, today=None): """Dernière observation connue, avec son âge réel et son caractère périmé ou non.""" with _connection(db) as db: ensure_schema(db) row = db.execute( "SELECT observed_at, usd_per_barrel, available_at, fetched_at, source" " FROM brent_daily ORDER BY observed_at DESC LIMIT 1" ).fetchone() if not row: return dict( available=False, summary="Brent spot temporairement indisponible", source=SOURCE, series=SERIES, ) observed = date.fromisoformat(row["observed_at"]) reference = today or date.today() age = (reference - observed).days return dict( available=True, observed_at=row["observed_at"], available_at=row["available_at"], fetched_at=row["fetched_at"], usd_per_barrel=round(float(row["usd_per_barrel"]), 2), age_days=age, stale=age > STALE_AFTER_DAYS, source=row["source"], series=SERIES, summary=( f"Dernière observation disponible il y a {age} jour{'s' if age != 1 else ''}" if age > STALE_AFTER_DAYS else f"Observation du {datetime.fromisoformat(row['observed_at']).strftime('%d/%m/%Y')}" ), ) def context(db=None, today=None): """Bloc prêt pour l'affichage : jamais un cours du jour inventé.""" return latest(db=db, today=today) def count(db=None): with _connection(db) as db: ensure_schema(db) return db.execute("SELECT COUNT(*) FROM brent_daily").fetchone()[0] def cached_path(): """Emplacement du fichier de série, pour information et sauvegarde.""" storage = _storage() return Path(storage.DB_PATH).parent / "brent_daily.csv"