GLOBALGRID2050 / EXPLORE CODE

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

GlobalGrid2050 Document UK Energy Trackers and 3 more files

A Python command-line tool in the scripts folder that reads live grid energy, live grid price, live oil prices and oil price history, using SHA-256.

686 lines of Python from globalgrid2050, in 4 files. Topic: Electricity markets and data pipelines. Section 874 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 Document UK Energy Trackers storage · globalgrid2050 / scripts/document_uk_energy_trackers.py lines 1–241
  2. GlobalGrid2050 Download Elexon Generation Sources energy-data · globalgrid2050 / scripts/download_elexon_generation_sources.py lines 1–159
  3. GlobalGrid2050 Download Elexon System Prices energy-data · globalgrid2050 / scripts/download_elexon_system_prices.py lines 1–126
  4. GlobalGrid2050 Download Elexon System Prices Range energy-data · globalgrid2050 / scripts/download_elexon_system_prices_range.py lines 1–160

GlobalGrid2050 Document UK Energy Trackers

A Python command-line tool in the scripts folder that reads live grid energy, live grid price, live oil prices and oil price history, using SHA-256.

storageglobalgrid2050 / scripts/document_uk_energy_trackers.py · lines 1–241 of 241 · Entry point · pattern line_count (shared by 4 files)

What it does
It loads live grid energy, live grid price, live oil prices and oil price history. Defines 10 functions or classes, including read_text, sha, line_count, json_summary, find_js_feed_refs. Uses libraries pathlib, datetime, hashlib, json, re. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (topic 'markets-data'): 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.
Inputs & outputs
In: JSON file live_grid_energy.json; JSON file live_grid_price.json; JSON file live_oil_prices.json; GeoJSON file oil_price_history.geojson; JSON file live_uk_fuel_prices.json; JSON file ev_charging_prices.json.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Document UK Energy Trackers Workflow (globalgrid2050).
What it achieves
It finds js feed refs (`find_js_feed_refs`) and is built from the JSON summary helper (`json_summary`) and the workflow summary helper (`workflow_summary`). Defines `read_text`, `sha`, `line_count` and 6 more.
Why it matters
Run by GlobalGrid2050 Document UK Energy Trackers Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
pathlib, datetime, hashlib, json, re
Used by
run by GlobalGrid2050 Document UK Energy Trackers Workflow (workflow run)
Produces
read_text, sha, line_count, json_summary, find_js_feed_refs, workflow_summary, script_summary, tracker_doc, comparison_doc, main
Defines here
read_text, sha, line_count, json_summary, find_js_feed_refs, workflow_summary, script_summary, tracker_doc, comparison_doc, 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/document_uk_energy_trackers.py:1-241 · blob 07f14cbe57a3d5eeec2aa7eaa04ac61d39024d0f · 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
from pathlib import Path
from datetime import datetime, timezone
import hashlib
import json
import re

ROOT = Path(__file__).resolve().parents[1]
V1 = ROOT / "uk_energy_tracking"
V2 = ROOT / "uk_energy_tracking_v2"
WF = ROOT / ".github" / "workflows"
SCRIPTS = ROOT / "scripts"
REPORT = ROOT / "gridbot_reports" / "document_uk_energy_trackers.md"

TRACKERS = {
    "stable": {
        "folder": V1,
        "url": "https://globalgrid2050.com/uk_energy_tracking/",
        "label": "Stable UK Live Grid Tracker",
        "workflow": WF / "fetch_uk_energy_and_prices.yml",
        "energy_script": SCRIPTS / "update_uk_energy.py",
        "price_script": SCRIPTS / "update_uk_price.py",
        "oil_script": SCRIPTS / "update_oil_prices.py",
        "fuel_script": SCRIPTS / "update_uk_fuel_prices.py",
    },
    "v2": {
        "folder": V2,
        "url": "https://globalgrid2050.com/uk_energy_tracking_v2/",
        "label": "UK Live Grid Tracker V2 Development Twin",
        "workflow": WF / "fetch_uk_energy_and_prices_v2.yml",
        "energy_script": SCRIPTS / "update_uk_energy_v2.py",
        "price_script": SCRIPTS / "update_uk_price_v2.py",
        "oil_script": SCRIPTS / "update_oil_prices_v2.py",
        "fuel_script": SCRIPTS / "update_uk_fuel_prices_v2.py",
    },
}

FEEDS = [
    "live_grid_energy.json",
    "live_grid_price.json",
    "live_oil_prices.json",
    "oil_price_history.geojson",
    "live_uk_fuel_prices.json",
    "ev_charging_prices.json",
]


def read_text(path):
    if not path.exists():
        return ""
    return path.read_text(encoding="utf-8", errors="replace")


def sha(path):
    if not path.exists():
        return "missing"
    return hashlib.sha256(path.read_bytes()).hexdigest()[:16]


def line_count(path):
    if not path.exists():
        return 0
    return len(read_text(path).splitlines())


def json_summary(path):
    if not path.exists():
        return "missing"
    try:
        data = json.loads(read_text(path))
    except Exception as exc:
        return f"invalid JSON: {type(exc).__name__}"
    if isinstance(data, dict):
        keys = ", ".join(sorted(data.keys())[:12])
        updated = data.get("updated") or data.get("date") or data.get("timestamp")
        extra = f"; updated: {updated}" if updated else ""
        return f"object keys: {keys}{extra}"
    if isinstance(data, list):
        return f"list length: {len(data)}"
    return type(data).__name__


def find_js_feed_refs(page_text):
    refs = sorted(set(re.findall(r"/uk_energy_tracking(?:_v2)?/[A-Za-z0-9_./-]+(?:json|geojson)", page_text)))
    return refs


def workflow_summary(path):
    text = read_text(path)
    if not text:
        return ["workflow missing"]
    rows = []
    schedule = re.findall(r"cron:\s*['\"]([^'\"]+)['\"]", text)
    if schedule:
        rows.append("cron: " + ", ".join(schedule))
    else:
        rows.append("cron: none")
    rows.append("manual workflow_dispatch: " + ("yes" if "workflow_dispatch" in text else "no"))
    rows.append("uses GRIDBOT_PAT: " + ("yes" if "GRIDBOT_PAT" in text else "no"))
    rows.append("concurrency: " + ("yes" if "concurrency:" in text else "no"))
    staged = re.findall(r"git add ([^\n]+)", text)
    if staged:
        rows.append("git add targets: " + " | ".join(s.strip() for s in staged))
    return rows


def script_summary(path):
    text = read_text(path)
    if not text:
        return ["script missing"]
    rows = []
    folder_match = re.search(r"FOLDER\s*=.*?/(?:\s*)[\"']([^\"']+)[\"']", text)
    if folder_match:
        rows.append("writes folder: " + folder_match.group(1))
    json_match = re.search(r"JSON_FILE\s*=\s*FOLDER\s*/\s*[\"']([^\"']+)[\"']", text)
    if json_match:
        rows.append("writes JSON: " + json_match.group(1))
    rows.append("zero price guard: " + ("yes" if "zero market price rejected" in text or "preserve_previous_price" in text else "no or not applicable"))
    rows.append("self regulated cadence: " + ("yes" if "MIN_UPDATE_MINUTES" in text or "should_skip_price_update" in text else "no or not applicable"))
    return rows


def tracker_doc(name, meta):
    folder = meta["folder"]
    page = folder / "index.md"
    page_text = read_text(page)
    now = datetime.now(timezone.utc).isoformat()
    lines = []
    lines.append(f"# {meta['label']} Diagnostic Notes")
    lines.append("")
    lines.append(f"Generated: `{now}`")
    lines.append(f"Public URL: `{meta['url']}`")
    lines.append(f"Folder: `{folder.relative_to(ROOT)}`")
    lines.append("")
    lines.append("## Purpose")
    if name == "stable":
        lines.append("This folder is the stable public UK live grid tracker and should be treated as the working reference twin. It must remain protected while V2 is developed.")
    else:
        lines.append("This folder is the isolated V2 development twin. It should mirror the stable tracker for core grid behaviour while carrying transport energy, DESNZ fuel and EV charging experiments.")
    lines.append("")
    lines.append("## Core files")
    core = [page, meta["workflow"], meta["energy_script"], meta["price_script"], meta["oil_script"], meta["fuel_script"]]
    for path in core:
        lines.append(f"- `{path.relative_to(ROOT)}` lines `{line_count(path)}` sha `{sha(path)}`")
    lines.append("")
    lines.append("## Feed files")
    for feed in FEEDS:
        path = folder / feed
        lines.append(f"- `{path.relative_to(ROOT)}` sha `{sha(path)}` summary: {json_summary(path)}")
    lines.append("")
    lines.append("## Workflow behaviour")
    for item in workflow_summary(meta["workflow"]):
        lines.append(f"- {item}")
    lines.append("")
    lines.append("## Script behaviour")
    for label in ["energy_script", "price_script", "oil_script", "fuel_script"]:
        path = meta[label]
        lines.append(f"### `{path.relative_to(ROOT)}`")
        for item in script_summary(path):
            lines.append(f"- {item}")
        lines.append("")
    lines.append("## Front end feed references")
    refs = find_js_feed_refs(page_text)
    if refs:
        for ref in refs:
            lines.append(f"- `{ref}`")
    else:
        lines.append("- no absolute JSON feed references found")
    lines.append("")
    lines.append("## Operational notes")
    if name == "stable":
        lines.append("- This tracker is the live reference and correction source.")
        lines.append("- Do not use it for experimental transport energy patches.")
        lines.append("- If V2 fails, compare against this folder before changing anything.")
    else:
        lines.append("- This tracker should use only V2 JSON outputs for grid values.")
        lines.append("- Its workflow should be offset from the stable tracker to reduce push races.")
        lines.append("- Transport energy work belongs here first, not in the stable tracker.")
    lines.append("")
    return "\n".join(lines)


def comparison_doc():
    now = datetime.now(timezone.utc).isoformat()
    lines = ["# UK Energy Tracker Stable vs V2 Comparison", "", f"Generated: `{now}`", ""]
    lines.append("## Summary")
    lines.append("The stable tracker is the public working reference. V2 is the isolated development twin for transport energy work.")
    lines.append("")
    lines.append("## File comparison")
    pairs = [
        ("page", V1 / "index.md", V2 / "index.md"),
        ("energy script", SCRIPTS / "update_uk_energy.py", SCRIPTS / "update_uk_energy_v2.py"),
        ("price script", SCRIPTS / "update_uk_price.py", SCRIPTS / "update_uk_price_v2.py"),
        ("oil script", SCRIPTS / "update_oil_prices.py", SCRIPTS / "update_oil_prices_v2.py"),
        ("fuel script", SCRIPTS / "update_uk_fuel_prices.py", SCRIPTS / "update_uk_fuel_prices_v2.py"),
        ("workflow", WF / "fetch_uk_energy_and_prices.yml", WF / "fetch_uk_energy_and_prices_v2.yml"),
    ]
    for label, a, b in pairs:
        same = sha(a) == sha(b)
        lines.append(f"- {label}: stable sha `{sha(a)}`, V2 sha `{sha(b)}`, identical: `{same}`")
    lines.append("")
    lines.append("## Feed comparison")
    for feed in FEEDS:
        a = V1 / feed
        b = V2 / feed
        lines.append(f"- {feed}: stable `{sha(a)}`, V2 `{sha(b)}`, V2 exists: `{b.exists()}`")
    lines.append("")
    lines.append("## Convergence")
    lines.append("- Both trackers use the same public data families for core grid values.")
    lines.append("- Both use GitHub Actions and GridBot authenticated execution.")
    lines.append("- Both write JSON feeds consumed by the front end.")
    lines.append("- V2 should follow the stable tracker cadence while keeping separate output files.")
    lines.append("")
    lines.append("## Divergence")
    lines.append("- V2 contains DESNZ road fuel and EV charging comparison work.")
    lines.append("- V2 has isolated `_v2` scripts and V2 folder outputs.")
    lines.append("- V2 may contain experimental UI and iframe references that are not present in the stable tracker.")
    lines.append("")
    lines.append("## Recovery rule")
    lines.append("If V2 breaks, compare against the stable tracker and patch only V2 files, V2 scripts or V2 workflows.")
    lines.append("")
    return "\n".join(lines)


def main():
    outputs = []
    for name, meta in TRACKERS.items():
        out = meta["folder"] / "DIAGNOSTIC_NOTES.md"
        out.write_text(tracker_doc(name, meta), encoding="utf-8")
        outputs.append(out.relative_to(ROOT).as_posix())
    compare = ROOT / "UK_ENERGY_TRACKER_COMPARISON.md"
    compare.write_text(comparison_doc(), encoding="utf-8")
    outputs.append(compare.relative_to(ROOT).as_posix())
    REPORT.parent.mkdir(parents=True, exist_ok=True)
    REPORT.write_text("# UK energy tracker documentation generator report\n\n" + "\n".join(f"- wrote `{x}`" for x in outputs) + "\n", encoding="utf-8")
    print("wrote diagnostic documentation")
    for item in outputs:
        print(item)


if __name__ == "__main__":
    main()

GlobalGrid2050 Download Elexon Generation Sources

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

energy-dataglobalgrid2050 / scripts/download_elexon_generation_sources.py · lines 1–159 of 159 · Entry point · pattern fetch_window (shared by 3 files)

What it does
It fetches Elexon generation sources half hourly. Defines 9 functions or classes, including iso_z, pick, num, fetch_window, load_existing. 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 upstream_foresight (path word 'elexon'): 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.
Inputs & outputs
In: data source: Elexon BMRS; CSV file elexon_generation_sources_half_hourly.csv.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Elexon Generation Sources Weekly Workflow (globalgrid2050).
What it achieves
It fetches window (`fetch_window`), loads existing (`load_existing`) and writes CSV (`write_csv`). Defines `iso_z`, `pick`, `num` and 5 more.
Why it matters
Run by GlobalGrid2050 Elexon Generation Sources Weekly Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
csv, datetime, json, os, sys, urllib.parse, urllib.request, pathlib
Used by
run by GlobalGrid2050 Elexon Generation Sources Weekly Workflow (workflow run)
Produces
iso_z, pick, num, fetch_window, load_existing, write_csv, write_report, main
Defines here
iso_z, pick, num, fetch_window, load_existing, write_csv, sort_key, write_report, 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/download_elexon_generation_sources.py:1-159 · blob e55eb7db5157be6cbb8b409c48c7cc8f71f7da36 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem, network, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import csv
import datetime as dt
import json
import os
import sys
import urllib.parse
import urllib.request
from pathlib import Path

BASE_URL = "https://data.elexon.co.uk/bmrs/api/v1/datasets/FUELINST"
OUT_DIR = Path("data/generation")
OUT_FILE = OUT_DIR / "elexon_generation_sources_half_hourly.csv"
REPORT_DIR = Path("uk_energy_tracking_v6/generation_history")
REPORT = REPORT_DIR / "GENERATION_HISTORY_DATA_REPORT.md"
FIELDS = [
    "source",
    "periodStartUTC",
    "fuelType",
    "generationMW",
    "publishTimeUTC",
    "fetchedAtUTC",
]


def iso_z(value):
    if not value:
        return ""
    text = str(value).replace("Z", "+00:00")
    try:
        d = dt.datetime.fromisoformat(text)
        if d.tzinfo is None:
            d = d.replace(tzinfo=dt.timezone.utc)
        return d.astimezone(dt.timezone.utc).isoformat().replace("+00:00", "Z")
    except Exception:
        return str(value)


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):.3f}"
    except Exception:
        return str(value)


def fetch_window(start_dt, end_dt):
    query = urllib.parse.urlencode({
        "publishDateTimeFrom": start_dt.strftime("%Y-%m-%dT%H:%MZ"),
        "publishDateTimeTo": end_dt.strftime("%Y-%m-%dT%H:%MZ"),
        "format": "json",
    })
    url = f"{BASE_URL}?{query}"
    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
        fuel = pick(row, ["fuelType", "fuelTypeName", "fuel", "psrType"])
        generation = pick(row, ["generation", "generationMW", "currentUsage", "quantity"])
        period_start = pick(row, ["startTime", "publishDateTime", "periodStartUTC", "settlementDate"])
        publish_time = pick(row, ["publishDateTime", "publishTime", "createdTime"])
        if not fuel or generation == "" or not period_start:
            continue
        output.append({
            "source": "Elexon BMRS FUELINST",
            "periodStartUTC": iso_z(period_start),
            "fuelType": str(fuel).strip().upper(),
            "generationMW": num(generation),
            "publishTimeUTC": iso_z(publish_time),
            "fetchedAtUTC": fetched,
        })
    return output


def load_existing():
    if not OUT_FILE.exists():
        return {}
    existing = {}
    with OUT_FILE.open("r", encoding="utf-8", newline="") as handle:
        for row in csv.DictReader(handle):
            key = (row.get("periodStartUTC", ""), row.get("fuelType", ""))
            if key[0] and key[1]:
                existing[key] = {field: row.get(field, "") for field in FIELDS}
    return existing


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


def write_report(status, days, fetched_rows, total_rows):
    REPORT_DIR.mkdir(parents=True, exist_ok=True)
    REPORT.write_text("\n".join([
        "# Generation History Data Report",
        "",
        f"Updated UTC: {dt.datetime.now(dt.timezone.utc).isoformat().replace('+00:00', 'Z')}",
        f"Status: {status}",
        f"Backfill days requested: {days}",
        f"Fetched rows this run: {fetched_rows}",
        f"Total master rows after merge: {total_rows}",
        "Source: Elexon BMRS FUELINST",
        "Module: uk_energy_tracking_v6/generation_history",
        "Note: This module is not wired into the main V6 page yet.",
    ]) + "\n", encoding="utf-8")


def main():
    days = int(os.getenv("BACKFILL_DAYS", "14"))
    today = dt.datetime.now(dt.timezone.utc).date()
    start_day = today - dt.timedelta(days=max(days, 1))
    end_day = today - dt.timedelta(days=1)
    existing = load_existing()
    fetched_count = 0
    day = start_day
    while day <= end_day:
        start_dt = dt.datetime.combine(day, dt.time(0, 0), tzinfo=dt.timezone.utc)
        end_dt = dt.datetime.combine(day, dt.time(23, 59), tzinfo=dt.timezone.utc)
        try:
            rows = fetch_window(start_dt, end_dt)
            print(f"Fetched {len(rows)} generation rows for {day}")
            fetched_count += len(rows)
            for row in rows:
                key = (row["periodStartUTC"], row["fuelType"])
                existing[key] = row
        except Exception as exc:
            print(f"Warning: failed {day}: {exc}")
        day += dt.timedelta(days=1)
    if not existing:
        write_report("failed", days, fetched_count, 0)
        sys.exit("No generation rows available")
    total = write_csv(existing)
    write_report("ok", days, fetched_count, total)


if __name__ == "__main__":
    main()

GlobalGrid2050 Download Elexon System Prices

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/download_elexon_system_prices.py · lines 1–126 of 126 · Entry point · pattern period_start (shared by 3 files)

What it does
It fetches Elexon system prices half hourly. Defines 8 functions or classes, including pick, num, period_start, fetch_date, load_existing. 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 Elexon System Prices Workflow (globalgrid2050).
What it achieves
It fetches date (`fetch_date`), loads existing (`load_existing`) and writes CSV (`write_csv`). Defines `pick`, `num`, `period_start` and 4 more.
Why it matters
Run by GlobalGrid2050 Elexon System Prices Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
csv, datetime, json, os, sys, urllib.request, pathlib
Used by
run by GlobalGrid2050 Elexon System Prices Workflow (workflow run)
Produces
pick, num, period_start, fetch_date, load_existing, write_csv, main
Defines here
pick, num, period_start, fetch_date, load_existing, write_csv, sort_key, 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/download_elexon_system_prices.py:1-126 · blob ea7424625222dd07556f78a7af89a42f106f4b60 · 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")
OUT_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=30) 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_existing():
    if not OUT_FILE.exists():
        return {}
    existing = {}
    with OUT_FILE.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]:
                existing[key] = {field: row.get(field, "") for field in FIELDS}
    return existing


def write_csv(rows_by_key):
    OUT_DIR.mkdir(parents=True, exist_ok=True)
    def sort_key(key):
        return (key[0], int(key[1]) if str(key[1]).isdigit() else 999)
    rows = [rows_by_key[key] for key in sorted(rows_by_key, key=sort_key)]
    with OUT_FILE.open("w", encoding="utf-8", newline="") as handle:
        writer = csv.DictWriter(handle, fieldnames=FIELDS)
        writer.writeheader()
        writer.writerows(rows)
    print(f"Wrote {len(rows)} rows to {OUT_FILE}")


def main():
    days = int(os.getenv("BACKFILL_DAYS", "30"))
    yesterday = dt.date.today() - dt.timedelta(days=1)
    start = yesterday - dt.timedelta(days=max(days - 1, 0))
    existing = load_existing()
    day = start
    while day <= yesterday:
        try:
            rows = fetch_date(day)
            print(f"Fetched {len(rows)} rows for {day}")
            for row in rows:
                key = (row["settlementDate"], row["settlementPeriod"])
                existing[key] = row
        except Exception as exc:
            print(f"Warning: failed {day}: {exc}")
        day += dt.timedelta(days=1)
    if not existing:
        sys.exit("No rows fetched")
    write_csv(existing)


if __name__ == "__main__":
    main()

GlobalGrid2050 Download Elexon System Prices Range

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/download_elexon_system_prices_range.py · lines 1–160 of 160 · Entry point · pattern period_start (shared by 3 files)

What it does
It fetches Elexon system prices half hourly. Defines 9 functions or classes, including pick, num, period_start, fetch_date, load_existing. 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 Elexon System Prices Backfill 10y Workflow (globalgrid2050).
What it achieves
It fetches date (`fetch_date`), loads existing (`load_existing`) and writes CSV (`write_csv`). Defines `pick`, `num`, `period_start` and 5 more.
Why it matters
Run by GlobalGrid2050 Elexon System Prices Backfill 10y Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
csv, datetime, json, os, sys, time, urllib.request, pathlib
Used by
run by GlobalGrid2050 Elexon System Prices Backfill 10y Workflow (workflow run)
Produces
pick, num, period_start, fetch_date, load_existing, write_csv, parse_date, main
Defines here
pick, num, period_start, fetch_date, load_existing, write_csv, sort_key, parse_date, 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/download_elexon_system_prices_range.py:1-160 · blob c87138a5d5c3fa04b850ea5f28d6b06dd60e59c8 · 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 time
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")
OUT_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, retries=3):
    date_text = day.isoformat()
    url = f"{BASE_URL}/{date_text}?format=json"
    last_error = None
    for attempt in range(1, retries + 1):
        try:
            req = urllib.request.Request(url, headers={"User-Agent": "GlobalGrid2050 GridBot"})
            with urllib.request.urlopen(req, timeout=30) 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
        except Exception as exc:
            last_error = exc
            time.sleep(min(10, attempt * 2))
    raise last_error


def load_existing():
    if not OUT_FILE.exists():
        return {}
    existing = {}
    with OUT_FILE.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]:
                existing[key] = {field: row.get(field, "") for field in FIELDS}
    return existing


def write_csv(rows_by_key):
    OUT_DIR.mkdir(parents=True, exist_ok=True)
    def sort_key(key):
        return (key[0], int(key[1]) if str(key[1]).isdigit() else 999)
    rows = [rows_by_key[key] for key in sorted(rows_by_key, key=sort_key)]
    with OUT_FILE.open("w", encoding="utf-8", newline="") as handle:
        writer = csv.DictWriter(handle, fieldnames=FIELDS)
        writer.writeheader()
        writer.writerows(rows)
    print(f"Wrote {len(rows)} rows to {OUT_FILE}")


def parse_date(name):
    value = os.getenv(name, "").strip()
    if not value:
        return None
    return dt.date.fromisoformat(value)


def main():
    start = parse_date("START_DATE")
    end = parse_date("END_DATE")
    if start is None or end is None:
        sys.exit("START_DATE and END_DATE are required in YYYY-MM-DD format")
    yesterday = dt.date.today() - dt.timedelta(days=1)
    if end > yesterday:
        end = yesterday
    if start > end:
        sys.exit(f"Empty date range after clamping: {start} to {end}")

    existing = load_existing()
    day = start
    fetched_days = 0
    fetched_rows = 0
    failed_days = []
    while day <= end:
        try:
            rows = fetch_date(day)
            print(f"Fetched {len(rows)} rows for {day}")
            fetched_days += 1
            fetched_rows += len(rows)
            for row in rows:
                key = (row["settlementDate"], row["settlementPeriod"])
                existing[key] = row
        except Exception as exc:
            print(f"Warning: failed {day}: {exc}")
            failed_days.append(day.isoformat())
        day += dt.timedelta(days=1)

    if not existing:
        sys.exit("No rows available after range fetch")
    write_csv(existing)
    print(f"Range complete | start={start} | end={end} | fetched_days={fetched_days} | fetched_rows={fetched_rows} | failed_days={len(failed_days)}")
    if failed_days:
        print("Failed day list:")
        for item in failed_days:
            print(item)


if __name__ == "__main__":
    main()