---
type: "Source File"
title: "\"\"\""
description: "\"\"\" ONS Data Fetcher for UK CopeCheck. Pulls real employment, pay, inflation, GDP, productivity, trade, and social data from the ONS website JSON API. No authentication required. Expanded to cover 16+ series with 3-5."
resource: "https://uk.copecheck.com"
tags: ["copecheck", "uk", "source-file", "py"]
timestamp: "2026-10-20T10:34:49Z"
site: "uk"
source_path: "copecheck-uk/ons_data.py"
---

# """

Source path: `copecheck-uk/ons_data.py`  
Index snapshot generated: `2026-11-24T13:42:54Z`  
File modified: `2026-10-20T10:34:49Z`

```py
"""
ONS Data Fetcher for UK CopeCheck.
Pulls real employment, pay, inflation, GDP, productivity, trade, and social data
from the ONS website JSON API. No authentication required.

Expanded to cover 16+ series with 3-5 years of historical data for trend charts.
"""
import json
import logging
import requests
from datetime import datetime

log = logging.getLogger("ons_data")

# ONS time series endpoints
ONS_SERIES = [
    {"id": "LF24", "url": "https://www.ons.gov.uk/employmentandlabourmarket/peopleinwork/employmentandemployeetypes/timeseries/lf24/lms/data", "field": "employment_rate", "title": "Employment rate (16-64, %)", "transform": "float", "group": "labour"},
    {"id": "MGSX", "url": "https://www.ons.gov.uk/employmentandlabourmarket/peoplenotinwork/unemployment/timeseries/mgsx/lms/data", "field": "unemployment_rate", "title": "Unemployment rate (%)", "transform": "float", "group": "labour"},
    {"id": "LF2S", "url": "https://www.ons.gov.uk/employmentandlabourmarket/peoplenotinwork/economicinactivity/timeseries/lf2s/lms/data", "field": "economic_inactivity_rate", "title": "Economic inactivity rate (16-64, %)", "transform": "float", "group": "labour"},
    {"id": "LF2M", "url": "https://www.ons.gov.uk/employmentandlabourmarket/peoplenotinwork/economicinactivity/timeseries/lf2m/lms/data", "field": "economic_inactivity_level", "title": "Economically inactive (thousands)", "transform": "float_thousands", "group": "labour"},
    {"id": "AP2Y", "url": "https://www.ons.gov.uk/employmentandlabourmarket/peopleinwork/employmentandemployeetypes/timeseries/ap2y/unem/data", "field": "vacancies", "title": "Vacancies (thousands)", "transform": "int_thousands", "group": "labour"},
    {"id": "MGWY", "url": "https://www.ons.gov.uk/employmentandlabourmarket/peoplenotinwork/unemployment/timeseries/mgwy/lms/data", "field": "youth_unemployment", "title": "Youth unemployment rate (16-24, %)", "transform": "float", "group": "labour"},
    {"id": "BCJD", "url": "https://www.ons.gov.uk/employmentandlabourmarket/peoplenotinwork/outofworkbenefits/timeseries/bcjd/unem/data", "field": "claimant_count", "title": "Claimant count (thousands)", "transform": "float_thousands", "group": "labour"},
    {"id": "YBVH", "url": "https://www.ons.gov.uk/employmentandlabourmarket/peoplenotinwork/unemployment/timeseries/ybvh/lms/data", "field": "long_term_unemployment", "title": "Unemployed 12+ months (thousands)", "transform": "float_thousands", "group": "labour"},
    {"id": "KAC3", "url": "https://www.ons.gov.uk/employmentandlabourmarket/peopleinwork/earningsandworkinghours/timeseries/kac3/lms/data", "field": "total_pay_growth", "title": "Total pay growth inc. bonuses (%)", "transform": "float", "group": "pay"},
    {"id": "KAI9", "url": "https://www.ons.gov.uk/employmentandlabourmarket/peopleinwork/earningsandworkinghours/timeseries/kai9/lms/data", "field": "regular_pay_growth", "title": "Regular pay growth excl. bonuses (%)", "transform": "float", "group": "pay"},
    {"id": "L55O", "url": "https://www.ons.gov.uk/economy/inflationandpriceindices/timeseries/l55o/mm23/data", "field": "cpih", "title": "CPIH inflation (%)", "transform": "float", "group": "inflation"},
    {"id": "D7G7", "url": "https://www.ons.gov.uk/economy/inflationandpriceindices/timeseries/d7g7/mm23/data", "field": "cpi", "title": "CPI inflation (%)", "transform": "float", "group": "inflation"},
    {"id": "IHYQ", "url": "https://www.ons.gov.uk/economy/grossdomesticproductgdp/timeseries/ihyq/pn2/data", "field": "gdp_growth_qoq", "title": "GDP quarterly growth (%)", "transform": "float", "group": "economy", "frequency": "quarterly"},
    {"id": "A4YM", "url": "https://www.ons.gov.uk/employmentandlabourmarket/peopleinwork/labourproductivity/timeseries/a4ym/prdy/data", "field": "productivity_output_per_hour", "title": "Output per hour (index)", "transform": "float", "group": "economy", "frequency": "quarterly"},
    {"id": "IKBJ", "url": "https://www.ons.gov.uk/economy/nationalaccounts/balanceofpayments/timeseries/ikbj/mret/data", "field": "trade_balance_goods", "title": "Trade balance in goods (£m)", "transform": "float", "group": "trade"},
    {"id": "IKBL", "url": "https://www.ons.gov.uk/economy/grossdomesticproductgdp/timeseries/ikbl/mret/data", "field": "trade_balance_services", "title": "Trade balance in services (£m)", "transform": "float", "group": "trade"},
    # DISABLED:     {"id": "CIUU", "url": "https://www.ons.gov.uk/peoplepopulationandcommunity/populationandmigration/internationalmigration/timeseries/ciuu/ltim/data", "field": "net_migration", "title": "Net migration (thousands, YE)", "transform": "float", "group": "migration", "frequency": "quarterly"},
]

MONTH_MAP = {
    "JAN": "January", "FEB": "February", "MAR": "March",
    "APR": "April", "MAY": "May", "JUN": "June",
    "JUL": "July", "AUG": "August", "SEP": "September",
    "OCT": "October", "NOV": "November", "DEC": "December",
}

QUARTER_MAP = {"Q1": "March", "Q2": "June", "Q3": "September", "Q4": "December"}


def _parse_value(raw_value, transform):
    try:
        v = str(raw_value).strip().replace(",", "")
        if not v or v == ".." or v == "":
            return None
        if transform == "float":
            return round(float(v), 1)
        elif transform == "int_thousands":
            return int(float(v) * 1000)
        elif transform == "float_thousands":
            return int(float(v) * 1000)
        else:
            return float(v)
    except (ValueError, TypeError):
        return None


def _parse_month_key(date_str):
    parts = date_str.strip().split()
    if len(parts) != 2:
        return None, 0
    year, mon = parts
    month_name = MONTH_MAP.get(mon.upper())
    if not month_name:
        return None, 0
    try:
        month_idx = list(MONTH_MAP.keys()).index(mon.upper()) + 1
        sort_key = int(year) * 100 + month_idx
    except (ValueError, IndexError):
        sort_key = 0
    return f"{month_name} {year}", sort_key


def _parse_quarter_key(date_str):
    parts = date_str.strip().split()
    if len(parts) != 2:
        return None, 0
    year, qtr = parts
    qtr_upper = qtr.upper()
    month_name = QUARTER_MAP.get(qtr_upper)
    if not month_name:
        return None, 0
    try:
        month_idx = list(MONTH_MAP.values()).index(month_name) + 1
        sort_key = int(year) * 100 + month_idx
    except (ValueError, IndexError):
        sort_key = 0
    return f"{month_name} {year}", sort_key


def fetch_series(series_config, num_points=60):
    url = series_config["url"]
    field = series_config["field"]
    transform = series_config["transform"]
    frequency = series_config.get("frequency", "monthly")

    try:
        resp = requests.get(url, timeout=30)
        resp.raise_for_status()
        data = resp.json()
    except Exception as e:
        log.warning("Failed to fetch ONS series %s: %s", series_config["id"], e)
        return []

    if frequency == "quarterly":
        periods = data.get("quarters", [])
    else:
        periods = data.get("months", [])

    if not periods:
        log.warning("No %s data for series %s", frequency, series_config["id"])
        return []

    results = []
    for p in periods[-num_points:]:
        date_str = p.get("date", "")
        value = _parse_value(p.get("value"), transform)
        if frequency == "quarterly":
            month_label, sort_key = _parse_quarter_key(date_str)
        else:
            month_label, sort_key = _parse_month_key(date_str)
        if month_label and value is not None:
            results.append((month_label, sort_key, field, value))

    return results


def fetch_all_latest(num_months=60):
    all_points = []
    for series in ONS_SERIES:
        try:
            points = fetch_series(series, num_points=num_months)
            all_points.extend(points)
            log.info("Fetched %d points for %s (%s)", len(points), series["id"], series["field"])
        except Exception as e:
            log.warning("Error fetching %s: %s", series["id"], e)

    if not all_points:
        log.error("No ONS data fetched at all")
        return []

    months_data = {}
    for month_label, sort_key, field, value in all_points:
        if month_label not in months_data:
            months_data[month_label] = {"month": month_label, "_sort": sort_key}
        months_data[month_label][field] = value

    for month_label, d in months_data.items():
        total = d.get("total_pay_growth")
        cpih = d.get("cpih")
        if total is not None and cpih is not None:
            d["real_pay_growth"] = round(total - cpih, 1)
        if d.get("regular_pay_growth") is not None:
            d["nominal_pay_growth"] = d["regular_pay_growth"]
        goods = d.get("trade_balance_goods")
        services = d.get("trade_balance_services")
        if goods is not None and services is not None:
            d["trade_balance_total"] = round(goods + services, 0)

    sorted_months = sorted(months_data.values(), key=lambda x: x.get("_sort", 0))

    for i, d in enumerate(sorted_months):
        if i > 0 and d.get("vacancies") and sorted_months[i - 1].get("vacancies"):
            d["vacancies_change"] = d["vacancies"] - sorted_months[i - 1]["vacancies"]

    for d in sorted_months:
        d.pop("_sort", None)

    return sorted_months


def get_latest_month():
    all_data = fetch_all_latest(num_months=6)
    if all_data:
        return all_data[-1]
    return None


def get_series_metadata():
    return [{"id": s["id"], "field": s["field"], "title": s["title"], "group": s.get("group", "other"), "frequency": s.get("frequency", "monthly")} for s in ONS_SERIES]


if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)
    data = fetch_all_latest(num_months=60)
    print(f"Fetched {len(data)} months of data")
    if data:
        latest = data[-1]
        print(f"\nLatest: {latest['month']}")
        for k, v in sorted(latest.items()):
            if k != "month":
                print(f"  {k}: {v}")
```
