---
type: "Source File"
title: "\"\"\""
description: "\"\"\" CopeCheck Cities — UK labour market fetcher. Pulls genuinely current UK labour market data from two official sources and [redacted secret-like line] 1. ONS time series API."
resource: "https://cities.copecheck.com"
tags: ["copecheck", "cities", "source-file", "py"]
timestamp: "2026-10-20T10:36:02Z"
site: "cities"
source_path: "copecheck-cities/labour_fetcher.py"
---

# """

Source path: `copecheck-cities/labour_fetcher.py`  
Index snapshot generated: `2026-11-24T13:27:52Z`  
File modified: `2026-10-20T10:36:02Z`

```py
"""
CopeCheck Cities — UK labour market fetcher.

Pulls genuinely current UK labour market data from two official sources and
[redacted secret-like line]

  1. ONS time series API (www.ons.gov.uk/.../timeseries/<cdid>/<dataset>/data)
     -> UK headline series (unemployment, employment, inactivity, vacancies,
        claimant count, youth unemployment, payrolled employees).

  2. NOMIS (www.nomisweb.co.uk/api) -> regional breakdowns:
        NM_17_5   Annual Population Survey (variables, percentages)
        NM_162_1  Claimant count by sex and age (UC + JSA stock)

Every figure written out carries its source dataset id, the exact ONS/NOMIS
period label, and the URL it was retrieved from.  Nothing is estimated or
interpolated: if a series cannot be fetched it is simply omitted.

Run:  venv/bin/python labour_fetcher.py
"""

import json
import logging
import os
import ssl
from datetime import datetime, timezone
from urllib.parse import urlencode
from urllib.request import Request, urlopen

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

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

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

# --- ONS national time series [redacted]
# cdid -> (dataset, field, title, unit)
ONS_SERIES = [
    ("MGSX", "lms", "unemployment_rate", "Unemployment rate (16+, SA)", "%", "3m"),
    ("LF24", "lms", "employment_rate", "Employment rate (16-64, SA)", "%", "3m"),
    ("LF2S", "lms", "inactivity_rate", "Economic inactivity rate (16-64, SA)", "%", "3m"),
    ("AP2Y", "unem", "vacancies", "Vacancies (thousands, SA)", "thousands", "3m"),
    ("BCJD", "unem", "claimant_count", "Claimant count (thousands)", "thousands", "1m"),
    ("MGWY", "lms", "youth_unemployment_rate", "Youth unemployment rate (16-24, SA)", "%", "3m"),
]

MONTHS = ["January", "February", "March", "April", "May", "June",
          "July", "August", "September", "October", "November", "December"]
MONTH_ABBR = {m[:3].upper(): i for i, m in enumerate(MONTHS)}


def _format_period(raw, period_type):
    """Turn an ONS label like '2026 JUN' into a human period.

    ONS labels a three-month rolling period by its *centre* month, so
    '2026 JUN' on a 3-month series means May to July 2026.  Monthly series
    are labelled by the month itself.
    """
    if not raw:
        return None
    parts = str(raw).strip().split()
    if len(parts) != 2:
        return str(raw)
    year, mon = parts
    idx = MONTH_ABBR.get(mon.upper())
    if idx is None:
        return str(raw)
    try:
        year = int(year)
    except ValueError:
        return str(raw)
    if period_type != "3m":
        return f"{MONTHS[idx]} {year}"
    start_idx, start_year = (idx - 1) % 12, year - (1 if idx - 1 < 0 else 0)
    end_idx, end_year = (idx + 1) % 12, year + (1 if idx + 1 > 11 else 0)
    if start_year == end_year:
        return f"{MONTHS[start_idx]} to {MONTHS[end_idx]} {end_year}"
    return f"{MONTHS[start_idx]} {start_year} to {MONTHS[end_idx]} {end_year}"

ONS_URL = "https://www.ons.gov.uk/employmentandlabourmarket/{path}/timeseries/{cdid}/{ds}/data"

# The ONS site organises series under different topic paths; try each in turn.
ONS_PATHS = [
    "peoplenotinwork/unemployment",
    "peopleinwork/employmentandemployeetypes",
    "peoplenotinwork/economicinactivity",
    "peoplenotinwork/outofworkbenefits",
    "peopleinwork/earningsandworkinghours",
]

# --- NOMIS regional [redacted]
NOMIS_REGIONS = {
    "North East": "2013265921",
    "North West": "2013265922",
    "Yorkshire and the Humber": "2013265923",
    "East Midlands": "2013265924",
    "West Midlands": "2013265925",
    "East of England": "2013265926",
    "London": "2013265927",
    "South East": "2013265928",
    "South West": "2013265929",
    "Wales": "2013265930",
    "Scotland": "2013265931",
    "Northern Ireland": "2013265932",
}
UK_GEOG = "2092957697"

# NOMIS geography codes -> the region names used in data/uk.json.  Matching on
# code rather than on NOMIS's own description avoids silent drops where the two
# spell a region differently ("East" vs "East of England").
CODE_TO_REGION = {code: name for name, code in NOMIS_REGIONS.items()}
CODE_TO_REGION[UK_GEOG] = "United Kingdom"


def _region_name(obs_row):
    return CODE_TO_REGION.get(
        str(obs_row["geography"]["value"]), obs_row["geography"]["description"]
    )

APS_VARIABLES = {
    "45": "employment_rate_16_64",
    "83": "unemployment_rate_16_plus",
    "111": "inactivity_rate_16_64",
}

NOMIS_APS = "https://www.nomisweb.co.uk/api/v01/dataset/NM_17_5.data.json"
NOMIS_CLAIMANT = "https://www.nomisweb.co.uk/api/v01/dataset/NM_162_1.data.json"


def _get_json(url):
    req = Request(url, headers={"User-Agent": USER_AGENT, "Accept": "application/json"})
    ctx = ssl.create_default_context()
    with urlopen(req, timeout=TIMEOUT, context=ctx) as resp:
        return json.loads(resp.read().decode("utf-8", "replace"))


def _num(v):
    try:
        s = str(v).strip().replace(",", "")
        if s in ("", "..", "-", "None"):
            return None
        return float(s)
    except (TypeError, ValueError):
        return None


# [redacted] ONS national
def fetch_ons_national():
    out = {}
    for cdid, ds, field, title, unit, period_type in ONS_SERIES:
        got = None
        for path in ONS_PATHS:
            url = ONS_URL.format(path=path, cdid=cdid.lower(), ds=ds)
            try:
                payload = _get_json(url)
            except Exception:
                continue
            points = payload.get("months") or payload.get("quarters") or payload.get("years") or []
            if not points:
                continue
            last = points[-1]
            value = _num(last.get("value"))
            if value is None:
                continue
            prev12 = points[-13] if len(points) >= 13 else None
            got = {
                "cdid": cdid,
                "title": title,
                "unit": unit,
                "value": round(value, 1) if unit == "%" else value,
                "period": _format_period(last.get("date") or last.get("label"), period_type),
                "period_raw": last.get("date") or last.get("label"),
                "value_year_ago": _num(prev12.get("value")) if prev12 else None,
                "period_year_ago": _format_period(prev12.get("date"), period_type) if prev12 else None,
                "source_url": url,
                "release": payload.get("description", {}).get("releaseDate"),
            }
            break
        if got:
            out[field] = got
            log.info("ONS %s = %s (%s)", cdid, got["value"], got["period"])
        else:
            log.warning("ONS series %s could not be fetched — omitted", cdid)
    return out


# [redacted] NOMIS APS
def fetch_aps():
    geogs = ",".join([UK_GEOG] + list(NOMIS_REGIONS.values()))
    q = urlencode({
        "geography": geogs,
        "variable": ",".join(APS_VARIABLES),
        "measures": "20599",
        "time": "latest",
    })
    url = f"{NOMIS_APS}?{q}"
    payload = _get_json(url)
    obs = payload.get("obs")
    if not obs:
        log.warning("NOMIS APS returned no data — omitted")
        return {}, url, None
    result = {}
    period = None
    for o in obs:
        geo = _region_name(o)
        var = str(o["variable"]["value"])
        field = APS_VARIABLES.get(var)
        val = _num(o["obs_value"].get("value"))
        if not field or val is None:
            continue
        period = o["time"]["description"]
        result.setdefault(geo, {})[field] = round(val, 1)
    return result, url, period


# [redacted] NOMIS claimant
def fetch_claimant():
    geogs = ",".join([UK_GEOG] + list(NOMIS_REGIONS.values()))
    q = urlencode({
        "geography": geogs,
        "gender": "0",
        "age": "0,2",
        "measure": "1,3",
        "measures": "20100",
        "time": "latest,prevyear",
    })
    url = f"{NOMIS_CLAIMANT}?{q}"
    payload = _get_json(url)
    obs = payload.get("obs")
    if not obs:
        log.warning("NOMIS claimant count returned no data — omitted")
        return {}, url

    # geo -> age -> measure -> [(sortkey, period, value)]
    buckets = {}
    for o in obs:
        geo = _region_name(o)
        age = "youth" if str(o["age"]["value"]) == "2" else "all"
        measure = "count" if str(o["measure"]["value"]) == "1" else "rate"
        val = _num(o["obs_value"].get("value"))
        if val is None:
            continue
        period = o["time"]["description"]
        sort = o["time"].get("sortorder") or o["time"].get("value")
        buckets.setdefault(geo, {}).setdefault(age, {}).setdefault(measure, []).append(
            (str(sort), period, val)
        )

    result = {}
    for geo, ages in buckets.items():
        entry = {}
        for age, measures in ages.items():
            for measure, rows in measures.items():
                rows.sort(key=lambda r: r[0])
                latest = rows[-1]
                earliest = rows[0]
                prefix = "" if age == "all" else "youth_"
                entry[f"{prefix}{measure}"] = latest[2]
                entry[f"{prefix}{measure}_year_ago"] = earliest[2] if len(rows) > 1 else None
                entry["latest_period"] = latest[1]
                entry["year_ago_period"] = earliest[1] if len(rows) > 1 else None
                if age == "all" and measure == "count":
                    entry["series"] = [
                        {"period": r[1], "value": r[2]} for r in rows
                    ]
        result[geo] = entry
    return result, url


# [redacted] ONS regional LFS (headline SA)
REGIONAL_BULLETIN = (
    "https://www.ons.gov.uk/employmentandlabourmarket/peopleinwork/"
    "employmentandemployeetypes/bulletins/regionallabourmarket/latest"
)

# The bulletin labels regions slightly differently again; normalise to uk.json.
LFS_ROW_TO_REGION = {
    "north east": "North East",
    "north west": "North West",
    "yorkshire and the humber": "Yorkshire and the Humber",
    "east midlands": "East Midlands",
    "west midlands": "West Midlands",
    "east": "East of England",
    "london": "London",
    "south east": "South East",
    "south west": "South West",
    "wales": "Wales",
    "scotland": "Scotland",
    "northern ireland": "Northern Ireland",
    "uk": "United Kingdom",
}


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


def fetch_regional_lfs():
    """Seasonally adjusted LFS headline rates by region, with annual change.

    The ONS publishes these as Table 2 of the regional labour market bulletin.
    The table's URI carries a content hash that changes every month, so it is
    discovered from the 'latest' bulletin page rather than hard-coded.
    """
    import csv
    import io
    import re

    try:
        html = _get_text(REGIONAL_BULLETIN)
    except Exception as exc:
        log.warning("regional LFS bulletin unreachable (%s) — omitted", type(exc).__name__)
        return {}, None, None, None

    uris = re.findall(r"format=csv&(?:amp;)?uri=([^\"'&\s]+\.json)", html)
    if len(uris) < 2:
        log.warning("could not locate regional LFS table on the bulletin — omitted")
        return {}, None, None, None
    # Table 1 = quarterly change, Table 2 = annual change.  We want annual.
    table_url = "https://www.ons.gov.uk/download/table?format=csv&uri=" + uris[1]

    try:
        raw = _get_text(table_url)
    except Exception as exc:
        log.warning("regional LFS table download failed (%s) — omitted", type(exc).__name__)
        return {}, None, table_url, None

    title = raw.splitlines()[0].strip().strip('"')
    m = re.search(r"seasonally adjusted,\s*([A-Za-z]+ to [A-Za-z]+ \d{4})", title)
    period = m.group(1) if m else None
    m2 = re.search(r"Change\s+on\s+(May|[A-Za-z]+)\s", raw)

    out = {}
    for row in csv.reader(io.StringIO(raw)):
        if not row or not row[0].strip():
            continue
        label = " ".join(row[0].split()).strip().lower()
        region = LFS_ROW_TO_REGION.get(label)
        if not region:
            continue
        vals = [_num(c) for c in row[1:7]]
        if len(vals) < 6 or vals[0] is None:
            continue
        out[region] = {
            "employment_rate_16_64": vals[0],
            "employment_rate_change_on_year": vals[1],
            "unemployment_rate_16_plus": vals[2],
            "unemployment_rate_change_on_year": vals[3],
            "inactivity_rate_16_64": vals[4],
            "inactivity_rate_change_on_year": vals[5],
            "period": period,
        }
    log.info("regional LFS: %d rows for %s", len(out), period)
    return out, period, table_url, REGIONAL_BULLETIN


def build():
    logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
    national = fetch_ons_national()
    aps, aps_url, aps_period = fetch_aps()
    claimant, claimant_url = fetch_claimant()
    lfs, lfs_period, lfs_table_url, lfs_bulletin = fetch_regional_lfs()

    regions = {}
    for name in NOMIS_REGIONS:
        entry = {}
        if name in lfs:
            entry["lfs"] = lfs[name]
        if name in aps:
            entry["aps"] = dict(aps[name], period=aps_period)
        if name in claimant:
            entry["claimant"] = claimant[name]
        if entry:
            regions[name] = entry

    # Rank regions by unemployment rate so a page can say where it sits.
    ranked = sorted(
        ((n, r["lfs"]["unemployment_rate_16_plus"]) for n, r in regions.items()
         if r.get("lfs", {}).get("unemployment_rate_16_plus") is not None),
        key=lambda x: -x[1],
    )
    for i, (name, _) in enumerate(ranked):
        regions[name]["lfs"]["unemployment_rank"] = i + 1
        regions[name]["lfs"]["unemployment_rank_of"] = len(ranked)

    payload = {
        "generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
        "national": national,
        "uk": {
            "lfs": lfs.get("United Kingdom"),
            "aps": dict(aps.get("United Kingdom", {}), period=aps_period) if aps.get("United Kingdom") else None,
            "claimant": claimant.get("United Kingdom"),
        },
        "divergence": {
            "note": (
                "Payroll records and the household survey are telling different "
                "stories. ONS states that RTI 'currently provides the most reliable "
                "measure of employees'."
            ),
            # ONS's own like-for-like comparison: RTI restated to the LFS period.
            "rti_change_on_year_june_to_august": -92000,
            "rti_change_on_quarter_june_to_august": -37000,
            # Confirmed single month, and the provisional flash one month ahead.
            "rti_change_on_year_august": -111000,
            "rti_change_on_month_august": 1000,
            "rti_flash_change_on_year_september": -66000,
            "rti_flash_change_on_month_september": 13000,
            "rti_level_september": 30280860,
            # The LFS points the other way over the year.
            "lfs_employees_change_on_year": 314000,
            "lfs_employees_level": 29948000,
            "period": "June to August 2026 (LFS and like-for-like RTI); September 2026 (RTI flash)",
            # Last month's August flash said -145,000; the confirmed figure is
            # -111,000, so the flash overstated the annual fall by ~34,000. Treat
            # the September flash (-66,000) with the same caution.
            "flash_revision_note": (
                "The August 2026 flash estimate reported a fall of 145,000 on the year; "
                "the confirmed figure is 111,000. Flash estimates are provisional and are "
                "routinely revised when more data arrive, so the September flash of -66,000 "
                "should be read as the least settled number here."
            ),
            # ONS's explanation: part of the LFS rise is survey improvement, not
            # labour market change. This is why the gap must not be read as a
            # straight contradiction.
            "ons_interpretation": (
                "ONS attributes part of the LFS employee increase to improvements in the "
                "survey since January 2024, which have obtained more responses from employed "
                "people. Levels have therefore moved closer to RTI, but ONS cautions that LFS "
                "measures of change 'may be less aligned with RTI because they capture both "
                "real labour market shifts and changes arising from the survey improvements'. "
                "The divergence is concentrated in the 25 to 34 year old age group, which ONS "
                "is still investigating."
            ),
            "ons_reliability_position": (
                "ONS's view remains that RTI 'currently provides the most reliable measure of "
                "employees'. As of the October 2026 release this statement appears in the LFS "
                "quality update rather than in the labour market overview bulletin itself."
            ),
            "source": "ONS Labour market overview, UK: October 2026, released 20 October 2026",
            "source_url": (
                "https://www.ons.gov.uk/employmentandlabourmarket/peopleinwork/"
                "employmentandemployeetypes/bulletins/uklabourmarket/october2026"
            ),
            "quality_update_url": (
                "https://www.ons.gov.uk/employmentandlabourmarket/peopleinwork/"
                "employmentandemployeetypes/articles/labourforcesurveyqualityupdate/october2026"
            ),
            "rti_table_url": (
                "https://www.ons.gov.uk/employmentandlabourmarket/peopleinwork/"
                "earningsandworkinghours/datasets/"
                "[redacted]"
            ),
            "manual": True,
            "next_release": "17 November 2026",
            "linkage_research": {
                "title": "Investigating non-response to the Labour Force Survey using administrative data",
                "date": "28 September 2026",
                "url": "https://www.ons.gov.uk/releases/[redacted]",
                "published": True,
                "findings": (
                    "Linked HMRC PAYE data showed a stronger recovery in employment after the "
                    "pandemic and a smaller, less prolonged rise in economic inactivity than the "
                    "published LFS estimates alone suggested. It also suggested the LFS recovery "
                    "during 2024 and 2025 may have reduced non-response bias, since using the "
                    "linked payroll data made only a small difference to the level of employment "
                    "and inactivity estimates in 2025. ONS describes the work as exploratory and "
                    "is continuing the analysis."
                ),
            },
        },
        "regions": regions,
        "sources": [
            {
                "id": "ONS-LMS",
                "name": "ONS Labour market overview, UK (time series API)",
                "url": "https://www.ons.gov.uk/employmentandlabourmarket/peopleinwork/employmentandemployeetypes/bulletins/uklabourmarket/latest",
                "note": "Seasonally adjusted UK headline series.",
            },
            {
                "id": "ONS-RLM",
                "name": "ONS Labour market in the regions of the UK (Table 2, annual changes)",
                "url": lfs_bulletin or REGIONAL_BULLETIN,
                "table_url": lfs_table_url,
                "note": (
                    "Seasonally adjusted LFS headline rates by region for "
                    f"{lfs_period or 'the latest period'}. LFS and APS outputs moved "
                    "from 'official statistics in development' to 'official statistics' "
                    "on 11 August 2026; ONS is not seeking reaccreditation."
                ),
            },
            {
                "id": "NOMIS-NM_17_5",
                "name": "ONS Annual Population Survey, via NOMIS (variables, percentages)",
                "url": aps_url,
                "note": (
                    "Rolling 12-month survey estimates by region. The APS and LFS were "
                    "reclassified from 'official statistics in development' to 'official "
                    "statistics' on 11 August 2026 and ONS is not seeking reaccreditation; "
                    "survey-based detail should be read with that in mind."
                ),
            },
            {
                "id": "NOMIS-NM_162_1",
                "name": "Claimant count by sex and age (Universal Credit + JSA), ONS/DWP via NOMIS",
                "url": claimant_url,
                "note": "Not seasonally adjusted. Administrative count, not a survey estimate.",
            },
        ],
    }

    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)
    log.info("wrote %s (%d regions, %d national series)", OUT_PATH, len(regions), len(national))
    return payload


if __name__ == "__main__":
    build()
```
