GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / globalgrid2050 / scripts

GlobalGrid2050 Update Oil Prices and 2 more files

A Python command-line tool in the scripts folder that fetches live oil prices, oil price history and fredgraph. It loads existing history (`load_existing_history`) and adds rows (`add_rows`).

505 lines of Python from globalgrid2050, in 3 files. Topic: Electricity markets and data pipelines. Section 890 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. GlobalGrid2050 Update Elexon System Prices Daily V4 energy-data · globalgrid2050 / scripts/update_elexon_system_prices_daily_v4.py lines 1–152
  2. GlobalGrid2050 Update Generation Recent MW V6 energy-data · globalgrid2050 / scripts/update_generation_recent_mw_v6.py lines 1–118
  3. GlobalGrid2050 Update Oil Prices energy-data · globalgrid2050 / scripts/update_oil_prices.py lines 1–235

GlobalGrid2050 Update Elexon System Prices Daily V4

A Python command-line tool in the scripts folder that fetches Elexon system prices half hourly from Elexon Balancing Mechanism Reporting Service (BMRS).

energy-dataglobalgrid2050 / scripts/update_elexon_system_prices_daily_v4.py · lines 1–152 of 152 · Entry point · pattern load_csv (shared by 2 files)

What it does
It fetches Elexon system prices half hourly. Defines 9 functions or classes, including pick, num, period_start, fetch_date, load_csv. Uses libraries csv, datetime, json, os, sys. Side effects: reads or writes files; makes network requests; starts processes.
Why it exists in the grid workflow
Domain stage hv_procurement (path word 'prices'): HV materials procurement, which Ventus Ltd states is within its commercial execution boundary.
Inputs & outputs
In: data source: Elexon BMRS; CSV file elexon_system_prices_half_hourly.csv.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Update Elexon System Prices Daily V4 Workflow (globalgrid2050).
What it achieves
It fetches date (`fetch_date`), loads CSV (`load_csv`) and sorts key (`sort_key`). Defines `pick`, `num`, `period_start` and 5 more.
Why it matters
Run by GlobalGrid2050 Update Elexon System Prices Daily V4 Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
csv, datetime, json, os, sys, urllib.request, pathlib
Used by
run by GlobalGrid2050 Update Elexon System Prices Daily V4 Workflow (workflow run)
Produces
pick, num, period_start, fetch_date, load_csv, sort_key, write_csv, year_file, main
Defines here
pick, num, period_start, fetch_date, load_csv, sort_key, write_csv, year_file, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 scripts/update_elexon_system_prices_daily_v4.py:1-152 · blob 35379ca39c87966677c1cf740f7563f4a4e20fd7 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem, network, process · domain stage: hv_procurement · users: EPC_contractor, procurement_buyer · canonical: production_core
import csv
import datetime as dt
import json
import os
import sys
import urllib.request
from pathlib import Path

BASE_URL = "https://data.elexon.co.uk/bmrs/api/v1/balancing/settlement/system-prices"
OUT_DIR = Path("data/electricity")
MASTER_FILE = OUT_DIR / "elexon_system_prices_half_hourly.csv"
FIELDS = [
    "source",
    "settlementDate",
    "settlementPeriod",
    "periodStartUTC",
    "systemBuyPriceGBPperMWh",
    "systemSellPriceGBPperMWh",
    "netImbalanceVolumeMWh",
    "fetchedAtUTC",
]


def pick(row, names):
    folded = {str(k).lower(): v for k, v in row.items()}
    for name in names:
        value = folded.get(name.lower())
        if value not in (None, ""):
            return value
    return ""


def num(value):
    if value in (None, ""):
        return ""
    try:
        return f"{float(value):.2f}"
    except Exception:
        return str(value)


def period_start(date_text, period):
    try:
        p = int(period)
        start = dt.datetime.fromisoformat(date_text).replace(tzinfo=dt.timezone.utc)
        start = start + dt.timedelta(minutes=(p - 1) * 30)
        return start.isoformat().replace("+00:00", "Z")
    except Exception:
        return ""


def fetch_date(day):
    date_text = day.isoformat()
    url = f"{BASE_URL}/{date_text}?format=json"
    req = urllib.request.Request(url, headers={"User-Agent": "GlobalGrid2050 GridBot"})
    with urllib.request.urlopen(req, timeout=45) as response:
        data = json.loads(response.read().decode("utf-8"))
    rows = data if isinstance(data, list) else data.get("data", [])
    fetched = dt.datetime.now(dt.timezone.utc).isoformat().replace("+00:00", "Z")
    output = []
    for row in rows:
        if not isinstance(row, dict):
            continue
        sp = pick(row, ["settlementPeriod", "period"])
        if sp == "":
            continue
        output.append({
            "source": "Elexon BMRS System Prices",
            "settlementDate": date_text,
            "settlementPeriod": str(sp),
            "periodStartUTC": period_start(date_text, sp),
            "systemBuyPriceGBPperMWh": num(pick(row, ["systemBuyPrice", "sbp"])),
            "systemSellPriceGBPperMWh": num(pick(row, ["systemSellPrice", "ssp"])),
            "netImbalanceVolumeMWh": num(pick(row, ["netImbalanceVolume", "niv"])),
            "fetchedAtUTC": fetched,
        })
    return output


def load_csv(path):
    if not path.exists():
        return {}
    rows = {}
    with path.open("r", encoding="utf-8", newline="") as handle:
        for row in csv.DictReader(handle):
            key = (row.get("settlementDate", ""), row.get("settlementPeriod", ""))
            if key[0] and key[1]:
                rows[key] = {field: row.get(field, "") for field in FIELDS}
    return rows


def sort_key(key):
    try:
        period = int(key[1])
    except Exception:
        period = 999
    return key[0], period


def write_csv(path, rows_by_key):
    path.parent.mkdir(parents=True, exist_ok=True)
    with path.open("w", encoding="utf-8", newline="") as handle:
        writer = csv.DictWriter(handle, fieldnames=FIELDS)
        writer.writeheader()
        for key in sorted(rows_by_key, key=sort_key):
            writer.writerow(rows_by_key[key])
    print(f"Wrote {len(rows_by_key)} rows to {path}")


def year_file(year):
    return OUT_DIR / f"elexon_system_prices_{year}.csv"


def main():
    today = dt.date.today()
    lookback_days = int(os.getenv("ELEXON_DAILY_LOOKBACK_DAYS", "3"))
    end_day = today - dt.timedelta(days=1)
    start_day = end_day - dt.timedelta(days=max(lookback_days - 1, 0))

    master = load_csv(MASTER_FILE)
    annual_cache = {}
    total_fetched = 0
    day = start_day
    while day <= end_day:
        try:
            rows = fetch_date(day)
            print(f"Fetched {len(rows)} Elexon System Price rows for {day}")
            if len(rows) not in (46, 48, 50):
                print(f"Warning: expected around 48 rows for {day}, received {len(rows)}")
            year = str(day.year)
            annual_path = year_file(year)
            if year not in annual_cache:
                annual_cache[year] = load_csv(annual_path)
            for row in rows:
                key = (row["settlementDate"], row["settlementPeriod"])
                master[key] = row
                annual_cache[year][key] = row
            total_fetched += len(rows)
        except Exception as exc:
            print(f"Warning: failed to fetch {day}: {exc}")
        day += dt.timedelta(days=1)

    if total_fetched == 0:
        sys.exit("No Elexon rows fetched")

    write_csv(MASTER_FILE, master)
    for year, rows in sorted(annual_cache.items()):
        write_csv(year_file(year), rows)


if __name__ == "__main__":
    main()

GlobalGrid2050 Update Generation Recent MW V6

A Python command-line tool in the scripts folder that parses time (`parse_time`) (units: MW), covering generation recent halfhourly 30d, solar and wind.

energy-dataglobalgrid2050 / scripts/update_generation_recent_mw_v6.py · lines 1–118 of 118 · Entry point · pattern parse_mw (shared by 6 files)

What it does
Defines group_for, parse_time, parse_mw, main. Uses libraries json, os, sys, datetime, collections. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'generation'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: solar, wind.
Inputs & outputs
In: JSON file generation_recent_halfhourly_30d.json; command-line arguments.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Update Generation Recent MW V6 Workflow (globalgrid2050).
What it achieves
Defines `group_for`, `parse_time` and `parse_mw`.
Why it matters
Run by GlobalGrid2050 Update Generation Recent MW V6 Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
GlobalGrid2050 Backfill Generation Sources Year V6 (import), json, os, sys, datetime, collections, pathlib
Used by
run by GlobalGrid2050 Update Generation Recent MW V6 Workflow (workflow run)
Produces
group_for, parse_time, parse_mw, main
Defines here
group_for, parse_time, parse_mw, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 scripts/update_generation_recent_mw_v6.py:1-118 · blob 1952492ad5f6a748818baf8ab7f676f6406be478 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import json
import os
import sys
import datetime as dt
from collections import defaultdict
from pathlib import Path

from backfill_generation_sources_year_v6 import fetch_elexon_day, fetch_pvlive_day, utc_now

OUT = Path('uk_energy_tracking_v6/generation_history/generation_recent_halfhourly_30d.json')
REPORT = Path('uk_energy_tracking_v6/generation_history/backfill_reports/GENERATION_RECENT_MW_SLICE.md')

GROUPS = {
    'Solar': ['SOLAR', 'PV'],
    'Wind': ['WIND'],
    'Hydro': ['NPSHYD', 'HYDRO'],
    'Gas': ['CCGT', 'OCGT'],
    'Coal': ['COAL'],
    'Biomass': ['BIOMASS'],
    'Nuclear': ['NUCLEAR'],
    'Pumped Storage': ['PS'],
    'Imports & Exports': ['INT'],
}


def group_for(fuel):
    f = str(fuel or '').upper()
    for label, prefixes in GROUPS.items():
        if any(f.startswith(prefix) for prefix in prefixes):
            return label
    return 'Other'


def parse_time(value):
    try:
        return dt.datetime.fromisoformat(str(value).replace('Z', '+00:00')).astimezone(dt.timezone.utc)
    except Exception:
        return None


def parse_mw(value):
    try:
        return float(value)
    except Exception:
        return None


def main():
    days = int(os.getenv('DAYS') or (sys.argv[1] if len(sys.argv) > 1 else 30))
    include_solar = os.getenv('INCLUDE_SOLAR', 'true').lower() not in ('0', 'false', 'no')
    today = dt.datetime.now(dt.timezone.utc).date()
    end_day = today - dt.timedelta(days=1)
    start_day = end_day - dt.timedelta(days=days - 1)
    deduped = {}
    raw_elexon = 0
    raw_solar = 0
    failed = []
    solar_status = 'not requested'
    solar_url = ''
    day = start_day
    while day <= end_day:
        try:
            rows = fetch_elexon_day(day)
            raw_elexon += len(rows)
            for row in rows:
                t = parse_time(row.get('periodStartUTC'))
                mw = parse_mw(row.get('generationMW'))
                fuel = row.get('fuelType', '')
                if not t or mw is None or not fuel:
                    continue
                tech = group_for(fuel)
                key = (t.isoformat().replace('+00:00', 'Z'), tech, fuel)
                deduped[key] = {'time': key[0], 'technology': tech, 'fuelType': fuel, 'generationMW': mw, 'source': row.get('source', 'Elexon BMRS FUELINST')}
            print(f'{day}: Elexon {len(rows)} rows')
        except Exception as exc:
            failed.append(f'{day} Elexon {exc}')
        if include_solar:
            try:
                rows, status, url = fetch_pvlive_day(day)
                raw_solar += len(rows)
                if url and not solar_url:
                    solar_url = url
                if rows:
                    solar_status = 'ok'
                elif solar_status != 'ok':
                    solar_status = status
                for row in rows:
                    t = parse_time(row.get('periodStartUTC'))
                    mw = parse_mw(row.get('generationMW'))
                    if not t or mw is None:
                        continue
                    key = (t.isoformat().replace('+00:00', 'Z'), 'Solar', 'SOLAR')
                    deduped[key] = {'time': key[0], 'technology': 'Solar', 'fuelType': 'SOLAR', 'generationMW': mw, 'source': 'Sheffield Solar PVLive'}
                print(f'{day}: PVLive solar {len(rows)} rows')
            except Exception as exc:
                failed.append(f'{day} PVLive {exc}')
                if solar_status != 'ok':
                    solar_status = str(exc)
        day += dt.timedelta(days=1)
    by_time_tech = defaultdict(float)
    source_by_time_tech = {}
    for row in deduped.values():
        key = (row['time'], row['technology'])
        by_time_tech[key] += row['generationMW']
        source_by_time_tech[key] = row['source']
    rows = []
    for (time, tech), mw in sorted(by_time_tech.items(), key=lambda item: (item[0][0], item[0][1])):
        rows.append({'time': time, 'technology': tech, 'generationMW': round(mw, 3), 'source': source_by_time_tech.get((time, tech), 'Aggregated generation MW')})
    OUT.parent.mkdir(parents=True, exist_ok=True)
    OUT.write_text(json.dumps({'generatedUTC': utc_now(), 'source': 'Elexon BMRS FUELINST and Sheffield Solar PVLive where available', 'description': 'Recent MW generation slice for engineering fluctuation chart', 'windowStart': start_day.isoformat(), 'windowEnd': end_day.isoformat(), 'unit': 'MW', 'rows': rows}, indent=2), encoding='utf-8')
    REPORT.parent.mkdir(parents=True, exist_ok=True)
    REPORT.write_text('\n'.join(['# Recent MW Generation Slice', '', f'Updated UTC: {utc_now()}', f'Window: {start_day} to {end_day}', f'Days: {days}', f'Elexon raw rows fetched: {raw_elexon}', f'PVLive raw solar rows fetched: {raw_solar}', f'Deduped raw rows: {len(deduped)}', f'Output rows: {len(rows)}', f'PVLive status: {solar_status}', f'PVLive working URL sample: {solar_url or "not confirmed"}  … [line shortened here: 636 characters; full line on GitHub]
    print(f'Wrote {len(rows)} rows to {OUT}')
    print(f'Wrote report {REPORT}')


if __name__ == '__main__':
    main()

GlobalGrid2050 Update Oil Prices

A Python command-line tool in the scripts folder that fetches live oil prices, oil price history and fredgraph. It loads existing history (`load_existing_history`) and adds rows (`add_rows`).

energy-dataglobalgrid2050 / scripts/update_oil_prices.py · lines 1–235 of 235 · Entry point · pattern load_existing_history (shared by 5 files)

What it does
It fetches live oil prices, oil price history and fredgraph. Defines 10 functions or classes, including build_session, now_utc, yahoo_price, yahoo_history, fred_csv. Uses libraries csv, json, os, datetime, io. Side effects: reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage hv_procurement (path word 'prices'): HV materials procurement, which Ventus Ltd states is within its commercial execution boundary.
Inputs & outputs
In: JSON file live_oil_prices.json; GeoJSON file oil_price_history.geojson; CSV file fredgraph.csv.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Update Oil Prices Workflow (globalgrid2050).
What it achieves
Defines `build_session`, `now_utc`, `yahoo_price` and 6 more.
Why it matters
Run by GlobalGrid2050 Update Oil Prices Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
csv, json, os, datetime, io, pathlib, requests, requests.adapters
Used by
run by GlobalGrid2050 Update Oil Prices Workflow (workflow run)
Produces
build_session, now_utc, yahoo_price, yahoo_history, fred_csv, load_existing_history, history_is_recent, add_rows, oil_history_geojson, main
Defines here
build_session, now_utc, yahoo_price, yahoo_history, fred_csv, load_existing_history, history_is_recent, add_rows, oil_history_geojson, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 scripts/update_oil_prices.py:1-235 · blob 084ea909c5689c39c9f658dfd763037d67349755 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem, network · domain stage: hv_procurement · users: EPC_contractor, procurement_buyer · canonical: production_core
import csv
import json
import os
from datetime import datetime, timezone, timedelta
from io import StringIO
from pathlib import Path

import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

OUT_DIR = Path(__file__).parent.parent / "uk_energy_tracking"
LIVE_FILE = OUT_DIR / "live_oil_prices.json"
HISTORY_FILE = OUT_DIR / "oil_price_history.geojson"
HEADERS = {"User-Agent": "Mozilla/5.0"}
LIVE_TIMEOUT = 15
HISTORY_TIMEOUT = 60
HISTORY_MAX_AGE_HOURS = 24
HISTORY_YEARS = 25


def build_session():
    retry_strategy = Retry(
        total=3,
        connect=3,
        read=3,
        status=3,
        backoff_factor=2,
        status_forcelist=[429, 500, 502, 503, 504],
        allowed_methods=["GET"],
        raise_on_status=False,
    )
    session = requests.Session()
    adapter = HTTPAdapter(max_retries=retry_strategy)
    session.mount("https://", adapter)
    session.mount("http://", adapter)
    session.headers.update(HEADERS)
    return session


SESSION = build_session()


def now_utc():
    return datetime.now(timezone.utc).isoformat()


def yahoo_price(ticker):
    url = f"https://query1.finance.yahoo.com/v8/finance/chart/{ticker}"
    r = SESSION.get(url, timeout=LIVE_TIMEOUT)
    r.raise_for_status()
    return float(r.json()["chart"]["result"][0]["meta"]["regularMarketPrice"])


def yahoo_history(ticker):
    url = f"https://query1.finance.yahoo.com/v8/finance/chart/{ticker}?range={HISTORY_YEARS}y&interval=1d"
    r = SESSION.get(url, timeout=HISTORY_TIMEOUT)
    r.raise_for_status()
    result = r.json()["chart"]["result"][0]
    timestamps = result.get("timestamp") or []
    closes = (((result.get("indicators") or {}).get("quote") or [{}])[0].get("close") or [])
    rows = []
    cutoff = datetime.now(timezone.utc) - timedelta(days=HISTORY_YEARS * 366)
    for ts, close in zip(timestamps, closes):
        if close is None:
            continue
        dt = datetime.fromtimestamp(ts, timezone.utc)
        if dt < cutoff:
            continue
        rows.append((dt.strftime("%Y-%m-%d"), float(close)))
    if not rows:
        raise RuntimeError(f"Yahoo returned no usable history rows for {ticker}")
    return rows


def fred_csv(series):
    url = f"https://fred.stlouisfed.org/graph/fredgraph.csv?id={series}"
    r = SESSION.get(url, timeout=HISTORY_TIMEOUT)
    r.raise_for_status()
    rows = []
    cutoff = datetime.now(timezone.utc) - timedelta(days=HISTORY_YEARS * 366)
    for row in csv.DictReader(StringIO(r.text)):
        date = row.get("observation_date")
        value = row.get(series)
        if not date or not value or value == ".":
            continue
        try:
            dt = datetime.strptime(date, "%Y-%m-%d").replace(tzinfo=timezone.utc)
            if dt >= cutoff:
                rows.append((date, float(value)))
        except ValueError:
            continue
    if not rows:
        raise RuntimeError(f"FRED returned no usable rows for {series}")
    return rows


def load_existing_history():
    if not HISTORY_FILE.exists():
        return None
    try:
        existing = json.loads(HISTORY_FILE.read_text(encoding="utf-8"))
        if isinstance(existing.get("features"), list) and len(existing["features"]) > 0:
            return existing
    except Exception:
        return None
    return None


def history_is_recent(existing):
    if not existing:
        return False
    updated = existing.get("metadata", {}).get("updated")
    if not updated:
        return False
    try:
        dt = datetime.fromisoformat(str(updated).replace("Z", "+00:00"))
        return datetime.now(timezone.utc) - dt < timedelta(hours=HISTORY_MAX_AGE_HOURS)
    except Exception:
        return False


def add_rows(merged, rows, field):
    for date, value in rows:
        merged.setdefault(date, {})[field] = value


def oil_history_geojson():
    existing = load_existing_history()
    force_history = os.getenv("FORCE_OIL_HISTORY", "0") == "1"
    if existing and history_is_recent(existing) and not force_history:
        existing.setdefault("metadata", {})["lastSkippedHistoryUpdate"] = now_utc()
        existing["metadata"]["skipReason"] = "Existing oil history is less than 24 hours old. Live oil update completed without re-downloading full history."
        return existing, False

    health = []
    merged = {}

    for series, field, label in [
        ("DCOILBRENTEU", "brentUSDperBarrel", "FRED Brent Europe daily spot price"),
        ("DCOILWTICO", "wtiUSDperBarrel", "FRED WTI Cushing daily spot price"),
    ]:
        try:
            rows = fred_csv(series)
            add_rows(merged, rows, field)
            health.append({"ok": True, "source": label, "rows": len(rows)})
        except Exception as exc:
            msg = f"Failed to fetch {label}: {exc}"
            print(f"::warning::{msg}")
            health.append({"ok": False, "source": label, "error": msg})

    if not merged:
        for ticker, field, label in [
            ("BZ=F", "brentUSDperBarrel", "Yahoo Brent futures history"),
            ("CL=F", "wtiUSDperBarrel", "Yahoo WTI futures history"),
        ]:
            try:
                rows = yahoo_history(ticker)
                add_rows(merged, rows, field)
                health.append({"ok": True, "source": label, "rows": len(rows), "fallback": True})
            except Exception as exc:
                msg = f"Failed to fetch {label}: {exc}"
                print(f"::warning::{msg}")
                health.append({"ok": False, "source": label, "error": msg, "fallback": True})

    features = []
    for date in sorted(merged):
        features.append({
            "type": "Feature",
            "geometry": {"type": "Point", "coordinates": [0, 0]},
            "properties": {"date": date, **merged[date]}
        })

    if not features:
        if existing:
            existing.setdefault("metadata", {})["lastAttemptedUpdate"] = now_utc()
            existing["metadata"]["latestAttemptHealth"] = health
            existing["metadata"]["note"] = existing["metadata"].get("note", "") + " Existing non empty history preserved after latest failed fetch attempt."
            return existing, False
        print("::warning::Oil history unavailable and no existing history file found. Writing live prices only.")
        return {
            "type": "FeatureCollection",
            "metadata": {
                "updated": now_utc(),
                "unit": "USD per barrel",
                "period": f"Last {HISTORY_YEARS} years",
                "note": "Oil history unavailable during this run. Live oil prices were still updated.",
                "sources": health,
            },
            "features": [],
        }, False

    return {
        "type": "FeatureCollection",
        "metadata": {
            "updated": now_utc(),
            "unit": "USD per barrel",
            "period": f"Last {HISTORY_YEARS} years",
            "note": "Placeholder Point geometry. This is a portable time series for charting, not a spatial dataset. FRED is preferred. Yahoo history is used as fallback when FRED is unavailable.",
            "sources": health,
        },
        "features": features,
    }, True


def main():
    OUT_DIR.mkdir(parents=True, exist_ok=True)
    health = {}
    live = {"updated": now_utc(), "brentUSDperBarrel": None, "wtiUSDperBarrel": None}

    for ticker, key in [("BZ=F", "brentUSDperBarrel"), ("CL=F", "wtiUSDperBarrel")]:
        try:
            live[key] = yahoo_price(ticker)
            health[ticker] = {"ok": True}
        except Exception as exc:
            msg = f"Failed to fetch Yahoo price {ticker}: {exc}"
            print(f"::warning::{msg}")
            health[ticker] = {"ok": False, "error": msg}

    live["health"] = health
    LIVE_FILE.write_text(json.dumps(live, indent=2), encoding="utf-8")

    history, fetched_fresh_history = oil_history_geojson()
    HISTORY_FILE.write_text(json.dumps(history, indent=2), encoding="utf-8")

    print(json.dumps({
        "live": live,
        "history_features": len(history.get("features", [])),
        "fresh_history_written": fetched_fresh_history,
        "history": history.get("metadata", {}),
    }, indent=2))


if __name__ == "__main__":
    main()