GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / data-gb-electricity / derived

Build Price Decade Rollup and 2 more files

A Python command-line tool in the derived folder of Data GB Electricity that reads solar.

591 lines of Python from data-gb-electricity, in 3 files. Topic: Electricity markets and data pipelines. Section 736 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Build Price Decade Rollup energy-data · data-gb-electricity / derived/build_price_decade_rollup.py lines 1–266
  2. Price Daily Browser energy-data · data-gb-electricity / derived/price_daily_browser.py lines 1–199
  3. Verify Price Decade Rollup energy-data · data-gb-electricity / derived/verify_price_decade_rollup.py lines 1–126

Build Price Decade Rollup

A Python command-line tool in the derived folder of Data GB Electricity that reads solar.

energy-datadata-gb-electricity / derived/build_price_decade_rollup.py · lines 1–266 of 266 · Entry point

What it does
It loads solar. Defines 6 functions or classes, including price_input_glob, require_price_grain, mean, percentage, extreme. Uses libraries calendar, io, json, os, collections. Side effects: uses storage (browser storage, DuckDB or Parquet).
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. Domain terms in the code: solar.
Inputs & outputs
In: JSON file price-decade-rollup.json; DuckDB queries.
Downstream impact
Used directly by 3 files: Price Daily Browser (data-gb-electricity); Verify Price Decade Rollup (data-gb-electricity); Refresh Price Decade Rollup Workflow (data-gb-electricity). Reached from 2 other entry points, including Monthly Update Workflow (data-gb-electricity); Test Price Daily Browser (data-gb-electricity).
What it achieves
It is built from the price input glob helper (`price_input_glob`), the require price grain helper (`require_price_grain`) and the mean step (`mean`). Derive the price record rollup: a browser-sized product over this repo's own Parquet.
Why it matters
Imported by Price Daily Browser and Verify Price Decade Rollup. Run by Refresh Price Decade Rollup Workflow.
Application
data-gb-electricity · derived · Python CLI
Uses
calendar, io, json, os, collections, duckdb
Used by
imported by Price Daily Browser (import), imported by Verify Price Decade Rollup (import), run by Refresh Price Decade Rollup Workflow (workflow run)
Produces
price_input_glob, require_price_grain, mean, percentage, extreme, main
Defines here
price_input_glob, require_price_grain, mean, percentage, extreme, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
data-gb-electricity@e888f35c1a65589b3eb7c78bcc542022bc707298 derived/build_price_decade_rollup.py:1-266 · blob 8cb375698b7501f47bd3968aab754d277de1f4c2 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: storage · domain stage: hv_procurement · users: EPC_contractor, procurement_buyer · canonical: supporting_data
"""Derive the price record rollup: a browser-sized product over this repo's own Parquet.

WHY IT LIVES HERE
-----------------
The governing rule in UI_CHARTS_MIGRATION_SCOPE.md is "data before charts": the
UI repository must consume data products that already sit clean, and must not
own source data or create a second source of truth. Blocker 2 of that scope
asks for exactly this -- "create any missing derived browser/rollup products
needed by the charts".

So the rollup is defined here, beside the Parquet it aggregates, and consumers
read it. It is about six kilobytes against roughly a hundred megabytes of
settlement periods, which is the difference between a chart that opens on a
phone and one that does not.

Known consumers:
  - Ventusltd/gb-electricity-ui   the chart layer
  - Ventusltd/gridatlas           a panel beside the map of generation projects

WHAT IT IS NOT
--------------
No resampling, smoothing, modelling or forecasting. Every figure is an
arithmetic aggregate of settlement periods that are already in this repository.
A day needs at least 24 of its 48 periods to count as a day at all. The number
of included dates, calendar dates and coverage percentage behind every year are
carried together, so a partial year reads as partial rather than being quietly
presented like a full calendar year. A day meeting the 24-period floor is called
included, never complete: 24 out of 48 is an inclusion rule, not proof that the
day is complete.

PRICES ONLY, DELIBERATELY
-------------------------
Solar is not here. PVLive has not been decided into this repository -- item 4 of
the migration scope leaves it open between here, a separate solar repo, or a
deferred no-data state. Inventing a solar product here to make a panel look
fuller would be the exact failure the discipline manual exists to prevent, so
the rollup states that solar is absent and why.

    python derived/build_price_decade_rollup.py
"""

import calendar
import io
import json
import os
from collections import defaultdict

HERE = os.path.dirname(os.path.abspath(__file__))
REPO = os.path.dirname(HERE)

# Half of the 48 settlement periods. Below that a "daily mean" is a mean of
# whatever happened to be collected, which is a different quantity.
MIN_PERIODS_PER_DAY = 24

FIELD = "systemSellPriceGBPperMWh"


def price_input_glob(repo):
    """All supported physical parts; data_1 and later are not duplicate evidence."""
    return os.path.join(repo, "prices", "year=*", "month=*",
                        "data_*.parquet").replace("\\", "/")


def require_price_grain(connection, parquet_glob):
    rows, keys, nulls, nonfinite = connection.execute("""
        SELECT count(*), count(DISTINCT periodStartUTC),
               count(*) FILTER (WHERE periodStartUTC IS NULL),
               count(*) FILTER (WHERE systemSellPriceGBPperMWh IS NOT NULL
                 AND NOT isfinite(systemSellPriceGBPperMWh))
        FROM read_parquet(?, hive_partitioning=false)
    """, [parquet_glob]).fetchone()
    if rows == 0 or rows != keys or nulls or nonfinite:
        raise ValueError("Price grain failed: rows=%s keys=%s nulls=%s nonfinite=%s"
                         % (rows, keys, nulls, nonfinite))
    return {"rows": rows, "distinct_periods": keys,
            "null_keys": nulls, "nonfinite_sell_prices": nonfinite}


def mean(values):
    return sum(values) / len(values) if values else None


def percentage(numerator, denominator):
    return round(100.0 * numerator / denominator, 2) if denominator else None


def extreme(con, glob, direction):
    """Return the exact price period at one extreme, on an included date."""
    if direction not in ("ASC", "DESC"):
        raise ValueError("invalid price direction")
    row = con.execute("""
        WITH included_days AS (
          SELECT settlementDate
          FROM read_parquet(?)
          WHERE {field} IS NOT NULL
          GROUP BY 1
          HAVING count(*) >= {minimum}
        )
        SELECT p.{field}, p.settlementDate, p.settlementPeriod,
               strftime(p.periodStartUTC AT TIME ZONE 'UTC',
                        '%Y-%m-%dT%H:%M:%SZ')
        FROM read_parquet(?) p
        INNER JOIN included_days d USING (settlementDate)
        WHERE p.{field} IS NOT NULL
        ORDER BY p.{field} {direction}, p.periodStartUTC ASC
        LIMIT 1
    """.format(field=FIELD, minimum=MIN_PERIODS_PER_DAY, direction=direction),
        [glob, glob]).fetchone()
    if row is None:
        return None
    value, day, period, start_utc = row
    return {
        "value": round(float(value), 2),
        "date": str(day),
        "settlement_period": int(period),
        "period_start_utc": start_utc,
    }


def main():
    import duckdb

    glob = price_input_glob(REPO)
    con = duckdb.connect()
    input_grain = require_price_grain(con, glob)

    periods = con.execute(
        "SELECT count(*) FROM read_parquet(?) WHERE %s IS NOT NULL" % FIELD,
        [glob]).fetchone()[0]

    rows = con.execute("""
        SELECT settlementDate AS day,
               avg({field}) AS day_mean,
               min({field}) AS day_low,
               max({field}) AS day_high,
               count(*) AS periods
        FROM read_parquet(?)
        WHERE {field} IS NOT NULL
        GROUP BY 1
        HAVING count(*) >= {min}
        ORDER BY 1
    """.format(field=FIELD, min=MIN_PERIODS_PER_DAY), [glob]).fetchall()

    if not rows:
        raise SystemExit("no price rows matched %s" % glob)

    by_year = defaultdict(list)
    negative = defaultdict(int)
    included_periods = 0
    for day, day_mean, day_low, _day_high, day_periods in rows:
        year = str(day)[:4]
        by_year[year].append(float(day_mean))
        included_periods += int(day_periods)
        # Counted separately from the daily mean because a daily mean can hide
        # a negative within-day observation. No project effect is inferred.
        if day_low is not None and float(day_low) < 0:
            negative[year] += 1

    lowest = extreme(con, glob, "ASC")
    highest = extreme(con, glob, "DESC")

    by_year_out = []
    for year, values in sorted(by_year.items()):
        included_days = len(values)
        calendar_days = 366 if calendar.isleap(int(year)) else 365
        negative_days = negative.get(year, 0)
        by_year_out.append({
            "year": year,
            # Compatibility alias for consumers published against v1. New
            # consumers must use days_included and show its coverage.
            "days": included_days,
            "days_included": included_days,
            "calendar_days": calendar_days,
            "calendar_date_coverage_pct": percentage(included_days, calendar_days),
            "calendar_date_coverage": (
                "FULL_DATE_COVERAGE" if included_days == calendar_days
                else "PARTIAL_DATE_COVERAGE"),
            "mean_gbp_per_mwh": round(mean(values), 2),
            "min_daily_mean": round(min(values), 2),
            "max_daily_mean": round(max(values), 2),
            "days_with_a_negative_settlement_period": negative_days,
            "negative_period_day_share_pct": percentage(negative_days, included_days),
        })

    all_days = [v for values in by_year.values() for v in values]

    product = {
        "schema": "data-gb-electricity.price-decade-rollup.v2",
        "what_this_is": (
            "Yearly aggregates of the available GB system sell-price record, "
            "derived from the Parquet in this repository so that a browser can "
            "carry the history without carrying the settlement periods. Arithmetic aggregates "
            "only: no resampling, smoothing, modelling or forecasting."),
        "not_a_forecast": (
            "Historic system conditions. Not a projection, not a price "
            "expectation, and not a statement about the economics of any "
            "project or asset."),
        "grain": {
            "source_grain": "half-hourly settlement period",
            "product_grain": "calendar year, over daily means",
            "minimum_periods_per_day": MIN_PERIODS_PER_DAY,
            "note": ("a date with fewer than the minimum available periods is "
                     "excluded rather than averaged. A retained date is included, "
                     "not necessarily complete; calendar-date coverage is carried "
                     "for every year"),
        },
        "derived_from": {
            "repository": "Ventusltd/data-gb-electricity",
            "path": "prices/year=*/month=*/data_*.parquet",
            "source_key": "periodStartUTC",
            "input_grain": input_grain,
            "field": FIELD,
            "upstream": "Elexon",
            "settlement_periods": periods,
            "settlement_periods_on_included_dates": included_periods,
            "included_days": len(all_days),
            # Compatibility alias for already-published readers. Its name is
            # deprecated: a 24-period floor does not prove a complete day.
            "complete_days": len(all_days),
        },
        "solar": {
            "present": False,
            "why": ("PVLive has not been decided into this repository. Item 4 of "
                    "UI_CHARTS_MIGRATION_SCOPE.md leaves it open between here, a "
                    "separate solar data repository, and a deferred no-data "
                    "state. Inventing a solar series here to make a panel look "
                    "fuller is the failure the data discipline exists to "
                    "prevent."),
        },
        "price": {
            "unit": "GBP per MWh",
            "span": [by_year_out[0]["year"], by_year_out[-1]["year"]],
            "available_record_daily_mean": round(mean(all_days), 2),
            # Compatibility alias for already-published readers. The available
            # record spans 11 calendar labels and has gaps.
            "decade_mean": round(mean(all_days), 2),
            "lowest_settlement_period": lowest,
            "highest_settlement_period": highest,
            "days_with_a_negative_settlement_period": sum(negative.values()),
            "negative_period_day_share_pct": percentage(
                sum(negative.values()), len(all_days)),
            "by_year": by_year_out,
        },
    }

    out_dir = os.path.join(HERE)
    out = os.path.join(out_dir, "price-decade-rollup.json")
    with io.open(out, "w", encoding="utf-8", newline="\n") as stream:
        stream.write(json.dumps(product, ensure_ascii=False, indent=2) + "\n")
    con.close()

    print("wrote derived/price-decade-rollup.json (%.1f kB)"
          % (os.path.getsize(out) / 1024.0))
    print("  %s-%s, %d settlement periods, %d included days"
          % (product["price"]["span"][0], product["price"]["span"][1],
             periods, len(all_days)))
    print("  mean %.2f GBP/MWh, %d days with a negative period"
          % (product["price"]["available_record_daily_mean"],
             product["price"]["days_with_a_negative_settlement_period"]))
    print("  lowest %s" % lowest)
    print("  highest %s" % highest)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

Price Daily Browser

A Python command-line tool in the derived folder of Data GB Electricity that reads sources, using SHA-256 from Elexon Balancing Mechanism Reporting Service (BMRS).

energy-datadata-gb-electricity / derived/price_daily_browser.py · lines 1–199 of 199 · Entry point · pattern encode (shared by 21 files)

What it does
It loads sources. Defines 8 functions or classes, including encode, digest, six, source_manifest, daily_rows. Uses libraries __future__, argparse, datetime, decimal, hashlib. Side effects: reads or writes files; uses storage (browser storage, DuckDB or Parquet).
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: data source: Elexon BMRS; Parquet file daily.parquet; JSON file sources.json; JSON file index.json; DuckDB queries; command-line arguments. Out: JSON file sources.json; JSON file index.json.
Downstream impact
Used directly by 2 files: Test Price Daily Browser (data-gb-electricity); Refresh Price Decade Rollup Workflow (data-gb-electricity). Reached from 1 other entry point, including Monthly Update Workflow (data-gb-electricity).
What it achieves
It compiles products (`compile_products`) and is built from the encode step (`encode`) and the digest step (`digest`). Offline, typed daily system-sell products for bounded browser consumption. It accepts `--repo`, `--output` and `--verify`.
Why it matters
Run by Refresh Price Decade Rollup Workflow. Checked by Test Price Daily Browser.
Application
data-gb-electricity · derived · Python CLI
Uses
GB Calendar (sys.path import), Build Price Decade Rollup (import), __future__, argparse, datetime, decimal, hashlib, json, pathlib, sys
Used by
imported by Test Price Daily Browser (sys.path import), run by Refresh Price Decade Rollup Workflow (workflow run)
Produces
encode, digest, six, source_manifest, daily_rows, compile_products, run, main
Defines here
encode, digest, six, source_manifest, daily_rows, compile_products, run, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
data-gb-electricity@e888f35c1a65589b3eb7c78bcc542022bc707298 derived/price_daily_browser.py:1-199 · blob 7d561721370bcb76294a7e844828480c96ddded6 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, storage · domain stage: hv_procurement · users: EPC_contractor, procurement_buyer · canonical: supporting_data
#!/usr/bin/env python3
"""Offline, typed daily system-sell products for bounded browser consumption."""
from __future__ import annotations

import argparse
import datetime as dt
from decimal import Decimal, localcontext, ROUND_HALF_EVEN
import hashlib
import json
from pathlib import Path
import sys
import tempfile

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'pipelines'))
from gb_calendar import london_midnight_utc
from build_price_decade_rollup import price_input_glob, require_price_grain

SCHEMA = 'data-gb-electricity.system-sell-daily.v1'
UNIT = 'GBP/MWh'
BASIS = 'ELEXON_SYSTEM_SELL_PRICE'
QUANTUM = Decimal('0.000001')


def encode(value):
    return (json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(',', ':'), allow_nan=False) + '\n').encode('utf-8')


def digest(raw):
    return hashlib.sha256(raw).hexdigest()


def six(value):
    if value is None:
        return None
    return float(value.quantize(QUANTUM, rounding=ROUND_HALF_EVEN))


def source_manifest(repo):
    return [{'path': str(p.relative_to(repo)).replace('\\', '/'), 'sha256': digest(p.read_bytes()), 'bytes': p.stat().st_size}
            for p in sorted((repo / 'prices').glob('year=*/month=*/data_*.parquet'))]


def daily_rows(repo):
    import duckdb
    with duckdb.connect() as db:
        db.execute("SET TimeZone='UTC'")
        grain = require_price_grain(db, price_input_glob(str(repo)))
        db.read_parquet(price_input_glob(str(repo)), hive_partitioning=False).create_view('prices')
        types = {row[0]: row[1] for row in db.execute('DESCRIBE prices').fetchall()}
        expected = {'settlementDate': 'DATE', 'settlementPeriod': 'BIGINT',
                    'periodStartUTC': 'TIMESTAMP WITH TIME ZONE', 'systemSellPriceGBPperMWh': 'DOUBLE'}
        if any(types.get(k) != v for k, v in expected.items()):
            raise ValueError('Unexpected original source types')
        date_values = [row[0] for row in db.execute('SELECT DISTINCT settlementDate::VARCHAR FROM prices ORDER BY 1').fetchall()]
        if any(value is None for value in date_values):
            raise ValueError('Missing source-declared settlement date')
        dates = [dt.date.fromisoformat(value) for value in date_values]
        start, end = dates[0], dates[-1]
        if start.year < 1996 or (end-start).days > 366*100:
            raise ValueError('Calendar is outside the declared bounded GB rules')
        calendar = []
        day = start
        while day <= end:
            first, next_first = london_midnight_utc(day), london_midnight_utc(day + dt.timedelta(days=1))
            calendar.append((day.isoformat(), int(first.timestamp()), int((next_first-first).total_seconds()/1800)))
            day += dt.timedelta(days=1)
        db.execute('CREATE TABLE gb_days(day VARCHAR PRIMARY KEY,start_epoch BIGINT,expected INTEGER)')
        db.execute('''INSERT INTO gb_days SELECT r.day,r.start_epoch,r.expected
            FROM UNNEST(?::STRUCT(day VARCHAR,start_epoch BIGINT,expected INTEGER)[]) input(r)''',
            [[{'day':day,'start_epoch':epoch,'expected':count} for day,epoch,count in calendar]])
        bad = db.execute('''SELECT count(*) FROM prices p LEFT JOIN gb_days c ON p.settlementDate::VARCHAR=c.day
            WHERE c.day IS NULL OR p.settlementPeriod IS NULL OR p.settlementPeriod<1 OR p.settlementPeriod>c.expected''').fetchone()[0]
        duplicate_declared = db.execute('SELECT count(*) FROM (SELECT settlementDate,settlementPeriod FROM prices GROUP BY 1,2 HAVING count(*)>1)').fetchone()[0]
        if bad or duplicate_declared:
            raise ValueError('Invalid or duplicate source-declared GB date/period identity')
        groups = {row[0]: row[1:] for row in db.execute('''SELECT settlementDate::VARCHAR,
            count(*), count(systemSellPriceGBPperMWh), list(systemSellPriceGBPperMWh ORDER BY settlementPeriod),
            count(*) FILTER(WHERE epoch(periodStartUTC)<>c.start_epoch+(settlementPeriod-1)*1800)
            FROM prices p JOIN gb_days c ON p.settlementDate::VARCHAR=c.day GROUP BY 1 ORDER BY 1''').fetchall()}
        rows = []
        with localcontext() as context:
            context.prec = 90
            for day, _, expected_periods in calendar:
                observed, priced, values, mismatches = groups.get(day, (0, 0, [], 0))
                values = [Decimal.from_float(v) for v in values if v is not None]
                mean = sum(values, Decimal(0)) / len(values) if values else None
                status = 'NO_OBSERVATIONS' if not observed else 'COMPLETE_SOURCE_DAY' if priced == observed == expected_periods else 'PARTIAL_SOURCE_DAY'
                rows.append({'date': day, 'expected_periods': expected_periods, 'observed_periods': observed,
                             'priced_periods': priced, 'coverage_status': status,
                             'utc_alignment_mismatches': mismatches,
                             'price_coverage_pct': round(100*priced/expected_periods, 6),
                             'mean_available_gbp_per_mwh': six(mean),
                             'minimum_observed_gbp_per_mwh': six(min(values)) if values else None,
                             'maximum_observed_gbp_per_mwh': six(max(values)) if values else None})
        window = db.execute('SELECT min(periodStartUTC)::VARCHAR,max(periodStartUTC)::VARCHAR FROM prices').fetchone()
    return rows, grain, window


def compile_products(repo, folder):
    import duckdb
    before = source_manifest(repo)
    rows, grain, window = daily_rows(repo)
    years = sorted({int(r['date'][:4]) for r in rows})
    source = {'schema': SCHEMA + '.sources', 'source_grain': 'periodStartUTC', 'price_basis': BASIS,
              'source_field': 'systemSellPriceGBPperMWh', 'repository': 'Ventusltd/data-gb-electricity',
              'endpoint': 'https://data.elexon.co.uk/bmrs/api/v1/balancing/settlement/system-prices',
              'files': before, 'input_grain': grain, 'first_stored_period_utc': window[0], 'last_stored_period_utc': window[1],
              'utc_alignment_mismatches': sum(r['utc_alignment_mismatches'] for r in rows),
              'calendar_quality': 'Source-declared settlement dates/periods retained. Legacy stored UTC fields can disagree; counters report this without correcting frozen source history.'}
    sources = encode(source)
    (folder / 'sources.json').write_bytes(sources)
    parts = []
    for year in years:
        selected = [r for r in rows if r['date'].startswith(str(year) + '-')]
        payload = {'schema': SCHEMA, 'year': year, 'unit': UNIT, 'price_basis': BASIS,
                   'time_basis': 'Source-declared GB settlement date in Europe/London; stored UTC alignment reported separately',
                   'mean_basis': 'Available reported settlement-period prices; no interpolation',
                   'rounding': 'Six decimal places, half-even, from exact stored IEEE-754 source values',
                   'rows': selected}
        raw = encode(payload)
        name = str(year) + '.json'
        (folder / name).write_bytes(raw)
        parts.append({'year': year, 'path': name, 'sha256': digest(raw), 'bytes': len(raw),
                      'calendar_days': len(selected), 'observed_days': sum(r['observed_periods']>0 for r in selected),
                      'complete_days': sum(r['coverage_status']=='COMPLETE_SOURCE_DAY' for r in selected),
                      'partial_days': sum(r['coverage_status']=='PARTIAL_SOURCE_DAY' for r in selected),
                      'missing_days': sum(r['coverage_status']=='NO_OBSERVATIONS' for r in selected)})
    parquet = folder / 'daily.parquet'
    with duckdb.connect() as db:
        db.execute('CREATE TABLE daily(date VARCHAR PRIMARY KEY,expected_periods INTEGER,observed_periods INTEGER,priced_periods INTEGER,coverage_status VARCHAR,utc_alignment_mismatches INTEGER,price_coverage_pct DOUBLE,mean_available_gbp_per_mwh DOUBLE,minimum_observed_gbp_per_mwh DOUBLE,maximum_observed_gbp_per_mwh DOUBLE)')
        fields = list(rows[0])
        actual_rows = [tuple(r[k] for k in fields) for r in rows]
        db.execute('''INSERT INTO daily SELECT r.date,r.expected_periods,r.observed_periods,r.priced_periods,
            r.coverage_status,r.utc_alignment_mismatches,r.price_coverage_pct,r.mean_available_gbp_per_mwh,
            r.minimum_observed_gbp_per_mwh,r.maximum_observed_gbp_per_mwh FROM UNNEST(?::STRUCT(
            date VARCHAR,expected_periods INTEGER,observed_periods INTEGER,priced_periods INTEGER,
            coverage_status VARCHAR,utc_alignment_mismatches INTEGER,price_coverage_pct DOUBLE,
            mean_available_gbp_per_mwh DOUBLE,minimum_observed_gbp_per_mwh DOUBLE,maximum_observed_gbp_per_mwh DOUBLE)[]) input(r)''', [rows])
        db.sql('SELECT * FROM daily ORDER BY date').write_parquet(str(parquet), compression='zstd')
        reread = db.execute('SELECT * FROM read_parquet(?,hive_partitioning=false) ORDER BY date', [str(parquet)]).fetchall()
        if reread != actual_rows:
            raise ValueError('Daily full-row Parquet readback mismatch')
        if db.execute('SELECT DISTINCT compression FROM parquet_metadata(?)', [str(parquet)]).fetchall() != [('ZSTD',)]:
            raise ValueError('Unexpected Parquet compression')
    if source_manifest(repo) != before:
        raise ValueError('Source files changed during build')
    index = {'schema': SCHEMA + '.index', 'unit': UNIT, 'price_basis': BASIS,
             'time_basis': 'Source-declared GB settlement date in Europe/London; stored UTC alignment reported separately',
             'source_grain': 'Source-declared settlementDate plus settlementPeriod; original stored periodStartUTC remains the upstream key',
             'first_date': rows[0]['date'], 'last_date': rows[-1]['date'], 'rows': len(rows),
             'source_periods': grain['rows'], 'observed_periods': sum(r['observed_periods'] for r in rows),
             'priced_periods': sum(r['priced_periods'] for r in rows), 'parts': parts,
             'utc_alignment_mismatches': source['utc_alignment_mismatches'], 'calendar_quality': source['calendar_quality'],
             'sources': {'path':'sources.json','bytes':len(sources),'sha256':digest(sources)},
             'parquet': {'path':'daily.parquet','bytes':parquet.stat().st_size,'sha256':digest(parquet.read_bytes()),'rows':len(rows),'compression':'ZSTD','full_row_readback':'PASS'},
             'engine': 'duckdb-' + duckdb.__version__, 'producer_sha256': digest(Path(__file__).read_bytes()),
             'scope': 'Historical system-sell prices; no market-index merge, realtime quote or forecast'}
    if index['source_periods'] != index['observed_periods']:
        raise ValueError('Daily aggregation lost source rows')
    (folder / 'index.json').write_bytes(encode(index))
    return index


def run(repo, output, verify=False):
    output.parent.mkdir(parents=True, exist_ok=True)
    with tempfile.TemporaryDirectory(prefix='price-daily-stage-', dir=output.parent) as temporary:
        stage = Path(temporary)
        index = compile_products(repo, stage)
        produced = {p.name for p in stage.iterdir()}
        if verify:
            actual = {p.name for p in output.iterdir() if p.is_file()}
            if actual != produced or any((output/p).read_bytes() != (stage/p).read_bytes() for p in produced):
                raise ValueError('Daily committed products differ from actual source rebuild')
        else:
            if output.exists() and any(p.is_file() and p.name not in produced for p in output.iterdir()):
                raise ValueError('Unexpected existing output; no silent history deletion')
            output.mkdir(exist_ok=True)
            for name in sorted(produced - {'index.json'}) + ['index.json']:
                target = output / name
                if not target.exists() or target.read_bytes() != (stage/name).read_bytes():
                    (stage/name).replace(target)
    return index


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--repo', type=Path, default=ROOT)
    parser.add_argument('--output', type=Path)
    parser.add_argument('--verify', action='store_true')
    args = parser.parse_args(argv)
    index = run(args.repo, args.output or args.repo/'derived/price-daily-browser', args.verify)
    print(json.dumps({'status':'PASS','source_periods':index['source_periods'],'calendar_days':index['rows'],
                      'last_date':index['last_date'],'years':len(index['parts']),
                      'largest_year_bytes':max(p['bytes'] for p in index['parts']), 'parquet_bytes':index['parquet']['bytes']}))


if __name__ == '__main__':
    main()

Verify Price Decade Rollup

A Python command-line tool in the derived folder of Data GB Electricity. It is built from the close step (`close`).

energy-datadata-gb-electricity / derived/verify_price_decade_rollup.py · lines 1–126 of 126 · Entry point

What it does
It loads data. Defines close, main. Uses libraries calendar, json, os, duckdb. Side effects: reads or writes files; uses storage (browser storage, DuckDB or Parquet).
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 price-decade-rollup.json; DuckDB queries.
Downstream impact
Used directly by 1 file: Refresh Price Decade Rollup Workflow (data-gb-electricity).
What it achieves
Fail-closed semantic proof for the browser-sized GB price product.
Why it matters
Run by Refresh Price Decade Rollup Workflow.
Application
data-gb-electricity · derived · Python CLI
Uses
Build Price Decade Rollup (import), calendar, json, os, duckdb
Used by
run by Refresh Price Decade Rollup Workflow (workflow run)
Produces
close, main
Defines here
close, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
data-gb-electricity@e888f35c1a65589b3eb7c78bcc542022bc707298 derived/verify_price_decade_rollup.py:1-126 · blob 2adcaba00b471ae1363e62a44884263480304d7a · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, storage · domain stage: hv_procurement · users: EPC_contractor, procurement_buyer · canonical: supporting_data
"""Fail-closed semantic proof for the browser-sized GB price product."""

import calendar
import json
import os
from build_price_decade_rollup import price_input_glob, require_price_grain


HERE = os.path.dirname(os.path.abspath(__file__))
REPO = os.path.dirname(HERE)
PATH = os.path.join(HERE, "price-decade-rollup.json")


def close(left, right, tolerance=0.011):
    return abs(float(left) - float(right)) <= tolerance


def main():
    with open(PATH, encoding="utf-8") as stream:
        product = json.load(stream)

    assert product["schema"] == "data-gb-electricity.price-decade-rollup.v2"
    assert product["not_a_forecast"]
    assert product["solar"]["present"] is False
    assert "complete days" not in product["grain"]["note"].lower()

    rows = product["price"]["by_year"]
    assert len(rows) >= 10
    assert [row["year"] for row in rows] == sorted(row["year"] for row in rows)

    included = 0
    negative = 0
    partial = 0
    for row in rows:
        expected = 366 if calendar.isleap(int(row["year"])) else 365
        assert row["days"] == row["days_included"]
        assert row["calendar_days"] == expected
        assert close(row["calendar_date_coverage_pct"],
                     100.0 * row["days_included"] / expected)
        want_status = ("FULL_DATE_COVERAGE"
                       if row["days_included"] == expected
                       else "PARTIAL_DATE_COVERAGE")
        assert row["calendar_date_coverage"] == want_status
        partial += want_status == "PARTIAL_DATE_COVERAGE"
        assert close(row["negative_period_day_share_pct"],
                     100.0 * row["days_with_a_negative_settlement_period"]
                     / row["days_included"])
        included += row["days_included"]
        negative += row["days_with_a_negative_settlement_period"]

    assert partial > 0, "disease fixture: real product must expose partial years"
    assert included == product["derived_from"]["included_days"]
    assert included == product["derived_from"]["complete_days"]
    assert negative == product["price"]["days_with_a_negative_settlement_period"]
    assert close(product["price"]["negative_period_day_share_pct"],
                 100.0 * negative / included)
    assert (product["price"]["available_record_daily_mean"]
            == product["price"]["decade_mean"])

    for name in ("lowest_settlement_period", "highest_settlement_period"):
        price_extreme = product["price"][name]
        assert set(price_extreme) == {
            "value", "date", "settlement_period", "period_start_utc"}
        assert 1 <= price_extreme["settlement_period"] <= 50
        assert price_extreme["period_start_utc"]

    assert (product["derived_from"]["settlement_periods_on_included_dates"]
            <= product["derived_from"]["settlement_periods"])

    # Re-read the owner Parquet. Shape-only tests would bless a self-consistent
    # lie if both the product and its builder drifted together.
    import duckdb
    parquet_glob = price_input_glob(REPO)
    connection = duckdb.connect()
    actual_grain = require_price_grain(connection, parquet_glob)
    assert product["derived_from"]["path"] == "prices/year=*/month=*/data_*.parquet"
    assert product["derived_from"]["source_key"] == "periodStartUTC"
    assert product["derived_from"]["input_grain"] == actual_grain
    source_periods = connection.execute(
        "SELECT count(*) FROM read_parquet(?) "
        "WHERE systemSellPriceGBPperMWh IS NOT NULL", [parquet_glob]).fetchone()[0]
    assert source_periods == product["derived_from"]["settlement_periods"]
    source_days = connection.execute("""
        SELECT count(*), sum(periods)
        FROM (
          SELECT settlementDate, count(*) AS periods
          FROM read_parquet(?)
          WHERE systemSellPriceGBPperMWh IS NOT NULL
          GROUP BY 1
          HAVING count(*) >= ?
        )
    """, [parquet_glob, product["grain"]["minimum_periods_per_day"]]).fetchone()
    assert source_days[0] == product["derived_from"]["included_days"]
    assert source_days[1] == product["derived_from"]["settlement_periods_on_included_dates"]

    for name, direction in (("lowest_settlement_period", "ASC"),
                            ("highest_settlement_period", "DESC")):
        row = connection.execute("""
            WITH included_days AS (
              SELECT settlementDate
              FROM read_parquet(?)
              WHERE systemSellPriceGBPperMWh IS NOT NULL
              GROUP BY 1 HAVING count(*) >= ?
            )
            SELECT p.systemSellPriceGBPperMWh, p.settlementDate,
                   p.settlementPeriod,
                   strftime(p.periodStartUTC AT TIME ZONE 'UTC',
                            '%Y-%m-%dT%H:%M:%SZ')
            FROM read_parquet(?) p
            INNER JOIN included_days d USING (settlementDate)
            WHERE p.systemSellPriceGBPperMWh IS NOT NULL
            ORDER BY p.systemSellPriceGBPperMWh {direction}, p.periodStartUTC ASC
            LIMIT 1
        """.format(direction=direction), [parquet_glob,
                           product["grain"]["minimum_periods_per_day"],
                           parquet_glob]).fetchone()
        observed = product["price"][name]
        assert close(observed["value"], row[0])
        assert observed["date"] == str(row[1])
        assert observed["settlement_period"] == row[2]
        assert observed["period_start_utc"] == row[3]
    print("PASS: price rollup v2 states inclusion, coverage, shares and exact extremes")


if __name__ == "__main__":
    main()