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.
598 lines
23 KiB
Python
598 lines
23 KiB
Python
"""Collecte quotidienne : prix locaux des favoris + sources amont officielles.
|
||
|
||
Deux responsabilités séparées :
|
||
- ``collect`` : prix locaux (nécessite au moins un favori) ;
|
||
- ``collect_upstream`` : séries amont officielles (DGEC, bulletin UE, détroits IMF),
|
||
indépendantes des favoris, donc collectées même sans lieu suivi.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import fcntl
|
||
import json
|
||
import os
|
||
import sqlite3
|
||
import time
|
||
from datetime import datetime, timedelta, timezone
|
||
|
||
import storage
|
||
import upstream
|
||
|
||
DGEC_SOURCE = "DGEC – ministère de la Transition écologique (mensuel)"
|
||
EU_SOURCE = "Commission européenne – Weekly Oil Bulletin (hebdomadaire)"
|
||
PORTWATCH_SOURCE = "IMF PortWatch (quotidien, publication différée)"
|
||
MARKET_SOURCE = "Cotation de marché (quotidienne, voir marché amont)"
|
||
|
||
|
||
def status():
|
||
with storage.connect() as db:
|
||
latest = db.execute("SELECT * FROM collections ORDER BY id DESC LIMIT 1").fetchone()
|
||
good = db.execute("SELECT * FROM collections WHERE status='ok' ORDER BY id DESC LIMIT 1").fetchone()
|
||
count = db.execute("SELECT count(*) FROM observations").fetchone()[0]
|
||
run = db.execute("SELECT * FROM upstream_runs ORDER BY day DESC LIMIT 1").fetchone()
|
||
return dict(
|
||
latest=dict(latest) if latest else None,
|
||
last_success=dict(good) if good else None,
|
||
observations=count,
|
||
upstream_run=dict(run) if run else None,
|
||
upstream=storage.latest_upstream(),
|
||
)
|
||
|
||
|
||
def _source_dgec():
|
||
"""Cours du Brent, marge brute de raffinage, prix HTT/TTC français."""
|
||
urls = upstream.dgec_urls()
|
||
out = []
|
||
brent = upstream.parse_dgec_brent(upstream.fetch_bytes(urls["brent"], 90))
|
||
out.append(
|
||
dict(
|
||
series="dgec_brent_usd",
|
||
unit="USD/baril",
|
||
source=DGEC_SOURCE,
|
||
rows=[dict(day=row["day"], value=row["value"]) for row in brent],
|
||
)
|
||
)
|
||
margin = upstream.parse_dgec_margin(upstream.fetch_bytes(urls["margin"], 90))
|
||
out.append(
|
||
dict(
|
||
series="dgec_margin_usd_per_bbl",
|
||
unit="USD/baril",
|
||
source=DGEC_SOURCE,
|
||
rows=[dict(day=row["day"], value=row["usd_per_bbl"]) for row in margin],
|
||
)
|
||
)
|
||
out.append(
|
||
dict(
|
||
series="dgec_margin_eur_per_tonne",
|
||
unit="EUR/tonne",
|
||
source=DGEC_SOURCE,
|
||
rows=[dict(day=row["day"], value=row["eur_per_tonne"]) for row in margin],
|
||
)
|
||
)
|
||
prices = upstream.parse_dgec_prices(upstream.fetch_bytes(urls["prices"], 90))
|
||
for fuel in storage.FUELS:
|
||
htt = [dict(day=row["day"], value=row["htt"][fuel]) for row in prices if fuel in row["htt"]]
|
||
ttc = [dict(day=row["day"], value=row["ttc"][fuel]) for row in prices if fuel in row["ttc"]]
|
||
if htt:
|
||
out.append(
|
||
dict(series=f"fr_htt_{fuel}", unit="EUR/L", source=f"{DGEC_SOURCE} – hors taxes", rows=htt)
|
||
)
|
||
if ttc:
|
||
out.append(dict(series=f"fr_ttc_{fuel}", unit="EUR/L", source=f"{DGEC_SOURCE} – TTC", rows=ttc))
|
||
return out
|
||
|
||
|
||
def _source_eu_bulletin():
|
||
"""Prix hebdomadaires français du bulletin pétrolier européen (TTC et hors taxes)."""
|
||
url = upstream.eu_bulletin_url()
|
||
raw = upstream.fetch_bytes(url, 200)
|
||
with_ttc = upstream.parse_eu_bulletin(raw, "FR", "Prices with taxes")
|
||
without = upstream.parse_eu_bulletin(raw, "FR", "Prices wo taxes")
|
||
out = []
|
||
for product in ("diesel", "euro95", "euro98"):
|
||
ttc = [
|
||
dict(day=row["day"], value=row["prices"][product]) for row in with_ttc if product in row["prices"]
|
||
]
|
||
htt = [
|
||
dict(day=row["day"], value=row["prices"][product]) for row in without if product in row["prices"]
|
||
]
|
||
if ttc:
|
||
out.append(
|
||
dict(series=f"eu_fr_{product}_ttc", unit="EUR/L", source=f"{EU_SOURCE} – TTC", rows=ttc)
|
||
)
|
||
if htt:
|
||
out.append(
|
||
dict(
|
||
series=f"eu_fr_{product}_htt", unit="EUR/L", source=f"{EU_SOURCE} – hors taxes", rows=htt
|
||
)
|
||
)
|
||
return out
|
||
|
||
|
||
def _source_market_daily():
|
||
"""Cotation quotidienne du Brent + taux BCE, pour l'historique de long terme."""
|
||
import market
|
||
|
||
quote = market.fetch(force=True)
|
||
if quote.get("trend") == "unknown" and quote.get("price_usd") is None:
|
||
raise ValueError(quote.get("summary", "cotation indisponible"))
|
||
out = []
|
||
if quote.get("price_usd") and quote.get("date"):
|
||
out.append(
|
||
dict(
|
||
series="brent_usd_daily",
|
||
unit="USD/baril",
|
||
source=quote.get("source") or MARKET_SOURCE,
|
||
rows=[dict(day=quote["date"], value=quote["price_usd"])],
|
||
)
|
||
)
|
||
if quote.get("price_eur") and quote.get("date"):
|
||
out.append(
|
||
dict(
|
||
series="brent_eur_daily",
|
||
unit="EUR/baril",
|
||
source=quote.get("source") or MARKET_SOURCE,
|
||
rows=[dict(day=quote["date"], value=quote["price_eur"])],
|
||
)
|
||
)
|
||
rate = market.ecb_usd_per_eur()
|
||
if rate:
|
||
out.append(
|
||
dict(
|
||
series="usd_per_eur",
|
||
unit="USD/EUR",
|
||
source="BCE (quotidien)",
|
||
rows=[dict(day=datetime.now(timezone.utc).date().isoformat(), value=rate)],
|
||
)
|
||
)
|
||
return out
|
||
|
||
|
||
def _source_chokepoints():
|
||
entries, warning = upstream.fetch_chokepoints()
|
||
if not entries:
|
||
raise ValueError(warning or "aucun détroit exploitable")
|
||
return entries
|
||
|
||
|
||
UPSTREAM_SOURCES = {
|
||
"dgec": _source_dgec,
|
||
"eu_bulletin": _source_eu_bulletin,
|
||
"market_daily": _source_market_daily,
|
||
"chokepoints": _source_chokepoints,
|
||
}
|
||
|
||
|
||
def collect_upstream(force=False, sources=None):
|
||
"""Collecte les séries amont une fois par jour civil (heure de Paris)."""
|
||
sources = UPSTREAM_SOURCES if sources is None else sources
|
||
now = datetime.now(timezone.utc)
|
||
day = now.astimezone(storage.PARIS).date().isoformat()
|
||
with storage.connect() as db:
|
||
previous = db.execute("SELECT status FROM upstream_runs WHERE day=?", (day,)).fetchone()
|
||
if not force and previous and previous["status"] == "ok":
|
||
return dict(status="skipped", day=day, detail="déjà collecté aujourd’hui")
|
||
storage.DB_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||
with (storage.DB_PATH.parent / "upstream.lock").open("a") as lock:
|
||
try:
|
||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||
except BlockingIOError:
|
||
return dict(status="busy", day=day, detail="collecte amont déjà en cours")
|
||
stored, failures, chokepoints = 0, [], 0
|
||
for name, source in sources.items():
|
||
try:
|
||
payload = source()
|
||
if name == "chokepoints":
|
||
chokepoints = storage.save_chokepoints(payload, PORTWATCH_SOURCE, now)
|
||
continue
|
||
for block in payload:
|
||
stored += storage.save_upstream(
|
||
block["series"], block["rows"], block["unit"], block["source"], now
|
||
)
|
||
except Exception as exc:
|
||
failures.append(f"{name}: {type(exc).__name__} {str(exc)[:90]}")
|
||
outcome = "partial" if failures and stored else "error" if failures else "ok"
|
||
detail = " ; ".join(failures)[:400]
|
||
with storage.connect() as db:
|
||
db.execute(
|
||
"REPLACE INTO upstream_runs VALUES(?,?,?,?,?,?)",
|
||
(day, outcome, stored, chokepoints, detail, now.isoformat()),
|
||
)
|
||
return dict(status=outcome, day=day, series=stored, chokepoints=chokepoints, detail=detail)
|
||
|
||
|
||
def collect(load=None, force=False):
|
||
upstream_result = {"status": "not_run"}
|
||
try:
|
||
upstream_result = collect_upstream(force=force)
|
||
except Exception as exc: # ne doit jamais empêcher la collecte locale
|
||
upstream_result = {"status": "error", "detail": f"{type(exc).__name__}: {str(exc)[:120]}"}
|
||
if load is None:
|
||
import app
|
||
|
||
def load():
|
||
return app.load_fuel_data(force=True)
|
||
|
||
now = datetime.now(timezone.utc)
|
||
day = now.astimezone(storage.PARIS).date().isoformat()
|
||
storage.DB_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||
with (storage.DB_PATH.parent / "collection.lock").open("a") as lock:
|
||
try:
|
||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||
except BlockingIOError:
|
||
return {"status": "busy", "count": 0, "upstream": upstream_result}
|
||
favorites = storage.list_entities("favorites")
|
||
if not favorites:
|
||
return {"status": "no_favorites", "count": 0, "upstream": upstream_result}
|
||
with storage.connect() as db:
|
||
last = db.execute(
|
||
"SELECT finished_at FROM collections WHERE status='ok' ORDER BY id DESC LIMIT 1"
|
||
).fetchone()
|
||
if (
|
||
not force
|
||
and last
|
||
and datetime.fromisoformat(last[0]).astimezone(storage.PARIS).date().isoformat() == day
|
||
):
|
||
return {"status": "skipped", "count": 0, "upstream": upstream_result}
|
||
db.execute(
|
||
"UPDATE collections SET status='error', detail='Collecte précédente interrompue' "
|
||
"WHERE status='running'"
|
||
)
|
||
job = db.execute(
|
||
"INSERT INTO collections(started_at,status) VALUES(?,'running')", (now.isoformat(),)
|
||
).lastrowid
|
||
count, detail, outcome = 0, "", "ok"
|
||
try:
|
||
rows = load()
|
||
if not rows:
|
||
raise ValueError("Le flux national ne contient aucune station exploitable")
|
||
selected = [
|
||
row
|
||
for row in rows
|
||
if any(
|
||
storage.distance_km(f["lat"], f["lon"], row["lat"], row["lon"]) <= f["radius_km"]
|
||
for f in favorites
|
||
)
|
||
]
|
||
count = storage.record_observations(selected, now)
|
||
storage.sync_station_names(rows, now)
|
||
if not selected:
|
||
detail = "Aucune station dans les favoris actuels"
|
||
except Exception as exc:
|
||
outcome, detail = "error", f"{type(exc).__name__}: {str(exc)[:250]}"
|
||
with storage.connect() as db:
|
||
db.execute(
|
||
"UPDATE collections SET finished_at=?, status=?, count=?, detail=? WHERE id=?",
|
||
(datetime.now(timezone.utc).isoformat(), outcome, count, detail, job),
|
||
)
|
||
db.execute(
|
||
"DELETE FROM observations WHERE day<?", ((now - timedelta(days=730)).date().isoformat(),)
|
||
)
|
||
db.execute(
|
||
"DELETE FROM market_daily WHERE day<?", ((now - timedelta(days=730)).date().isoformat(),)
|
||
)
|
||
db.execute(
|
||
"DELETE FROM chokepoint_daily WHERE day<?", ((now - timedelta(days=730)).date().isoformat(),)
|
||
)
|
||
db.execute(
|
||
"DELETE FROM upstream_runs WHERE day<?", ((now - timedelta(days=400)).date().isoformat(),)
|
||
)
|
||
db.execute(
|
||
"DELETE FROM collections WHERE started_at<?", ((now - timedelta(days=90)).isoformat(),)
|
||
)
|
||
return dict(status=outcome, count=count, detail=detail, upstream=upstream_result)
|
||
|
||
|
||
def _selected_stations(rows, favorites):
|
||
return [
|
||
row
|
||
for row in rows
|
||
if any(
|
||
storage.distance_km(f["lat"], f["lon"], row["lat"], row["lon"]) <= f["radius_km"]
|
||
for f in favorites
|
||
)
|
||
]
|
||
|
||
|
||
def job_local_prices(force=False, load=None):
|
||
"""Prix locaux : chaque heure pour chaque zone suivie, sans doublon à l'identique.
|
||
|
||
Un événement prix n'est journalisé que si le prix ou l'horodatage déclaré par la station
|
||
a changé ; l'instantané quotidien reste disponible pour les médianes et les tendances.
|
||
"""
|
||
favorites = storage.list_entities("favorites")
|
||
if not favorites:
|
||
return dict(status="unchanged", stored=0, detail="aucun favori suivi")
|
||
if load is None:
|
||
import app
|
||
|
||
def load():
|
||
return app.load_fuel_data(force=True)
|
||
|
||
now = datetime.now(timezone.utc)
|
||
rows = load()
|
||
selected = _selected_stations(rows, favorites)
|
||
if not selected:
|
||
return dict(status="unchanged", stored=0, detail="aucune station dans le rayon des favoris actuels")
|
||
storage.record_observations(selected, now)
|
||
storage.sync_station_names(rows, now)
|
||
events = storage.record_price_events(selected, now)
|
||
declared = [
|
||
row["updates"].get(fuel) for row in selected for fuel in row["prices"] if row["updates"].get(fuel)
|
||
]
|
||
return dict(
|
||
status="ok",
|
||
stored=events,
|
||
events=events,
|
||
stations=len(selected),
|
||
last_observation_at=max(declared) if declared else None,
|
||
detail=f"{len(selected)} stations comparées, {events} changement(s) de prix enregistré(s)",
|
||
)
|
||
|
||
|
||
def ensure_fresh_local(max_age_seconds=900):
|
||
"""Actualise le flux local s'il a plus de 10–15 minutes, sur demande de conseil."""
|
||
import app
|
||
|
||
cached = app.cache_get("fuel_data", ttl=10**9)
|
||
stamp = None
|
||
with sqlite3.connect(app.CACHE_DB, timeout=20) as db:
|
||
row = db.execute("SELECT ts FROM cache WHERE key='fuel_data'").fetchone()
|
||
stamp = row[0] if row else None
|
||
age = None if stamp is None else time.time() - stamp
|
||
if cached is not None and age is not None and age <= max_age_seconds:
|
||
return dict(refreshed=False, age_seconds=round(age, 1))
|
||
rows = app.load_fuel_data(force=True)
|
||
storage.sync_station_names(rows)
|
||
return dict(refreshed=True, age_seconds=None if age is None else round(age, 1), stations=len(rows))
|
||
|
||
|
||
def _delta_series(name, rows):
|
||
"""Nombre de valeurs réellement nouvelles pour une série (détection de nouvelle période)."""
|
||
known = {row["day"] for row in storage.upstream_series(name)}
|
||
return [row for row in rows if row["day"] not in known]
|
||
|
||
|
||
def job_dgec_monthly(force=False):
|
||
"""DGEC : Brent, marge de raffinage, prix HTT/TTC — contrôle quotidien, publication mensuelle."""
|
||
urls = upstream.dgec_urls()
|
||
stored, newest, unchanged = 0, None, True
|
||
brent = upstream.parse_dgec_brent(upstream.fetch_bytes(urls["brent"], 90))
|
||
if _delta_series("dgec_brent_usd", brent):
|
||
unchanged = False
|
||
stored += storage.save_upstream("dgec_brent_usd", brent, "USD/baril", DGEC_SOURCE)
|
||
margin = upstream.parse_dgec_margin(upstream.fetch_bytes(urls["margin"], 90))
|
||
stored += storage.save_upstream(
|
||
"dgec_margin_usd_per_bbl",
|
||
[dict(day=row["day"], value=row["usd_per_bbl"]) for row in margin],
|
||
"USD/baril",
|
||
DGEC_SOURCE,
|
||
)
|
||
stored += storage.save_upstream(
|
||
"dgec_margin_eur_per_tonne",
|
||
[dict(day=row["day"], value=row["eur_per_tonne"]) for row in margin],
|
||
"EUR/tonne",
|
||
DGEC_SOURCE,
|
||
)
|
||
prices = upstream.parse_dgec_prices(upstream.fetch_bytes(urls["prices"], 90))
|
||
for fuel in storage.FUELS:
|
||
htt = [dict(day=row["day"], value=row["htt"][fuel]) for row in prices if fuel in row["htt"]]
|
||
ttc = [dict(day=row["day"], value=row["ttc"][fuel]) for row in prices if fuel in row["ttc"]]
|
||
if htt and _delta_series(f"fr_htt_{fuel}", htt):
|
||
unchanged = False
|
||
if htt:
|
||
stored += storage.save_upstream(f"fr_htt_{fuel}", htt, "EUR/L", f"{DGEC_SOURCE} – hors taxes")
|
||
if ttc:
|
||
stored += storage.save_upstream(f"fr_ttc_{fuel}", ttc, "EUR/L", f"{DGEC_SOURCE} – TTC")
|
||
newest = max([row["day"] for row in prices] or [row["day"] for row in brent] or [None])
|
||
return dict(
|
||
status="unchanged" if unchanged else "ok",
|
||
stored=stored,
|
||
last_observation_at=newest,
|
||
month=newest,
|
||
detail=("période déjà connue" if unchanged else "nouvelle période DGEC enregistrée"),
|
||
)
|
||
|
||
|
||
def job_eu_bulletin(force=False):
|
||
"""Bulletin pétrolier européen : publication hebdomadaire du jeudi."""
|
||
url = upstream.eu_bulletin_url()
|
||
raw = upstream.fetch_bytes(url, 200)
|
||
with_ttc = upstream.parse_eu_bulletin(raw, "FR", "Prices with taxes")
|
||
without = upstream.parse_eu_bulletin(raw, "FR", "Prices wo taxes")
|
||
stored = 0
|
||
for product in ("diesel", "euro95", "euro98"):
|
||
ttc = [
|
||
dict(day=row["day"], value=row["prices"][product]) for row in with_ttc if product in row["prices"]
|
||
]
|
||
htt = [
|
||
dict(day=row["day"], value=row["prices"][product]) for row in without if product in row["prices"]
|
||
]
|
||
if ttc:
|
||
stored += storage.save_upstream(f"eu_fr_{product}_ttc", ttc, "EUR/L", f"{EU_SOURCE} – TTC")
|
||
if htt:
|
||
stored += storage.save_upstream(f"eu_fr_{product}_htt", htt, "EUR/L", f"{EU_SOURCE} – hors taxes")
|
||
newest = max(row["day"] for row in with_ttc)
|
||
return dict(
|
||
status="ok", stored=stored, last_observation_at=newest, detail=f"semaine du {newest} enregistrée"
|
||
)
|
||
|
||
|
||
def job_market_daily(force=False):
|
||
"""Cotation quotidienne du Brent (Stooq, puis page publique ; clé EIA si fournie)."""
|
||
import market
|
||
|
||
quote = market.fetch(force=True)
|
||
if quote.get("price_usd") is None or not quote.get("date"):
|
||
return dict(status="error", stored=0, detail=quote.get("summary", "cotation indisponible")[:200])
|
||
rows = [
|
||
dict(
|
||
day=quote["date"], value=quote["price_usd"], observed_at=quote["date"], published_at=quote["date"]
|
||
)
|
||
]
|
||
stored = storage.save_upstream("brent_usd_daily", rows, "USD/baril", quote.get("source") or MARKET_SOURCE)
|
||
if quote.get("price_eur"):
|
||
stored += storage.save_upstream(
|
||
"brent_eur_daily",
|
||
[dict(rows[0], value=quote["price_eur"])],
|
||
"EUR/baril",
|
||
quote.get("source") or MARKET_SOURCE,
|
||
)
|
||
return dict(
|
||
status="ok",
|
||
stored=stored,
|
||
last_observation_at=quote["date"],
|
||
trend=quote.get("trend"),
|
||
detail=quote.get("summary", "")[:200],
|
||
)
|
||
|
||
|
||
def job_ecb_fx(force=False):
|
||
"""Taux BCE USD/EUR : jours ouvrés, après la publication de 16 h."""
|
||
import market
|
||
|
||
series = market.ecb_rate_series()
|
||
stored = storage.save_upstream(
|
||
"usd_per_eur",
|
||
[
|
||
dict(day=row["day"], value=row["value"], observed_at=row["day"], published_at=row["day"])
|
||
for row in series
|
||
],
|
||
"USD/EUR",
|
||
"BCE (quotidien, jours ouvrés)",
|
||
)
|
||
newest = max(row["day"] for row in series)
|
||
return dict(
|
||
status="ok", stored=stored, last_observation_at=newest, detail=f"taux de référence BCE du {newest}"
|
||
)
|
||
|
||
|
||
def job_portwatch(force=False):
|
||
"""Détroits : collecte quotidienne avec fenêtre glissante pour les révisions."""
|
||
pairs = upstream.fetch_chokepoint_window(12)
|
||
stored = storage.save_chokepoints(pairs, PORTWATCH_SOURCE)
|
||
newest = max(entry["day"] for _name, entry in pairs)
|
||
return dict(
|
||
status="ok",
|
||
stored=stored,
|
||
chokepoints=len({name for name, _ in pairs}),
|
||
last_observation_at=newest,
|
||
detail=f"fenêtre de 12 jours, dernière observation {newest}",
|
||
)
|
||
|
||
|
||
def job_brent_history(force=False):
|
||
"""Historique quotidien du Brent (plusieurs années), indépendant de la collecte du jour."""
|
||
import market
|
||
|
||
series = market.fetch_brent_history(years=int(os.environ.get("FUEL_BRENT_HISTORY_YEARS", 10)))
|
||
if not series:
|
||
raise RuntimeError("aucune cotation récupérée")
|
||
stored = storage.save_upstream(
|
||
"brent_futures_usd",
|
||
series,
|
||
"USD/baril",
|
||
"Brent futures BZ=F (Yahoo Finance) – contrat à échéance enchaîné, à n’utiliser qu’en variations",
|
||
)
|
||
return dict(
|
||
status="ok",
|
||
stored=stored,
|
||
last_observation_at=series[-1]["day"],
|
||
detail=f"{len(series)} jours ({series[0]['day']} → {series[-1]['day']})",
|
||
)
|
||
|
||
|
||
def job_fx_history(force=False):
|
||
"""Historique quotidien USD/EUR (BCE, service EXR) : indispensable aux variantes de marché."""
|
||
import market
|
||
|
||
series = market.fetch_fx_history(start=os.environ.get("FUEL_FX_HISTORY_START", "2015-01-01"))
|
||
if not series:
|
||
raise RuntimeError("aucun taux récupéré")
|
||
stored = storage.save_upstream("usd_per_eur", series, "USD/EUR", "BCE (EXR, API officielle)")
|
||
return dict(
|
||
status="ok",
|
||
stored=stored,
|
||
last_observation_at=series[-1]["day"],
|
||
detail=f"{len(series)} jours ({series[0]['day']} → {series[-1]['day']})",
|
||
)
|
||
|
||
|
||
def job_price_backfill(force=False):
|
||
"""Import rétrospectif des archives annuelles officielles (2007 → aujourd'hui).
|
||
|
||
Sépare de la collecte courante : les lignes importées gardent la date déclarée par la station
|
||
et portent ``origin=archive:<année>``. Sans cet import, les percentiles historiques devraient
|
||
attendre des mois de collecte.
|
||
"""
|
||
import backfill as backfill_module
|
||
|
||
fuels = tuple(
|
||
fuel.strip()
|
||
for fuel in os.environ.get("FUEL_BACKFILL_FUELS", "Gazole,E10").split(",")
|
||
if fuel.strip()
|
||
)
|
||
result = backfill_module.backfill(fuels=fuels)
|
||
years_done = len(result["years"])
|
||
detail = (
|
||
f"{years_done} année(s) importée(s), {result['imported']} nouvelles lignes, "
|
||
f"{result['skipped']} déjà à jour, {len(result['failures'])} échec(s)"
|
||
)
|
||
if result["failures"]:
|
||
detail += " : " + " ; ".join(
|
||
f"{item['year']} ({item['detail'][:60]})" for item in result["failures"][:3]
|
||
)
|
||
return dict(
|
||
status="ok",
|
||
stored=result["imported"],
|
||
detail=detail,
|
||
last_observation_at=max((item["year"] for item in result["years"]), default=None),
|
||
)
|
||
|
||
|
||
def job_chokepoint_reference(force=False):
|
||
"""Référence « normale » pré-crise des détroits, mesurée avant la période récente.
|
||
|
||
Indispensable avant tout apprentissage : sans référence pré-crise, un historique local commencé
|
||
pendant une perturbation ferait passer un trafic effondré pour un niveau normal.
|
||
"""
|
||
rows = upstream.fetch_chokepoint_reference()
|
||
if not rows:
|
||
raise RuntimeError("aucune référence pré-crise récupérée")
|
||
saved = storage.save_chokepoint_reference(list(rows.values()))
|
||
detail = " · ".join(
|
||
f"{name} : médiane {row['tankers_median']:.0f} pétroliers/jour "
|
||
f"({row['observations']} jours, {row['window_start']} → {row['window_end']})"
|
||
for name, row in list(rows.items())[:4]
|
||
)
|
||
return dict(status="ok", saved=saved, detail=detail)
|
||
|
||
|
||
def job_news_geo(force=False):
|
||
"""Actualités géopolitiques et logistiques : contrôle toutes les 2 heures."""
|
||
import news
|
||
|
||
outcome = news.collect(force=force)
|
||
outcome.setdefault("stored", outcome.get("events", 0))
|
||
return outcome
|
||
|
||
|
||
def job_promotions(force=False):
|
||
"""Opérations commerciales : plusieurs contrôles par jour."""
|
||
import promotions
|
||
|
||
outcome = promotions.collect(force=force)
|
||
outcome.setdefault("stored", outcome.get("promotions", 0))
|
||
return outcome
|
||
|
||
|
||
if __name__ == "__main__":
|
||
import sys
|
||
|
||
if "--upstream-only" in sys.argv:
|
||
result = collect_upstream(force="--force" in sys.argv)
|
||
else:
|
||
result = collect(force="--force" in sys.argv)
|
||
print(datetime.now(timezone.utc).isoformat(), json.dumps(result, ensure_ascii=False), flush=True)
|
||
sys.exit(1 if result["status"] in ("error",) else 0)
|