In this section
- GlobalGrid2050 Fix UK Renewables Pipeline CSV Export energy-data · globalgrid2050 / scripts/fix_uk_renewables_pipeline_csv_export.py lines 1–175
- GlobalGrid2050 Generate Generation History Daily V6 energy-data · globalgrid2050 / scripts/generate_generation_history_daily_v6.py lines 1–83
- GlobalGrid2050 Generate Generation Recent Halfhourly V6 energy-data · globalgrid2050 / scripts/generate_generation_recent_halfhourly_v6.py lines 1–106
- GlobalGrid2050 Generate Price History 4bucket V2 energy-data · globalgrid2050 / scripts/generate_price_history_4bucket_v2.py lines 1–140
- GlobalGrid2050 Generate Price History Daily V5 energy-data · globalgrid2050 / scripts/generate_price_history_daily_v5.py lines 1–118
- GlobalGrid2050 Generate Price History Daily V6 energy-data · globalgrid2050 / scripts/generate_price_history_daily_v6.py lines 1–12
GlobalGrid2050 Fix UK Renewables Pipeline CSV Export
A Python command-line tool in the scripts folder. It is built from the read step (`read`) and the write step (`write`).
energy-dataglobalgrid2050 / scripts/fix_uk_renewables_pipeline_csv_export.py · lines 1–175 of 175 · Entry point
- What it does
- It draws its content. Defines read, write, main. Uses libraries __future__, datetime, pathlib. Side effects: changes the web page (DOM); reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'renewables'): 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.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 Fix UK Renewables Pipeline CSV Export Workflow (globalgrid2050).
- What it achieves
- Sidebar contains EXPORT CSV link, but no JavaScript export function is wired.
- Why it matters
- Run by GlobalGrid2050 Fix UK Renewables Pipeline CSV Export Workflow.
- Application
- globalgrid2050 · scripts · Python CLI
- Uses
- __future__, datetime, pathlib
- Used by
- run by GlobalGrid2050 Fix UK Renewables Pipeline CSV Export Workflow (workflow run)
- Produces
- read, write, main
- Defines here
- read, write, 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/fix_uk_renewables_pipeline_csv_export.py:1-175 · blob 70073f5f26f580b3a102cde848044d2ccfb09185 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""
Fix CSV export for UK Renewables Pipeline dashboard.
Current issue:
- Sidebar contains EXPORT CSV link, but no JavaScript export function is wired.
Fix:
- Give the export link an id.
- Track the currently filtered dataset.
- Add a safe CSV generator with escaping.
- Download the filtered rows as a CSV file.
"""
from __future__ import annotations
import datetime as dt
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
DASHBOARD = ROOT / "uk_renewables_pipeline" / "dashboard.html"
REPORTS = ROOT / "gridbot_reports"
REPORT = REPORTS / "fix_uk_renewables_pipeline_csv_export.md"
OLD_EXPORT_LINK = '<a href="#" class="nav-item">EXPORT CSV</a>'
NEW_EXPORT_LINK = '<a href="#" class="nav-item" id="btn-export-csv">EXPORT CSV</a>'
OLD_DATA_STATE = " let allData = [];\n"
NEW_DATA_STATE = " let allData = [];\n let currentFilteredData = [];\n"
OLD_APPLY_SNIPPET = """ updateGauges(filtered);
updateTable(filtered);
}
"""
NEW_APPLY_SNIPPET = """ currentFilteredData = filtered;
updateGauges(filtered);
updateTable(filtered);
}
"""
LISTENERS_MARKER = " // Listeners\n"
EXPORT_FUNCTION = r'''
function csvEscape(value) {
if (value === null || value === undefined) return '""';
const text = String(value).replace(/"/g, '""');
return `"${text}"`;
}
function exportFilteredCSV(event) {
if (event) event.preventDefault();
const rows = currentFilteredData && currentFilteredData.length ? currentFilteredData : allData;
const headers = ["Site Name", "County", "Operator", "Technology", "Status", "Capacity MW"];
const csvRows = [headers.map(csvEscape).join(",")];
rows.forEach(item => {
csvRows.push([
item["Site Name"],
item["County"],
item["Operator"],
item["Tech Category"],
item["Status"],
Number(item.Capacity_MW || 0).toFixed(3)
].map(csvEscape).join(","));
});
const csv = "\ufeff" + csvRows.join("\n");
const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
const date = new Date().toISOString().slice(0, 10);
const tech = String(currentTech || "All").replace(/[^a-z0-9]+/gi, "_").toLowerCase();
const status = String(currentStatus || "All").replace(/[^a-z0-9]+/gi, "_").toLowerCase();
link.href = url;
link.download = `globalgrid2050_uk_renewables_pipeline_${tech}_${status}_${date}.csv`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
}
'''
EXPORT_LISTENER_MARKER = " document.getElementById('county-dropdown').addEventListener('change', (e) => {"
EXPORT_LISTENER = " document.getElementById('btn-export-csv')?.addEventListener('click', exportFilteredCSV);\n\n"
def read(path: Path) -> str:
return path.read_text(encoding="utf-8")
def write(path: Path, text: str) -> None:
path.write_text(text, encoding="utf-8")
def main() -> int:
if not DASHBOARD.exists():
raise SystemExit(f"Missing dashboard: {DASHBOARD.relative_to(ROOT)}")
html = read(DASHBOARD)
actions: list[str] = []
if OLD_EXPORT_LINK in html:
html = html.replace(OLD_EXPORT_LINK, NEW_EXPORT_LINK, 1)
actions.append("added id to EXPORT CSV sidebar link")
elif NEW_EXPORT_LINK in html:
actions.append("EXPORT CSV sidebar link already has id")
else:
raise SystemExit("Could not find EXPORT CSV sidebar link")
if "let currentFilteredData = [];" not in html:
if OLD_DATA_STATE not in html:
raise SystemExit("Could not find allData state declaration")
html = html.replace(OLD_DATA_STATE, NEW_DATA_STATE, 1)
actions.append("added currentFilteredData state")
else:
actions.append("currentFilteredData state already present")
if "currentFilteredData = filtered;" not in html:
if OLD_APPLY_SNIPPET not in html:
raise SystemExit("Could not find applyFilters update snippet")
html = html.replace(OLD_APPLY_SNIPPET, NEW_APPLY_SNIPPET, 1)
actions.append("stored currently filtered data before rendering")
else:
actions.append("filtered data is already stored")
if "function exportFilteredCSV" not in html:
if LISTENERS_MARKER not in html:
raise SystemExit("Could not find listeners marker")
html = html.replace(LISTENERS_MARKER, EXPORT_FUNCTION + LISTENERS_MARKER, 1)
actions.append("added CSV export function")
else:
actions.append("CSV export function already present")
if "btn-export-csv')?.addEventListener('click', exportFilteredCSV" not in html:
if EXPORT_LISTENER_MARKER not in html:
raise SystemExit("Could not find export listener insertion marker")
html = html.replace(EXPORT_LISTENER_MARKER, EXPORT_LISTENER + EXPORT_LISTENER_MARKER, 1)
actions.append("wired EXPORT CSV click handler")
else:
actions.append("EXPORT CSV click handler already wired")
write(DASHBOARD, html)
REPORTS.mkdir(parents=True, exist_ok=True)
timestamp = dt.datetime.now(dt.timezone.utc).isoformat()
report = "\n".join([
"# Fix UK Renewables Pipeline CSV Export",
"",
f"UTC created: {timestamp}",
"",
"## Purpose",
"",
"Fix the dead EXPORT CSV link on the UK Renewables Pipeline dashboard so it downloads the currently filtered table data.",
"",
"## Actions",
"",
*[f"- {a}" for a in actions],
"",
"## Manual acceptance test",
"",
"1. Open `/uk_renewables_pipeline/dashboard.html`.",
"2. Apply a technology or status filter.",
"3. Click `EXPORT CSV` in the sidebar.",
"4. Confirm a CSV downloads with the filtered rows only.",
"5. Open the CSV and confirm columns: Site Name, County, Operator, Technology, Status, Capacity MW.",
"",
])
write(REPORT, report)
print(f"CSV export fix complete. Report: {REPORT.relative_to(ROOT)}")
return 0
if __name__ == "__main__":
raise SystemExit(main())GlobalGrid2050 Generate Generation History Daily V6
A Python command-line tool in the scripts folder that parses MW (`parse_mw`) (units: MW), covering Elexon generation sources half hourly, generation history daily decade, solar and wind.
energy-dataglobalgrid2050 / scripts/generate_generation_history_daily_v6.py · lines 1–83 of 83 · Entry point · pattern parse_mw (shared by 6 files)
- What it does
- Defines group_for, parse_mw, main. Uses libraries csv, json, collections, datetime, pathlib. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'generation'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: solar, wind.
- Inputs & outputs
- In: CSV file elexon_generation_sources_half_hourly.csv; JSON file generation_history_daily_decade.json.
- Downstream impact
- Used directly by 6 files: GlobalGrid2050 Auto Test Generation Sources 2026 V6 Workflow (globalgrid2050); GlobalGrid2050 Backfill Generation Sources Decade V6 Workflow (globalgrid2050); GlobalGrid2050 Backfill Generation Sources Overnight Sequence V6 Workflow (globalgrid2050); GlobalGrid2050 Backfill Generation Sources Staggered Years V6 Workflow (globalgrid2050); and 2 more.
- What it achieves
- Defines `group_for` and `parse_mw`.
- Why it matters
- Run by 5 workflows and scripts, including GlobalGrid2050 Backfill Generation Sources Decade V6 Workflow, GlobalGrid2050 Backfill Generation Sources Overnight Sequence V6 Workflow and GlobalGrid2050 Backfill Generation Sources Staggered Years V6 Workflow. Checked by GlobalGrid2050 Auto Test Generation Sources 2026 V6 Workflow.
- Application
- globalgrid2050 · scripts · Python CLI
- Uses
- csv, json, collections, datetime, pathlib
- Used by
- run by GlobalGrid2050 Auto Test Generation Sources 2026 V6 Workflow (workflow run), run by GlobalGrid2050 Backfill Generation Sources Decade V6 Workflow (workflow run), run by GlobalGrid2050 Backfill Generation Sources Overnight Sequence V6 Workflow (workflow run), run by GlobalGrid2050 Backfill Generation Sources Staggered Years V6 Workflow (workflow run), run by GlobalGrid2050 Backfill Generation Sources Year V6 Workflow (workflow run), run by GlobalGrid2050 Elexon Generation Sources Weekly Workflow (workflow run)
- Produces
- group_for, parse_mw, main
- Defines here
- group_for, parse_mw, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 scripts/generate_generation_history_daily_v6.py:1-83 · blob 8ca3853627aaa8e569d8c8e781974a4a814f345c · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import csv
import json
from collections import defaultdict
from datetime import datetime, timezone
from pathlib import Path
SOURCE = Path('data/generation/elexon_generation_sources_half_hourly.csv')
OUT = Path('uk_energy_tracking_v6/generation_history/generation_history_daily_decade.json')
GROUPS = {
'Solar': ['SOLAR', 'PV'],
'Wind': ['WIND'],
'Hydro': ['NPSHYD', 'HYDRO'],
'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']
def group_for(fuel):
f = str(fuel or '').upper()
for label, prefixes in GROUPS.items():
if any(f.startswith(prefix) for prefix in prefixes):
return label
return 'Other'
def parse_mw(value):
try:
return float(value)
except Exception:
return None
def main():
if not SOURCE.exists():
OUT.parent.mkdir(parents=True, exist_ok=True)
OUT.write_text(json.dumps({'rows': [], 'generatedUTC': datetime.now(timezone.utc).isoformat()}, indent=2), encoding='utf-8')
print(f'Missing source, wrote empty aggregate: {OUT}')
return
buckets = defaultdict(list)
with SOURCE.open('r', encoding='utf-8', newline='') as handle:
for row in csv.DictReader(handle):
t = row.get('periodStartUTC', '')
if len(t) < 10:
continue
date = t[:10]
label = group_for(row.get('fuelType', ''))
mw = parse_mw(row.get('generationMW'))
if mw is None:
continue
buckets[(date, label)].append(mw)
rows = []
for (date, label), values in sorted(buckets.items()):
if not values:
continue
rows.append({
'date': date,
'technology': label,
'averageMW': round(sum(values) / len(values), 3),
'highMW': round(max(values), 3),
'lowMW': round(min(values), 3),
'records': len(values),
'source': 'Elexon BMRS FUELINST and Sheffield Solar PVLive daily aggregate',
})
OUT.parent.mkdir(parents=True, exist_ok=True)
OUT.write_text(json.dumps({
'generatedUTC': datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
'source': 'Elexon BMRS FUELINST and Sheffield Solar PVLive where available',
'rows': rows,
}, indent=2), encoding='utf-8')
print(f'Wrote {len(rows)} daily generation rows to {OUT}')
if __name__ == '__main__':
main()GlobalGrid2050 Generate Generation Recent Halfhourly V6
A Python command-line tool in the scripts folder that parses time and MW and writes empty, covering Elexon generation sources half hourly, generation recent halfhourly 30d, solar and wind.
energy-dataglobalgrid2050 / scripts/generate_generation_recent_halfhourly_v6.py · lines 1–106 of 106 · Entry point · pattern parse_mw (shared by 6 files)
- What it does
- Defines group_for, parse_time, parse_mw, write_empty, main. Uses libraries csv, json, datetime, pathlib. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'generation'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: solar, wind.
- Inputs & outputs
- In: CSV file elexon_generation_sources_half_hourly.csv; JSON file generation_recent_halfhourly_30d.json.
- Downstream impact
- Used directly by 3 files: GlobalGrid2050 Backfill Generation Sources Overnight Sequence V6 Workflow (globalgrid2050); GlobalGrid2050 Backfill Generation Sources Staggered Years V6 Workflow (globalgrid2050); GlobalGrid2050 Elexon Generation Sources Weekly Workflow (globalgrid2050).
- What it achieves
- It writes empty (`write_empty`). Defines `group_for`, `parse_time`, `parse_mw` and 1 more.
- Why it matters
- Run by GlobalGrid2050 Backfill Generation Sources Overnight Sequence V6 Workflow, GlobalGrid2050 Backfill Generation Sources Staggered Years V6 Workflow and GlobalGrid2050 Elexon Generation Sources Weekly Workflow.
- Application
- globalgrid2050 · scripts · Python CLI
- Uses
- csv, json, datetime, pathlib
- Used by
- run by GlobalGrid2050 Backfill Generation Sources Overnight Sequence V6 Workflow (workflow run), run by GlobalGrid2050 Backfill Generation Sources Staggered Years V6 Workflow (workflow run), run by GlobalGrid2050 Elexon Generation Sources Weekly Workflow (workflow run)
- Produces
- group_for, parse_time, parse_mw, write_empty, main
- Defines here
- group_for, parse_time, parse_mw, write_empty, 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/generate_generation_recent_halfhourly_v6.py:1-106 · blob e49741e7848e257895bf01b5d1b41f299b2817db · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import csv
import json
from datetime import datetime, timezone, timedelta
from pathlib import Path
SOURCE = Path('data/generation/elexon_generation_sources_half_hourly.csv')
OUT = Path('uk_energy_tracking_v6/generation_history/generation_recent_halfhourly_30d.json')
DAYS = 30
GROUPS = {
'Solar': ['SOLAR', 'PV'],
'Wind': ['WIND'],
'Hydro': ['NPSHYD', 'HYDRO'],
'Gas': ['CCGT', 'OCGT'],
'Coal': ['COAL'],
'Biomass': ['BIOMASS'],
'Nuclear': ['NUCLEAR'],
'Pumped Storage': ['PS'],
'Imports & Exports': ['INT'],
}
def group_for(fuel):
f = str(fuel or '').upper()
for label, prefixes in GROUPS.items():
if any(f.startswith(prefix) for prefix in prefixes):
return label
return 'Other'
def parse_time(value):
try:
return datetime.fromisoformat(str(value).replace('Z', '+00:00')).astimezone(timezone.utc)
except Exception:
return None
def parse_mw(value):
try:
return float(value)
except Exception:
return None
def write_empty(reason):
OUT.parent.mkdir(parents=True, exist_ok=True)
OUT.write_text(json.dumps({
'generatedUTC': datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
'source': 'Generation recent half hourly slice',
'windowDays': DAYS,
'status': reason,
'rows': [],
}, indent=2), encoding='utf-8')
print(f'Wrote empty recent half hourly slice: {reason}')
def main():
if not SOURCE.exists() or SOURCE.stat().st_size == 0:
write_empty('missing or empty master half hourly CSV')
return
raw = []
latest = None
with SOURCE.open('r', encoding='utf-8', newline='') as handle:
for row in csv.DictReader(handle):
t = parse_time(row.get('periodStartUTC'))
mw = parse_mw(row.get('generationMW'))
if not t or mw is None:
continue
tech = group_for(row.get('fuelType', ''))
item = {
'time': t.isoformat().replace('+00:00', 'Z'),
'technology': tech,
'generationMW': round(mw, 3),
'fuelType': row.get('fuelType', ''),
'source': row.get('source', 'Generation half hourly source'),
}
raw.append((t, item))
if latest is None or t > latest:
latest = t
if not raw or latest is None:
write_empty('no parseable half hourly generation rows')
return
cutoff = latest - timedelta(days=DAYS)
rows_by_key = {}
for t, item in raw:
if t < cutoff:
continue
key = (item['time'], item['technology'])
rows_by_key[key] = item
rows = [rows_by_key[key] for key in sorted(rows_by_key, key=lambda x: (x[0], x[1]))]
OUT.parent.mkdir(parents=True, exist_ok=True)
OUT.write_text(json.dumps({
'generatedUTC': datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
'source': 'Recent generation half hourly slice from repository master CSV',
'windowDays': DAYS,
'latestUTC': latest.isoformat().replace('+00:00', 'Z'),
'rows': rows,
}, indent=2), encoding='utf-8')
print(f'Wrote {len(rows)} rows to {OUT}')
if __name__ == '__main__':
main()GlobalGrid2050 Generate Price History 4bucket V2
A Python command-line tool in the scripts folder that parses dt (`parse_dt`) and reads CSV rows (`read_csv_rows`), covering electricity price history 4bucket decade.
energy-dataglobalgrid2050 / scripts/generate_price_history_4bucket_v2.py · lines 1–140 of 140 · Entry point · pattern source_rows (shared by 2 files)
- What it does
- Defines 6 functions or classes, including parse_dt, read_csv_rows, source_rows, bucket_name, mean. Uses libraries csv, json, datetime, pathlib. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage hv_procurement (path word 'price'): HV materials procurement, which Ventus Ltd states is within its commercial execution boundary.
- Inputs & outputs
- In: JSON file electricity_price_history_4bucket_decade.json; CSV file electricity_price_history.csv.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 Generate Price History 4bucket V2 Workflow (globalgrid2050).
- What it achieves
- It is built from the bucket name helper (`bucket_name`) and the mean step (`mean`). Defines `parse_dt`, `read_csv_rows`, `source_rows` and 2 more.
- Why it matters
- Run by GlobalGrid2050 Generate Price History 4bucket V2 Workflow.
- Application
- globalgrid2050 · scripts · Python CLI
- Uses
- csv, json, datetime, pathlib
- Used by
- run by GlobalGrid2050 Generate Price History 4bucket V2 Workflow (workflow run)
- Produces
- parse_dt, read_csv_rows, source_rows, bucket_name, mean, main
- Defines here
- parse_dt, read_csv_rows, source_rows, bucket_name, mean, 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/generate_price_history_4bucket_v2.py:1-140 · blob 3356351e075c38b4a7089ec31c43ab8da0218280 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: hv_procurement · users: EPC_contractor, procurement_buyer · canonical: production_core
import csv
import json
from datetime import datetime, timezone, timedelta
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
OUT_DIR = ROOT / "uk_energy_tracking_v5"
OUT_FILE = OUT_DIR / "electricity_price_history_4bucket_decade.json"
DATA_DIR = ROOT / "data" / "electricity"
CAPTURED_CSV = OUT_DIR / "electricity_price_history.csv"
MIN_OBSERVATIONS_PER_DAY = 24
RETENTION_DAYS = 3653
def parse_dt(value):
if not value:
return None
text = str(value).strip().replace("Z", "+00:00")
try:
dt = datetime.fromisoformat(text)
except ValueError:
return None
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
return dt.astimezone(timezone.utc)
def read_csv_rows(path):
if not path.exists():
return []
rows = []
with path.open("r", encoding="utf-8", newline="") as f:
for r in csv.DictReader(f):
price_time = r.get("periodStartUTC") or r.get("priceTimeUTC") or r.get("startTime") or ""
price_text = r.get("systemBuyPriceGBPperMWh") or r.get("systemSellPriceGBPperMWh") or r.get("priceGBPperMWh") or r.get("price") or ""
dt = parse_dt(price_time)
if not dt or price_text == "":
continue
try:
price = float(price_text)
except ValueError:
continue
rows.append((dt, price))
return rows
def source_rows():
cutoff = datetime.now(timezone.utc) - timedelta(days=RETENTION_DAYS)
all_rows = []
current_year = datetime.now(timezone.utc).year
for year in range(cutoff.year, current_year + 1):
all_rows.extend(read_csv_rows(DATA_DIR / f"elexon_system_prices_{year}.csv"))
all_rows.extend(read_csv_rows(CAPTURED_CSV))
deduped = {}
for dt, price in all_rows:
if dt >= cutoff:
deduped[dt.isoformat()] = (dt, price)
return [deduped[k] for k in sorted(deduped)]
def bucket_name(hour):
if hour < 6:
return "night"
if hour < 12:
return "morning"
if hour < 18:
return "midday"
return "evening"
def mean(values):
return round(sum(values) / len(values), 2) if values else None
def main():
started = datetime.now(timezone.utc)
rows = source_rows()
by_day = {}
for dt, price in rows:
by_day.setdefault(dt.date().isoformat(), []).append((dt, price))
output_rows = []
skipped = []
for date in sorted(by_day):
points = sorted(by_day[date], key=lambda x: x[0])
if len(points) < MIN_OBSERVATIONS_PER_DAY:
skipped.append({"date": date, "observations": len(points)})
continue
buckets = {"night": [], "morning": [], "midday": [], "evening": []}
peak_dt, peak_price = max(points, key=lambda x: x[1])
for dt, price in points:
buckets[bucket_name(dt.hour)].append(price)
output_rows.append({
"date": date,
"night": mean(buckets["night"]),
"morning": mean(buckets["morning"]),
"midday": mean(buckets["midday"]),
"evening": mean(buckets["evening"]),
"peakAt": peak_dt.strftime("%H:%M"),
"peakPrice": round(peak_price, 2),
"observations": len(points),
})
payload = {
"generated_utc": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
"source": "Derived from Elexon System Price half hourly history and V5 captured price history",
"schema": "date|night|morning|midday|evening|peakAt|peakPrice|observations",
"bucket_definitions_utc": {
"night": "00:00 to 06:00 mean",
"morning": "06:00 to 12:00 mean",
"midday": "12:00 to 18:00 mean",
"evening": "18:00 to 00:00 mean",
},
"retention_days": RETENTION_DAYS,
"minimum_observations_per_day": MIN_OBSERVATIONS_PER_DAY,
"skipped_incomplete_days": skipped[-50:],
"rows": output_rows,
}
OUT_DIR.mkdir(parents=True, exist_ok=True)
tmp = OUT_FILE.with_suffix(".json.tmp")
tmp.write_text(json.dumps(payload, indent=2), encoding="utf-8")
tmp.replace(OUT_FILE)
size = OUT_FILE.stat().st_size
elapsed = (datetime.now(timezone.utc) - started).total_seconds()
print(json.dumps({
"source_rows": len(rows),
"output_days": len(output_rows),
"skipped_days": len(skipped),
"file": str(OUT_FILE),
"size_bytes": size,
"elapsed_seconds": round(elapsed, 2),
"first_date": output_rows[0]["date"] if output_rows else None,
"last_date": output_rows[-1]["date"] if output_rows else None,
}, indent=2))
if __name__ == "__main__":
main()GlobalGrid2050 Generate Price History Daily V5
A Python command-line tool in the scripts folder that reads electricity price history daily decade. It is built from the mean step (`mean`).
energy-dataglobalgrid2050 / scripts/generate_price_history_daily_v5.py · lines 1–118 of 118 · Entry point · pattern source_rows (shared by 2 files)
- What it does
- It loads electricity price history daily decade. Defines parse_dt, read_csv, source_rows, mean, main. Uses libraries csv, json, datetime, pathlib. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage hv_procurement (path word 'price'): HV materials procurement, which Ventus Ltd states is within its commercial execution boundary.
- Inputs & outputs
- In: JSON file electricity_price_history_daily_decade.json; CSV file electricity_price_history.csv.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 Fetch UK Energy and Prices V5 Workflow (globalgrid2050).
- What it achieves
- Defines `parse_dt`, `read_csv`, `source_rows` and 1 more.
- Why it matters
- Run by GlobalGrid2050 Fetch UK Energy and Prices V5 Workflow.
- Application
- globalgrid2050 · scripts · Python CLI
- Uses
- csv, json, datetime, pathlib
- Used by
- run by GlobalGrid2050 Fetch UK Energy and Prices V5 Workflow (workflow run)
- Produces
- parse_dt, read_csv, source_rows, mean, main
- Defines here
- parse_dt, read_csv, source_rows, mean, 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/generate_price_history_daily_v5.py:1-118 · blob e9238a4ac14ca52f0ce2ee51753f8a727fa10434 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: hv_procurement · users: EPC_contractor, procurement_buyer · canonical: production_core
import csv
import json
from datetime import datetime, timezone, timedelta
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
OUT_DIR = ROOT / "uk_energy_tracking_v5"
OUT_FILE = OUT_DIR / "electricity_price_history_daily_decade.json"
DATA_DIR = ROOT / "data" / "electricity"
CAPTURED_CSV = OUT_DIR / "electricity_price_history.csv"
RETENTION_DAYS = 3653
MIN_OBSERVATIONS_PER_DAY = 24
def parse_dt(value):
if not value:
return None
text = str(value).strip().replace("Z", "+00:00")
try:
dt = datetime.fromisoformat(text)
except ValueError:
return None
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
return dt.astimezone(timezone.utc)
def read_csv(path):
if not path.exists():
return []
rows = []
with path.open("r", encoding="utf-8", newline="") as f:
for r in csv.DictReader(f):
t = r.get("periodStartUTC") or r.get("priceTimeUTC") or r.get("startTime") or ""
p = r.get("systemBuyPriceGBPperMWh") or r.get("systemSellPriceGBPperMWh") or r.get("priceGBPperMWh") or r.get("price") or ""
dt = parse_dt(t)
if not dt or p == "":
continue
try:
price = float(p)
except ValueError:
continue
rows.append((dt, price))
return rows
def source_rows():
cutoff = datetime.now(timezone.utc) - timedelta(days=RETENTION_DAYS)
current_year = datetime.now(timezone.utc).year
rows = []
for year in range(cutoff.year, current_year + 1):
rows.extend(read_csv(DATA_DIR / f"elexon_system_prices_{year}.csv"))
rows.extend(read_csv(CAPTURED_CSV))
deduped = {}
for dt, price in rows:
if dt >= cutoff:
deduped[dt.isoformat()] = (dt, price)
return [deduped[k] for k in sorted(deduped)]
def mean(values):
return round(sum(values) / len(values), 2) if values else None
def main():
started = datetime.now(timezone.utc)
rows = source_rows()
by_day = {}
for dt, price in rows:
by_day.setdefault(dt.date().isoformat(), []).append((dt, price))
out_rows = []
skipped = []
for date in sorted(by_day):
points = sorted(by_day[date], key=lambda x: x[0])
if len(points) < MIN_OBSERVATIONS_PER_DAY:
skipped.append({"date": date, "observations": len(points)})
continue
low_dt, low_price = min(points, key=lambda x: x[1])
high_dt, high_price = max(points, key=lambda x: x[1])
vals = [p for _, p in points]
out_rows.append({
"date": date,
"average": mean(vals),
"high": round(high_price, 2),
"highAt": high_dt.strftime("%H:%M"),
"low": round(low_price, 2),
"lowAt": low_dt.strftime("%H:%M"),
"observations": len(points),
})
payload = {
"generated_utc": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
"source": "Derived from Elexon System Price half hourly history and V5 captured price history",
"schema": "date|average|high|highAt|low|lowAt|observations",
"retention_days": RETENTION_DAYS,
"minimum_observations_per_day": MIN_OBSERVATIONS_PER_DAY,
"skipped_incomplete_days": skipped[-50:],
"rows": out_rows,
}
OUT_DIR.mkdir(parents=True, exist_ok=True)
tmp = OUT_FILE.with_suffix(".json.tmp")
tmp.write_text(json.dumps(payload, indent=2), encoding="utf-8")
tmp.replace(OUT_FILE)
print(json.dumps({
"source_rows": len(rows),
"output_days": len(out_rows),
"skipped_days": len(skipped),
"file": str(OUT_FILE),
"size_bytes": OUT_FILE.stat().st_size,
"elapsed_seconds": round((datetime.now(timezone.utc) - started).total_seconds(), 2),
"first_date": out_rows[0]["date"] if out_rows else None,
"last_date": out_rows[-1]["date"] if out_rows else None,
}, indent=2))
if __name__ == "__main__":
main()GlobalGrid2050 Generate Price History Daily V6
A Python module in the scripts folder covering electricity price history daily decade.
energy-dataglobalgrid2050 / scripts/generate_price_history_daily_v6.py · lines 1–12 of 12 · Entry point
- What it does
- Uses libraries pathlib, shutil. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage hv_procurement (path word 'price'): HV materials procurement, which Ventus Ltd states is within its commercial execution boundary.
- Inputs & outputs
- In: JSON file electricity_price_history_daily_decade.json.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 Fetch UK Energy and Prices V6 Workflow (globalgrid2050).
- What it achieves
- No statement of purpose was found in the file, a README line naming it, or its name.
- Why it matters
- Run by GlobalGrid2050 Fetch UK Energy and Prices V6 Workflow.
- Application
- globalgrid2050 · scripts · Python module
- Uses
- pathlib, shutil
- Used by
- run by GlobalGrid2050 Fetch UK Energy and Prices V6 Workflow (workflow run)
- Produces
- none declared
- Defines here
- none
- 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/generate_price_history_daily_v6.py:1-12 · blob d8929e8c82e9202ab6f8ef9a22d69e5a47106603 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: hv_procurement · users: EPC_contractor, procurement_buyer · canonical: production_core
from pathlib import Path
import shutil
ROOT = Path(__file__).parent.parent
src = ROOT / 'uk_energy_tracking_v5' / 'electricity_price_history_daily_decade.json'
dst = ROOT / 'uk_energy_tracking_v6' / 'electricity_price_history_daily_decade.json'
dst.parent.mkdir(parents=True, exist_ok=True)
if src.exists():
shutil.copyfile(src, dst)
else:
dst.write_text('{"rows": []}\n', encoding='utf-8')
print(f'V6 daily aggregate prepared: {dst}')