GLOBALGRID2050 / EXPLORE CODE

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

GlobalGrid2050 Update Oil Prices V4 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`).

633 lines of Python from globalgrid2050, in 3 files. Topic: Electricity markets and data pipelines. Section 892 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 Oil Prices V4 energy-data · globalgrid2050 / scripts/update_oil_prices_v4.py lines 1–235
  2. GlobalGrid2050 Update UK Energy energy-data · globalgrid2050 / scripts/update_uk_energy.py lines 1–199
  3. GlobalGrid2050 Update UK Energy V2 energy-data · globalgrid2050 / scripts/update_uk_energy_v2.py lines 1–199

GlobalGrid2050 Update Oil Prices V4

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`).

Set aside from the main view: 99% of its lines are the same as scripts/update_oil_prices.py (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 98% of lines shared with GlobalGrid2050 Update Oil Prices; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9875 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 scripts/update_oil_prices.py:1-235 084ea909c5689c39c9f658dfd763037d67349755
  • sha256 012985be09b3b4790326c515801cb108afb4047ab2a6a3be963898d27dbaf430
  • target sha256 cf82557b401d35ddba31dbc31d738eccb8e978ca9caac4e7dd1a2e8f719cc1cf
  • group of 4 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

energy-dataglobalgrid2050 / scripts/update_oil_prices_v4.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
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
Defines `build_session`, `now_utc`, `yahoo_price` and 6 more.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
globalgrid2050 · scripts · Python CLI
Uses
csv, json, os, datetime, io, pathlib, requests, requests.adapters
Used by
none found
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_v4.py:1-235 · blob 3aacd21648dc2458d73fe8170b9c81a73ccae568 · 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_v4"
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()

GlobalGrid2050 Update UK Energy

A Python command-line tool in the scripts folder covering live grid energy and live grid price, and uses data from Elexon Balancing Mechanism Reporting Service (BMRS) and Carbon Intensity API.

energy-dataglobalgrid2050 / scripts/update_uk_energy.py · lines 1–199 of 199 · Entry point · pattern write_shell_if_missing (shared by 4 files)

What it does
It draws live grid energy, live grid price, solar and wind. Defines 6 functions or classes, including _iso_minutes_ago, _get_json, fetch_generation_mix, fetch_solar_gw, write_shell_if_missing. Uses libraries requests, os, json, pathlib, datetime. Side effects: changes the web page (DOM); reads or writes files; makes network requests.
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. Domain terms in the code: solar, wind.
Inputs & outputs
In: data source: Elexon BMRS; data source: Carbon Intensity API; JSON file live_grid_energy.json; JSON file live_grid_price.json. Out: JSON file.
Downstream impact
Used directly by 1 file: GlobalGrid2050 Fetch UK Energy and Prices Workflow (globalgrid2050).
What it achieves
It fetches generation mix (`fetch_generation_mix`), fetches solar GW (`fetch_solar_gw`) and writes shell if missing (`write_shell_if_missing`). Runs every 5 minutes. Fetches demand + generation mix (Elexon FUELINST) and national solar (Sheffield Solar).
Why it matters
Run by GlobalGrid2050 Fetch UK Energy and Prices Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
requests, os, json, pathlib, datetime
Used by
run by GlobalGrid2050 Fetch UK Energy and Prices Workflow (workflow run)
Produces
fetch_generation_mix, fetch_solar_gw, write_shell_if_missing, main
Defines here
_iso_minutes_ago, _get_json, fetch_generation_mix, fetch_solar_gw, write_shell_if_missing, 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_uk_energy.py:1-199 · blob 91d93ed8ad65d6596b21f4fce9b80a9a36b93838 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import requests
import os
import json
from pathlib import Path
from datetime import datetime, timezone, timedelta

# Runs every 5 minutes. Fetches demand + generation mix (Elexon FUELINST)
# and national solar (Sheffield Solar). Writes ONLY the energy slice so a
# failure here never touches the half-hourly price slice.

FOLDER = Path(__file__).parent.parent / "uk_energy_tracking"
JSON_FILE = FOLDER / "live_grid_energy.json"
MD_FILE = FOLDER / "index.md"

ELEXON = "https://data.elexon.co.uk/bmrs/api/v1"
PVLIVE = "https://api.solar.sheffield.ac.uk/pvlive/api/v4"
TIMEOUT = 12

FUEL_GROUPS = {
    "Wind": ["WIND"], "Hydro": ["NPSHYD"], "Gas": ["CCGT", "OCGT"],
    "Coal": ["COAL"], "Biomass": ["BIOMASS"], "Nuclear": ["NUCLEAR"],
    "Pumped Storage": ["PS"], "Imports & Exports": ["INT"],
}
ROW_ORDER = ["Solar", "Wind", "Hydro", "Gas", "Coal",
             "Biomass", "Nuclear", "Pumped Storage", "Imports & Exports"]
ROW_COLORS = {
    "Solar": "#f5c518", "Wind": "#00d0ff", "Hydro": "#0090c0",
    "Gas": "#c0399a", "Coal": "#888888", "Biomass": "#f59e2b",
    "Nuclear": "#5cb85c", "Pumped Storage": "#9b59b6", "Imports & Exports": "#e8615a",
}


def _iso_minutes_ago(mins):
    return (datetime.now(timezone.utc) - timedelta(minutes=mins)).strftime("%Y-%m-%dT%H:%MZ")


def _get_json(url):
    last = None
    for _ in range(2):
        try:
            r = requests.get(url, timeout=TIMEOUT,
                             headers={"Accept": "application/json", "User-Agent": "Mozilla/5.0"})
            r.raise_for_status()
            return r.json()
        except Exception as e:  # noqa: BLE001
            last = e
    raise last


def fetch_generation_mix():
    url = (f"{ELEXON}/datasets/FUELINST?publishDateTimeFrom={_iso_minutes_ago(30)}"
           f"&publishDateTimeTo={_iso_minutes_ago(0)}&format=json")
    data = _get_json(url).get("data", [])
    if not data:
        return {}
    latest = max(row["startTime"] for row in data)
    snap = [r for r in data if r["startTime"] == latest]
    return {r["fuelType"]: float(r.get("generation") or 0) for r in snap}


def fetch_solar_gw():
    rows = _get_json(f"{PVLIVE}/gsp/0").get("data", [])
    if not rows:
        return 0.0
    mw = rows[0][2]
    return (float(mw) / 1000.0) if mw is not None else 0.0


MD_SHELL = """---
layout: page
title: UK Live Grid Tracker
permalink: /uk_energy_tracking/
---
<style>
.scada-grid { font-family: "Courier New", monospace; }
.scada-metrics { display:flex; flex-wrap:wrap; gap:18px; margin:18px 0; }
.scada-card { flex:1 1 160px; border:1px solid #00ffff; border-radius:4px;
  background:rgba(0,255,255,0.05); padding:14px 16px; }
.scada-card .val { font-size:30px; font-weight:bold; color:#00ffff; letter-spacing:-1px; }
.scada-card .val .u { font-size:15px; color:#7fdfff; font-weight:normal; }
.scada-card .lab { font-size:13px; color:#a6adbb; margin-top:4px; text-transform:uppercase; }
.scada-bar-name { display:flex; justify-content:space-between; font-size:14px; margin:10px 0 4px; }
.scada-bar-name b { color:#e8e8f0; font-weight:normal; }
.scada-bar-name span { color:#7fdfff; font-variant-numeric:tabular-nums; }
.scada-track { height:7px; border-radius:4px; background:rgba(255,255,255,0.08); overflow:hidden; }
.scada-fill { height:100%; border-radius:4px; transition:width .6s ease; }
.scada-status { font-size:12px; color:#a6adbb; margin-top:14px; }
.scada-status.stale { color:#ffb020; }
.scada-credit { font-size:12px; color:#a6adbb; margin-top:10px; line-height:1.5; }
.scada-credit a { color:#7fdfff; }
</style>

# UK Live Grid Tracker

Near-real-time GB electricity demand, market price, carbon intensity and generation mix.
Generation mix refreshes every 5 minutes; price and carbon update every half hour (their native cadence).

<div class="scada-grid" id="scada-grid">
  <div class="scada-metrics">
    <div class="scada-card"><div class="val" id="m-demand">—<span class="u"> GW</span></div><div class="lab">Electricity demand</div></div>
    <div class="scada-card"><div class="val" id="m-price">£—<span class="u">/MWh</span></div><div class="lab">Electricity price</div></div>
    <div class="scada-card"><div class="val" id="m-carbon">—<span class="u"> g/kWh</span></div><div class="lab">Carbon emissions</div></div>
  </div>
  <div id="scada-mix"></div>
  <div class="scada-status" id="scada-status">Loading live feed…</div>
</div>

<script>
(function(){
  var ENERGY="./live_grid_energy.json", PRICE="./live_grid_price.json", POLL=5*60*1000;
  function fmt(n,dp){return (n===null||n===undefined||isNaN(n))?"\\u2014":Number(n).toFixed(dp==null?2:dp);}
  function renderMix(mix){
    var w=document.getElementById("scada-mix"); if(!Array.isArray(mix)){return;}
    w.innerHTML=mix.map(function(r){
      var width=Math.max(0,Math.min(100,Math.abs(r.pct)));
      return '<div class="scada-bar-name"><b>'+r.label+'</b><span>'+fmt(r.gw)+' GW &nbsp; '+fmt(r.pct)+'%</span></div>'+
        '<div class="scada-track"><div class="scada-fill" style="width:'+width+'%;background:'+r.color+'"></div></div>';
    }).join("");
  }
  function ageMin(iso){return iso?(Date.now()-new Date(iso).getTime())/60000:Infinity;}
  function getJSON(u){return fetch(u+"?t="+Date.now(),{cache:"no-store"}).then(function(r){if(!r.ok)throw 0;return r.json();}).catch(function(){return null;});}
  function refresh(){
    Promise.all([getJSON(ENERGY),getJSON(PRICE)]).then(function(res){
      var e=res[0]||{}, p=res[1]||{};
      if(e.demandGW!=null) document.getElementById("m-demand").innerHTML=fmt(e.demandGW)+'<span class="u"> GW</span>';
      document.getElementById("m-price").innerHTML='£'+(p.priceGBPperMWh==null?"\\u2014":fmt(p.priceGBPperMWh))+'<span class="u">/MWh</span>';
      document.getElementById("m-carbon").innerHTML=(p.carbonGperKWh==null?"\\u2014":Math.round(p.carbonGperKWh))+'<span class="u"> g/kWh</span>';
      if(e.mix) renderMix(e.mix);
      var s=document.getElementById("scada-status"), mins=ageMin(e.updated);
      if(mins>20){s.textContent="Mix feed is "+Math.round(mins)+" min old \\u2014 may be stale.";s.className="scada-status stale";}
      else if(e.updated){s.textContent="Mix updated "+new Date(e.updated).toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"})+" \\u00b7 price/carbon updated "+(p.updated?new Date(p.updated).toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"}):"\\u2014");s.className="scada-status";}
      else{s.textContent="Live feed unavailable \\u2014 awaiting first data write.";s.className="scada-status stale";}
    });
  }
  refresh(); setInterval(refresh, POLL);
})();
</script>

## Data sources & attribution

This tracker uses three free public sources. We gratefully acknowledge them:

- **Generation mix & demand** — Elexon BMRS Insights (Balancing Mechanism Reporting Service), used under the BMRS Data Licence Terms.
- **Carbon intensity** — National Energy System Operator [Carbon Intensity API](https://carbonintensity.org.uk/), developed with the Environmental Defense Fund, University of Oxford and WWF. Licensed under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/).
- **Solar generation** — [Sheffield Solar PV_Live](https://www.solar.sheffield.ac.uk/api/), University of Sheffield.

Indicative near-real-time values for screening and situational awareness only. No representation is made that the data is accurate or complete.
"""


def write_shell_if_missing():
    FOLDER.mkdir(parents=True, exist_ok=True)
    if not MD_FILE.exists():
        MD_FILE.write_text(MD_SHELL, encoding="utf-8")
        print(f"Wrote markdown shell: {MD_FILE}")


def main():
    write_shell_if_missing()
    health = {}
    try:
        raw_mw = fetch_generation_mix(); health["generation"] = "ok"
    except Exception as e:  # noqa: BLE001
        raw_mw = {}; health["generation"] = f"error: {e}"
    try:
        solar_gw = fetch_solar_gw(); health["solar"] = "ok"
    except Exception as e:  # noqa: BLE001
        solar_gw = 0.0; health["solar"] = f"error: {e}"

    groups = {}
    for label, codes in FUEL_GROUPS.items():
        groups[label] = sum(mw for c, mw in raw_mw.items()
                            if any(c.startswith(p) for p in codes)) / 1000.0
    groups["Solar"] = solar_gw
    demand = sum(groups.values())

    mix = [{
        "label": l, "gw": round(groups.get(l, 0.0), 2),
        "pct": round((groups.get(l, 0.0) / demand * 100), 2) if demand else 0,
        "color": ROW_COLORS[l],
    } for l in ROW_ORDER]

    out = {
        "updated": datetime.now(timezone.utc).isoformat(),
        "demandGW": round(demand, 2),
        "solarGW": round(solar_gw, 2),
        "mix": mix,
        "health": health,
    }
    FOLDER.mkdir(parents=True, exist_ok=True)
    with open(JSON_FILE, "w", encoding="utf-8") as f:
        json.dump(out, f, indent=2)
    if any(v != "ok" for v in health.values()):
        print(f"::warning::Energy source issue: {health}")
    print(f"✅ Energy slice | demand {out['demandGW']} GW | solar {out['solarGW']} GW | {health}")


if __name__ == "__main__":
    main()

GlobalGrid2050 Update UK Energy V2

A Python command-line tool in the scripts folder covering live grid energy and live grid price, and uses data from Elexon Balancing Mechanism Reporting Service (BMRS) and Carbon Intensity API.

Set aside from the main view: 96% of its lines are the same as scripts/update_uk_energy.py (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 96% of lines shared with GlobalGrid2050 Update UK Energy; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9618 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 scripts/update_uk_energy.py:1-199 91d93ed8ad65d6596b21f4fce9b80a9a36b93838
  • sha256 8eddd8c91aed06fa7619c7bdf86e92949c130fabc35d024e5da111d980afb4bf
  • target sha256 415aac8eca9225996b839925f1a1203107fc463bbd283a356a8b06a5605c770e
  • group of 4 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

energy-dataglobalgrid2050 / scripts/update_uk_energy_v2.py · lines 1–199 of 199 · Entry point · pattern write_shell_if_missing (shared by 4 files)

What it does
It draws live grid energy, live grid price, solar and wind. Defines 6 functions or classes, including _iso_minutes_ago, _get_json, fetch_generation_mix, fetch_solar_gw, write_shell_if_missing. Uses libraries requests, os, json, pathlib, datetime. Side effects: changes the web page (DOM); reads or writes files; makes network requests.
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. Domain terms in the code: solar, wind.
Inputs & outputs
In: data source: Elexon BMRS; data source: Carbon Intensity API; JSON file live_grid_energy.json; JSON file live_grid_price.json. Out: JSON file.
Downstream impact
Used directly by 2 files: GlobalGrid2050 Isolate UK Energy Tracking V2 (globalgrid2050); GlobalGrid2050 Fetch UK Energy and Prices V2 Workflow (globalgrid2050). Reached from 1 other entry point, including GlobalGrid2050 Isolate UK Energy Tracking V2 Workflow (globalgrid2050).
What it achieves
It fetches generation mix (`fetch_generation_mix`), fetches solar GW (`fetch_solar_gw`) and writes shell if missing (`write_shell_if_missing`). Runs every 5 minutes. Fetches demand + generation mix (Elexon FUELINST) and national solar (Sheffield Solar).
Why it matters
Run by GlobalGrid2050 Isolate UK Energy Tracking V2 and GlobalGrid2050 Fetch UK Energy and Prices V2 Workflow.
Application
globalgrid2050 · scripts · Python CLI
Uses
requests, os, json, pathlib, datetime
Used by
run by GlobalGrid2050 Isolate UK Energy Tracking V2 (script call), run by GlobalGrid2050 Fetch UK Energy and Prices V2 Workflow (workflow run)
Produces
fetch_generation_mix, fetch_solar_gw, write_shell_if_missing, main
Defines here
_iso_minutes_ago, _get_json, fetch_generation_mix, fetch_solar_gw, write_shell_if_missing, 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_uk_energy_v2.py:1-199 · blob e8be336e1410d0b91dd661b613f33b93bced5a28 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import requests
import os
import json
from pathlib import Path
from datetime import datetime, timezone, timedelta

# Runs every 5 minutes. Fetches demand + generation mix (Elexon FUELINST)
# and national solar (Sheffield Solar). Writes ONLY the energy slice so a
# failure here never touches the half-hourly price slice.

FOLDER = Path(__file__).parent.parent / "uk_energy_tracking_v2"
JSON_FILE = FOLDER / "live_grid_energy.json"
MD_FILE = FOLDER / "index.md"

ELEXON = "https://data.elexon.co.uk/bmrs/api/v1"
PVLIVE = "https://api.solar.sheffield.ac.uk/pvlive/api/v4"
TIMEOUT = 12

FUEL_GROUPS = {
    "Wind": ["WIND"], "Hydro": ["NPSHYD"], "Gas": ["CCGT", "OCGT"],
    "Coal": ["COAL"], "Biomass": ["BIOMASS"], "Nuclear": ["NUCLEAR"],
    "Pumped Storage": ["PS"], "Imports & Exports": ["INT"],
}
ROW_ORDER = ["Solar", "Wind", "Hydro", "Gas", "Coal",
             "Biomass", "Nuclear", "Pumped Storage", "Imports & Exports"]
ROW_COLORS = {
    "Solar": "#f5c518", "Wind": "#00d0ff", "Hydro": "#0090c0",
    "Gas": "#c0399a", "Coal": "#888888", "Biomass": "#f59e2b",
    "Nuclear": "#5cb85c", "Pumped Storage": "#9b59b6", "Imports & Exports": "#e8615a",
}


def _iso_minutes_ago(mins):
    return (datetime.now(timezone.utc) - timedelta(minutes=mins)).strftime("%Y-%m-%dT%H:%MZ")


def _get_json(url):
    last = None
    for _ in range(2):
        try:
            r = requests.get(url, timeout=TIMEOUT,
                             headers={"Accept": "application/json", "User-Agent": "Mozilla/5.0"})
            r.raise_for_status()
            return r.json()
        except Exception as e:  # noqa: BLE001
            last = e
    raise last


def fetch_generation_mix():
    url = (f"{ELEXON}/datasets/FUELINST?publishDateTimeFrom={_iso_minutes_ago(30)}"
           f"&publishDateTimeTo={_iso_minutes_ago(0)}&format=json")
    data = _get_json(url).get("data", [])
    if not data:
        return {}
    latest = max(row["startTime"] for row in data)
    snap = [r for r in data if r["startTime"] == latest]
    return {r["fuelType"]: float(r.get("generation") or 0) for r in snap}


def fetch_solar_gw():
    rows = _get_json(f"{PVLIVE}/gsp/0").get("data", [])
    if not rows:
        return 0.0
    mw = rows[0][2]
    return (float(mw) / 1000.0) if mw is not None else 0.0


MD_SHELL = """---
layout: page
title: UK Live Grid Tracker V2
permalink: /uk_energy_tracking_v2/
---
<style>
.scada-grid { font-family: "Courier New", monospace; }
.scada-metrics { display:flex; flex-wrap:wrap; gap:18px; margin:18px 0; }
.scada-card { flex:1 1 160px; border:1px solid #00ffff; border-radius:4px;
  background:rgba(0,255,255,0.05); padding:14px 16px; }
.scada-card .val { font-size:30px; font-weight:bold; color:#00ffff; letter-spacing:-1px; }
.scada-card .val .u { font-size:15px; color:#7fdfff; font-weight:normal; }
.scada-card .lab { font-size:13px; color:#a6adbb; margin-top:4px; text-transform:uppercase; }
.scada-bar-name { display:flex; justify-content:space-between; font-size:14px; margin:10px 0 4px; }
.scada-bar-name b { color:#e8e8f0; font-weight:normal; }
.scada-bar-name span { color:#7fdfff; font-variant-numeric:tabular-nums; }
.scada-track { height:7px; border-radius:4px; background:rgba(255,255,255,0.08); overflow:hidden; }
.scada-fill { height:100%; border-radius:4px; transition:width .6s ease; }
.scada-status { font-size:12px; color:#a6adbb; margin-top:14px; }
.scada-status.stale { color:#ffb020; }
.scada-credit { font-size:12px; color:#a6adbb; margin-top:10px; line-height:1.5; }
.scada-credit a { color:#7fdfff; }
</style>

# UK Live Grid Tracker

Near-real-time GB electricity demand, market price, carbon intensity and generation mix.
Generation mix refreshes every 5 minutes; price and carbon update every half hour (their native cadence).

<div class="scada-grid" id="scada-grid">
  <div class="scada-metrics">
    <div class="scada-card"><div class="val" id="m-demand">—<span class="u"> GW</span></div><div class="lab">Electricity demand</div></div>
    <div class="scada-card"><div class="val" id="m-price">£—<span class="u">/MWh</span></div><div class="lab">Electricity price</div></div>
    <div class="scada-card"><div class="val" id="m-carbon">—<span class="u"> g/kWh</span></div><div class="lab">Carbon emissions</div></div>
  </div>
  <div id="scada-mix"></div>
  <div class="scada-status" id="scada-status">Loading live feed…</div>
</div>

<script>
(function(){
  var ENERGY="./live_grid_energy.json", PRICE="./live_grid_price.json", POLL=5*60*1000;
  function fmt(n,dp){return (n===null||n===undefined||isNaN(n))?"\\u2014":Number(n).toFixed(dp==null?2:dp);}
  function renderMix(mix){
    var w=document.getElementById("scada-mix"); if(!Array.isArray(mix)){return;}
    w.innerHTML=mix.map(function(r){
      var width=Math.max(0,Math.min(100,Math.abs(r.pct)));
      return '<div class="scada-bar-name"><b>'+r.label+'</b><span>'+fmt(r.gw)+' GW &nbsp; '+fmt(r.pct)+'%</span></div>'+
        '<div class="scada-track"><div class="scada-fill" style="width:'+width+'%;background:'+r.color+'"></div></div>';
    }).join("");
  }
  function ageMin(iso){return iso?(Date.now()-new Date(iso).getTime())/60000:Infinity;}
  function getJSON(u){return fetch(u+"?t="+Date.now(),{cache:"no-store"}).then(function(r){if(!r.ok)throw 0;return r.json();}).catch(function(){return null;});}
  function refresh(){
    Promise.all([getJSON(ENERGY),getJSON(PRICE)]).then(function(res){
      var e=res[0]||{}, p=res[1]||{};
      if(e.demandGW!=null) document.getElementById("m-demand").innerHTML=fmt(e.demandGW)+'<span class="u"> GW</span>';
      document.getElementById("m-price").innerHTML='£'+(p.priceGBPperMWh==null?"\\u2014":fmt(p.priceGBPperMWh))+'<span class="u">/MWh</span>';
      document.getElementById("m-carbon").innerHTML=(p.carbonGperKWh==null?"\\u2014":Math.round(p.carbonGperKWh))+'<span class="u"> g/kWh</span>';
      if(e.mix) renderMix(e.mix);
      var s=document.getElementById("scada-status"), mins=ageMin(e.updated);
      if(mins>20){s.textContent="Mix feed is "+Math.round(mins)+" min old \\u2014 may be stale.";s.className="scada-status stale";}
      else if(e.updated){s.textContent="Mix updated "+new Date(e.updated).toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"})+" \\u00b7 price/carbon updated "+(p.updated?new Date(p.updated).toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"}):"\\u2014");s.className="scada-status";}
      else{s.textContent="Live feed unavailable \\u2014 awaiting first data write.";s.className="scada-status stale";}
    });
  }
  refresh(); setInterval(refresh, POLL);
})();
</script>

## Data sources & attribution

This tracker uses three free public sources. We gratefully acknowledge them:

- **Generation mix & demand** — Elexon BMRS Insights (Balancing Mechanism Reporting Service), used under the BMRS Data Licence Terms.
- **Carbon intensity** — National Energy System Operator [Carbon Intensity API](https://carbonintensity.org.uk/), developed with the Environmental Defense Fund, University of Oxford and WWF. Licensed under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/).
- **Solar generation** — [Sheffield Solar PV_Live](https://www.solar.sheffield.ac.uk/api/), University of Sheffield.

Indicative near-real-time values for screening and situational awareness only. No representation is made that the data is accurate or complete.
"""


def write_shell_if_missing():
    FOLDER.mkdir(parents=True, exist_ok=True)
    if not MD_FILE.exists():
        MD_FILE.write_text(MD_SHELL, encoding="utf-8")
        print(f"Wrote markdown shell: {MD_FILE}")


def main():
    write_shell_if_missing()
    health = {}
    try:
        raw_mw = fetch_generation_mix(); health["generation"] = "ok"
    except Exception as e:  # noqa: BLE001
        raw_mw = {}; health["generation"] = f"error: {e}"
    try:
        solar_gw = fetch_solar_gw(); health["solar"] = "ok"
    except Exception as e:  # noqa: BLE001
        solar_gw = 0.0; health["solar"] = f"error: {e}"

    groups = {}
    for label, codes in FUEL_GROUPS.items():
        groups[label] = sum(mw for c, mw in raw_mw.items()
                            if any(c.startswith(p) for p in codes)) / 1000.0
    groups["Solar"] = solar_gw
    demand = sum(groups.values())

    mix = [{
        "label": l, "gw": round(groups.get(l, 0.0), 2),
        "pct": round((groups.get(l, 0.0) / demand * 100), 2) if demand else 0,
        "color": ROW_COLORS[l],
    } for l in ROW_ORDER]

    out = {
        "updated": datetime.now(timezone.utc).isoformat(),
        "demandGW": round(demand, 2),
        "solarGW": round(solar_gw, 2),
        "mix": mix,
        "health": health,
    }
    FOLDER.mkdir(parents=True, exist_ok=True)
    with open(JSON_FILE, "w", encoding="utf-8") as f:
        json.dump(out, f, indent=2)
    if any(v != "ok" for v in health.values()):
        print(f"::warning::Energy source issue: {health}")
    print(f"✅ Energy slice | demand {out['demandGW']} GW | solar {out['solarGW']} GW | {health}")


if __name__ == "__main__":
    main()