Chaque source a sa cadence et sa fenetre (prix locaux horaires 24/7, BCE jours ouvres apres 16h15, bulletin UE le jeudi, DGEC mensuel avec detection de nouvelle periode, PortWatch quotidien avec fenetre glissante pour les revisions, actualites toutes les 2 heures, promotions 3 fois par jour). Supervision persistante (table jobs) exposee par /api/jobs et une fenetre dediee. Evenements prix uniquement en cas de changement de prix ou d horodatage declare, actualisation forcee du flux local au-dela de 15 minutes lors d un conseil. Extraction Ollama (mistral-small3.2:24b) des actualites geopolitiques et des operations commerciales, sans jamais decider du conseil, avec observed_at, published_at, fetched_at, valid_from et valid_until distincts.
250 lines
9.1 KiB
Python
250 lines
9.1 KiB
Python
"""Cours du pétrole : fournisseurs en chaîne, conversion BCE, jamais de fausse stabilité.
|
|
|
|
Deux fournisseurs sans clé d'API sont disponibles :
|
|
- ``stooq`` : CSV public (source historique, actuellement en maintenance côté Stooq) ;
|
|
- ``page`` : page publique Trading Economics, lue de façon légère (une requête par heure).
|
|
|
|
Aucun n'est officiel ni garanti : en cas d'échec, la tendance doit rester ``unknown``.
|
|
Le taux de change vient de la BCE (données officielles, sans clé).
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import csv
|
|
import io
|
|
import json
|
|
import math
|
|
import os
|
|
import re
|
|
import sqlite3
|
|
import time
|
|
import urllib.parse
|
|
import urllib.request
|
|
from datetime import date, datetime, timedelta, timezone
|
|
from pathlib import Path
|
|
|
|
DB_PATH = Path(os.environ.get("FUEL_ADVISOR_DATA_DIR", "/var/lib/fuel-advisor")) / "fuel.sqlite3"
|
|
STOOQ_URL = os.environ.get("FUEL_MARKET_URL", "https://stooq.com/q/l/?s=cl.f&f=sd2t2ohlcv&h&e=csv")
|
|
PAGE_URL = os.environ.get("FUEL_MARKET_PAGE_URL", "https://tradingeconomics.com/commodity/brent-crude-oil")
|
|
ECB_URL = (
|
|
"https://data-api.ecb.europa.eu/service/data/EXR/D.USD.EUR.SP00.A?format=csvdata&lastNObservations=6"
|
|
)
|
|
CACHE_TTL = int(os.environ.get("FUEL_MARKET_TTL", "3600"))
|
|
MAX_QUOTE_AGE_DAYS = 5
|
|
USER_AGENT = os.environ.get(
|
|
"FUEL_HTTP_USER_AGENT",
|
|
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Safari/537.36",
|
|
)
|
|
LABELS = {"stooq": "Stooq (CSV public)", "page": "Trading Economics (page publique)"}
|
|
|
|
|
|
def connect():
|
|
DB_PATH.parent.mkdir(parents=True, exist_ok=True)
|
|
db = sqlite3.connect(DB_PATH, timeout=20)
|
|
db.row_factory = sqlite3.Row
|
|
db.execute(
|
|
"CREATE TABLE IF NOT EXISTS market_cache (key TEXT PRIMARY KEY, payload TEXT NOT NULL, ts INTEGER NOT NULL)"
|
|
)
|
|
return db
|
|
|
|
|
|
def cache_get(key, ttl):
|
|
with connect() as db:
|
|
row = db.execute("SELECT payload,ts FROM market_cache WHERE key=?", (key,)).fetchone()
|
|
if not row or time.time() - row["ts"] > ttl:
|
|
return None
|
|
try:
|
|
return json.loads(row["payload"])
|
|
except ValueError:
|
|
return None
|
|
|
|
|
|
def cache_set(key, payload):
|
|
with connect() as db:
|
|
db.execute(
|
|
"REPLACE INTO market_cache VALUES(?,?,?)",
|
|
(key, json.dumps(payload, ensure_ascii=False), int(time.time())),
|
|
)
|
|
|
|
|
|
def fetch_bytes(url, timeout=20, limit=4_000_000):
|
|
request = urllib.request.Request(
|
|
url, headers={"User-Agent": USER_AGENT, "Accept-Language": "fr-FR,fr;q=0.9"}
|
|
)
|
|
with urllib.request.urlopen(request, timeout=timeout) as response:
|
|
return response.read(limit)
|
|
|
|
|
|
def _signed(value, name):
|
|
try:
|
|
out = float(str(value).replace(",", ".").strip())
|
|
except (TypeError, ValueError):
|
|
raise ValueError(f"{name} illisible") from None
|
|
if not math.isfinite(out):
|
|
raise ValueError(f"{name} invalide")
|
|
return out
|
|
|
|
|
|
def _number(value, name):
|
|
try:
|
|
out = float(str(value).replace(",", ".").strip())
|
|
except (TypeError, ValueError):
|
|
raise ValueError(f"{name} illisible") from None
|
|
if not math.isfinite(out) or out <= 0:
|
|
raise ValueError(f"{name} invalide")
|
|
return out
|
|
|
|
|
|
def parse_stooq(text, today=None):
|
|
"""CSV Stooq : Symbol,Date,Open,Close (ignore les lignes N/D)."""
|
|
today = today or datetime.now(timezone.utc).date()
|
|
rows = list(csv.DictReader(io.StringIO(text)))
|
|
if not rows:
|
|
raise ValueError("flux vide")
|
|
row = rows[-1]
|
|
quote_day = date.fromisoformat(str(row.get("Date", "")).strip())
|
|
if not 0 <= (today - quote_day).days <= MAX_QUOTE_AGE_DAYS:
|
|
raise ValueError("cours périmé ou daté dans le futur")
|
|
close = _number(row.get("Close"), "cours")
|
|
opening = _number(row.get("Open"), "ouverture")
|
|
return {"price_usd": close, "date": quote_day, "change_pct": (close - opening) / opening * 100}
|
|
|
|
|
|
def parse_page(html, today=None):
|
|
"""Page publique de cotation : ligne Brent identifiée par son symbole CO1:COM."""
|
|
today = today or datetime.now(timezone.utc).date()
|
|
for chunk in re.findall(r"<tr[^>]*>.*?</tr>", html, re.S):
|
|
if "CO1:COM" not in chunk or not re.search(r"brent", chunk, re.I):
|
|
continue
|
|
price = re.search(r'id="p"[^>]*>\s*([0-9][0-9.,]*)', chunk)
|
|
if not price:
|
|
continue
|
|
change = re.search(r'id="pch"[^>]*>\s*([+\-]?[0-9][0-9.,]*)%', chunk)
|
|
quote_day = today
|
|
stamp = re.search(r'id="date"[^>]*>\s*([A-Za-z]{3})/([0-9]{1,2})', chunk)
|
|
if stamp:
|
|
months = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"]
|
|
try:
|
|
month = months.index(stamp.group(1).lower()) + 1
|
|
quote_day = date(today.year, month, int(stamp.group(2)))
|
|
if quote_day > today + timedelta(days=1):
|
|
quote_day = date(today.year - 1, month, int(stamp.group(2)))
|
|
except ValueError:
|
|
quote_day = today
|
|
if not 0 <= (today - quote_day).days <= MAX_QUOTE_AGE_DAYS:
|
|
raise ValueError("cours périmé")
|
|
return {
|
|
"price_usd": _number(price.group(1), "cours"),
|
|
"date": quote_day,
|
|
"change_pct": _signed(change.group(1).replace("%", ""), "variation") if change else 0.0,
|
|
}
|
|
raise ValueError("ligne Brent absente")
|
|
|
|
|
|
def provider_stooq():
|
|
return parse_stooq(fetch_bytes(STOOQ_URL, 8).decode("utf-8", "replace"))
|
|
|
|
|
|
def provider_page():
|
|
return parse_page(fetch_bytes(PAGE_URL, 12).decode("utf-8", "replace"))
|
|
|
|
|
|
PROVIDERS = {"stooq": provider_stooq, "page": provider_page}
|
|
|
|
|
|
def ecb_rate_series():
|
|
"""Taux USD/EUR de la BCE avec leur date de référence (observed_at = jour de cotation)."""
|
|
text = fetch_bytes(ECB_URL, 15).decode("utf-8", "replace")
|
|
out = []
|
|
for line in text.splitlines()[1:]:
|
|
parts = line.split(",")
|
|
if len(parts) < 9 or not re.fullmatch(r"\d{4}-\d{2}-\d{2}", parts[6].strip('"')):
|
|
continue
|
|
try:
|
|
out.append(dict(day=parts[6].strip('"'), value=_number(parts[7], "taux de change")))
|
|
except ValueError:
|
|
continue
|
|
if not out:
|
|
raise ValueError("série BCE illisible")
|
|
return out
|
|
|
|
|
|
def ecb_usd_per_eur():
|
|
"""Taux USD par euro publié par la BCE (cache 24 h). Retourne None si indisponible."""
|
|
cached = cache_get("fx", 86400)
|
|
if cached is not None:
|
|
return cached or None
|
|
try:
|
|
text = fetch_bytes(ECB_URL, 15).decode("utf-8", "replace")
|
|
rows = [line for line in text.splitlines() if line and not line.startswith(("KEY,", '"KEY'))]
|
|
rate = _number(rows[-1].split(",")[7], "taux de change")
|
|
cache_set("fx", rate)
|
|
return rate
|
|
except Exception:
|
|
cache_set("fx", 0)
|
|
return None
|
|
|
|
|
|
def trend_from_pct(pct):
|
|
if pct is None or not isinstance(pct, (int, float)) or not math.isfinite(pct):
|
|
return "unknown"
|
|
return "up" if pct > 0.7 else "down" if pct < -0.7 else "flat"
|
|
|
|
|
|
def fetch(providers=None, force=False):
|
|
"""Interroge les fournisseurs dans l'ordre et renvoie toujours un dictionnaire exploitable."""
|
|
if not force:
|
|
cached = cache_get("market", CACHE_TTL)
|
|
if cached is not None:
|
|
return cached
|
|
names = providers or [
|
|
n.strip() for n in os.environ.get("FUEL_MARKET_PROVIDERS", "stooq,page").split(",") if n.strip()
|
|
]
|
|
out = {
|
|
"summary": "Pétrole indisponible — tendance inconnue",
|
|
"trend": "unknown",
|
|
"delta_pct": None,
|
|
"price_usd": None,
|
|
"price_eur": None,
|
|
"date": None,
|
|
"source": None,
|
|
"stale": False,
|
|
"reference": "Brent en USD, converti en euros avec le taux BCE quand il est disponible.",
|
|
}
|
|
errors = []
|
|
for name in names:
|
|
provider = PROVIDERS.get(name)
|
|
if provider is None:
|
|
continue
|
|
try:
|
|
quote = provider()
|
|
except Exception as exc:
|
|
errors.append(f"{name} : {type(exc).__name__}")
|
|
continue
|
|
age = (datetime.now(timezone.utc).date() - quote["date"]).days
|
|
stale = not 0 <= age <= MAX_QUOTE_AGE_DAYS
|
|
out.update(
|
|
price_usd=round(quote["price_usd"], 2),
|
|
date=quote["date"].isoformat(),
|
|
delta_pct=round(quote["change_pct"], 2),
|
|
source=LABELS.get(name, name),
|
|
stale=stale,
|
|
trend="unknown" if stale else trend_from_pct(quote["change_pct"]),
|
|
)
|
|
rate = ecb_usd_per_eur()
|
|
if rate:
|
|
out["price_eur"] = round(quote["price_usd"] / rate, 2)
|
|
parts = [f"Brent {out['price_usd']:.2f} USD/baril"]
|
|
if out["price_eur"]:
|
|
parts.append(f"{out['price_eur']:.2f} €/baril")
|
|
if out["delta_pct"] is not None:
|
|
parts.append(f"{out['delta_pct']:+.2f} % sur la dernière séance cotée")
|
|
parts.append(f"({out['date']}, {out['source']})")
|
|
out["summary"] = " ; ".join(parts) + ". Indicateur de contexte, pas une prévision du prix à la pompe."
|
|
break
|
|
else:
|
|
if errors:
|
|
out["summary"] = "Pétrole indisponible — tendance inconnue (" + ", ".join(errors) + ")."
|
|
cache_set("market", out)
|
|
return out
|