Ordonnanceur multi-frequences, supervision, promotions et metadonnees temporelles

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.
This commit is contained in:
root
2026-09-12 22:49:22 +02:00
parent a2434836c4
commit 41ddb98749
21 changed files with 2041 additions and 146 deletions

View File

@@ -3,6 +3,7 @@
Aucune clé d'API. Aucune donnée inventée : une source absente reste absente et est signalée
avec sa fraîcheur. Les parseurs sont purs (ils reçoivent des octets) pour rester testables.
"""
from __future__ import annotations
import io
@@ -14,32 +15,40 @@ import zipfile
from datetime import date, datetime, timedelta, timezone
from xml.etree import ElementTree as ET
NS = '{http://schemas.openxmlformats.org/spreadsheetml/2006/main}'
NS = "{http://schemas.openxmlformats.org/spreadsheetml/2006/main}"
USER_AGENT = (
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Safari/537.36'
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Safari/537.36"
)
EXCEL_EPOCH = datetime(1899, 12, 30)
DGEC_BASE = 'https://www.ecologie.gouv.fr/sites/default/files/documents/'
DGEC_BASE = "https://www.ecologie.gouv.fr/sites/default/files/documents/"
DGEC_FILES = {
'brent': 'Historique%20du%20cours%20du%20Brent%20depuis%202015%20%28moyennes%20mensuelles%29_0.xlsx',
'margin': ('Historique%20de%20la%20marge%20brute%20de%20raffinage%20sur%20Brent%20depuis%202015'
'%20%28moyennes%20mensuelles%29.xlsx'),
'prices': 'Prix%20HTT%20et%20TTC%20depuis%20janvier%202020_0.xlsx',
"brent": "Historique%20du%20cours%20du%20Brent%20depuis%202015%20%28moyennes%20mensuelles%29_0.xlsx",
"margin": (
"Historique%20de%20la%20marge%20brute%20de%20raffinage%20sur%20Brent%20depuis%202015"
"%20%28moyennes%20mensuelles%29.xlsx"
),
"prices": "Prix%20HTT%20et%20TTC%20depuis%20janvier%202020_0.xlsx",
}
FUEL_COLUMNS = {
'Gazole': 'Gazole', 'SP95': 'Super SP95-E5', 'E10': 'Super SP95-E10',
'SP98': 'Super SP98', 'E85': 'Superéthanol E85', 'GPLc': 'GPLc',
"Gazole": "Gazole",
"SP95": "Super SP95-E5",
"E10": "Super SP95-E10",
"SP98": "Super SP98",
"E85": "Superéthanol E85",
"GPLc": "GPLc",
}
EU_BULLETIN_PAGE = 'https://energy.ec.europa.eu/data-and-analysis/weekly-oil-bulletin_en'
EU_FUELS = {'Gazole': 'diesel', 'SP95': 'euro95', 'SP98': 'euro98', 'E10': 'euro95', 'E85': 'euro95'}
PORTWATCH_QUERY = ('https://services9.arcgis.com/weJ1QsnbMYJlCHdG/arcgis/rest/services/'
'Daily_Chokepoints_Data/FeatureServer/0/query')
WATCHED_CHOKEPOINTS = ('Strait of Hormuz', 'Bab el-Mandeb Strait', 'Suez Canal', 'Malacca Strait')
EU_BULLETIN_PAGE = "https://energy.ec.europa.eu/data-and-analysis/weekly-oil-bulletin_en"
EU_FUELS = {"Gazole": "diesel", "SP95": "euro95", "SP98": "euro98", "E10": "euro95", "E85": "euro95"}
PORTWATCH_QUERY = (
"https://services9.arcgis.com/weJ1QsnbMYJlCHdG/arcgis/rest/services/"
"Daily_Chokepoints_Data/FeatureServer/0/query"
)
WATCHED_CHOKEPOINTS = ("Strait of Hormuz", "Bab el-Mandeb Strait", "Suez Canal", "Malacca Strait")
def fetch_bytes(url, timeout=60, limit=12_000_000):
request = urllib.request.Request(url, headers={'User-Agent': USER_AGENT, 'Accept': '*/*'})
request = urllib.request.Request(url, headers={"User-Agent": USER_AGENT, "Accept": "*/*"})
with urllib.request.urlopen(request, timeout=timeout) as response:
return response.read(limit)
@@ -58,28 +67,30 @@ def excel_date(serial):
def xlsx_cells(raw, sheet=None):
"""Cellules {'A1': valeur} d'une feuille, valeurs partagées résolues."""
with zipfile.ZipFile(io.BytesIO(raw)) as archive:
workbook = archive.read('xl/workbook.xml').decode('utf-8', 'replace')
rels = archive.read('xl/_rels/workbook.xml.rels').decode('utf-8', 'replace')
workbook = archive.read("xl/workbook.xml").decode("utf-8", "replace")
rels = archive.read("xl/_rels/workbook.xml.rels").decode("utf-8", "replace")
targets = dict(re.findall(r'Id="(rId\d+)"[^>]*Target="([^"]+)"', rels))
sheets = dict((name, targets.get(rid)) for name, rid in
re.findall(r'<sheet[^>]*name="([^"]+)"[^>]*r:id="(rId\d+)"', workbook))
sheets = dict(
(name, targets.get(rid))
for name, rid in re.findall(r'<sheet[^>]*name="([^"]+)"[^>]*r:id="(rId\d+)"', workbook)
)
if not sheets:
raise ValueError('classeur sans feuille')
raise ValueError("classeur sans feuille")
name = sheet if sheet in sheets else next(iter(sheets))
strings = []
if 'xl/sharedStrings.xml' in archive.namelist():
root = ET.fromstring(archive.read('xl/sharedStrings.xml'))
strings = [''.join(node.text or '' for node in item.iter()) for item in root]
sheet_xml = ET.fromstring(archive.read('xl/' + sheets[name].lstrip('/')))
if "xl/sharedStrings.xml" in archive.namelist():
root = ET.fromstring(archive.read("xl/sharedStrings.xml"))
strings = ["".join(node.text or "" for node in item.iter()) for item in root]
sheet_xml = ET.fromstring(archive.read("xl/" + sheets[name].lstrip("/")))
cells = {}
for cell in sheet_xml.iter(NS + 'c'):
value = cell.find(NS + 'v')
for cell in sheet_xml.iter(NS + "c"):
value = cell.find(NS + "v")
if value is None or value.text is None:
continue
reference = cell.attrib.get('r', '')
reference = cell.attrib.get("r", "")
if not reference:
continue
cells[reference] = strings[int(value.text)] if cell.attrib.get('t') == 's' else value.text
cells[reference] = strings[int(value.text)] if cell.attrib.get("t") == "s" else value.text
return cells
@@ -87,17 +98,17 @@ def column_headers(cells, row=1):
"""En-têtes de la ligne ``row`` : {'CN': 'FR_price_with_tax_euro95'}."""
out = {}
for reference, value in cells.items():
match = re.fullmatch(r'([A-Z]{1,3})%d' % row, reference)
match = re.fullmatch(r"([A-Z]{1,3})%d" % row, reference)
if match and isinstance(value, str):
out[match.group(1)] = value
return out
def _rows_by_date(cells, date_column='A', first_row=4):
def _rows_by_date(cells, date_column="A", first_row=4):
"""Associe chaque ligne à sa date ISO via la colonne de dates."""
out = {}
for reference, value in cells.items():
match = re.fullmatch(re.escape(date_column) + r'(\d+)', reference)
match = re.fullmatch(re.escape(date_column) + r"(\d+)", reference)
if not match:
continue
day = excel_date(value)
@@ -106,12 +117,12 @@ def _rows_by_date(cells, date_column='A', first_row=4):
return out
def parse_dgec_brent(raw, sheet='Cours du Brent'):
def parse_dgec_brent(raw, sheet="Cours du Brent"):
"""Cours moyen mensuel du Brent daté (DGEC, $/baril), lignes annuelles écartées."""
cells = xlsx_cells(raw, sheet)
out = []
for row, day in sorted(_rows_by_date(cells, 'A', 3).items()):
value = cells.get('B%d' % row)
for row, day in sorted(_rows_by_date(cells, "A", 3).items()):
value = cells.get("B%d" % row)
try:
price = float(value)
except (TypeError, ValueError):
@@ -119,98 +130,101 @@ def parse_dgec_brent(raw, sheet='Cours du Brent'):
if 5 <= price <= 400:
out.append(dict(day=day, value=round(price, 2)))
if not out:
raise ValueError('cours du Brent illisible')
raise ValueError("cours du Brent illisible")
return out
def parse_dgec_margin(raw, sheet='Marge brute raffinage sur Brent'):
def parse_dgec_margin(raw, sheet="Marge brute raffinage sur Brent"):
"""Marge brute de raffinage sur Brent (DGEC) en $/baril et en €/tonne."""
cells = xlsx_cells(raw, sheet)
out = []
for row, day in sorted(_rows_by_date(cells, 'A', 3).items()):
for row, day in sorted(_rows_by_date(cells, "A", 3).items()):
try:
usd = float(cells.get('B%d' % row))
eur = float(cells.get('C%d' % row))
usd = float(cells.get("B%d" % row))
eur = float(cells.get("C%d" % row))
except (TypeError, ValueError):
continue
if -20 <= usd <= 100 and -100 <= eur <= 800:
out.append(dict(day=day, usd_per_bbl=round(usd, 2), eur_per_tonne=round(eur, 2)))
if not out:
raise ValueError('marge de raffinage illisible')
raise ValueError("marge de raffinage illisible")
return out
def parse_dgec_prices(raw, sheet='Carburants routiers'):
def parse_dgec_prices(raw, sheet="Carburants routiers"):
"""Prix moyens français HTT et TTC par carburant (DGEC)."""
cells = xlsx_cells(raw, sheet)
headers = column_headers(cells, 2)
htt = {letter: name for letter, name in headers.items() if letter < 'H'}
ttc = {letter: name for letter, name in headers.items() if letter >= 'H'}
htt = {letter: name for letter, name in headers.items() if letter < "H"}
ttc = {letter: name for letter, name in headers.items() if letter >= "H"}
out = []
for row, day in sorted(_rows_by_date(cells, 'A', 3).items()):
for row, day in sorted(_rows_by_date(cells, "A", 3).items()):
entry = dict(day=day, htt={}, ttc={})
for letter, name in htt.items():
fuel = next((f for f, label in FUEL_COLUMNS.items() if label == name), None)
try:
entry['htt'][fuel] = round(float(cells['%s%d' % (letter, row)]), 3)
entry["htt"][fuel] = round(float(cells["%s%d" % (letter, row)]), 3)
except (KeyError, TypeError, ValueError):
continue
for letter, name in ttc.items():
fuel = next((f for f, label in FUEL_COLUMNS.items() if label == name), None)
try:
entry['ttc'][fuel] = round(float(cells['%s%d' % (letter, row)]), 3)
entry["ttc"][fuel] = round(float(cells["%s%d" % (letter, row)]), 3)
except (KeyError, TypeError, ValueError):
continue
if entry['htt'] or entry['ttc']:
if entry["htt"] or entry["ttc"]:
out.append(entry)
if not out:
raise ValueError('prix HTT/TTC illisibles')
raise ValueError("prix HTT/TTC illisibles")
return out
def parse_eu_bulletin(raw, country='FR', sheet='Prices with taxes'):
def parse_eu_bulletin(raw, country="FR", sheet="Prices with taxes"):
"""Prix hebdomadaires par pays du bulletin pétrolier UE (€/1000 L -> €/L)."""
cells = xlsx_cells(raw, sheet)
headers = column_headers(cells, 1)
columns = {}
for letter, name in headers.items():
match = re.fullmatch(re.escape(country) + r'_price_(?:with_tax|wo_tax|without_tax)_(\w+)', name)
match = re.fullmatch(re.escape(country) + r"_price_(?:with_tax|wo_tax|without_tax)_(\w+)", name)
if match:
columns[letter] = match.group(1)
if not columns:
raise ValueError(f'pays {country} absent du bulletin')
raise ValueError(f"pays {country} absent du bulletin")
out = []
for row, day in sorted(_rows_by_date(cells, 'A', 4).items()):
for row, day in sorted(_rows_by_date(cells, "A", 4).items()):
entry = dict(day=day, prices={})
for letter, product in columns.items():
try:
entry['prices'][product] = round(float(cells['%s%d' % (letter, row)]) / 1000, 3)
entry["prices"][product] = round(float(cells["%s%d" % (letter, row)]) / 1000, 3)
except (KeyError, TypeError, ValueError):
continue
if entry['prices']:
if entry["prices"]:
out.append(entry)
if not out:
raise ValueError('aucune semaine exploitable')
raise ValueError("aucune semaine exploitable")
return out
def parse_chokepoints(payload):
"""Dernière valeur connue par détroit surveillé (source IMF PortWatch)."""
try:
features = json.loads(payload)['features']
features = json.loads(payload)["features"]
except (KeyError, TypeError, ValueError):
raise ValueError('flux PortWatch illisible') from None
raise ValueError("flux PortWatch illisible") from None
latest = {}
for feature in features:
attributes = feature.get('attributes') or {}
name = attributes.get('portname')
day = str(attributes.get('date') or '')
if name not in WATCHED_CHOKEPOINTS or not re.fullmatch(r'\d{4}-\d{2}-\d{2}', day):
attributes = feature.get("attributes") or {}
name = attributes.get("portname")
day = str(attributes.get("date") or "")
if name not in WATCHED_CHOKEPOINTS or not re.fullmatch(r"\d{4}-\d{2}-\d{2}", day):
continue
if name not in latest or day > latest[name]['day']:
if name not in latest or day > latest[name]["day"]:
latest[name] = dict(
day=day, transit_tankers=attributes.get('n_tanker'), transit_total=attributes.get('n_total'),
capacity_tankers=attributes.get('capacity_tanker'), capacity_total=attributes.get('capacity'),
day=day,
transit_tankers=attributes.get("n_tanker"),
transit_total=attributes.get("n_total"),
capacity_tankers=attributes.get("capacity_tanker"),
capacity_total=attributes.get("capacity"),
)
return latest
@@ -221,10 +235,10 @@ def freshness(day, today=None, max_age_days=10):
try:
age = (today - date.fromisoformat(day)).days
except (TypeError, ValueError):
return dict(state='unknown', age_days=None)
return dict(state="unknown", age_days=None)
if age < 0:
return dict(state='unknown', age_days=age)
return dict(state='fresh' if age <= max_age_days else 'stale', age_days=age)
return dict(state="unknown", age_days=age)
return dict(state="fresh" if age <= max_age_days else "stale", age_days=age)
def dgec_urls():
@@ -233,27 +247,76 @@ def dgec_urls():
def eu_bulletin_url():
"""Le bulletin hebdomadaire est publié derrière une URL à identifiant variable."""
html = fetch_bytes(EU_BULLETIN_PAGE, timeout=45).decode('utf-8', 'replace')
html = fetch_bytes(EU_BULLETIN_PAGE, timeout=45).decode("utf-8", "replace")
links = re.findall(r'href="([^"]*filename=[^"]*\.xlsx)"', html, re.I)
history = [link for link in links if re.search(r'histor', urllib.parse.unquote(link), re.I)]
history = [link for link in links if re.search(r"histor", urllib.parse.unquote(link), re.I)]
if not history:
raise ValueError('fichier d’historique du bulletin introuvable')
url = history[0].replace('&amp;', '&')
return url if url.startswith('http') else 'https://energy.ec.europa.eu' + url
raise ValueError("fichier d’historique du bulletin introuvable")
url = history[0].replace("&amp;", "&")
return url if url.startswith("http") else "https://energy.ec.europa.eu" + url
def fetch_chokepoint_window(days=12, today=None):
"""Fenêtre glissante : les révisions de PortWatch doivent mettre à jour les jours déjà connus."""
today = today or datetime.now(timezone.utc).date()
start = (today - timedelta(days=days)).isoformat()
query = urllib.parse.urlencode(
{
"where": f"date >= DATE '{start}' AND date <= DATE '{today.isoformat()}'",
"outFields": "*",
"returnGeometry": "false",
"orderByFields": "date ASC",
"resultRecordCount": "1000",
"f": "json",
}
)
payload = fetch_bytes(f"{PORTWATCH_QUERY}?{query}", timeout=45)
try:
features = json.loads(payload)["features"]
except (KeyError, TypeError, ValueError):
raise ValueError("flux PortWatch illisible") from None
pairs = []
for feature in features:
attributes = feature.get("attributes") or {}
name = attributes.get("portname")
day = str(attributes.get("date") or "")
if name not in WATCHED_CHOKEPOINTS or not re.fullmatch(r"\d{4}-\d{2}-\d{2}", day):
continue
pairs.append(
(
name,
dict(
day=day,
transit_tankers=attributes.get("n_tanker"),
transit_total=attributes.get("n_total"),
capacity_tankers=attributes.get("capacity_tanker"),
capacity_total=attributes.get("capacity"),
),
)
)
if not pairs:
raise ValueError("aucune donnée de détroit dans la fenêtre demandée")
return pairs
def fetch_chokepoints(days=6, today=None):
"""Détroits surveillés : quelques jours suffisent, la source a du retard."""
today = today or datetime.now(timezone.utc).date()
query = urllib.parse.urlencode({
'where': f"date >= DATE '{today.isoformat()}'", 'outFields': '*',
'returnGeometry': 'false', 'orderByFields': 'date DESC', 'resultRecordCount': '200', 'f': 'json',
})
query = urllib.parse.urlencode(
{
"where": f"date >= DATE '{today.isoformat()}'",
"outFields": "*",
"returnGeometry": "false",
"orderByFields": "date DESC",
"resultRecordCount": "200",
"f": "json",
}
)
for offset in range(days, days + 12, 6):
lookback = (today - timedelta(days=offset)).isoformat()
probe = query.replace(urllib.parse.quote(today.isoformat()), urllib.parse.quote(lookback))
payload = fetch_bytes(f'{PORTWATCH_QUERY}?{probe}', timeout=40)
payload = fetch_bytes(f"{PORTWATCH_QUERY}?{probe}", timeout=40)
found = parse_chokepoints(payload)
if found:
return found, None
return {}, 'PortWatch : aucune donnée récente (retard de publication ou service indisponible)'
return {}, "PortWatch : aucune donnée récente (retard de publication ou service indisponible)"