In this section
- GlobalGrid2050 Update UK Energy V3 energy-data · globalgrid2050 / scripts/update_uk_energy_v3.py lines 1–199
- GlobalGrid2050 Update UK Energy V4 energy-data · globalgrid2050 / scripts/update_uk_energy_v4.py lines 1–199
- GlobalGrid2050 Update UK Energy V5 energy-data · globalgrid2050 / scripts/update_uk_energy_v5.py lines 1–109
- GlobalGrid2050 Update UK Energy V6 storage · globalgrid2050 / scripts/update_uk_energy_v6.py lines 1–144
GlobalGrid2050 Update UK Energy V3
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 127c2aba6386694ad5c329d68e582922efdebd50aaf59a65ddc6394179669b91
- 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_v3.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 V3 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 V3 Workflow.
- Application
- globalgrid2050 · scripts · Python CLI
- Uses
- requests, os, json, pathlib, datetime
- Used by
- run by GlobalGrid2050 Fetch UK Energy and Prices V3 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_v3.py:1-199 · blob a4af13c840f0e05587f34384cc300f05a0a8542d · 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_v3"
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_v3/
---
<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 '+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 V4
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 940ef39c60bb935fe47c8d309b525aeafced095fb21a77c43577e96d7eea22bf
- 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_v4.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 V4 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 V4 Workflow.
- Application
- globalgrid2050 · scripts · Python CLI
- Uses
- requests, os, json, pathlib, datetime
- Used by
- run by GlobalGrid2050 Fetch UK Energy and Prices V4 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_v4.py:1-199 · blob b6bb440de1ece82aa71d61779ca17a0a479e5523 · 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_v4"
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_v4/
---
<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 '+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 V5
A Python command-line tool in the scripts folder that fetches live grid energy, solar and wind from Elexon Balancing Mechanism Reporting Service (BMRS).
energy-dataglobalgrid2050 / scripts/update_uk_energy_v5.py · lines 1–109 of 109 · Entry point · pattern fetch_generation_mix (shared by 5 files)
- What it does
- It fetches live grid energy, solar and wind. Defines _iso_minutes_ago, _get_json, fetch_generation_mix, fetch_solar_gw, main. Uses libraries requests, os, json, pathlib, datetime. Side effects: 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; JSON file live_grid_energy.json. Out: JSON file.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 Fetch UK Energy and Prices V5 Workflow (globalgrid2050).
- What it achieves
- It fetches generation mix (`fetch_generation_mix`) and fetches solar GW (`fetch_solar_gw`). 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 V5 Workflow.
- Application
- globalgrid2050 · scripts · Python CLI
- Uses
- requests, os, json, pathlib, datetime
- Used by
- run by GlobalGrid2050 Fetch UK Energy and Prices V5 Workflow (workflow run)
- Produces
- fetch_generation_mix, fetch_solar_gw, main
- Defines here
- _iso_minutes_ago, _get_json, fetch_generation_mix, fetch_solar_gw, 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_v5.py:1-109 · blob d2ca32c3a267be1a2989af157528bbb5e4a7cb0b · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: 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 V5 energy slice so a
# failure here never touches the half hourly price slice.
FOLDER = Path(__file__).parent.parent / "uk_energy_tracking_v5"
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
def main():
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 V5 | demand {out['demandGW']} GW | solar {out['solarGW']} GW | {health}")
if __name__ == "__main__":
main()GlobalGrid2050 Update UK Energy V6
A Python command-line tool in the scripts folder that fetches live grid energy, solar and wind from Elexon Balancing Mechanism Reporting Service (BMRS).
storageglobalgrid2050 / scripts/update_uk_energy_v6.py · lines 1–144 of 144 · Entry point · pattern get_json (shared by 4 files)
- What it does
- It fetches live grid energy, solar and wind. Defines 9 functions or classes, including ago, now_iso, get_json, fetch_mix, fetch_solar. Uses libraries json, datetime, pathlib, requests. Side effects: 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; JSON file live_grid_energy.json.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 Fetch UK Energy and Prices V6 Workflow (globalgrid2050).
- What it achieves
- It fetches mix (`fetch_mix`) and fetches solar (`fetch_solar`). Defines `ago`, `now_iso`, `get_json` and 5 more.
- Why it matters
- Run by GlobalGrid2050 Fetch UK Energy and Prices V6 Workflow.
- Application
- globalgrid2050 · scripts · Python CLI
- Uses
- json, datetime, pathlib, requests
- Used by
- run by GlobalGrid2050 Fetch UK Energy and Prices V6 Workflow (workflow run)
- Produces
- ago, now_iso, get_json, fetch_mix, fetch_solar, previous_payload, write_report, valid_energy_payload, main
- Defines here
- ago, now_iso, get_json, fetch_mix, fetch_solar, previous_payload, write_report, valid_energy_payload, 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_v6.py:1-144 · blob 2b8130fbdf111be0888a5774a75fc2609e4669db · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import json
from datetime import datetime, timezone, timedelta
from pathlib import Path
import requests
FOLDER = Path(__file__).parent.parent / 'uk_energy_tracking_v6'
OUT = FOLDER / 'live_grid_energy.json'
REPORT_DIR = Path(__file__).parent.parent / 'gridbot_reports'
REPORT = REPORT_DIR / 'v6_live_feed_guardrail_report.md'
ELEXON = 'https://data.elexon.co.uk/bmrs/api/v1'
PVLIVE = 'https://api.solar.sheffield.ac.uk/pvlive/api/v4'
TIMEOUT = 12
GROUPS = {
'Wind': ['WIND'], 'Hydro': ['NPSHYD'], 'Gas': ['CCGT', 'OCGT'],
'Coal': ['COAL'], 'Biomass': ['BIOMASS'], 'Nuclear': ['NUCLEAR'],
'Pumped Storage': ['PS'], 'Imports & Exports': ['INT'],
}
ORDER = ['Solar','Wind','Hydro','Gas','Coal','Biomass','Nuclear','Pumped Storage','Imports & Exports']
COLORS = {'Solar':'#f5c518','Wind':'#00d0ff','Hydro':'#0090c0','Gas':'#c0399a','Coal':'#888888','Biomass':'#f59e2b','Nuclear':'#5cb85c','Pumped Storage':'#9b59b6','Imports & Exports':'#e8615a'}
MIN_NON_SOLAR_GW = 5.0
MIN_TOTAL_GW = 15.0
def ago(minutes):
return (datetime.now(timezone.utc) - timedelta(minutes=minutes)).strftime('%Y-%m-%dT%H:%MZ')
def now_iso():
return datetime.now(timezone.utc).isoformat()
def get_json(url):
last = None
for _ in range(2):
try:
r = requests.get(url, timeout=TIMEOUT, headers={'Accept':'application/json','User-Agent':'GlobalGrid2050 V6'})
r.raise_for_status()
return r.json()
except Exception as exc:
last = exc
raise last
def fetch_mix():
url = f'{ELEXON}/datasets/FUELINST?publishDateTimeFrom={ago(90)}&publishDateTimeTo={ago(0)}&format=json'
rows = get_json(url).get('data', [])
if not rows:
raise RuntimeError('Elexon FUELINST returned no rows')
latest = max(r['startTime'] for r in rows if r.get('startTime'))
snap = [r for r in rows if r.get('startTime') == latest]
if len(snap) < 3:
raise RuntimeError(f'Elexon FUELINST thin snapshot: {len(snap)} rows')
return {r['fuelType']: float(r.get('generation') or 0) for r in snap if r.get('fuelType')}
def fetch_solar():
rows = get_json(f'{PVLIVE}/gsp/0').get('data', [])
if not rows:
raise RuntimeError('PVLive returned no rows')
return float(rows[0][2] or 0) / 1000.0
def previous_payload():
if not OUT.exists():
return None
try:
return json.loads(OUT.read_text(encoding='utf-8'))
except Exception:
return None
def write_report(status, detail, payload=None):
REPORT_DIR.mkdir(parents=True, exist_ok=True)
lines = [
'# V6 Live Feed Guardrail Report',
'',
f'Updated UTC: {now_iso()}',
f'Status: {status}',
f'Detail: {detail}',
]
if payload:
lines += [
'',
f"Demand GW: {payload.get('demandGW')}",
f"Solar GW: {payload.get('solarGW')}",
f"Health: {json.dumps(payload.get('health', {}), ensure_ascii=False)}",
]
REPORT.write_text('\n'.join(lines) + '\n', encoding='utf-8')
def valid_energy_payload(out):
mix = out.get('mix') or []
non_solar = sum(float(r.get('gw') or 0) for r in mix if r.get('label') != 'Solar')
total = float(out.get('demandGW') or 0)
solar = float(out.get('solarGW') or 0)
if total < MIN_TOTAL_GW:
return False, f'total demand too low for GB live mix: {total} GW'
if non_solar < MIN_NON_SOLAR_GW:
return False, f'non solar generation too low: {non_solar} GW, solar {solar} GW'
if solar > 0 and total <= solar * 1.15:
return False, f'solar-only collapse risk: demand {total} GW, solar {solar} GW'
return True, 'ok'
def main():
health = {}
try:
raw = fetch_mix(); health['generation'] = 'ok'
except Exception as exc:
raw = None; health['generation'] = f'error: {exc}'
try:
solar = fetch_solar(); health['solar'] = 'ok'
except Exception as exc:
solar = 0.0; health['solar'] = f'error: {exc}'
if raw is None:
old = previous_payload()
write_report('blocked', 'Elexon generation failed, previous V6 energy file preserved', old)
print(f"::warning::V6 energy guardrail blocked overwrite: {health}")
return
grouped = {}
for label, codes in GROUPS.items():
grouped[label] = sum(mw for code, mw in raw.items() if any(code.startswith(prefix) for prefix in codes)) / 1000.0
grouped['Solar'] = solar
demand = sum(grouped.values())
mix = [{'label': label, 'gw': round(grouped.get(label,0),2), 'pct': round((grouped.get(label,0)/demand*100),2) if demand else 0, 'color': COLORS[label]} for label in ORDER]
out = {'updated': now_iso(), 'demandGW': round(demand,2), 'solarGW': round(solar,2), 'mix': mix, 'health': health}
valid, reason = valid_energy_payload(out)
if not valid:
old = previous_payload()
write_report('blocked', reason + '; previous V6 energy file preserved', old)
print(f'::warning::V6 energy guardrail blocked overwrite: {reason}')
return
FOLDER.mkdir(parents=True, exist_ok=True)
OUT.write_text(json.dumps(out, indent=2), encoding='utf-8')
write_report('ok', 'V6 energy feed passed guardrails', out)
print(json.dumps({'v6_energy_updated': out['updated'], 'demandGW': out['demandGW'], 'health': health}, indent=2))
if __name__ == '__main__':
main()