"""sahm-rule-real-time.py - the Sahm rule as it read on each jobs-report day since January 2010, recomputed from the unemployment rate exactly as published that day (one ALFRED vintage at a time), against the same months computed from the newest vintage and against FRED's real-time series SAHMREALTIME. Inputs : datasets/llm-time-series-forecasting-claims-vintages-UNRATE.csv (every ALFRED vintage of UNRATE dated 2010-01-08 to 2026-10-02, 202 columns, retrieved 2026-10-30) datasets/sahm-rule-real-time.csv (kind=unrate_vintage: the vintage of 2026-11-06, from alfredgraph.csv; kind=sahmrealtime: SAHMREALTIME from fredgraph.csv; both retrieved 2026-11-14) datasets/sahm-rule-unemployment-recessions.csv (SAHMREALTIME as retrieved 2026-09-05, to check that the published real-time history did not change) Rules : three-month average = mean of the months present among t, t-1, t-2 when at least two are present (the same min_periods=2 choice as sahm-rule-unemployment-recessions.py; only October 2025 is missing); Sahm(t) = average(t) - lowest average over t-1 .. t-12 (at least 11 of the 12 present); the rule fires when Sahm(t) >= 0.50. Exact fractions; printed values rounded half up to two decimals, which is how SAHMREALTIME is published. "Real time" = Sahm(t) computed inside the vintage that first published month t (the release day). "Newest" = Sahm(t) computed inside the vintage of 2026-11-06. Output : Markdown tables and the counts quoted in the article. Run : python code/sahm-rule-real-time.py Needs : Python 3.13 standard library only. Makes no network request. """ import csv from fractions import Fraction OLD = "datasets/llm-time-series-forecasting-claims-vintages-UNRATE.csv" NEW = "datasets/sahm-rule-real-time.csv" SEP = "datasets/sahm-rule-unemployment-recessions.csv" HALF = Fraction(1, 2) def back(m, k): y, mo = int(m[:4]), int(m[5:7]) - k while mo < 1: mo += 12 y -= 1 return f"{y:04d}-{mo:02d}" def r2(x): """half up to two decimals, as a string; exact on fractions""" if x is None: return "-" t = abs(x) * 100 n = (t + HALF).__floor__() s = f"{n // 100}.{n % 100:02d}" return "-" + s if x < 0 and n else s def avg3(d, m, fill=None): xs = [d.get(back(m, k), fill.get(back(m, k)) if fill else None) for k in range(3)] xs = [x for x in xs if x is not None] return sum(xs) / len(xs) if len(xs) >= 2 else None def sahm(d, m, fill=None): a = avg3(d, m, fill) lows = [avg3(d, back(m, k), fill) for k in range(1, 13)] lows = [x for x in lows if x is not None] if a is None or len(lows) < 11: return None return a - min(lows) def load(): vint = {} with open(OLD, encoding="utf-8", newline="") as f: rows = list(csv.reader(f)) names = [h[-8:] for h in rows[0][1:]] names = [f"{v[:4]}-{v[4:6]}-{v[6:]}" for v in names] for v in names: vint[v] = {} for r in rows[1:]: for i, v in enumerate(names): if r[i + 1] not in ("", "."): vint[v][r[0][:7]] = Fraction(r[i + 1]) srt = {} with open(NEW, encoding="utf-8", newline="") as f: for r in csv.DictReader(f): if r["kind"] == "unrate_vintage": vint.setdefault(r["vintage_date"], {})[r["observation_month"]] = Fraction(r["value"]) elif r["value"] not in ("", "."): srt[r["observation_month"]] = r["value"] sep = {} with open(SEP, encoding="utf-8", newline="") as f: for r in csv.DictReader(f): if r["SAHMREALTIME"]: sep[r["date"][:7]] = r["SAHMREALTIME"] return vint, srt, sep def main(): vint, srt, sep = load() order = sorted(vint) newest = vint[order[-1]] print(f"vintages: {len(order)}, {order[0]} .. {order[-1]}") same = sum(1 for m in sep if m in srt and float(sep[m]) == float(srt[m])) print(f"SAHMREALTIME retrieved 2026-09-05 vs 2026-11-14: {same} of {len(sep)} months identical; " f"new months since: {sorted(set(srt) - set(sep))}") # 1. the first-print reading of every month, from the vintage that first published it first = {} for v in order: last = max(vint[v]) if last not in first: first[last] = (v, sahm(vint[v], last)) months = sorted(first) print(f"months read on their release day: {len(months)}, {months[0]} .. {months[-1]}") match = [m for m in months if m in srt and r2(first[m][1]) == r2(Fraction(srt[m]))] miss = [m for m in months if m in srt and m not in match] print(f"our real-time value equals SAHMREALTIME at two decimals in {len(match)} of " f"{sum(1 for m in months if m in srt)} months; differ: " + ", ".join(f"{m} ours {r2(first[m][1])} vs {srt[m]}" for m in miss)) for m in miss: d0 = vint[first[m][0]] # one input month at a time: which value, found in some other vintage, reproduces the published reading? for k in range(15, 0, -1): mk = back(m, k) for x in sorted({vint[w][mk] for w in order if mk in vint[w]} - {d0.get(mk)}): if r2(sahm({**d0, mk: x}, m)) == srt[m]: held = [w for w in order if vint[w].get(mk) == x] lo = [w for w in held if w < first[m][0]] print(f" {m}: SAHMREALTIME {srt[m]} is reproduced with {mk} at {float(x)} instead of " f"{float(d0[mk])} (the release-day vintage {first[m][0]}); {float(x)} is the value in " f"{len(held)} vintages, {len(lo)} of them earlier ({lo[0] if lo else '-'} .. {lo[-1] if lo else '-'})" f" and {len(held) - len(lo)} later ({held[len(lo)] if len(held) > len(lo) else '-'} .. {held[-1]})") # 2. real time against the newest vintage rows = [(m, first[m][1], sahm(newest, m)) for m in months] diffs = [(m, a, b, b - a) for m, a, b in rows if a is not None and b is not None] absd = [abs(d) for _, _, _, d in diffs] print(f"\nreal time vs newest vintage, {len(diffs)} months: mean abs gap {r2(sum(absd) / len(absd))}" f" ({float(sum(absd) / len(absd)):.4f}), max {r2(max(absd))} in " + ", ".join(m for m, _, _, d in diffs if abs(d) == max(absd))) for cut in (Fraction(5, 100), Fraction(1, 10)): n = sum(1 for x in absd if x >= cut) print(f" months with a gap of at least {r2(cut)}: {n}") up = sum(1 for *_, d in diffs if d > 0) dn = sum(1 for *_, d in diffs if d < 0) print(f" newest higher than release day: {up}; lower: {dn}; equal: {len(diffs) - up - dn}") fired_rt = [m for m, a, b in rows if a is not None and a >= HALF] fired_nw = [m for m, a, b in rows if b is not None and b >= HALF] print(f" months at or above 0.50 on release day: {len(fired_rt)}; on the newest vintage: {len(fired_nw)}") print(f" on release day only: {sorted(set(fired_rt) - set(fired_nw))}; newest only: {sorted(set(fired_nw) - set(fired_rt))}") for lo, hi in (("2009-12", "2019-12"), ("2020-01", "2021-12"), ("2022-01", "2026-12")): rt = [m for m in fired_rt if lo <= m <= hi] nw = [m for m in fired_nw if lo <= m <= hi] print(f" {lo}..{hi}: release day {rt[0] if rt else '-'}..{rt[-1] if rt else '-'} ({len(rt)});" f" newest {nw[0] if nw else '-'}..{nw[-1] if nw else '-'} ({len(nw)})") # 3. when a month's reading changes: which vintage moved it moves = {} for m in months: v0 = first[m][0] prev = r2(first[m][1]) for w in [w for w in order if w > v0]: cur = r2(sahm(vint[w], m)) if cur != prev: moves.setdefault(w, []).append(m) prev = cur jan = {w: ms for w, ms in moves.items() if w[5:7] == "01"} other = {w: ms for w, ms in moves.items() if w[5:7] != "01"} print(f"\nreading changes at two decimals after the release day: {sum(map(len, moves.values()))} in " f"{len(moves)} vintages; in January vintages {sum(map(len, jan.values()))} ({len(jan)} vintages);" f" in other vintages {sum(map(len, other.values()))}: " + "; ".join(f"{w} {ms}" for w, ms in sorted(other.items()))) print("| January vintage | months whose reading moved | first .. last |") print("|---|---|---|") for w, ms in sorted(jan.items()): print(f"| {w} | {len(ms)} | {ms[0]} .. {ms[-1]} |") for w in sorted(jan): p = order[order.index(w) - 1] if max(vint[w]) == max(vint[p]): # a vintage that published no new month ch = [(m, float(vint[p][m]), float(vint[w][m])) for m in sorted(vint[w]) if m >= "2000" and vint[p].get(m) != vint[w][m]] print(f" {w} published no new month; against {p} it changed: {ch}") # 4. the 2024 trigger, traced print("\n| month | release day (vintage) | " + " | ".join(f"after {w}" for w in sorted(jan) if w >= "2025") + " | newest |") print("|---|---|" + "---|" * (len([w for w in jan if w >= "2025"]) + 1)) for m in ("2024-06", "2024-07", "2024-08", "2024-09", "2024-10"): cells = [r2(sahm(vint[w], m)) for w in sorted(jan) if w >= "2025"] print(f"| {m} | {r2(first[m][1])} ({first[m][0]}) | " + " | ".join(cells) + f" | {r2(sahm(newest, m))} |") for m in ("2024-07",): print(f" {m} UNRATE by vintage: release day {float(vint[first[m][0]][m])}; " + ", ".join(f"after {w} {float(vint[w][m])}" for w in sorted(jan) if w >= "2025")) print(f" {m} newest reading exactly: {sahm(newest, m)}") print(f" {m} UNRATE: release day {float(vint[first[m][0]][m])}, newest {float(newest[m])};" f" 3-month average release day {float(avg3(vint[first[m][0]], m)):.4f}, newest {float(avg3(newest, m)):.4f}") lows = [(back(m, k), avg3(newest, back(m, k))) for k in range(1, 13)] lows0 = [(back(m, k), avg3(vint[first[m][0]], back(m, k))) for k in range(1, 13)] print(f" low of the previous 12 averages: release day {min(x for _, x in lows0):.4f} " f"({[k for k, x in lows0 if x == min(y for _, y in lows0)]}), newest {min(x for _, x in lows):.4f} " f"({[k for k, x in lows if x == min(y for _, y in lows)]})") # 5. the October 2025 gap v = first["2025-11"][0] d = vint[v] print(f"\nNovember 2025 first published in the vintage of {v}: Sep {d.get('2025-09')}, Oct {d.get('2025-10')}, " f"Nov {d.get('2025-11')}; Sahm two-month average {r2(sahm(d, '2025-11'))}") interp = {"2025-10": (d["2025-09"] + d["2025-11"]) / 2} print(f" October filled by linear interpolation: {r2(sahm(d, '2025-11', fill=interp))}; SAHMREALTIME {srt.get('2025-11')}") strict = [d.get(back("2025-11", k)) for k in range(3)] print(f" strict three-month window: {'not computable' if None in strict else 'computable'}") for w in order: if w > v and vint[w].get("2025-11") != d.get("2025-11"): print(f" November 2025 first revised in {w}: {d['2025-11']} -> {vint[w]['2025-11']};" f" Sahm {r2(sahm(vint[w], '2025-11'))}") break for m in ("2025-12",): dd = vint[first[m][0]] f2 = {"2025-10": (dd["2025-09"] + dd["2025-11"]) / 2} print(f" {m}: two-month average {r2(sahm(dd, m))}, interpolated {r2(sahm(dd, m, fill=f2))}, SAHMREALTIME {srt.get(m)}") # 6. the latest readings print("\n| month | UNRATE on release day | release day | SAHMREALTIME | newest vintage |") print("|---|---|---|---|---|") for m in months[-6:]: v = first[m][0] print(f"| {m} | {float(vint[v][m])} | {r2(first[m][1])} ({v}) | {srt.get(m, '-')} | {r2(sahm(newest, m))} |") print(f"exact release-day readings: {months[-2]} {first[months[-2]][1]}, {months[-1]} {first[months[-1]][1]}") hi = max((first[m][1], m) for m in months if m >= "2025-01") print(f"highest release-day reading since January 2025: {r2(hi[0])} in {hi[1]}") if __name__ == "__main__": main()