Spaces:
Running

electrocheap / sources.py
kugguk's picture
Repair complete-month feeds and add portable LLM forecast challenge
afb6251 verified
Raw History Blame Contribute Delete
13.4 kB
"""Bounded official data readers. No user-provided URL is fetched."""
from datetime import date, datetime, timezone, timedelta
from functools import lru_cache
import hashlib
import io
import json
import time
import math
from urllib.request import Request, urlopen
from urllib.parse import urlencode, quote
import pandas as pd
REN_BASE = "https://servicebus.ren.pt/datahubapi/electricity/"
AER_BRANDS = ["agl", "origin", "energyaustralia"]
AU_REGIONS = ["NSW1", "QLD1", "VIC1", "SA1", "TAS1"]
SOURCES = [
{"market": "Portugal", "publisher": "REN", "type": "Grid consumption / wholesale prices", "link": "https://datahub.ren.pt/pt/instrucoes-api/", "scope": "Mainland Portugal; revised/provisional source data"},
{"market": "Portugal", "publisher": "ERSE", "type": "Retail offer reference", "link": "https://simuladorprecos.erse.pt/eletricidade", "scope": "Import a complete dated quote; no automated retail feed validated"},
{"market": "Germany", "publisher": "Bundesnetzagentur / SMARD", "type": "Grid consumption / wholesale prices", "link": "https://www.smard.de/en/downloadcenter", "scope": "DE grid load; DE-LU wholesale prices since October 2018"},
{"market": "Germany", "publisher": "Provider quotes", "type": "Retail offers", "link": "https://www.bundesnetzagentur.de/EN/Areas/Energy/Companies/EnergySupply/start.html", "scope": "Import tax-inclusive quote for postcode/grid/meter; no national retail feed claimed"},
{"market": "Australia", "publisher": "AEMO", "type": "Grid demand / wholesale prices", "link": "https://www.aemo.com.au/energy-systems/electricity/national-electricity-market-nem/data-nem/aggregated-data", "scope": "NEM regions only; excludes WA, NT and isolated grids; fixed UTC+10 market time"},
{"market": "Australia", "publisher": "AER / Energy Made Easy", "type": "Live retailer plans", "link": "https://www.aer.gov.au/energy-product-reference-data", "scope": "Selected retailers via public CDR PRD; list v1, detail v3; not whole-market coverage"},
]
def read_url(url, version=None):
headers = {"User-Agent": "Electrocheap/0.1 (source benchmark)"}
if version:
headers.update({"x-v": str(version), "x-min-v": str(version), "Accept": "application/json"})
req = Request(url, headers=headers)
with urlopen(req, timeout=15) as r:
raw = r.read(12_000_001)
if len(raw) > 12_000_000:
raise ValueError("Official response exceeds the 12 MB request cap.")
return raw
@lru_cache(maxsize=32)
def cached_json(url, version, bucket):
raw = read_url(url, version)
return json.loads(raw), hashlib.sha256(raw).hexdigest(), datetime.now(timezone.utc).isoformat()
def get_json(url, version=None):
return cached_json(url, version, int(time.time() // 600))
def latest_complete_month():
return (date.today().replace(day=1) - timedelta(days=1)).strftime("%Y-%m")
def check_month(month):
parsed = datetime.strptime(month, "%Y-%m")
if parsed.strftime("%Y-%m") != month or month > latest_complete_month() or month < "2018-10":
raise ValueError("Use a complete month between 2018-10 and the previous calendar month.")
return parsed
def smard_month(filter_id, region_code, month, nonnegative=True, reader=None):
"""Read every publication block covering a local month, including DST."""
reader = reader or get_json
parsed = check_month(month)
start = pd.Timestamp(parsed).tz_localize("Europe/Berlin").tz_convert("UTC")
end = (pd.Timestamp(parsed) + pd.offsets.MonthBegin()).tz_localize("Europe/Berlin").tz_convert("UTC")
start_ms, end_ms = int(start.timestamp()*1000), int(end.timestamp()*1000)
index_url = f"https://www.smard.de/app/chart_data/{filter_id}/{region_code}/index_hour.json"
index, index_digest, index_time = reader(index_url)
stamps = index.get("timestamps") if isinstance(index, dict) else None
if not isinstance(stamps, list) or not stamps or any(isinstance(t, bool) or not isinstance(t, int) for t in stamps):
raise ValueError("SMARD hourly index schema changed.")
stamps = sorted(set(stamps))
preceding = [t for t in stamps if t <= start_ms]
if not preceding:
raise ValueError("SMARD has no publication block covering the month start.")
blocks = [preceding[-1]] + [t for t in stamps if start_ms < t < end_ms]
if len(blocks) > 7:
raise ValueError("SMARD publication layout exceeds the bounded monthly reader.")
urls, hashes, times = [index_url], [index_digest], [index_time]
observations = {}
for block in blocks:
url = f"https://www.smard.de/app/chart_data/{filter_id}/{region_code}/{filter_id}_{region_code}_hour_{block}.json"
data, sha, retrieved = reader(url)
values = data.get("series") if isinstance(data, dict) else None
if not isinstance(values, list):
raise ValueError("SMARD hourly response schema changed.")
for row in values:
if not isinstance(row, list) or len(row) != 2:
raise ValueError("SMARD hourly row schema changed.")
stamp, value = row
if isinstance(stamp, bool) or not isinstance(stamp, int):
raise ValueError("SMARD hourly timestamp is invalid.")
if start_ms <= stamp < end_ms:
if stamp in observations:
raise ValueError("Duplicate SMARD hourly observation in the requested month.")
if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or (nonnegative and value < 0):
raise ValueError("SMARD month contains missing or nonfinite observations.")
observations[stamp] = float(value)
urls.append(url); hashes.append(sha); times.append(retrieved)
expected = pd.date_range(start, end, freq="h", inclusive="left")
if sorted(observations) != [int(t.timestamp()*1000) for t in expected]:
raise ValueError("SMARD month has missing or unexpected hourly observations; no monthly total inferred.")
frame = pd.DataFrame({"timestamp": expected, "value": [observations[int(t.timestamp()*1000)] for t in expected]})
return frame, {"source_urls": urls, "response_sha256": hashes, "source_retrieved_at": times,
"coverage_basis": "Every expected UTC hourly observation checked; DST follows Europe/Berlin",
"observations": len(expected), "month": month}
def live_market(country, region, month):
parsed = check_month(month)
fetched = datetime.now(timezone.utc).isoformat()
meta = {"country": country, "retrieved_at": fetched, "cache_ttl_seconds": 600,
"limits": "Official published data can be revised. Wholesale prices are not household bills. Grid demand cannot identify retailer demand."}
if country == "PT":
suffix = "?" + urlencode({"culture": "en-US", "year": parsed.year, "month": parsed.month})
consumption_url = REN_BASE + "ElectricityConsumptionSupplyMonthly" + suffix
price_url = REN_BASE + "ElectricityMarketPricesMonthly" + suffix
consumption, h1, time1 = get_json(consumption_url)
prices, h2, time2 = get_json(price_url)
rows = [{"metric": x["type"], "value": x["monthly_Accumulation"], "unit": "GWh"} for x in consumption]
if not any(x["metric"] == "CONSUMPTION" for x in rows):
raise ValueError("REN consumption schema changed; no guessed values returned.")
meta.update({"scope": "Portugal mainland", "source_urls": [consumption_url, price_url],
"response_sha256": [h1, h2], "source_retrieved_at": [time1, time2], "wholesale_prices": prices,
"price_unit": "EUR/MWh", "month": month})
return pd.DataFrame(rows), meta
if country == "AU":
if region not in AU_REGIONS:
raise ValueError("Select NSW1, QLD1, VIC1, SA1 or TAS1.")
url = f"https://www.aemo.com.au/aemo/data/nem/priceanddemand/PRICE_AND_DEMAND_{parsed:%Y%m}_{region}.csv"
# CSV downloads are bounded but not persisted on the Space.
raw = read_url(url)
d = pd.read_csv(io.BytesIO(raw))
required = {"SETTLEMENTDATE", "TOTALDEMAND", "RRP", "REGION", "PERIODTYPE"}
if not required <= set(d):
raise ValueError("AEMO schema changed; no guessed values returned.")
if not (d.REGION == region).all() or not (d.PERIODTYPE == "TRADE").all():
raise ValueError("Unexpected AEMO region or period type.")
interval = 5 if month >= "2021-10" else 30
stamp = pd.to_datetime(d.SETTLEMENTDATE, format="ISO8601")
expected = pd.date_range(parsed + timedelta(minutes=interval), (pd.Timestamp(parsed) + pd.offsets.MonthBegin(1)), freq=f"{interval}min")
if stamp.duplicated().any() or not pd.DatetimeIndex(stamp).equals(expected):
raise ValueError("Incomplete, duplicate or unexpected interval-end timestamps in AEMO file.")
if not d[["TOTALDEMAND", "RRP"]].apply(pd.to_numeric).map(lambda v: pd.notna(v) and abs(v) < float("inf")).all().all():
raise ValueError("Nonfinite demand/price in AEMO file.")
out = pd.DataFrame({"timestamp_AEST": stamp.astype(str), "demand_MW": d.TOTALDEMAND,
"wholesale_AUD_per_MWh": d.RRP})
meta.update({"source_urls": [url], "response_sha256": [hashlib.sha256(raw).hexdigest()],
"scope": region + "; NEM excludes WA/NT", "interval_minutes": interval,
"integrated_demand_GWh": float(d.TOTALDEMAND.sum() * interval / 60 / 1000),
"mean_wholesale_AUD_per_MWh": float(d.RRP.mean()), "month": month,
"timezone": "Fixed AEST UTC+10; timestamp is interval end"})
return out, meta
if country == "DE":
frames, urls, hashes, times = [], [], [], []
for filter_id, region_code, column in [(410, "DE", "grid_load_MWh"), (4169, "DE-LU", "wholesale_EUR_per_MWh")]:
d, detail = smard_month(filter_id, region_code, month, nonnegative=filter_id==410)
frames.append(d.rename(columns={"value": column}))
urls.extend(detail["source_urls"]); hashes.extend(detail["response_sha256"])
times.extend(detail["source_retrieved_at"])
out = frames[0].merge(frames[1], on="timestamp", how="inner", validate="one_to_one").sort_values("timestamp")
if len(out) != len(frames[0]) or len(out) != len(frames[1]):
raise ValueError("SMARD demand and price timestamps do not align.")
out["timestamp"] = out.timestamp.astype(str)
meta.update({"source_urls": urls, "response_sha256": hashes, "source_retrieved_at": times,
"scope": "DE grid load / DE-LU wholesale price; complete local calendar month",
"month": month, "observations": len(out), "complete_month": True,
"null_policy": "Missing, duplicate or nonfinite observations reject the month.",
"timezone": "UTC timestamps; original DE local time follows Europe/Berlin"})
return out, meta
raise ValueError("country must be PT, DE or AU.")
def aer_plans(brand, postcode=""):
if brand not in AER_BRANDS:
raise ValueError("Select a configured AER retailer.")
url = f"https://cdr.energymadeeasy.gov.au/{brand}/cds-au/v1/energy/plans?fuelType=ELECTRICITY&page-size=1000"
data, sha, fetched = get_json(url, 1)
plans = data["data"]["plans"]
if data.get("meta", {}).get("totalPages", 1) > 1:
limit_note = "First 1000 plans only; further pages omitted."
else:
limit_note = "Published list for selected retailer; not the whole market."
if postcode:
if not postcode.isdigit() or len(postcode) != 4:
raise ValueError("Australian postcode must contain four digits.")
# A postcode missing in publisher geography cannot establish eligibility.
plans = [p for p in plans if postcode in p.get("geography", {}).get("includedPostcodes", [])
and postcode not in p.get("geography", {}).get("excludedPostcodes", [])]
rows = [{"plan_id": p["planId"], "provider": p.get("brandName", brand),
"plan": p.get("displayName", ""), "customer_type": p.get("customerType", ""),
"distributors": ", ".join(p.get("geography", {}).get("distributors", [])),
"effective_from": p.get("effectiveFrom", ""), "last_updated": p.get("lastUpdated", "")} for p in plans]
return pd.DataFrame(rows), {"source_url": url, "response_sha256": sha,
"retrieved_at": fetched, "scope": limit_note,
"limits": "Postcode match is partial eligibility only. Read plan details, distributor, meter, fees and conditions before normalizing a quote. No savings inferred from list data."}
def aer_detail(brand, plan_id):
if brand not in AER_BRANDS or not 1 <= len(plan_id) <= 200:
raise ValueError("Select a configured brand and valid plan ID.")
url = f"https://cdr.energymadeeasy.gov.au/{brand}/cds-au/v1/energy/plans/{quote(plan_id, safe='')}"
data, sha, fetched = get_json(url, 3)
return {"publisher_response": data, "source_url": url, "response_sha256": sha,
"retrieved_at": fetched,
"limits": "Raw official plan detail. No automatic flattening of demand, tier, export or conditional pricing into a simple quote."}