"""Sources amont officielles : DGEC, bulletin pétrolier UE, détroits maritimes (IMF PortWatch). 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 import json import re import urllib.parse import urllib.request import zipfile from datetime import date, datetime, timedelta, timezone from xml.etree import ElementTree as ET 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" ) EXCEL_EPOCH = datetime(1899, 12, 30) 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", } FUEL_COLUMNS = { "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") def fetch_bytes(url, timeout=60, limit=12_000_000): request = urllib.request.Request(url, headers={"User-Agent": USER_AGENT, "Accept": "*/*"}) with urllib.request.urlopen(request, timeout=timeout) as response: return response.read(limit) def excel_date(serial): """Convertit une date série Excel (avec le bug 1900) en date ISO. None si illisible.""" try: value = float(serial) except (TypeError, ValueError): return None if not 20000 <= value <= 60000: return None return (EXCEL_EPOCH + timedelta(days=value)).date().isoformat() 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") targets = dict(re.findall(r'Id="(rId\d+)"[^>]*Target="([^"]+)"', rels)) sheets = dict( (name, targets.get(rid)) for name, rid in re.findall(r']*name="([^"]+)"[^>]*r:id="(rId\d+)"', workbook) ) if not sheets: 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("/"))) cells = {} 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", "") if not reference: continue cells[reference] = strings[int(value.text)] if cell.attrib.get("t") == "s" else value.text return cells 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) if match and isinstance(value, str): out[match.group(1)] = value return out 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) if not match: continue day = excel_date(value) if day and int(match.group(1)) >= first_row: out[int(match.group(1))] = day return out 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) try: price = float(value) except (TypeError, ValueError): continue if 5 <= price <= 400: out.append(dict(day=day, value=round(price, 2))) if not out: raise ValueError("cours du Brent illisible") return out 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()): try: 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") return out 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"} out = [] 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) 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) except (KeyError, TypeError, ValueError): continue if entry["htt"] or entry["ttc"]: out.append(entry) if not out: raise ValueError("prix HTT/TTC illisibles") return out 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) if match: columns[letter] = match.group(1) if not columns: raise ValueError(f"pays {country} absent du bulletin") out = [] 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) except (KeyError, TypeError, ValueError): continue if entry["prices"]: out.append(entry) if not out: 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"] except (KeyError, TypeError, ValueError): 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): continue 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"), ) return latest def freshness(day, today=None, max_age_days=10): """Fraîcheur d'une observation jamais présentée comme « à jour » par défaut.""" today = today or datetime.now(timezone.utc).date() try: age = (today - date.fromisoformat(day)).days except (TypeError, ValueError): 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) def dgec_urls(): return {key: DGEC_BASE + name for key, name in DGEC_FILES.items()} 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") 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)] if not history: raise ValueError("fichier d’historique du bulletin introuvable") url = history[0].replace("&", "&") 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", } ) 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) found = parse_chokepoints(payload) if found: return found, None return {}, "PortWatch : aucune donnée récente (retard de publication ou service indisponible)"