---
type: "Source File"
title: "\"\"\""
description: "\"\"\" CopeCheck Cities — HMRC PAYE RTI payrolled employees parser. The RTI payroll series is the one ONS says \"currently provides the most reliable measure of employees\", and it is the other half of the payroll-vs-."
resource: "https://cities.copecheck.com"
tags: ["copecheck", "cities", "source-file", "py"]
timestamp: "2026-09-25T14:09:13Z"
site: "cities"
source_path: "copecheck-cities/rti_fetcher.py"
---

# """

Source path: `copecheck-cities/rti_fetcher.py`  
Index snapshot generated: `2026-11-24T13:27:52Z`  
File modified: `2026-09-25T14:09:13Z`

```py
"""
CopeCheck Cities — HMRC PAYE RTI payrolled employees parser.

The RTI payroll series is the one ONS says "currently provides the most
reliable measure of employees", and it is the other half of the payroll-vs-
survey divergence.  ONS publishes it only as an XLSX reference table, so this
module downloads that table and reads the regional (NUTS1) payrolled-employee
sheet, which gives a London-specific figure the time-series API does not.

Design rule: FAIL LOUDLY.  A spreadsheet layout can change between releases
without warning.  Every structural assumption is asserted, and any failure
raises RTIParseError rather than returning a partial or plausible-looking
number.  The caller keeps the previous known-good values instead of publishing
something wrong.

Writes data/uk_rti.json.  Run: venv/bin/python rti_fetcher.py
"""

import json
import logging
import os
import re
import ssl
import tempfile
from datetime import datetime, timezone
from urllib.request import Request, urlopen

log = logging.getLogger("cities.rti")

DATA_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data")
OUT_PATH = os.path.join(DATA_DIR, "uk_rti.json")

USER_AGENT = "CopeCheck-Cities/1.0 (+https://cities.copecheck.com)"
TIMEOUT = 120

DATASET_PAGE = (
    "https://www.ons.gov.uk/employmentandlabourmarket/peopleinwork/"
    "earningsandworkinghours/datasets/"
    "[redacted]"
)
BULLETIN_URL = (
    "https://www.ons.gov.uk/employmentandlabourmarket/peopleinwork/"
    "earningsandworkinghours/bulletins/"
    "[redacted]/latest"
)

# Sheet 7 holds payrolled employees by NUTS1 region.
SHEET_HINT = "Employees (NUTS1)"

# NUTS1 codes are far more stable than the region names printed beside them.
NUTS1_TO_REGION = {
    "UKC": "North East",
    "UKD": "North West",
    "UKE": "Yorkshire and the Humber",
    "UKF": "East Midlands",
    "UKG": "West Midlands",
    "UKH": "East of England",
    "UKI": "London",
    "UKJ": "South East",
    "UKK": "South West",
    "UKL": "Wales",
    "UKM": "Scotland",
    "UKN": "Northern Ireland",
}

# Sanity bands.  These are deliberately wide: they exist to catch a column
# shift or a units change (thousands vs persons), not to second-guess ONS.
SANE_UK = (25_000_000, 40_000_000)
SANE_LONDON = (3_000_000, 6_000_000)
MIN_ROWS = 100

MONTHS = ["January", "February", "March", "April", "May", "June",
          "July", "August", "September", "October", "November", "December"]


class RTIParseError(RuntimeError):
    """The published workbook did not match the structure we rely on."""


def _get_text(url):
    req = Request(url, headers={"User-Agent": USER_AGENT})
    with urlopen(req, timeout=TIMEOUT, context=ssl.create_default_context()) as r:
        return r.read().decode("utf-8", "replace")


def find_workbook_url():
    """Discover the current RTI workbook; its filename encodes the month."""
    html = _get_text(DATASET_PAGE)
    hits = re.findall(r'/file\?uri=(/[^"\']*?rtisa[^"\']*?\.xlsx)', html, re.I)
    if not hits:
        raise RTIParseError("no rtisa*.xlsx link found on the ONS dataset page")
    return "https://www.ons.gov.uk/file?uri=" + hits[0], hits[0].rsplit("/", 1)[-1]


def download(url):
    req = Request(url, headers={"User-Agent": USER_AGENT})
    fd, path = tempfile.mkstemp(suffix=".xlsx", prefix="rti-")
    os.close(fd)
    with urlopen(req, timeout=TIMEOUT, context=ssl.create_default_context()) as r:
        data = r.read()
    if len(data) < 500_000:
        os.unlink(path)
        raise RTIParseError(f"workbook suspiciously small ({len(data)} bytes)")
    with open(path, "wb") as f:
        f.write(data)
    return path


def _parse_month(label):
    parts = str(label).strip().split()
    if len(parts) != 2 or parts[0] not in MONTHS:
        return None
    try:
        return int(parts[1]) * 100 + MONTHS.index(parts[0]) + 1
    except ValueError:
        return None


def parse_workbook(path):
    try:
        import openpyxl
    except ImportError as exc:
        raise RTIParseError("openpyxl is not installed") from exc

    wb = openpyxl.load_workbook(path, read_only=True, data_only=True)

    names = [s for s in wb.sheetnames if SHEET_HINT.lower() in s.lower()]
    if not names:
        raise RTIParseError(
            f"no sheet matching {SHEET_HINT!r}; sheets were {wb.sheetnames[:12]}"
        )
    ws = wb[names[0]]

    rows = list(ws.iter_rows(min_row=1, max_row=40, max_col=20, values_only=True))

    # Locate the NUTS1 code header row and the 'Date' row beneath it.
    code_row = date_row = None
    for i, row in enumerate(rows):
        cells = [str(c).strip() if c is not None else "" for c in row]
        if "UKI" in cells and "UKC" in cells:
            code_row = (i, cells)
        if cells and cells[0].strip().lower() == "date":
            date_row = (i, cells)
            break
    if code_row is None:
        raise RTIParseError("could not find the NUTS1 code header row (UKC..UKI)")
    if date_row is None:
        raise RTIParseError("could not find the 'Date' header row")

    codes = code_row[1]
    col_for = {}
    for code, region in NUTS1_TO_REGION.items():
        if code not in codes:
            raise RTIParseError(f"NUTS1 code {code} ({region}) missing from header")
        col_for[region] = codes.index(code)

    # The UK total column is labelled in the Date row, not the code row.
    labels = date_row[1]
    uk_idx = next(
        (i for i, c in enumerate(labels) if c.strip().upper() in ("UK", "UNITED KINGDOM")),
        None,
    )
    if uk_idx is None:
        raise RTIParseError("could not find the UK total column")
    col_for["United Kingdom"] = uk_idx

    # Cross-check: the name printed under UKI really should say London.
    london_label = labels[col_for["London"]] if col_for["London"] < len(labels) else ""
    if "london" not in london_label.strip().lower():
        raise RTIParseError(
            f"column under UKI is labelled {london_label!r}, expected London — "
            "the sheet layout has changed"
        )

    first_data_row = date_row[0] + 2  # 1-based, row after the Date header
    series = {name: [] for name in col_for}
    max_col = max(col_for.values()) + 1
    for row in ws.iter_rows(min_row=first_data_row, max_col=max_col, values_only=True):
        if not row or row[0] in (None, ""):
            continue
        key = _parse_month(row[0])
        if key is None:
            continue
        for name, idx in col_for.items():
            val = row[idx] if idx < len(row) else None
            try:
                val = int(float(str(val).replace(",", "")))
            except (TypeError, ValueError):
                val = None
            if val is not None:
                series[name].append((key, str(row[0]).strip(), val))

    if len(series["United Kingdom"]) < MIN_ROWS:
        raise RTIParseError(
            f"only {len(series['United Kingdom'])} UK data rows, expected >= {MIN_ROWS}"
        )

    out = {}
    for name, rows_ in series.items():
        rows_.sort(key=lambda r: r[0])
        if len(rows_) < 13:
            raise RTIParseError(f"{name}: fewer than 13 months of data")
        latest, year_ago = rows_[-1], rows_[-13]
        out[name] = {
            "latest_period": latest[1],
            "latest": latest[2],
            "year_ago_period": year_ago[1],
            "year_ago": year_ago[2],
            "change_on_year": latest[2] - year_ago[2],
            "change_on_year_pct": round((latest[2] - year_ago[2]) / year_ago[2] * 100, 2),
            "change_on_month": latest[2] - rows_[-2][2],
        }

    uk_latest = out["United Kingdom"]["latest"]
    lon_latest = out["London"]["latest"]
    if not SANE_UK[0] <= uk_latest <= SANE_UK[1]:
        raise RTIParseError(f"UK payrolled employees {uk_latest:,} outside sane band")
    if not SANE_LONDON[0] <= lon_latest <= SANE_LONDON[1]:
        raise RTIParseError(f"London payrolled employees {lon_latest:,} outside sane band")

    regional_sum = sum(out[r]["latest"] for r in NUTS1_TO_REGION.values())
    drift = abs(regional_sum - uk_latest) / uk_latest
    if drift > 0.02:
        raise RTIParseError(
            f"regions sum to {regional_sum:,} but UK total is {uk_latest:,} "
            f"({drift:.1%} apart) — columns are probably misaligned"
        )

    return out


def build():
    logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
    url, filename = find_workbook_url()
    log.info("workbook: %s", filename)
    path = download(url)
    try:
        regions = parse_workbook(path)
    finally:
        try:
            os.unlink(path)
        except OSError:
            pass

    payload = {
        "generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
        "workbook": filename,
        "regions": regions,
        "source": {
            "name": "Earnings and employment from PAYE Real Time Information, seasonally adjusted (Table 7, payrolled employees by NUTS1 region)",
            "dataset_url": DATASET_PAGE,
            "file_url": url,
            "bulletin_url": BULLETIN_URL,
            "note": (
                "HMRC PAYE RTI administrative data, seasonally adjusted. Accredited "
                "official statistics. The most recent month is a provisional flash "
                "estimate and is routinely revised when more data arrive."
            ),
        },
    }

    os.makedirs(DATA_DIR, exist_ok=True)
    tmp = OUT_PATH + ".tmp"
    with open(tmp, "w") as f:
        json.dump(payload, f, indent=1)
    os.replace(tmp, OUT_PATH)
    lon = regions["London"]
    log.info(
        "wrote %s — London %s: %s (%+d on the year)",
        OUT_PATH, lon["latest_period"], f"{lon['latest']:,}", lon["change_on_year"],
    )
    return payload


if __name__ == "__main__":
    try:
        build()
    except RTIParseError as exc:
        logging.error("RTI PARSE FAILED — keeping previous data: %s", exc)
        raise SystemExit(2)
```
