In this section
- GlobalGrid2050 Update UK Fuel Prices energy-data · globalgrid2050 / scripts/update_uk_fuel_prices.py lines 1–146
- GlobalGrid2050 Update UK Fuel Prices V2 energy-data · globalgrid2050 / scripts/update_uk_fuel_prices_v2.py lines 1–146
- GlobalGrid2050 Update UK Fuel Prices V3 energy-data · globalgrid2050 / scripts/update_uk_fuel_prices_v3.py lines 1–146
- GlobalGrid2050 Update UK Fuel Prices V4 energy-data · globalgrid2050 / scripts/update_uk_fuel_prices_v4.py lines 1–146
GlobalGrid2050 Update UK Fuel Prices
A Python command-line tool in the scripts folder that fetches live UK fuel prices. It parses number (`parse_number`) and is built from the normalise step (`normalise`).
energy-dataglobalgrid2050 / scripts/update_uk_fuel_prices.py · lines 1–146 of 146 · Entry point · pattern find_latest_csv_url (shared by 4 files)
- What it does
- It fetches live UK fuel prices. Defines 8 functions or classes, including now_utc, fetch_text, find_latest_csv_url, normalise, parse_number. Uses libraries csv, json, re, 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_uk_fuel_prices.json.
- Downstream impact
- Used directly by 1 file: GlobalGrid2050 Update UK Fuel Prices Workflow (globalgrid2050).
- What it achieves
- Defines `now_utc`, `fetch_text`, `find_latest_csv_url` and 4 more.
- Why it matters
- Run by GlobalGrid2050 Update UK Fuel Prices Workflow.
- Application
- globalgrid2050 · scripts · Python CLI
- Uses
- csv, json, re, datetime, io, pathlib, urllib.parse, requests
- Used by
- run by GlobalGrid2050 Update UK Fuel Prices Workflow (workflow run)
- Produces
- now_utc, fetch_text, find_latest_csv_url, normalise, parse_number, parse_desnz_csv, main
- Defines here
- now_utc, fetch_text, find_latest_csv_url, normalise, parse_number, parse_desnz_csv, find_col, 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_fuel_prices.py:1-146 · blob 1462863da46bba024361170be953f5ea28e1d382 · 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 re
from datetime import datetime, timezone
from io import StringIO
from pathlib import Path
from urllib.parse import urljoin
import requests
OUT_DIR = Path(__file__).parent.parent / "uk_energy_tracking"
LIVE_FILE = OUT_DIR / "live_uk_fuel_prices.json"
GOV_PAGE = "https://www.gov.uk/government/statistics/weekly-road-fuel-prices"
TIMEOUT = 20
HEADERS = {"User-Agent": "GlobalGrid2050/1.0"}
def now_utc():
return datetime.now(timezone.utc).isoformat()
def fetch_text(url):
r = requests.get(url, timeout=TIMEOUT, headers=HEADERS)
r.raise_for_status()
return r.text
def find_latest_csv_url():
html = fetch_text(GOV_PAGE)
matches = re.findall(r'href="([^"]*weekly_road_fuel_prices_[0-9]{6}\.csv)"', html, flags=re.I)
current = [m for m in matches if "2003_to_2017" not in m.lower()]
if not current:
raise RuntimeError("Could not find current DESNZ weekly road fuel prices CSV link on GOV.UK page")
return urljoin(GOV_PAGE, current[0])
def normalise(text):
return re.sub(r"[^a-z0-9]", "", str(text).lower())
def parse_number(value):
if value is None:
return None
text = str(value).replace(",", "").strip()
if not text or text in {".", "-"}:
return None
try:
return float(text)
except ValueError:
return None
def parse_desnz_csv(csv_text):
rows = list(csv.reader(StringIO(csv_text)))
header_i = None
for i, row in enumerate(rows[:20]):
joined = " ".join(row).lower()
if ("ulsp" in joined or "unleaded" in joined) and ("ulsd" in joined or "diesel" in joined):
header_i = i
break
if header_i is None:
raise RuntimeError("Could not identify DESNZ CSV header row")
headers = rows[header_i]
normalised = [normalise(h) for h in headers]
def find_col(candidates):
for needle in candidates:
for idx, name in enumerate(normalised):
if needle in name:
return idx
return None
date_col = find_col(["date", "weekcommencing", "week"])
petrol_col = find_col(["ulsp", "unleaded", "petrol"])
diesel_col = find_col(["ulsd", "diesel"])
if petrol_col is None or diesel_col is None:
raise RuntimeError(f"Could not identify petrol or diesel columns. Headers: {headers}")
parsed = []
for row in rows[header_i + 1:]:
if len(row) <= max(petrol_col, diesel_col, date_col or 0):
continue
petrol = parse_number(row[petrol_col])
diesel = parse_number(row[diesel_col])
if petrol is None and diesel is None:
continue
parsed.append({
"week": row[date_col].strip() if date_col is not None else None,
"petrolPencePerLitre": petrol,
"dieselPencePerLitre": diesel,
})
if not parsed:
raise RuntimeError("DESNZ CSV parsed but no usable fuel price rows were found")
return parsed
def main():
OUT_DIR.mkdir(parents=True, exist_ok=True)
health = {"source": "DESNZ weekly road fuel prices", "page": GOV_PAGE}
try:
csv_url = find_latest_csv_url()
rows = parse_desnz_csv(fetch_text(csv_url))
latest = rows[-1]
health.update({"ok": True, "csv": csv_url, "rows": len(rows)})
out = {
"updated": now_utc(),
"source": "Department for Energy Security and Net Zero weekly road fuel prices",
"sourcePage": GOV_PAGE,
"sourceCsv": csv_url,
"unit": "pence per litre",
"latest": latest,
"history": rows,
"health": health,
}
except Exception as exc:
health.update({"ok": False, "error": str(exc)})
existing = None
if LIVE_FILE.exists():
try:
existing = json.loads(LIVE_FILE.read_text(encoding="utf-8"))
except Exception:
existing = None
if existing and existing.get("history"):
existing["lastAttemptedUpdate"] = now_utc()
existing["health"] = health
out = existing
else:
out = {
"updated": now_utc(),
"source": "Department for Energy Security and Net Zero weekly road fuel prices",
"sourcePage": GOV_PAGE,
"unit": "pence per litre",
"latest": {"week": None, "petrolPencePerLitre": None, "dieselPencePerLitre": None},
"history": [],
"health": health,
}
LIVE_FILE.write_text(json.dumps(out, indent=2), encoding="utf-8")
print(json.dumps({"latest": out.get("latest"), "health": out.get("health")}, indent=2))
if __name__ == "__main__":
main()GlobalGrid2050 Update UK Fuel Prices V2
A Python command-line tool in the scripts folder that fetches live UK fuel prices. It parses number (`parse_number`) and is built from the normalise step (`normalise`).
Set aside from the main view: 98% of its lines are the same as scripts/update_uk_fuel_prices.py (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 98% of lines shared with GlobalGrid2050 Update UK Fuel Prices; read that one first. All set-aside files, with reasons. Nothing was deleted.
Evidence
- line-jaccard 0.9811 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 scripts/update_uk_fuel_prices.py:1-146 1462863da46bba024361170be953f5ea28e1d382
- sha256 c1013027dc0ceb7f91d2033936ebb249e7e92c26f8a7d1edc58c64abfeca4b60
- target sha256 147ef95fe9d6905eaefa1f4359547e53a3830aca71c7df5c3d1d3b05f3e11ec7
- group of 4 (identity.json near-copy edges >= 0.9)
- canonical rule: reachable, newest stamp, core repo, most lines
energy-dataglobalgrid2050 / scripts/update_uk_fuel_prices_v2.py · lines 1–146 of 146 · Entry point · pattern find_latest_csv_url (shared by 4 files)
- What it does
- It fetches live UK fuel prices. Defines 8 functions or classes, including now_utc, fetch_text, find_latest_csv_url, normalise, parse_number. Uses libraries csv, json, re, 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_uk_fuel_prices.json.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- Defines `now_utc`, `fetch_text`, `find_latest_csv_url` and 4 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, re, datetime, io, pathlib, urllib.parse, requests
- Used by
- none found
- Produces
- now_utc, fetch_text, find_latest_csv_url, normalise, parse_number, parse_desnz_csv, main
- Defines here
- now_utc, fetch_text, find_latest_csv_url, normalise, parse_number, parse_desnz_csv, find_col, 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_fuel_prices_v2.py:1-146 · blob 0c086cdaf9f4a26156a97a7d5a4e46a5e302995e · 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 re
from datetime import datetime, timezone
from io import StringIO
from pathlib import Path
from urllib.parse import urljoin
import requests
OUT_DIR = Path(__file__).parent.parent / "uk_energy_tracking_v2"
LIVE_FILE = OUT_DIR / "live_uk_fuel_prices.json"
GOV_PAGE = "https://www.gov.uk/government/statistics/weekly-road-fuel-prices"
TIMEOUT = 20
HEADERS = {"User-Agent": "GlobalGrid2050/1.0"}
def now_utc():
return datetime.now(timezone.utc).isoformat()
def fetch_text(url):
r = requests.get(url, timeout=TIMEOUT, headers=HEADERS)
r.raise_for_status()
return r.text
def find_latest_csv_url():
html = fetch_text(GOV_PAGE)
matches = re.findall(r'href="([^"]*weekly_road_fuel_prices_[0-9]{6}\.csv)"', html, flags=re.I)
current = [m for m in matches if "2003_to_2017" not in m.lower()]
if not current:
raise RuntimeError("Could not find current DESNZ weekly road fuel prices CSV link on GOV.UK page")
return urljoin(GOV_PAGE, current[0])
def normalise(text):
return re.sub(r"[^a-z0-9]", "", str(text).lower())
def parse_number(value):
if value is None:
return None
text = str(value).replace(",", "").strip()
if not text or text in {".", "-"}:
return None
try:
return float(text)
except ValueError:
return None
def parse_desnz_csv(csv_text):
rows = list(csv.reader(StringIO(csv_text)))
header_i = None
for i, row in enumerate(rows[:20]):
joined = " ".join(row).lower()
if ("ulsp" in joined or "unleaded" in joined) and ("ulsd" in joined or "diesel" in joined):
header_i = i
break
if header_i is None:
raise RuntimeError("Could not identify DESNZ CSV header row")
headers = rows[header_i]
normalised = [normalise(h) for h in headers]
def find_col(candidates):
for needle in candidates:
for idx, name in enumerate(normalised):
if needle in name:
return idx
return None
date_col = find_col(["date", "weekcommencing", "week"])
petrol_col = find_col(["ulsp", "unleaded", "petrol"])
diesel_col = find_col(["ulsd", "diesel"])
if petrol_col is None or diesel_col is None:
raise RuntimeError(f"Could not identify petrol or diesel columns. Headers: {headers}")
parsed = []
for row in rows[header_i + 1:]:
if len(row) <= max(petrol_col, diesel_col, date_col or 0):
continue
petrol = parse_number(row[petrol_col])
diesel = parse_number(row[diesel_col])
if petrol is None and diesel is None:
continue
parsed.append({
"week": row[date_col].strip() if date_col is not None else None,
"petrolPencePerLitre": petrol,
"dieselPencePerLitre": diesel,
})
if not parsed:
raise RuntimeError("DESNZ CSV parsed but no usable fuel price rows were found")
return parsed
def main():
OUT_DIR.mkdir(parents=True, exist_ok=True)
health = {"source": "DESNZ weekly road fuel prices", "page": GOV_PAGE}
try:
csv_url = find_latest_csv_url()
rows = parse_desnz_csv(fetch_text(csv_url))
latest = rows[-1]
health.update({"ok": True, "csv": csv_url, "rows": len(rows)})
out = {
"updated": now_utc(),
"source": "Department for Energy Security and Net Zero weekly road fuel prices",
"sourcePage": GOV_PAGE,
"sourceCsv": csv_url,
"unit": "pence per litre",
"latest": latest,
"history": rows,
"health": health,
}
except Exception as exc:
health.update({"ok": False, "error": str(exc)})
existing = None
if LIVE_FILE.exists():
try:
existing = json.loads(LIVE_FILE.read_text(encoding="utf-8"))
except Exception:
existing = None
if existing and existing.get("history"):
existing["lastAttemptedUpdate"] = now_utc()
existing["health"] = health
out = existing
else:
out = {
"updated": now_utc(),
"source": "Department for Energy Security and Net Zero weekly road fuel prices",
"sourcePage": GOV_PAGE,
"unit": "pence per litre",
"latest": {"week": None, "petrolPencePerLitre": None, "dieselPencePerLitre": None},
"history": [],
"health": health,
}
LIVE_FILE.write_text(json.dumps(out, indent=2), encoding="utf-8")
print(json.dumps({"latest": out.get("latest"), "health": out.get("health")}, indent=2))
if __name__ == "__main__":
main()GlobalGrid2050 Update UK Fuel Prices V3
A Python command-line tool in the scripts folder that fetches live UK fuel prices. It parses number (`parse_number`) and is built from the normalise step (`normalise`).
Set aside from the main view: 98% of its lines are the same as scripts/update_uk_fuel_prices.py (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 98% of lines shared with GlobalGrid2050 Update UK Fuel Prices; read that one first. All set-aside files, with reasons. Nothing was deleted.
Evidence
- line-jaccard 0.9811 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 scripts/update_uk_fuel_prices.py:1-146 1462863da46bba024361170be953f5ea28e1d382
- sha256 c5171caa02cb33ee30f059668052cae956be1a6786c6c39a2b337ee81cea5219
- target sha256 147ef95fe9d6905eaefa1f4359547e53a3830aca71c7df5c3d1d3b05f3e11ec7
- group of 4 (identity.json near-copy edges >= 0.9)
- canonical rule: reachable, newest stamp, core repo, most lines
energy-dataglobalgrid2050 / scripts/update_uk_fuel_prices_v3.py · lines 1–146 of 146 · Entry point · pattern find_latest_csv_url (shared by 4 files)
- What it does
- It fetches live UK fuel prices. Defines 8 functions or classes, including now_utc, fetch_text, find_latest_csv_url, normalise, parse_number. Uses libraries csv, json, re, 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_uk_fuel_prices.json.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- Defines `now_utc`, `fetch_text`, `find_latest_csv_url` and 4 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, re, datetime, io, pathlib, urllib.parse, requests
- Used by
- none found
- Produces
- now_utc, fetch_text, find_latest_csv_url, normalise, parse_number, parse_desnz_csv, main
- Defines here
- now_utc, fetch_text, find_latest_csv_url, normalise, parse_number, parse_desnz_csv, find_col, 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_fuel_prices_v3.py:1-146 · blob ae90df3e3056c2392f0dddbe2c26f3d724ead3f7 · 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 re
from datetime import datetime, timezone
from io import StringIO
from pathlib import Path
from urllib.parse import urljoin
import requests
OUT_DIR = Path(__file__).parent.parent / "uk_energy_tracking_v3"
LIVE_FILE = OUT_DIR / "live_uk_fuel_prices.json"
GOV_PAGE = "https://www.gov.uk/government/statistics/weekly-road-fuel-prices"
TIMEOUT = 20
HEADERS = {"User-Agent": "GlobalGrid2050/1.0"}
def now_utc():
return datetime.now(timezone.utc).isoformat()
def fetch_text(url):
r = requests.get(url, timeout=TIMEOUT, headers=HEADERS)
r.raise_for_status()
return r.text
def find_latest_csv_url():
html = fetch_text(GOV_PAGE)
matches = re.findall(r'href="([^"]*weekly_road_fuel_prices_[0-9]{6}\.csv)"', html, flags=re.I)
current = [m for m in matches if "2003_to_2017" not in m.lower()]
if not current:
raise RuntimeError("Could not find current DESNZ weekly road fuel prices CSV link on GOV.UK page")
return urljoin(GOV_PAGE, current[0])
def normalise(text):
return re.sub(r"[^a-z0-9]", "", str(text).lower())
def parse_number(value):
if value is None:
return None
text = str(value).replace(",", "").strip()
if not text or text in {".", "-"}:
return None
try:
return float(text)
except ValueError:
return None
def parse_desnz_csv(csv_text):
rows = list(csv.reader(StringIO(csv_text)))
header_i = None
for i, row in enumerate(rows[:20]):
joined = " ".join(row).lower()
if ("ulsp" in joined or "unleaded" in joined) and ("ulsd" in joined or "diesel" in joined):
header_i = i
break
if header_i is None:
raise RuntimeError("Could not identify DESNZ CSV header row")
headers = rows[header_i]
normalised = [normalise(h) for h in headers]
def find_col(candidates):
for needle in candidates:
for idx, name in enumerate(normalised):
if needle in name:
return idx
return None
date_col = find_col(["date", "weekcommencing", "week"])
petrol_col = find_col(["ulsp", "unleaded", "petrol"])
diesel_col = find_col(["ulsd", "diesel"])
if petrol_col is None or diesel_col is None:
raise RuntimeError(f"Could not identify petrol or diesel columns. Headers: {headers}")
parsed = []
for row in rows[header_i + 1:]:
if len(row) <= max(petrol_col, diesel_col, date_col or 0):
continue
petrol = parse_number(row[petrol_col])
diesel = parse_number(row[diesel_col])
if petrol is None and diesel is None:
continue
parsed.append({
"week": row[date_col].strip() if date_col is not None else None,
"petrolPencePerLitre": petrol,
"dieselPencePerLitre": diesel,
})
if not parsed:
raise RuntimeError("DESNZ CSV parsed but no usable fuel price rows were found")
return parsed
def main():
OUT_DIR.mkdir(parents=True, exist_ok=True)
health = {"source": "DESNZ weekly road fuel prices", "page": GOV_PAGE}
try:
csv_url = find_latest_csv_url()
rows = parse_desnz_csv(fetch_text(csv_url))
latest = rows[-1]
health.update({"ok": True, "csv": csv_url, "rows": len(rows)})
out = {
"updated": now_utc(),
"source": "Department for Energy Security and Net Zero weekly road fuel prices",
"sourcePage": GOV_PAGE,
"sourceCsv": csv_url,
"unit": "pence per litre",
"latest": latest,
"history": rows,
"health": health,
}
except Exception as exc:
health.update({"ok": False, "error": str(exc)})
existing = None
if LIVE_FILE.exists():
try:
existing = json.loads(LIVE_FILE.read_text(encoding="utf-8"))
except Exception:
existing = None
if existing and existing.get("history"):
existing["lastAttemptedUpdate"] = now_utc()
existing["health"] = health
out = existing
else:
out = {
"updated": now_utc(),
"source": "Department for Energy Security and Net Zero weekly road fuel prices",
"sourcePage": GOV_PAGE,
"unit": "pence per litre",
"latest": {"week": None, "petrolPencePerLitre": None, "dieselPencePerLitre": None},
"history": [],
"health": health,
}
LIVE_FILE.write_text(json.dumps(out, indent=2), encoding="utf-8")
print(json.dumps({"latest": out.get("latest"), "health": out.get("health")}, indent=2))
if __name__ == "__main__":
main()GlobalGrid2050 Update UK Fuel Prices V4
A Python command-line tool in the scripts folder that fetches live UK fuel prices. It parses number (`parse_number`) and is built from the normalise step (`normalise`).
Set aside from the main view: 98% of its lines are the same as scripts/update_uk_fuel_prices.py (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 98% of lines shared with GlobalGrid2050 Update UK Fuel Prices; read that one first. All set-aside files, with reasons. Nothing was deleted.
Evidence
- line-jaccard 0.9811 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 scripts/update_uk_fuel_prices.py:1-146 1462863da46bba024361170be953f5ea28e1d382
- sha256 73c12d5883b460d8ba2f12dc398e878575a4416aaa50fb8348c30c305d33bbb5
- target sha256 147ef95fe9d6905eaefa1f4359547e53a3830aca71c7df5c3d1d3b05f3e11ec7
- group of 4 (identity.json near-copy edges >= 0.9)
- canonical rule: reachable, newest stamp, core repo, most lines
energy-dataglobalgrid2050 / scripts/update_uk_fuel_prices_v4.py · lines 1–146 of 146 · Entry point · pattern find_latest_csv_url (shared by 4 files)
- What it does
- It fetches live UK fuel prices. Defines 8 functions or classes, including now_utc, fetch_text, find_latest_csv_url, normalise, parse_number. Uses libraries csv, json, re, 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_uk_fuel_prices.json.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- Defines `now_utc`, `fetch_text`, `find_latest_csv_url` and 4 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, re, datetime, io, pathlib, urllib.parse, requests
- Used by
- none found
- Produces
- now_utc, fetch_text, find_latest_csv_url, normalise, parse_number, parse_desnz_csv, main
- Defines here
- now_utc, fetch_text, find_latest_csv_url, normalise, parse_number, parse_desnz_csv, find_col, 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_fuel_prices_v4.py:1-146 · blob 725ff4f1238d9a8e293df91808fbc48f55667e63 · 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 re
from datetime import datetime, timezone
from io import StringIO
from pathlib import Path
from urllib.parse import urljoin
import requests
OUT_DIR = Path(__file__).parent.parent / "uk_energy_tracking_v4"
LIVE_FILE = OUT_DIR / "live_uk_fuel_prices.json"
GOV_PAGE = "https://www.gov.uk/government/statistics/weekly-road-fuel-prices"
TIMEOUT = 20
HEADERS = {"User-Agent": "GlobalGrid2050/1.0"}
def now_utc():
return datetime.now(timezone.utc).isoformat()
def fetch_text(url):
r = requests.get(url, timeout=TIMEOUT, headers=HEADERS)
r.raise_for_status()
return r.text
def find_latest_csv_url():
html = fetch_text(GOV_PAGE)
matches = re.findall(r'href="([^"]*weekly_road_fuel_prices_[0-9]{6}\.csv)"', html, flags=re.I)
current = [m for m in matches if "2003_to_2017" not in m.lower()]
if not current:
raise RuntimeError("Could not find current DESNZ weekly road fuel prices CSV link on GOV.UK page")
return urljoin(GOV_PAGE, current[0])
def normalise(text):
return re.sub(r"[^a-z0-9]", "", str(text).lower())
def parse_number(value):
if value is None:
return None
text = str(value).replace(",", "").strip()
if not text or text in {".", "-"}:
return None
try:
return float(text)
except ValueError:
return None
def parse_desnz_csv(csv_text):
rows = list(csv.reader(StringIO(csv_text)))
header_i = None
for i, row in enumerate(rows[:20]):
joined = " ".join(row).lower()
if ("ulsp" in joined or "unleaded" in joined) and ("ulsd" in joined or "diesel" in joined):
header_i = i
break
if header_i is None:
raise RuntimeError("Could not identify DESNZ CSV header row")
headers = rows[header_i]
normalised = [normalise(h) for h in headers]
def find_col(candidates):
for needle in candidates:
for idx, name in enumerate(normalised):
if needle in name:
return idx
return None
date_col = find_col(["date", "weekcommencing", "week"])
petrol_col = find_col(["ulsp", "unleaded", "petrol"])
diesel_col = find_col(["ulsd", "diesel"])
if petrol_col is None or diesel_col is None:
raise RuntimeError(f"Could not identify petrol or diesel columns. Headers: {headers}")
parsed = []
for row in rows[header_i + 1:]:
if len(row) <= max(petrol_col, diesel_col, date_col or 0):
continue
petrol = parse_number(row[petrol_col])
diesel = parse_number(row[diesel_col])
if petrol is None and diesel is None:
continue
parsed.append({
"week": row[date_col].strip() if date_col is not None else None,
"petrolPencePerLitre": petrol,
"dieselPencePerLitre": diesel,
})
if not parsed:
raise RuntimeError("DESNZ CSV parsed but no usable fuel price rows were found")
return parsed
def main():
OUT_DIR.mkdir(parents=True, exist_ok=True)
health = {"source": "DESNZ weekly road fuel prices", "page": GOV_PAGE}
try:
csv_url = find_latest_csv_url()
rows = parse_desnz_csv(fetch_text(csv_url))
latest = rows[-1]
health.update({"ok": True, "csv": csv_url, "rows": len(rows)})
out = {
"updated": now_utc(),
"source": "Department for Energy Security and Net Zero weekly road fuel prices",
"sourcePage": GOV_PAGE,
"sourceCsv": csv_url,
"unit": "pence per litre",
"latest": latest,
"history": rows,
"health": health,
}
except Exception as exc:
health.update({"ok": False, "error": str(exc)})
existing = None
if LIVE_FILE.exists():
try:
existing = json.loads(LIVE_FILE.read_text(encoding="utf-8"))
except Exception:
existing = None
if existing and existing.get("history"):
existing["lastAttemptedUpdate"] = now_utc()
existing["health"] = health
out = existing
else:
out = {
"updated": now_utc(),
"source": "Department for Energy Security and Net Zero weekly road fuel prices",
"sourcePage": GOV_PAGE,
"unit": "pence per litre",
"latest": {"week": None, "petrolPencePerLitre": None, "dieselPencePerLitre": None},
"history": [],
"health": health,
}
LIVE_FILE.write_text(json.dumps(out, indent=2), encoding="utf-8")
print(json.dumps({"latest": out.get("latest"), "health": out.get("health")}, indent=2))
if __name__ == "__main__":
main()