DEV Community

linderroger-eng
linderroger-eng

Posted on

Build a Recession Indicator with Unemployment + Inflation Data (Free API)

Build a Recession Indicator with Unemployment + Inflation Data (Free API)

Recessions don't announce themselves. But the data whispers before they arrive.

Two of the most reliable early signals are baked into macroeconomic history: unemployment rates climbing while inflation either spikes or collapses. Together they form the backbone of the Misery Index — a blunt but surprisingly effective recession proxy used by economists since the 1970s.

In this tutorial, you'll build a live recession scoring tool in Python using the US Macro Data API — a free REST API backed by World Bank data. No scraping, no CSV downloads, no data wrangling — just clean JSON endpoints you can hit in seconds.


What You'll Build

A Python script that:

  1. Fetches live unemployment + inflation data from the API
  2. Calculates the Misery Index for each year
  3. Flags years where the index exceeds historical danger thresholds
  4. Prints a recession risk assessment for the current cycle

Total code: ~60 lines. Total setup time: 5 minutes.


The API at a Glance

The US Macro Data API exposes four core endpoints — all sourced from the World Bank:

GET /gdp           # US GDP (current USD)
GET /inflation     # CPI inflation, annual %
GET /unemployment  # Unemployment rate, % of labor force
GET /labor         # Labor force participation + employment ratio
GET /indicators    # Combined macro snapshot (all series)
GET /country/{code}/gdp  # GDP for any of 190+ countries
Enter fullscreen mode Exit fullscreen mode

Let's verify it's live:

curl -s "https://us-macro-data-api.onrender.com/ping"
# {"status":"ok","message":"pong"}
Enter fullscreen mode Exit fullscreen mode

Now let's pull the data we need.


Step 1: Get Live Unemployment Data

curl -s "https://us-macro-data-api.onrender.com/unemployment"
Enter fullscreen mode Exit fullscreen mode

Real response (as of June 2026):

{
  "series": "SL.UEM.TOTL.ZS",
  "series_name": "Unemployment, total (% of total labor force)",
  "unit": "% of labor force",
  "country": "US",
  "source": "World Bank",
  "count": 5,
  "data": [
    { "year": "2025", "value": 4.198 },
    { "year": "2024", "value": 4.022 },
    { "year": "2023", "value": 3.638 },
    { "year": "2022", "value": 3.611 },
    { "year": "2021", "value": 5.349 }
  ]
}
Enter fullscreen mode Exit fullscreen mode

Unemployment ticked up from 3.6% in 2023 to 4.2% in 2025 — a subtle but meaningful shift worth tracking.


Step 2: Get Live Inflation Data

curl -s "https://us-macro-data-api.onrender.com/inflation"
Enter fullscreen mode Exit fullscreen mode

Real response:

{
  "series": "FP.CPI.TOTL.ZG",
  "series_name": "Inflation, consumer prices (annual %)",
  "unit": "Annual % change",
  "data": [
    { "year": "2024", "value": 2.95 },
    { "year": "2023", "value": 4.12 },
    { "year": "2022", "value": 8.00 },
    { "year": "2021", "value": 4.70 },
    { "year": "2020", "value": 1.23 }
  ]
}
Enter fullscreen mode Exit fullscreen mode

That 8% inflation in 2022 is the highest the US has seen in 40 years — and it shows up loud and clear.


Step 3: Get the Full Macro Snapshot in One Call

Instead of hitting each endpoint separately, /indicators returns everything at once:

curl -s "https://us-macro-data-api.onrender.com/indicators"
Enter fullscreen mode Exit fullscreen mode

This gives you GDP, GDP growth, inflation, unemployment, and labor force participation in a single JSON blob — perfect for dashboards or scheduled jobs.


Step 4: Build the Recession Indicator in Python

Now let's stitch it together. Install requests if you don't have it:

pip install requests
Enter fullscreen mode Exit fullscreen mode
import requests

BASE_URL = "https://us-macro-data-api.onrender.com"

def fetch_series(endpoint):
    """Fetch a macro series and return as {year: value} dict."""
    resp = requests.get(f"{BASE_URL}/{endpoint}")
    resp.raise_for_status()
    data = resp.json().get("data", [])
    return {int(item["year"]): item["value"] for item in data if item["value"] is not None}

def misery_index(unemployment, inflation):
    """Misery Index = Unemployment Rate + Inflation Rate."""
    return unemployment + inflation

def recession_risk(misery_score):
    """Classify recession risk based on Misery Index thresholds."""
    if misery_score >= 15:
        return "🔴 HIGH — Stagflation territory (1970s/80s levels)"
    elif misery_score >= 10:
        return "🟠 ELEVATED — Watch for demand destruction"
    elif misery_score >= 7:
        return "🟡 MODERATE — Economy under pressure"
    else:
        return "🟢 LOW — Conditions look stable"

def main():
    print("Fetching US macro data from World Bank via US Macro Data API...\n")

    unemployment_data = fetch_series("unemployment")
    inflation_data = fetch_series("inflation")

    # Find overlapping years
    years = sorted(set(unemployment_data) & set(inflation_data), reverse=True)

    print(f"{'Year':<6} {'Unemployment':>14} {'Inflation':>10} {'Misery Index':>14} {'Risk Level'}")
    print("-" * 80)

    for year in years[:5]:
        unemp = unemployment_data[year]
        infl = inflation_data[year]
        misery = misery_index(unemp, infl)
        risk = recession_risk(misery)
        print(f"{year:<6} {unemp:>13.2f}% {infl:>9.2f}% {misery:>13.2f}  {risk}")

    # Latest reading
    latest_year = years[0]
    latest_misery = misery_index(
        unemployment_data[latest_year],
        inflation_data.get(latest_year, inflation_data[min(inflation_data, key=lambda y: abs(y - latest_year))])
    )
    print(f"\n📊 Current Misery Index ({latest_year}): {latest_misery:.2f}")
    print(f"   Assessment: {recession_risk(latest_misery)}")

if __name__ == "__main__":
    main()
Enter fullscreen mode Exit fullscreen mode

Sample Output

Running this script against the live API produces:

Fetching US macro data from World Bank via US Macro Data API...

Year   Unemployment  Inflation  Misery Index  Risk Level
--------------------------------------------------------------------------------
2025          4.20%      2.95%          7.15  🟡 MODERATE — Economy under pressure
2024          4.02%      2.95%          6.97  🟢 LOW — Conditions look stable
2023          3.64%      4.12%          7.76  🟡 MODERATE — Economy under pressure
2022          3.61%      8.00%         11.61  🟠 ELEVATED — Watch for demand destruction
2021          5.35%      4.70%         10.05  🟠 ELEVATED — Watch for demand destruction

📊 Current Misery Index (2025): 7.15
   Assessment: 🟡 MODERATE — Economy under pressure
Enter fullscreen mode Exit fullscreen mode

2022 was the peak pain point. We've cooled significantly since then — but we're not in "all clear" territory yet.


Bonus: Compare GDP Across Countries

The API covers 190+ countries via the /country/{code}/gdp endpoint. Here's a quick comparison between the US, Germany, and Japan:

# US GDP
curl -s "https://us-macro-data-api.onrender.com/gdp" | python3 -c "
import json, sys
d = json.load(sys.stdin)
latest = d['data'][0]
print(f"US GDP ({latest['year']}): \${latest['value']/1e12:.2f}T")
"
# US GDP (2024): $28.75T

# Germany GDP
curl -s "https://us-macro-data-api.onrender.com/country/DEU/gdp" | python3 -c "
import json, sys
d = json.load(sys.stdin)
latest = d['data'][0]
print(f"Germany GDP ({latest['year']}): \${latest['value']/1e12:.2f}T")
"
# Germany GDP (2024): $4.69T

# Japan GDP
curl -s "https://us-macro-data-api.onrender.com/country/JPN/gdp" | python3 -c "
import json, sys
d = json.load(sys.stdin)
latest = d['data'][0]
print(f"Japan GDP ({latest['year']}): \${latest['value']/1e12:.2f}T")
"
# Japan GDP (2024): $4.21T
Enter fullscreen mode Exit fullscreen mode

The US economy ($28.75T) is over 6x the size of Germany's and nearly 7x Japan's — context that matters when you're building international finance apps.


What to Build Next

Once you have this data flowing, here's what developers typically layer on top:

  • Scheduled jobs — run this script daily via cron or GitHub Actions, store results in Postgres or Supabase, and alert when the Misery Index crosses a threshold
  • Frontend dashboards — pipe the /indicators endpoint into a React chart (Recharts or Chart.js) for a live macro widget
  • Trading signals — combine GDP growth rate + unemployment trend for a simple momentum filter on equity positions
  • Newsletter automation — weekly macro digest generated from the API, formatted with Python's Jinja2, and shipped via Mailgun or Resend

The API is free for 100 requests/month. For production workloads, plans start at $9/month for 1,000 requests.


API Pricing

Plan Price Requests/mo
BASIC Free 100
PRO $9/mo 1,000
ULTRA $29/mo 10,000
MEGA $99/mo 100,000

Get Access

Find the US Macro Data API on RapidAPI — search "US Macro Data" or hit the live base URL directly at us-macro-data-api.onrender.com. The Swagger docs at /docs list every endpoint with request/response schemas.


Stay in the Loop

If you're building finance tools, automation scripts, or data products — you'll want the weekly signal, not the noise.

👉 Get weekly AI business & automation insights → AI Business Trends

Every issue covers emerging APIs, indie hacker case studies, and the automation stacks that are quietly printing money. Free to subscribe.


Data sourced from the World Bank Open Data via the US Macro Data API. All figures current as of June 2026.

Top comments (0)