---
type: "Source File"
title: "!/usr/bin/env python3"
description: "#!/usr/bin/env python3 \"\"\" CopeCheck Data Fetcher — pulls economic data from public APIs. Run daily via systemd timer. No API keys needed (except optional FRED). Sources: World Bank, Eurostat, BLS \"\"\" import json."
resource: "https://data.copecheck.com"
tags: ["copecheck", "data", "source-file", "py"]
timestamp: "2026-08-24T09:46:04Z"
site: "data"
source_path: "copecheck-data/data_fetcher.py"
---

# !/usr/bin/env python3

Source path: `copecheck-data/data_fetcher.py`  
Index snapshot generated: `2026-11-24T13:27:52Z`  
File modified: `2026-08-24T09:46:04Z`

```py
#!/usr/bin/env python3
"""
CopeCheck Data Fetcher — pulls economic data from public APIs.
Run daily via systemd timer. No API keys needed (except optional FRED).

Sources: World Bank, Eurostat, BLS
"""
import json, logging, os, re, sys, time, traceback
from datetime import datetime, timezone
from pathlib import Path

import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

# Add parent to path for db import
sys.path.insert(0, str(Path(__file__).parent))
import db

LOG_DIR = Path(__file__).parent / "logs"
LOG_DIR.mkdir(parents=True, exist_ok=True)
logging.basicConfig(
    filename=str(LOG_DIR / "fetcher.log"),
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(message)s",
)
log = logging.getLogger(__name__)

SESSION = requests.Session()
SESSION.headers.update({"User-Agent": "CopeCheck-Data/1.0 (research)"})
SESSION.mount("https://", HTTPAdapter(max_retries=Retry(
    total=2,
    connect=2,
    read=2,
    status=2,
    backoff_factor=1.0,
    status_forcelist=(429, 500, 502, 503, 504),
    allowed_methods=frozenset(("GET", "POST")),
    respect_retry_after_header=True,
)))

# ── Country mappings ──
COUNTRIES = {
    "US": {"wb": "USA", "eurostat": None, "bls": True, "name": "United States"},
    "UK": {"wb": "GBR", "eurostat": "UK", "bls": False, "name": "United Kingdom"},
    "DE": {"wb": "DEU", "eurostat": "DE", "bls": False, "name": "Germany"},
    "FR": {"wb": "FRA", "eurostat": "FR", "bls": False, "name": "France"},
    "ES": {"wb": "ESP", "eurostat": "ES", "bls": False, "name": "Spain"},
    "IT": {"wb": "ITA", "eurostat": "IT", "bls": False, "name": "Italy"},
    "NL": {"wb": "NLD", "eurostat": "NL", "bls": False, "name": "Netherlands"},
    "SE": {"wb": "SWE", "eurostat": "SE", "bls": False, "name": "Sweden"},
    "PL": {"wb": "POL", "eurostat": "PL", "bls": False, "name": "Poland"},
    "EU": {"wb": "EUU", "eurostat": "EU27_2020", "bls": False, "name": "EU-27"},
}


# ── Series definitions ──
SERIES_DEFS = [
    {"id": "youth_unemployment", "name": "Youth Unemployment Rate (15-24)",
     "description": "Unemployment rate for ages 15-24 as % of youth labour force",
     "category": "employment", "unit": "%", "frequency": "annual",
     "source": "World Bank / Eurostat"},
    {"id": "youth_unemployment_us_bls_16_24", "name": "US Youth Unemployment Rate (16-24, BLS)",
     "description": "US unemployment rate for ages 16-24, stored as complete calendar-year averages from monthly BLS observations",
     "category": "employment", "unit": "%", "frequency": "annual",
     "source": "U.S. Bureau of Labor Statistics"},
    {"id": "labour_share_gdp", "name": "Labour Share of GDP",
     "description": "Compensation of employees as % of GDP — how much of the economy goes to workers vs capital",
     "category": "income", "unit": "%", "frequency": "annual",
     "source": "Legacy historical snapshot (manual; provenance under review; through 2024)"},
    {"id": "gdp_growth", "name": "GDP Growth Rate",
     "description": "Annual GDP growth rate (%)",
     "category": "macro", "unit": "%", "frequency": "annual",
     "source": "World Bank"},
    {"id": "employment_ratio", "name": "Employment-to-Population Ratio",
     "description": "% of working-age population that is employed",
     "category": "employment", "unit": "%", "frequency": "annual",
     "source": "World Bank"},
    {"id": "labour_force_participation", "name": "Labour Force Participation Rate",
     "description": "% of working-age population in the labour force",
     "category": "employment", "unit": "%", "frequency": "annual",
     "source": "World Bank"},
    {"id": "neet_rate", "name": "NEET Rate (Youth)",
     "description": "% of youth Not in Employment, Education, or Training",
     "category": "employment", "unit": "%", "frequency": "annual",
     "source": "World Bank"},
    {"id": "industry_employment_share", "name": "Industry Employment Share",
     "description": "% of total employment in industry sector",
     "category": "structure", "unit": "%", "frequency": "annual",
     "source": "World Bank"},
    {"id": "services_employment_share", "name": "Services Employment Share",
     "description": "% of total employment in services sector",
     "category": "structure", "unit": "%", "frequency": "annual",
     "source": "World Bank"},
    {"id": "gini_index", "name": "Gini Index",
     "description": "Income inequality measure (0 = perfect equality, 100 = perfect inequality)",
     "category": "income", "unit": "index", "frequency": "annual",
     "source": "World Bank"},
]


# ── World Bank indicator mappings ──
WB_INDICATORS = {
    "youth_unemployment": "SL.UEM.1524.ZS",
    "gdp_growth": "NY.GDP.MKTP.KD.ZG",
    "employment_ratio": "SL.EMP.TOTL.SP.ZS",
    "labour_force_participation": "SL.TLF.CACT.ZS",
    "neet_rate": "SL.UEM.NEET.ZS",
    "industry_employment_share": "SL.IND.EMPL.ZS",
    "services_employment_share": "SL.SRV.EMPL.ZS",
    "gini_index": "SI.POV.GINI",
    # "labour_share_gdp" is intentionally excluded: the retained historical
    # snapshot has no reproducible source import yet.
}

def fetch_world_bank(series_id, indicator, country_wb, years=20):
    """Fetch from World Bank API v2. Returns list of (date, value) tuples."""
    url = f"https://api.worldbank.org/v2/country/{country_wb}/indicator/{indicator}"
    current_year = datetime.now(timezone.utc).year
    # Fetch the complete requested date interval.  A fixed 20-row page omitted
    # 2005 once the range grew past twenty years, leaving one legacy BLS value
    # in the cross-country World Bank series after the age-band split.
    params = {
        "format": "json",
        "per_page": max(years, current_year - 2005 + 1),
        "date": f"2005:{current_year}",
    }
    try:
        # Three bounded attempts recover transient upstream stalls without
        # spending longer on an unreachable source than the old two 30s reads.
        r = SESSION.get(url, params=params, timeout=(5, 20))
        r.raise_for_status()
        data = r.json()
        if len(data) < 2 or not data[1]:
            return []
        results = []
        for item in data[1]:
            if item.get("value") is not None:
                results.append((item["date"], float(item["value"])))
        return results
    except Exception as e:
        log.error(f"World Bank error {series_id}/{country_wb}: {e}")
        raise


# ── Eurostat fetcher ──
EUROSTAT_DATASETS = {
    "youth_unemployment": {
        "dataset": "une_rt_a",
        "params": {"age": "Y15-24", "sex": "T", "unit": "PC_ACT"},
    },
}

def fetch_eurostat(series_id, country_es, years=20):
    """Fetch from Eurostat JSON API."""
    cfg = EUROSTAT_DATASETS.get(series_id)
    if not cfg or not country_es:
        return []
    url = f"https://ec.europa.eu/eurostat/api/dissemination/statistics/1.0/data/{cfg['dataset']}"
    params = {"format": "JSON", "geo": country_es, "lang": "en",
              "sinceTimePeriod": "2005", "untilTimePeriod": str(datetime.now().year)}
    params.update(cfg.get("params", {}))
    try:
        r = SESSION.get(url, params=params, timeout=30)
        r.raise_for_status()
        data = r.json()
        # Eurostat JSON format: dimension indices map to values
        time_dim = data.get("dimension", {}).get("time", {}).get("category", {}).get("index", {})
        values = data.get("value", {})
        results = []
        for year_str, idx in time_dim.items():
            val = values.get(str(idx))
            if val is not None:
                results.append((year_str, float(val)))
        return results
    except Exception as e:
        log.error(f"Eurostat error {series_id}/{country_es}: {e}")
        raise


# ── BLS fetcher (US only, no key needed) ──
BLS_SERIES = {
    # Keep the BLS 16-24 population separate from the 15-24 World Bank /
    # Eurostat comparison series; writing both under one ID silently replaced
    # the US value with a non-comparable age band.
    "youth_unemployment_us_bls_16_24": "LNS14024887",
}

def fetch_bls(series_id):
    """Fetch BLS in supported windows and return complete-year averages."""
    bls_id = BLS_SERIES.get(series_id)
    if not bls_id:
        return []
    url = "https://api.bls.gov/publicAPI/v1/timeseries/data/"
    # The unregistered v1 API supports a maximum ten-year window.  Asking for
    # 2005-current silently returned only the *oldest* ten years (ending 2014).
    # Fetch separate inclusive windows so the retained history does not have a
    # misleading 2015-16 gap when the current window is refreshed.
    current_year = datetime.now(timezone.utc).year
    try:
        yearly = {}
        for start_year in range(2005, current_year + 1, 10):
            payload = {
                "seriesid": [bls_id],
                "startyear": str(start_year),
                "endyear": str(min(start_year + 9, current_year)),
            }
            r = SESSION.post(url, json=payload, timeout=30)
            r.raise_for_status()
            data = r.json()
            if data.get("status") != "REQUEST_SUCCEEDED":
                message = "; ".join(data.get("message") or []) or "unknown BLS API error"
                raise RuntimeError(message)
            series = data.get("Results", {}).get("series") or []
            if not series:
                raise RuntimeError("BLS response contained no series data")
            for item in series[0].get("data", []):
                period = item.get("period", "")
                if not re.fullmatch(r"M(?:0[1-9]|1[0-2])", period):
                    continue
                year = item.get("year")
                try:
                    val = float(item.get("value"))
                except (TypeError, ValueError):
                    # BLS uses '-' for an unpublished current-month observation.
                    continue
                # Key by month so an overlapping or repeated API observation
                # cannot make an incomplete year look complete.
                yearly.setdefault(year, {})[period] = val
        results = []
        for year, observations in sorted(yearly.items()):
            # Do not label a year-to-date mean as an annual observation.
            if len(observations) == 12:
                values = observations.values()
                results.append((year, round(sum(values) / len(observations), 1)))
        return results
    except Exception as e:
        log.error(f"BLS error {series_id}: {e}")
        raise


# ── Main fetch orchestrator ──
def register_series():
    """Ensure all series definitions exist in DB."""
    with db.conn() as c:
        for s in SERIES_DEFS:
            c.execute("""INSERT INTO data_series
                (id, name, description, category, unit, source, frequency)
                VALUES (?, ?, ?, ?, ?, ?, ?)
                ON CONFLICT(id) DO UPDATE SET
                    name=excluded.name,
                    description=excluded.description,
                    category=excluded.category,
                    unit=excluded.unit,
                    source=excluded.source,
                    frequency=excluded.frequency""",
                (s["id"], s["name"], s["description"], s["category"],
                 s["unit"], s["source"], s["frequency"]))


def record_fetch(source, series_id, status, records_added=0, error_msg=None):
    """Persist one source attempt so partial failures are visible to monitoring."""
    with db.conn() as c:
        c.execute("""INSERT INTO fetch_log
            (source, series_id, status, records_added, error_msg)
            VALUES (?, ?, ?, ?, ?)""",
            (source, series_id, status, records_added, error_msg))

def fetch_all():
    """Main entry point: fetch all data from all sources."""
    db.init()
    register_series()
    total_added = 0
    errors = 0

    for country_code, info in COUNTRIES.items():
        wb_code = info["wb"]
        es_code = info.get("eurostat")

        for series_id, indicator in WB_INDICATORS.items():
            log.info(f"Fetching WB {series_id} for {country_code}")
            try:
                points = fetch_world_bank(series_id, indicator, wb_code)
            except Exception as exc:
                errors += 1
                record_fetch("world_bank", f"{series_id}/{country_code}", "error", error_msg=str(exc)[:500])
                continue
            if points:
                with db.conn() as c:
                    for date, value in points:
                        db.upsert_data_point(c, series_id, country_code, date, value)
                total_added += len(points)
                record_fetch("world_bank", f"{series_id}/{country_code}", "ok", len(points))
            else:
                record_fetch("world_bank", f"{series_id}/{country_code}", "empty", error_msg="no data")
            time.sleep(0.3)  # be nice to APIs

        # Eurostat (EU countries only)
        if es_code:
            for series_id in EUROSTAT_DATASETS:
                log.info(f"Fetching Eurostat {series_id} for {country_code}")
                try:
                    points = fetch_eurostat(series_id, es_code)
                except Exception as exc:
                    errors += 1
                    record_fetch("eurostat", f"{series_id}/{country_code}", "error", error_msg=str(exc)[:500])
                    continue
                if points:
                    with db.conn() as c:
                        for date, value in points:
                            db.upsert_data_point(c, series_id, country_code, date, value)
                    total_added += len(points)
                    record_fetch("eurostat", f"{series_id}/{country_code}", "ok", len(points))
                else:
                    record_fetch("eurostat", f"{series_id}/{country_code}", "empty", error_msg="no data")
                time.sleep(0.3)

        # BLS (US only)
        if info.get("bls"):
            for series_id in BLS_SERIES:
                log.info(f"Fetching BLS {series_id} for US")
                try:
                    points = fetch_bls(series_id)
                except Exception as exc:
                    errors += 1
                    record_fetch("bls", f"{series_id}/US", "error", error_msg=str(exc)[:500])
                    continue
                if points:
                    with db.conn() as c:
                        for date, value in points:
                            db.upsert_data_point(c, series_id, "US", date, value)
                    total_added += len(points)
                    record_fetch("bls", f"{series_id}/US", "ok", len(points))
                else:
                    record_fetch("bls", f"{series_id}/US", "empty", error_msg="no data")
                time.sleep(0.5)

    log.info(f"Fetch complete: {total_added} data points added/updated; {errors} source errors")
    print(f"Fetch complete: {total_added} data points added/updated; {errors} source errors")
    if errors:
        raise RuntimeError(f"{errors} source request(s) failed; see fetch_log")
    return total_added


if __name__ == "__main__":
    print(f"Starting data fetch at {datetime.now(timezone.utc).isoformat()}")
    try:
        n = fetch_all()
        print(f"Done. {n} data points.")
    except Exception as e:
        log.error(f"Fatal: {traceback.format_exc()}")
        print(f"Error: {e}")
        sys.exit(1)
```
