Four-panel recession dashboard, January 2015 to November 2026: US unemployment rate, Sahm rule reading with the 0.50 trigger line, 10-year minus 3-month Treasury spread, and Alphabet's year-on-year revenue growth against real GDP growth, with the March to April 2020 NBER recession shaded
|

How to get FRED data in Python with no API key: a recession dashboard

All the FRED data Python needs for the dashboard below downloads without an API key or a FRED library: one requests call per series, against the CSV download FRED serves for every chart. Unemployment was 4.1% in October 2026 and the Sahm rule read 0.00, a full 0.50 points short of its 0.50 trigger. The 10-year minus 3-month Treasury spread was 0.59 percentage points on 27 November 2026, so the curve isn’t inverted, and real GDP grew at a 4.3% annual rate in the third quarter. The fourth panel adds Alphabet’s revenue from its SEC filings, up 24.7% on the year in the same quarter.

What I’d actually take from the build is 2024. The Sahm rule fired that summer, the yield curve was in the middle of a 534-trading-day inversion, and the NBER’s chronology still ends with the 2020 recession. So the code also shows when each alarm fired, and the NBER’s dates show what followed.

Four-panel recession dashboard, January 2015 to November 2026: US unemployment rate, Sahm rule reading with the 0.50 trigger line, 10-year minus 3-month Treasury spread, and Alphabet's year-on-year revenue growth against real GDP growth, with the March to April 2020 NBER recession shaded

Step 1: get the FRED data Python can read without an API key

FRED serves each series as a CSV at fred.stlouisfed.org/graph/fredgraph.csv. Put the series id in id and the start date in cosd, and two columns come back: a date and the values. No account, no key, nothing beyond pandas and requests.

I picked four series whose FRED pages carry the tag “Public Domain: Citation Requested”: the unemployment rate from the Bureau of Labor Statistics, the 10-year and 3-month Treasury yields from the Federal Reserve’s H.15 release, and real GDP from the Bureau of Economic Analysis. The obvious fifth series, FRED’s recession flag USREC, is tagged “Copyrighted: Citation Required”. So the grey band on the chart comes from the NBER’s own dates instead. Two dates are quicker to type than a licence is to read.

import io
import os
import requests
import pandas as pd
import matplotlib.pyplot as plt

FREDGRAPH = "https://fred.stlouisfed.org/graph/fredgraph.csv"


def fred(series_id, start="2014-01-01"):
    """One FRED series as a float Series, from the keyless CSV download."""
    r = requests.get(FREDGRAPH, params={"id": series_id, "cosd": start}, timeout=30)
    r.raise_for_status()
    df = pd.read_csv(io.StringIO(r.text), index_col=0, parse_dates=True)
    return pd.to_numeric(df.iloc[:, 0], errors="coerce").rename(series_id)


SERIES = {
    "UNRATE": "Unemployment rate, %, monthly (BLS)",
    "DGS10": "10-year Treasury yield, %, daily (Federal Reserve H.15)",
    "DGS3MO": "3-month Treasury yield, %, daily (Federal Reserve H.15)",
    "GDPC1": "Real GDP, chained 2017 $bn, quarterly (BEA)",
}
data = {sid: fred(sid) for sid in SERIES}
for sid, s in data.items():
    last = s.last_valid_index()
    print(f"{sid:7} {len(s):5} rows, {s.isna().sum():3} blank, last {last:%Y-%m-%d} = {s[last]}")
UNRATE    154 rows,   1 blank, last 2026-10-01 = 4.1
DGS10    3367 rows, 140 blank, last 2026-11-27 = 4.94
DGS3MO   3367 rows, 140 blank, last 2026-11-27 = 4.35
GDPC1      51 rows,   0 blank, last 2026-07-01 = 24665.201

The output shows the first trap already. Each yield series has 140 blank rows since January 2014, rows for weekdays with no published yield. The last one is 26 November 2026, Thanksgiving, which the Fed’s H.15 release marks “Markets closed”. The same release has 4.94% for the 10-year and 4.35% for the 3-month on 27 November, the two values the code got. The unemployment rate has one blank as well, and that one has a better story.

For heavier work, such as hundreds of series in a loop or a job that runs every hour, the documented route is the FRED API, through a package like fredapi, whose page says you can apply for a key for free. For a dashboard that pulls four series once a day, the CSV is enough.

Step 2: compute the Sahm rule from the unemployment rate

The Sahm rule, from Claudia Sahm’s 2019 Hamilton Project proposal, signals a recession when the three-month average of the unemployment rate rises at least 0.50 percentage points above its low of the previous 12 months. In pandas it’s a three-line function, and two of those lines carry a comment because the data bit back. October 2025 is blank because the BLS did not collect that month’s household survey during the government shutdown. The average uses the months that exist. And the round(2) is there because today’s data put July 2024 at exactly 0.50, but the rolling-average subtraction comes out at 0.49999999999999956 in floating point. A plain >= 0.5 then skips the first month the rule fired.

def sahm(unrate, digits=2):
    """Sahm rule: 3-month average unemployment minus its lowest 3-month average in the previous 12 months."""
    ma3 = unrate.rolling(3, min_periods=2).mean()  # October 2025 is blank: average the months that exist
    gap = ma3 - ma3.shift(1).rolling(12, min_periods=1).min()
    return gap if digits is None else gap.round(digits) + 0.0  # round, or 0.50 compares as 0.4999...


unrate = data["UNRATE"]
sahm_now = sahm(unrate)
print(sahm_now.tail(3).to_string())
fired = sahm_now.loc["2015":][sahm_now >= 0.5]
print("months at or above 0.50 since 2015:", fired.index.strftime("%Y-%m").tolist())
print(f"July 2024: unemployment {unrate['2024-07-01']}, reading {sahm_now['2024-07-01']:.2f}, "
      f"unrounded {sahm(unrate, digits=None)['2024-07-01']:.17g}")

ma3 = unrate.rolling(3, min_periods=2).mean()
trigger = ma3.iloc[-12:].min() + 0.5
print(f"next month's 3-month average that would reach 0.50: {trigger:.2f}%")

fig, ax = plt.subplots(figsize=(10, 4))
recent = sahm_now.loc["2023":]
ax.plot(recent, marker=".", color="tab:red")
ax.axhline(0.5, color="black", lw=0.8, ls="--")
ax.annotate("July 2024: exactly 0.50 after rounding", (pd.Timestamp("2024-07-01"), 0.5), xytext=(-260, 10),
            textcoords="offset points", arrowprops={"arrowstyle": "->"})
ax.set_title("Sahm rule reading on today's unemployment data, January 2023 onward (BLS via FRED: UNRATE)", loc="left")
plt.savefig("sahm-rule-2023-2026.png", dpi=150, bbox_inches="tight")
observation_date
2026-08-01   -0.07
2026-09-01    0.00
2026-10-01    0.00
months at or above 0.50 since 2015: ['2020-04', '2020-05', '2020-06', '2020-07', '2020-08', '2020-09', '2020-10', '2020-11', '2020-12', '2021-01', '2021-02', '2021-03', '2024-07', '2024-08', '2024-09']
July 2024: unemployment 4.2, reading 0.50, unrounded 0.49999999999999956
next month's 3-month average that would reach 0.50: 4.63%

Today’s reading is 0.00. To reach 0.50 next month, the three-month average would have to climb to 4.63%, well above the 4.1% of October 2026.

The revisions are the part I’d keep. The July 2024 jobs report, out on 2 August 2024, put unemployment at 4.3%. Today’s revised data put the same month at 4.2% and the Sahm reading at exactly 0.50. It still counts, on the second decimal, and the revised series fired for 3 months, July to September, peaking at 0.57 in August 2024. The NBER’s chronology still ends with the April 2020 trough. On the record so far, 2024 was a false alarm.

Sahm rule reading from January 2023 to October 2026 on today's unemployment data, with the 0.50 trigger line; July 2024 sits exactly on the line after rounding, and the readings for August and September 2024 are above it

Any test of a labour-market signal that runs on today’s revised series sees history the signal never had. ALFRED, the St. Louis Fed’s archive, keeps each past release of a series for when you need what was known on a date.

Step 3: measure the yield curve, 10-year minus 3-month

The spread takes two daily series and one subtraction. The dropna() drops the holiday rows from Step 1, and the run counter finds the longest stretch below zero.

spread = (data["DGS10"] - data["DGS3MO"]).dropna()  # holidays are blank rows in daily series
inverted = spread < 0
run_id = (inverted != inverted.shift()).cumsum()
runs = inverted[inverted].groupby(run_id[inverted])
first, last, days = runs.apply(lambda s: s.index[0]), runs.apply(lambda s: s.index[-1]), runs.size()
k = days.idxmax()
print(f"10-year minus 3-month on {spread.index[-1]:%Y-%m-%d}: {spread.iloc[-1]:+.2f} percentage points")
print(f"longest inversion since 2014: {first[k]:%Y-%m-%d} to {last[k]:%Y-%m-%d}, {days[k]} trading days")
10-year minus 3-month on 2026-11-27: +0.59 percentage points
longest inversion since 2014: 2022-10-25 to 2024-12-12, 534 trading days

The curve stayed inverted from 25 October 2022 to 12 December 2024, 534 trading days, the longest stretch in this download. The NBER has dated no recession since, and on 27 November 2026 the spread was back at 0.59 points. The yield curve recession predictor post goes through the spread’s longer record.

Step 4: compute real GDP growth and check it against the BEA

The BEA’s headline is quarter-on-quarter growth at an annual rate, so the code compounds each quarterly change four times. The year-on-year rate is the one the dashboard plots, because that’s what you can set next to a company’s revenue growth.

gdp = data["GDPC1"].dropna()
gdp_saar = (gdp / gdp.shift(1)) ** 4 - 1   # BEA's headline: quarter on quarter, at an annual rate
gdp_yoy = gdp / gdp.shift(4) - 1
print((pd.DataFrame({"annualized": gdp_saar, "year_on_year": gdp_yoy}).tail(4) * 100).round(1).to_string())
                  annualized  year_on_year
observation_date                          
2025-10-01               0.2           2.0
2026-01-01               2.5           2.6
2026-04-01               2.2           2.2
2026-07-01               4.3           2.3

Third-quarter growth comes out at 4.3%, the 4.3 percent in the BEA’s second estimate of 25 November 2026. Year on year, real GDP grew 2.3%.

Step 5: add Alphabet’s revenue from SEC XBRL

The company panel uses the SEC’s companyfacts API, the same call as in the SEC EDGAR API tutorial. Alphabet is a good test because its revenue tag moved. Its filings carry total revenue under Revenues in some years and under RevenueFromContractWithCustomerExcludingAssessedTax in others, so the function reads both. The 10-K facts in this data cover the full year only, so the fourth quarter is the year minus the first three.

# The SEC asks every automated request to identify itself. Set your own contact first:
#   export SEC_USER_AGENT="Your Name you@example.com"
HEADERS = {"User-Agent": os.environ["SEC_USER_AGENT"]}
CONCEPTS = ["Revenues", "RevenueFromContractWithCustomerExcludingAssessedTax"]


def company_facts(ticker):
    """Company-wide XBRL facts (standard taxonomies) a company has filed with the SEC."""
    tickers = requests.get("https://www.sec.gov/files/company_tickers.json", headers=HEADERS, timeout=30).json()
    cik = next(v["cik_str"] for v in tickers.values() if v["ticker"] == ticker)
    url = f"https://data.sec.gov/api/xbrl/companyfacts/CIK{cik:010d}.json"
    return requests.get(url, headers=HEADERS, timeout=30).json()


def quarterly_revenue(facts):
    """Calendar-quarter revenue from either revenue tag; Q4 is the 10-K year minus the first nine months."""
    rows = []
    for c in CONCEPTS:
        df = pd.DataFrame(facts["facts"]["us-gaap"][c]["units"]["USD"]).assign(tag=c)
        rows.append(df[df["form"].isin(["10-Q", "10-K"])])
    df = pd.concat(rows)
    df["end"] = pd.to_datetime(df["end"])
    df["days"] = (df["end"] - pd.to_datetime(df["start"])).dt.days
    tags = df.groupby(["start", "end"])["tag"].agg(lambda t: "both tags" if t.nunique() > 1 else t.iloc[0])
    df = df.sort_values("filed").drop_duplicates(["start", "end"], keep="last")  # latest filing wins
    df["tag"] = [tags[(s, e)] for s, e in zip(df["start"], df["end"])]
    q = df[df["days"].between(80, 100)].set_index("end")[["val", "tag"]]
    for end, year in df[df["days"].between(350, 380)].set_index("end").iterrows():
        q1_q3 = q["val"][(q.index > end - pd.Timedelta(days=360)) & (q.index < end)]
        if len(q1_q3) == 3 and end not in q.index:
            q.loc[end] = [year["val"] - q1_q3.sum(), "Q4 = 10-K year minus Q1 to Q3"]
    return q.sort_index()


rev = quarterly_revenue(company_facts("GOOGL"))
year_ago = rev["val"].reindex(rev.index - pd.DateOffset(years=1)).to_numpy()
rev["yoy"] = rev["val"] / year_ago - 1  # matched by date: a missing quarter gives a blank, not a wrong ratio
print(f"{len(rev)} quarters from {rev.index[0]:%Y-%m} to {rev.index[-1]:%Y-%m}, {rev['yoy'].notna().sum()} with a year-ago match")
print(rev.tail(3).assign(val=lambda d: (d["val"] / 1e6).round(0), yoy=lambda d: (d["yoy"] * 100).round(1)).to_string())
print("quarters with lower revenue than a year earlier:", rev.index[rev["yoy"] < 0].strftime("%Y-%m").tolist())
print(rev["tag"].value_counts().to_string())

START = "2015-01-01"
fig, ax = plt.subplots(figsize=(10, 4))
colors = {"Revenues": "tab:blue", "RevenueFromContractWithCustomerExcludingAssessedTax": "tab:orange",
          "both tags": "tab:green", "Q4 = 10-K year minus Q1 to Q3": "lightgrey"}
shown = rev.loc[START:]
for tag, color in colors.items():
    part = shown[shown["tag"] == tag]
    ax.bar(part.index, part["val"] / 1e9, width=60, color=color, label=tag)
ax.set_title("Alphabet quarterly revenue, $bn, by the XBRL tag that carries it (SEC companyfacts)", loc="left")
ax.legend(fontsize=8)
plt.savefig("alphabet-revenue-xbrl-tags.png", dpi=150, bbox_inches="tight")
48 quarters from 2014-09 to 2026-09, 44 with a year-ago match
                 val       tag   yoy
end                                 
2026-03-31  109896.0  Revenues  21.8
2026-06-30  119796.0  Revenues  24.2
2026-09-30  127577.0  Revenues  24.7
quarters with lower revenue than a year earlier: ['2020-06']
tag
both tags                                              14
Revenues                                               12
Q4 = 10-K year minus Q1 to Q3                          11
RevenueFromContractWithCustomerExcludingAssessedTax    11

Third-quarter 2026 revenue comes out at $127.6 billion, the $127,577 million on the income statement in Alphabet’s 10-Q for the quarter, against $102.3 billion a year earlier. Of the 44 quarters with a year-ago match, revenue fell in one: the second quarter of 2020, the quarter that contains the April 2020 trough, by 1.7%. For a look at Alphabet’s growth prospects, see Alphabet’s growth drivers.

Alphabet's quarterly revenue from 2015 to the third quarter of 2026 in billions of US dollars, coloured by the XBRL tag that carries each quarter: Revenues only, RevenueFromContractWithCustomerExcludingAssessedTax only, both tags, or a fourth quarter derived from the 10-K year

Neither tag covers the whole history. 12 quarters exist only under Revenues, 11 only under the long tag, 14 under both, and 11 are fourth quarters built by subtraction. Ask for Revenues alone and the orange quarters go missing, scattered from 2019 to 2024. Ask for the long tag alone and you lose the blue ones at both ends. The XBRL parser post shows how to list the numeric fact tags in a filing.

Step 6: draw the dashboard

Four panels on one time axis, with the NBER recession shaded on each. GDP moves to quarter-end dates first, so GDP growth and Alphabet’s revenue growth for the same quarter share a date wherever both exist.

RECESSION = ("2020-03-01", "2020-04-30")  # NBER: peak February 2020, trough April 2020, so March and April
gdp_q = gdp_yoy.copy()
gdp_q.index = gdp_q.index + pd.offsets.QuarterEnd(0)  # FRED dates a quarter by its first day, the SEC by its last

fig, ax = plt.subplots(4, 1, figsize=(10, 11), sharex=True)
ax[0].plot(unrate.loc[START:], color="tab:blue")
ax[0].set_title("Unemployment rate, % (BLS via FRED: UNRATE)", loc="left")
ax[1].plot(sahm_now.loc[START:], color="tab:red")
ax[1].axhline(0.5, color="black", lw=0.8, ls="--")
ax[1].set_ylim(-0.5, 1.5)
ax[1].set_title("Sahm rule reading, points (0.50 = signal; the 2020 peak runs off the scale)", loc="left")
ax[2].plot(spread.loc[START:], color="tab:green", lw=0.8)
ax[2].axhline(0, color="black", lw=0.8)
ax[2].set_title("10-year minus 3-month Treasury yield, points (Fed H.15 via FRED)", loc="left")
ax[3].bar(rev.loc[START:].index, rev.loc[START:, "yoy"] * 100, width=60, color="tab:orange",
          label="Alphabet revenue, year on year (SEC XBRL)")
ax[3].plot(gdp_q.loc[START:] * 100, color="black", label="Real GDP, year on year (BEA via FRED: GDPC1)")
ax[3].axhline(0, color="black", lw=0.8)
ax[3].set_title("Growth, %", loc="left")
ax[3].legend(loc="upper left", fontsize=8)
for a in ax:
    a.axvspan(*pd.to_datetime(RECESSION), color="grey", alpha=0.3)
fig.suptitle(f"Recession dashboard, data to {spread.index[-1]:%d %B %Y} (grey: NBER recession)", x=0.01, ha="left")
fig.tight_layout()
plt.savefig("fred-recession-dashboard.png", dpi=150, bbox_inches="tight")

figures = {
    "unrate": float(unrate.dropna().iloc[-1]) / 100,
    "sahm_latest": float(sahm_now.dropna().iloc[-1]),
    "sahm_gap": 0.5 - float(sahm_now.dropna().iloc[-1]),
    "sahm_trigger": float(trigger),
    "sahm_jul24_now": float(sahm_now["2024-07-01"]),
    "unrate_jul24_now": float(unrate["2024-07-01"]) / 100,
    "sahm_max_2024": float(sahm_now.loc["2024"].max()),
    "sahm_fired_2024": len(fired.loc["2024"]),
    "spread": float(spread.iloc[-1]),
    "inversion_days": int(days[k]),
    "gdp_saar": float(gdp_saar.iloc[-1]),
    "gdp_yoy": float(gdp_yoy.iloc[-1]),
    "goog_rev_q3": float(rev["val"].iloc[-1]),
    "goog_rev_q3_prior": float(rev["val"].shift(4).iloc[-1]),
    "goog_yoy_q3": float(rev["yoy"].iloc[-1]),
    "goog_yoy_q2_2020": -float(rev.loc["2020-06-30", "yoy"]),
    "goog_quarters": int(rev["yoy"].notna().sum()),
    "tag_revenues_only": int((rev["tag"] == "Revenues").sum()),
    "tag_rfcc_only": int((rev["tag"] == CONCEPTS[1]).sum()),
    "tag_both": int((rev["tag"] == "both tags").sum()),
    "q4_derived": int(rev["tag"].str.startswith("Q4").sum()),
    "dgs_blank": int(data["DGS10"].isna().sum()),
}

What can go wrong

Blank rows. Daily series can have blank rows on weekdays with no published value, and monthly ones can have a gap like October 2025. pd.to_numeric(..., errors="coerce") turns anything that isn’t a number into NaN, and then you decide what each calculation does with it. A rolling window with the default settings returns NaN for every window that touches the gap. For a 12-month minimum that blanks more than a year of Sahm readings.

Dates that mean different things. FRED dates a month or a quarter by its first day, so 2026-07-01 in GDPC1 is the third quarter. SEC facts are dated by the period’s last day, 2026-09-30 for the same quarter. An exact-date join between the two finds no matches at all. Put both on one quarterly key first, as Step 6 does with quarter-end dates.

Positional shifts. shift(4) compares with whatever sits four rows up. Alphabet’s data has no fourth quarter of 2014, so a positional year-on-year rate for the fourth quarter of 2015 would divide by the third quarter of 2014. The code matches each quarter to the date a year earlier instead.

Licences. FRED’s terms of use say series can be owned by third parties and subject to copyright. Check the tag on each series page before you publish a chart, as with USREC above.

The endpoint. fredgraph.csv isn’t one of the endpoints in the FRED API documentation. If it changes, swap the body of fred() for an API call with a key. The rest of the code only sees a pandas Series.

What to watch

The BEA’s next GDP release is due on 23 December 2026, according to its GDP page, and it can move the 4.3% third-quarter rate. On the labour side, a three-month average of 4.63% is the level that would put the Sahm rule at 0.50. Alphabet filed its 10-K for 2025 on 5 February 2026. When the 10-K for 2026 arrives, the code falls back to subtraction again if the filing has no standalone fourth-quarter figure. Check which revenue tag it uses before you rerun Step 5.

For weekly labour data to sit next to the monthly unemployment rate, the jobless claims tutorial pulls initial claims from FRED.

My longer company research is published on the newsletter Sector Playbook, which is available by email subscription.

Sources

FRED series pages: UNRATE, DGS10, DGS3MO, GDPC1, and USREC; Claudia Sahm, Direct Stimulus Payments to Individuals (Hamilton Project, 2019; Sahm rule definition); ALFRED; FRED API documentation and terms of use; fredapi on PyPI. Federal Reserve, H.15 Selected Interest Rates (release of 30 November 2026). U.S. Bureau of Economic Analysis, Gross Domestic Product (second estimate for the third quarter of 2026). U.S. Bureau of Labor Statistics, The Employment Situation, November 2025. NBER, Business Cycle Dating. U.S. Bureau of Labor Statistics, The Employment Situation, July 2024. Alphabet Inc., Form 10-Q for the quarter ended 30 September 2026 and Form 10-K for 2025; SEC companyfacts API.

*Time: 20 minutes. Python 3.12.14, matplotlib 3.11.2, pandas 3.1.0, requests 2.34.2. API key: none. FRED’s CSV download needs no account, and the SEC’s API needs no key but asks automated clients to identify themselves in the User-Agent and to send no more than 10 requests per second (SEC webmaster FAQ). Tested 1 December 2026.*

Disclaimer

Disclosure: I hold long GOOGL shares. I also hold diversified funds (IWDA, QQQ, SPY, VWRL) that may include GOOGL. Positions checked on 1 December 2026.

This article is general information about a listed company, written for educational purposes. It is not investment advice and not a personal recommendation to buy, sell or hold any security, and it does not take into account anyone’s financial situation or objectives. I am not a registered investment adviser or a licensed financial services provider. Figures come from company filings and the other sources linked in the text, as of the dates given, and may have changed since. I may hold positions in the securities discussed; see the disclosure above. Investment decisions call for independent research or the advice of a licensed professional.

This is my own research, done with the help of AI tools.

This post contains no affiliate links.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.