---
type: "Source File"
title: "from __future__ import annotations"
description: "from __future__ import annotations import argparse import json import math import tempfile import time import urllib.parse import urllib.request from datetime import datetime, timezone from pathlib import Path from."
resource: "https://codex.copecheck.com/tools/fetch_doom_markets.py"
tags: ["copecheck", "codex", "source-file", "py"]
timestamp: "2026-05-15T07:52:59Z"
site: "codex"
source_path: "copecheck-codex/tools/fetch_doom_markets.py"
---

# from __future__ import annotations

Source path: `copecheck-codex/tools/fetch_doom_markets.py`  
Index snapshot generated: `2026-11-24T13:27:52Z`  
File modified: `2026-05-15T07:52:59Z`

```py
from __future__ import annotations

import argparse
import json
import math
import tempfile
import time
import urllib.parse
import urllib.request
from datetime import datetime, timezone
from pathlib import Path
from typing import Any


ROOT = Path(__file__).resolve().parents[1]
DATA_DIR = ROOT / "data"
DEFAULT_JSON_OUT = DATA_DIR / "doom-markets.json"
DEFAULT_JS_OUT = DATA_DIR / "doom-markets.js"
USER_AGENT = "CopeCheckCodex/0.3 (+https://codex.copecheck.com)"

MARKET_QUERIES = [
    {"term": "AI jobs", "topic": "AI jobs", "geography": "global"},
    {"term": "AI unemployment", "topic": "AI unemployment", "geography": "global"},
    {"term": "automation jobs", "topic": "Automation jobs", "geography": "global"},
    {"term": "mass unemployment", "topic": "Mass unemployment", "geography": "global"},
    {"term": "universal basic income", "topic": "Basic income", "geography": "global"},
    {"term": "AGI", "topic": "AGI capability", "geography": "global"},
    {"term": "best AI model", "topic": "AI capability", "geography": "global"},
    {"term": "AI regulation", "topic": "AI regulation", "geography": "global"},
    {"term": "UK AI jobs", "topic": "UK AI jobs", "geography": "uk"},
]

DOOM_KEYWORDS = {
    "ai": 10,
    "agi": 10,
    "automation": 13,
    "automate": 13,
    "job": 13,
    "jobs": 13,
    "unemployment": 16,
    "unemployed": 16,
    "displaced": 18,
    "displacement": 18,
    "replace": 13,
    "remote jobs": 14,
    "mass unemployment": 24,
    "basic income": 10,
    "ubi": 10,
    "labour": 12,
    "labor": 12,
    "uk": 8,
    "britain": 8,
}

ONS_SERIES = [
    {
        "id": "ons:mgsx",
        "label": "UK unemployment rate",
        "url": "https://www.ons.gov.uk/employmentandlabourmarket/peoplenotinwork/unemployment/timeseries/mgsx/lms",
        "data_url": "https://www.ons.gov.uk/employmentandlabourmarket/peoplenotinwork/unemployment/timeseries/mgsx/lms/data",
        "pressure": "higher_is_worse",
    },
    {
        "id": "ons:jp9z",
        "label": "UK vacancies, total services",
        "url": "https://www.ons.gov.uk/employmentandlabourmarket/peopleinwork/employmentandemployeetypes/timeseries/jp9z/lms",
        "data_url": "https://www.ons.gov.uk/employmentandlabourmarket/peopleinwork/employmentandemployeetypes/timeseries/jp9z/lms/data",
        "pressure": "lower_is_worse",
    },
]

YOUGOV_WATCHLIST = [
    {
        "id": "yougov:ai-western-attitudes",
        "title": "English-speaking Western countries are more negative about AI than Western Europeans",
        "source": "YouGov",
        "geography": "uk",
        "url": "https://yougov.com/en-gb/articles/[redacted]",
        "license": "YouGov public data is CC BY-NC 4.0; use attribution and avoid automated scraping without permission.",
        "oracle_read": "This is the UK sentiment layer: public anxiety can run ahead of labour-market data, which is exactly the gap CopeCheck should make visible.",
    },
    {
        "id": "yougov:public-data-license",
        "title": "YouGov Public Data Licence",
        "source": "YouGov",
        "geography": "uk",
        "url": "https://yougov.com/en-gb/about/terms/public-data-license",
        "license": "Reference page for attribution and non-commercial reuse constraints.",
        "oracle_read": "Keep YouGov as a curated and attributed polling source unless a paid API or explicit scraping permission is added.",
    },
]

SOURCE_NOTES = [
    {
        "source": "Manifold",
        "url": "https://docs.manifold.markets/api",
        "note": "No-auth market search and read endpoints. Primary free prediction-market source for CopeCheck.",
    },
    {
        "source": "Polymarket",
        "url": "https://docs.polymarket.com/market-data/overview",
        "note": "No-auth public market data. Use Gamma/public-search for discovery and CLOB/Data API only if order-book detail is needed.",
    },
    {
        "source": "ONS",
        "url": "https://developer.ons.gov.uk/",
        "note": "Official UK labour baseline with no API key required.",
    },
    {
        "source": "YouGov",
        "url": "https://yougov.com/en-gb/about/terms/public-data-license",
        "note": "Curated UK polling layer. Avoid blind scraping; link and attribute public data.",
    },
]


def utc_now() -> str:
    return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")


def fetch_json(url: str, timeout: int) -> Any:
    request = urllib.request.Request(
        url,
        headers={
            "User-Agent": USER_AGENT,
            "Accept": "application/json, text/plain;q=0.8, */*;q=0.5",
        },
    )
    with urllib.request.urlopen(request, timeout=timeout) as response:
        return json.loads(response.read().decode("utf-8"))


def parse_float(value: Any) -> float | None:
    try:
        if value is None or value == "":
            return None
        return float(value)
    except (TypeError, ValueError):
        return None


def parse_json_field(value: Any) -> Any:
    if isinstance(value, str):
        try:
            return json.loads(value)
        except json.JSONDecodeError:
            return None
    return value


def ms_to_iso(value: Any) -> str | None:
    number = parse_float(value)
    if number is None:
        return None
    return datetime.fromtimestamp(number / 1000, tz=timezone.utc).isoformat().replace("+00:00", "Z")


def relevance_score(text: str) -> int:
    probe = text.lower()
    score = 0
    for keyword, weight in DOOM_KEYWORDS.items():
        if keyword in probe:
            score += weight
    return min(100, score)


def confidence_from_market(liquidity: float | None, volume: float | None, bettors: float | None = None) -> int:
    base = 20
    if liquidity:
        base += min(35, int(math.log10(max(liquidity, 1)) * 9))
    if volume:
        base += min(30, int(math.log10(max(volume, 1)) * 7))
    if bettors:
        base += min(15, int(math.log10(max(bettors, 1)) * 8))
    return max(10, min(95, base))


def classify_pressure(text: str, probability: float | None, relevance: int, confidence: int) -> int:
    probe = text.lower()
    if probability is None:
        base = 35 + relevance * 0.35
    elif any(term in probe for term in ("unemployment", "displaced", "displacement", "automate", "replace", "job")):
        base = probability * 100
    elif any(term in probe for term in ("agi", "best ai model", "capability", "ai model")):
        base = 25 + probability * 55
    elif any(term in probe for term in ("basic income", "ubi")):
        base = 30 + probability * 45
    else:
        base = 25 + probability * 50
    base += relevance * 0.18
    base += confidence * 0.08
    return max(0, min(100, round(base)))


def probability_label(probability: float | None) -> str:
    if probability is None:
        return "n/a"
    return f"{round(probability * 100)}%"


def market_oracle_read(provider: str, title: str, probability: float | None, confidence: int) -> str:
    if probability is None:
        return (
            f"{provider} has this as an open forecast signal, but not a clean binary price. "
            "Use it as narrative smoke rather than a headline probability."
        )
    label = probability_label(probability)
    if confidence >= 70:
        confidence_text = "enough liquidity to treat as a useful market signal"
    elif confidence >= 45:
        confidence_text = "some liquidity, but still a thin-market signal"
    else:
        confidence_text = "thin liquidity, so treat it as directional only"
    return (
        f"Markets put this near {label}. The important part for CopeCheck is not whether "
        f"the crowd is right today, but that {title.lower()} is now a priced question with {confidence_text}."
    )


def normalize_manifold_market(market: dict[str, Any], query: dict[str, str]) -> dict[str, Any] | None:
    if market.get("isResolved"):
        return None
    title = str(market.get("question") or "").strip()
    url = str(market.get("url") or "").strip()
    if not title or not url:
        return None
    source_text = " ".join([title, str(market.get("description") or "")])
    relevance = relevance_score(source_text)
    if relevance < 18:
        return None
    probability = parse_float(market.get("probability"))
    liquidity = parse_float(market.get("totalLiquidity"))
    volume = parse_float(market.get("volume"))
    bettors = parse_float(market.get("uniqueBettorCount"))
    confidence = confidence_from_market(liquidity, volume, bettors)
    pressure = classify_pressure(f"{source_text} {query['term']}", probability, relevance, confidence)
    return {
        "id": f"manifold:{market.get('id')}",
        "provider": "Manifold",
        "provider_market_id": market.get("id"),
        "topic": query["topic"],
        "geography": query["geography"],
        "title": title,
        "url": url,
        "status": "open",
        "outcome_type": market.get("outcomeType"),
        "probability": probability,
        "probability_label": probability_label(probability),
        "liquidity": liquidity,
        "volume": volume,
        "volume_24h": parse_float(market.get("volume24Hours")),
        "unique_bettors": bettors,
        "close_time": ms_to_iso(market.get("closeTime")),
        "updated_at": ms_to_iso(market.get("lastUpdatedTime")),
        "relevance_score": relevance,
        "signal_confidence": confidence,
        "doom_pressure": pressure,
        "oracle_read": market_oracle_read("Manifold", title, probability, confidence),
    }


def fetch_manifold_signals(timeout: int, per_query: int) -> tuple[list[dict[str, Any]], list[str]]:
    signals: list[dict[str, Any]] = []
    errors: list[str] = []
    for query in MARKET_QUERIES:
        params = urllib.parse.urlencode({"term": query["term"], "limit": per_query})
        url = f"https://api.manifold.markets/v0/search-markets?{params}"
        try:
            markets = fetch_json(url, timeout=timeout)
        except Exception as exc:
            errors.append(f"Manifold {query['term']}: {type(exc).__name__}: {exc}")
            continue
        if not isinstance(markets, list):
            continue
        for market in markets:
            if isinstance(market, dict):
                signal = normalize_manifold_market(market, query)
                if signal:
                    signals.append(signal)
        time.sleep(0.15)
    return signals, errors


def polymarket_url(slug: Any, kind: str = "event") -> str:
    clean = str(slug or "").strip("/")
    return f"https://polymarket.com/{kind}/{clean}" if clean else "https://polymarket.com"


def yes_probability(market: dict[str, Any]) -> float | None:
    outcomes = parse_json_field(market.get("outcomes")) or []
    prices = parse_json_field(market.get("outcomePrices")) or []
    if not isinstance(outcomes, list) or not isinstance(prices, list):
        return None
    for index, outcome in enumerate(outcomes):
        if str(outcome).lower() == "yes" and index < len(prices):
            return parse_float(prices[index])
    if len(prices) == 2:
        return parse_float(prices[0])
    return None


def normalize_polymarket_event(event: dict[str, Any], query: dict[str, str]) -> dict[str, Any] | None:
    title = str(event.get("title") or event.get("question") or "").strip()
    if not title:
        return None
    markets = event.get("markets") if isinstance(event.get("markets"), list) else []
    open_markets = [
        market for market in markets
        if isinstance(market, dict) and market.get("active") is not False and not market.get("closed")
    ]
    market = open_markets[0] if open_markets else {}
    market_title = str(market.get("question") or title).strip()
    source_text = " ".join([title, market_title, str(event.get("description") or "")])
    relevance = relevance_score(source_text)
    if relevance < 18:
        return None
    probability = yes_probability(market) if market else None
    liquidity = parse_float(market.get("liquidity") or event.get("liquidity"))
    volume = parse_float(market.get("volume") or event.get("volume"))
    confidence = confidence_from_market(liquidity, volume)
    pressure = classify_pressure(f"{source_text} {query['term']}", probability, relevance, confidence)
    event_slug = event.get("slug") or market.get("slug")
    return {
        "id": f"polymarket:{event.get('id') or event_slug}",
        "provider": "Polymarket",
        "provider_market_id": market.get("id") or event.get("id"),
        "topic": query["topic"],
        "geography": query["geography"],
        "title": market_title,
        "event_title": title,
        "url": polymarket_url(event_slug, "event"),
        "status": "open",
        "outcome_type": "BINARY" if probability is not None else "EVENT",
        "probability": probability,
        "probability_label": probability_label(probability),
        "liquidity": liquidity,
        "volume": volume,
        "volume_24h": parse_float(market.get("volume24hr") or event.get("volume24hr")),
        "close_time": market.get("endDate") or event.get("endDate"),
        "updated_at": market.get("updatedAt") or event.get("updatedAt"),
        "relevance_score": relevance,
        "signal_confidence": confidence,
        "doom_pressure": pressure,
        "oracle_read": market_oracle_read("Polymarket", market_title, probability, confidence),
    }


def fetch_polymarket_signals(timeout: int, per_query: int) -> tuple[list[dict[str, Any]], list[str]]:
    signals: list[dict[str, Any]] = []
    errors: list[str] = []
    for query in MARKET_QUERIES:
        params = urllib.parse.urlencode({"q": query["term"], "limit": per_query})
        url = f"https://gamma-api.polymarket.com/public-search?{params}"
        try:
            body = fetch_json(url, timeout=timeout)
        except Exception as exc:
            errors.append(f"Polymarket {query['term']}: {type(exc).__name__}: {exc}")
            continue
        events = body.get("events") if isinstance(body, dict) else []
        if not isinstance(events, list):
            continue
        for event in events:
            if isinstance(event, dict):
                signal = normalize_polymarket_event(event, query)
                if signal:
                    signals.append(signal)
        time.sleep(0.15)
    return signals, errors


def latest_points(data: dict[str, Any]) -> list[dict[str, Any]]:
    for key in ("months", "quarters", "years"):
        values = data.get(key)
        if isinstance(values, list) and values:
            return [item for item in values if isinstance(item, dict)]
    return []


def official_pressure(series: dict[str, Any], latest: float | None, previous: float | None) -> int:
    if latest is None:
        return 40
    change = latest - previous if previous is not None else 0
    if series["pressure"] == "higher_is_worse":
        base = 42 + max(0, latest - 4.0) * 12
        if change > 0:
            base += 8
        elif change < 0:
            base -= 5
    else:
        base = 48
        if change < 0:
            base += min(18, abs(change) / max(abs(previous or latest), 1) * 200)
        elif change > 0:
            base -= 6
    return max(0, min(100, round(base)))


def normalize_ons_series(series: dict[str, Any], timeout: int) -> dict[str, Any]:
    data = fetch_json(series["data_url"], timeout=timeout)
    description = data.get("description") if isinstance(data, dict) else {}
    points = latest_points(data if isinstance(data, dict) else {})
    latest_point = points[-1] if points else {}
    previous_point = points[-2] if len(points) > 1 else {}
    latest = parse_float(latest_point.get("value"))
    previous = parse_float(previous_point.get("value"))
    change = latest - previous if latest is not None and previous is not None else None
    change_pct = (change / previous * 100) if change is not None and previous not in (None, 0) else None
    pressure = official_pressure(series, latest, previous)
    return {
        "id": series["id"],
        "source": "ONS",
        "title": description.get("title") or series["label"],
        "label": series["label"],
        "geography": "uk",
        "url": series["url"],
        "data_url": series["data_url"],
        "latest_date": latest_point.get("label") or latest_point.get("date") or description.get("date"),
        "latest_value": latest,
        "previous_value": previous,
        "unit": description.get("unit") or "",
        "change": change,
        "change_pct": change_pct,
        "release_date": description.get("releaseDate"),
        "next_release": description.get("nextRelease"),
        "doom_pressure": pressure,
        "oracle_read": (
            "Official labour data is the reality check. Prediction markets can move first, "
            "but this series tells whether the UK labour surface has actually started to crack."
        ),
    }


def fetch_ons_indicators(timeout: int) -> tuple[list[dict[str, Any]], list[str]]:
    indicators: list[dict[str, Any]] = []
    errors: list[str] = []
    for series in ONS_SERIES:
        try:
            indicators.append(normalize_ons_series(series, timeout))
        except Exception as exc:
            errors.append(f"ONS {series['label']}: {type(exc).__name__}: {exc}")
        time.sleep(0.1)
    return indicators, errors


def dedupe_signals(signals: list[dict[str, Any]]) -> list[dict[str, Any]]:
    by_key: dict[str, dict[str, Any]] = {}
    for signal in signals:
        key = str(signal.get("id") or signal.get("url") or signal.get("title"))
        existing = by_key.get(key)
        if not existing or int(signal.get("doom_pressure") or 0) > int(existing.get("doom_pressure") or 0):
            by_key[key] = signal
    output = list(by_key.values())
    output.sort(
        key=lambda item: (
            int(item.get("doom_pressure") or 0),
            int(item.get("signal_confidence") or 0),
            float(item.get("volume") or 0),
        ),
        reverse=True,
    )
    return output


def weighted_average(items: list[dict[str, Any]], value_key: str, weight_key: str) -> float | None:
    total = 0.0
    weights = 0.0
    for item in items:
        value = parse_float(item.get(value_key))
        weight = parse_float(item.get(weight_key)) or 1.0
        if value is None:
            continue
        total += value * weight
        weights += weight
    if weights == 0:
        return None
    return total / weights


def build_summary(signals: list[dict[str, Any]], indicators: list[dict[str, Any]]) -> dict[str, Any]:
    market_pressure = weighted_average(signals[:12], "doom_pressure", "signal_confidence") or 0
    official_pressure_value = weighted_average(indicators, "doom_pressure", "latest_value") or 0
    doom_index = round(market_pressure * 0.72 + official_pressure_value * 0.28)
    providers: dict[str, int] = {}
    topics: dict[str, int] = {}
    for signal in signals:
        providers[str(signal.get("provider") or "unknown")] = providers.get(str(signal.get("provider") or "unknown"), 0) + 1
        topics[str(signal.get("topic") or "unknown")] = topics.get(str(signal.get("topic") or "unknown"), 0) + 1
    top_signal = signals[0] if signals else {}
    verdict = (
        "Prediction markets are now a useful radar layer for the thesis. "
        "They should not be treated as proof, but they expose which discontinuity questions have become priced, liquid, and repeatable."
    )
    if doom_index >= 70:
        verdict = "The market layer is hot: priced AI/job-displacement questions are clustering with enough confidence to deserve regular Oracle review."
    elif doom_index >= 50:
        verdict = "The market layer is warm: there is enough priced anxiety to track, but official UK labour data is still the reality anchor."
    return {
        "doom_index": doom_index,
        "market_pressure": round(market_pressure),
        "official_pressure": round(official_pressure_value),
        "market_count": len(signals),
        "provider_counts": providers,
        "topic_counts": topics,
        "top_signal": {
            "title": top_signal.get("title"),
            "provider": top_signal.get("provider"),
            "probability_label": top_signal.get("probability_label"),
            "url": top_signal.get("url"),
        } if top_signal else None,
        "oracle_verdict": verdict,
    }


def write_outputs(json_path: Path, js_path: Path, body: dict[str, Any]) -> None:
    json_path.parent.mkdir(parents=True, exist_ok=True)
    with tempfile.NamedTemporaryFile("w", encoding="utf-8", dir=json_path.parent, delete=False) as handle:
        json.dump(body, handle, ensure_ascii=False, indent=2)
        handle.write("\n")
        tmp_name = handle.name
    Path(tmp_name).replace(json_path)
    json_path.chmod(0o644)
    js_path.parent.mkdir(parents=True, exist_ok=True)
    js_body = "export const doomMarkets = " + json.dumps(body, ensure_ascii=False, indent=2) + ";\n"
    with tempfile.NamedTemporaryFile("w", encoding="utf-8", dir=js_path.parent, delete=False) as handle:
        handle.write(js_body)
        tmp_name = handle.name
    Path(tmp_name).replace(js_path)
    js_path.chmod(0o644)


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--json-out", type=Path, default=DEFAULT_JSON_OUT)
    parser.add_argument("--js-out", type=Path, default=DEFAULT_JS_OUT)
    parser.add_argument("--timeout", type=int, default=20)
    parser.add_argument("--per-query", type=int, default=8)
    parser.add_argument("--limit", type=int, default=24)
    args = parser.parse_args()

    manifold, manifold_errors = fetch_manifold_signals(args.timeout, args.per_query)
    polymarket, polymarket_errors = fetch_polymarket_signals(args.timeout, args.per_query)
    indicators, ons_errors = fetch_ons_indicators(args.timeout)
    signals = dedupe_signals(manifold + polymarket)[: max(1, args.limit)]
    body = {
        "generatedAt": utc_now(),
        "summary": build_summary(signals, indicators),
        "signals": signals,
        "official_indicators": indicators,
        "poll_watchlist": YOUGOV_WATCHLIST,
        "source_notes": SOURCE_NOTES,
        "errors": (manifold_errors + polymarket_errors + ons_errors)[:12],
    }
    write_outputs(args.json_out, args.js_out, body)
    print(
        json.dumps(
            {
                "signals": len(signals),
                "official_indicators": len(indicators),
                "doom_index": body["summary"]["doom_index"],
                "errors": body["errors"],
            },
            ensure_ascii=False,
        )
    )
    return 0 if signals or indicators else 1


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