"""llm-time-series-forecasting-baselines.py - the baselines any forecasting claim on macro data has to beat, run on four FRED series twice: once with only the data that existed before each number was first published (real time), once on today's revised series (the way a downloaded benchmark is usually built). Data : ALFRED vintages (St. Louis Fed archive; public-domain BLS/BEA series), one wide CSV per series: observation_date, then one column per vintage named _YYYYMMDD (blank = not yet published) Shipped as datasets/llm-time-series-forecasting-claims-vintages-.csv (every vintage dated 2010-01-01 to the newest at retrieval, observations from 2000). They are refreshed with the site's revision tracker, which saves every ALFRED response it receives; this script makes no network request. Series : PAYEMS -> monthly change (thousands); UNRATE -> level (percent); CPIAUCSL -> month-on-month change (percent); GDPC1 -> annualised quarterly growth (percent). Each measure is computed inside one vintage. Design (fixed before any statistic was computed; the plan is quoted in the article): target t every observation from 2012-01 (2012Q1) whose first print is in the file real time history = the newest vintage dated before t's first print; scored against that first print revised history = the latest vintage, cut at the same last observation; scored against the latest value window the last 120 defined values (40 for GDPC1); horizon h = periods from the last value to t methods naive (last value); mean (last 12 values, 4 for GDPC1); ses (simple exponential smoothing, alpha on a 0.05 grid chosen by in-window one-step squared error); ar1 (OLS AR(1) with intercept, iterated h) metrics MAE in the series' units; MASE = mean of |error| / s, s = mean absolute first difference of the window eval windows A = all targets; B = targets dated 2020-01..2021-12 removed Output : prints the article's tables; with --csv writes one row per series x setting x window x method. Run : python code/llm-time-series-forecasting-baselines.py [--vintages DIR] [--prefix P] [--csv OUT] Needs : Python 3.13 standard library only. Nothing here is a forecast for use or investment advice. """ from __future__ import annotations import argparse import csv import statistics import sys from pathlib import Path ROOT = Path(__file__).resolve().parent.parent SERIES = {"PAYEMS": ("change_k", 1, 120, 12), "UNRATE": ("level_pct", 1, 120, 12), "CPIAUCSL": ("mom_pct", 1, 120, 12), "GDPC1": ("saar_pct", 3, 40, 4)} UNITS = {"PAYEMS": "thousand jobs", "UNRATE": "points", "CPIAUCSL": "points", "GDPC1": "points"} START = "2012-01-01" PANDEMIC = ("2020-01-01", "2021-12-01") METHODS = ("naive", "mean", "ses", "ar1") def load(path: Path) -> tuple[list[str], list[str], dict[str, dict[str, float]]]: with open(path, encoding="utf-8", newline="") as f: rows = list(csv.reader(f)) vint = [f"{h[-8:-4]}-{h[-4:-2]}-{h[-2:]}" for h in rows[0][1:]] data: dict[str, dict[str, float]] = {v: {} for v in vint} for r in rows[1:]: for v, x in zip(vint, r[1:]): if x != "": data[v][r[0]] = float(x) return [r[0] for r in rows[1:]], vint, data def shift(d: str, months: int) -> str: y, m = int(d[:4]), int(d[5:7]) + months while m < 1: m += 12 y -= 1 while m > 12: m -= 12 y += 1 return f"{y:04d}-{m:02d}-01" def measure(kind: str, step: int, col: dict[str, float], o: str) -> float | None: if kind == "level_pct": return col.get(o) a, b = col.get(o), col.get(shift(o, -step)) if a is None or b is None: return None if kind == "change_k": return a - b if kind == "mom_pct": return 100 * (a / b - 1) return 100 * ((a / b) ** 4 - 1) def forecast(hist: list[float], h: int, n_mean: int) -> dict[str, float]: out = {"naive": hist[-1], "mean": statistics.fmean(hist[-n_mean:])} best = None for i in range(1, 21): alpha = i / 20 level, sse = hist[0], 0.0 for y in hist[1:]: sse += (y - level) ** 2 level += alpha * (y - level) if best is None or sse < best[0] - 1e-12: best = (sse, level) out["ses"] = best[1] x, y = hist[:-1], hist[1:] mx, my = statistics.fmean(x), statistics.fmean(y) sxx = sum((a - mx) ** 2 for a in x) phi = sum((a - mx) * (b - my) for a, b in zip(x, y)) / sxx if sxx else 0.0 c = my - phi * mx f = hist[-1] for _ in range(h): f = c + phi * f out["ar1"] = f return out def run(series: str, vdir: Path, prefix: str) -> tuple[list[dict], dict]: kind, step, win, n_mean = SERIES[series] obs, vint, data = load(vdir / f"{prefix}{series}.csv") latest = vint[-1] meas = {v: {} for v in vint} for v in vint: for o in obs: x = measure(kind, step, data[v], o) if x is not None: meas[v][o] = x recs = [] for t in obs: if t < START: continue firsts = [v for v in vint if t in meas[v]] if not firsts or firsts[0] == vint[0] or t not in meas[latest]: continue fv = firsts[0] dv = max(v for v in vint if v < fv) rt_obs = [o for o in obs if o < t and o in meas[dv]] last = rt_obs[-1] h = (int(t[:4]) * 12 + int(t[5:7]) - int(last[:4]) * 12 - int(last[5:7])) // step rv_obs = [o for o in obs if o <= last and o in meas[latest]] rec = {"t": t, "first_vintage": fv, "decision_vintage": dv, "h": h, "first": meas[fv][t], "latest": meas[latest][t]} for setting, v, olist, truth in (("real_time", dv, rt_obs, rec["first"]), ("revised", latest, rv_obs, rec["latest"])): hist = [meas[v][o] for o in olist][-win:] s = statistics.fmean(abs(b - a) for a, b in zip(hist, hist[1:])) for m, f in forecast(hist, h, n_mean).items(): rec[f"{setting}_{m}_err"] = f - truth rec[f"{setting}_{m}_scaled"] = abs(f - truth) / s recs.append(rec) return recs, {"latest_vintage": latest, "n_vintages": len(vint), "first_vintage_in_file": vint[0]} def summarise(recs: list[dict], window: str) -> dict: sel = [r for r in recs if window == "A_all" or not (PANDEMIC[0] <= r["t"] <= PANDEMIC[1])] out = {"n": len(sel), "rev_mae": statistics.fmean(abs(r["latest"] - r["first"]) for r in sel), "span": f"{sel[0]['t'][:7]} to {sel[-1]['t'][:7]}", "h_gt_1": sum(1 for r in sel if r["h"] > 1)} for setting in ("real_time", "revised"): for m in METHODS: out[(setting, m, "mae")] = statistics.fmean(abs(r[f"{setting}_{m}_err"]) for r in sel) out[(setting, m, "mase")] = statistics.fmean(r[f"{setting}_{m}_scaled"] for r in sel) return out def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--vintages", type=Path, default=ROOT / "datasets") ap.add_argument("--prefix", default="llm-time-series-forecasting-claims-vintages-") ap.add_argument("--csv", type=Path) a = ap.parse_args() rows = [] for series in SERIES: recs, info = run(series, a.vintages, a.prefix) print(f"\n## {series} ({SERIES[series][0]}): {info['n_vintages']} vintages {info['first_vintage_in_file']} " f"to {info['latest_vintage']}") for window in ("B_ex_pandemic", "A_all"): S = summarise(recs, window) print(f"\nwindow {window}: {S['n']} targets, {S['span']}; {S['h_gt_1']} with horizon > 1; " f"mean |latest - first print| = {S['rev_mae']:.4f}") print("| method | MAE real time | MASE real time | MAE revised | MASE revised |") print("|---|---|---|---|---|") for m in METHODS: print(f"| {m} | {S[('real_time', m, 'mae')]:.4f} | {S[('real_time', m, 'mase')]:.3f} | " f"{S[('revised', m, 'mae')]:.4f} | {S[('revised', m, 'mase')]:.3f} |") for setting in ("real_time", "revised"): rows.append({"series": series, "measure": SERIES[series][0], "window": window, "setting": setting, "method": m, "targets": S["n"], "span": S["span"], "mae": round(S[(setting, m, "mae")], 6), "mase": round(S[(setting, m, "mase")], 6), "mean_abs_revision": round(S["rev_mae"], 6), "latest_vintage": info["latest_vintage"]}) for setting in ("real_time", "revised"): best = min(METHODS, key=lambda m: S[(setting, m, "mase")]) print(f"best by MASE, {setting}: {best}") print("MAE revised vs real time: " + ", ".join( f"{m} {100 * (S[('revised', m, 'mae')] / S[('real_time', m, 'mae')] - 1):+.1f}%" for m in METHODS)) print(f"mean |revision| as a share of the real-time MAE: naive " f"{100 * S['rev_mae'] / S[('real_time', 'naive', 'mae')]:.0f}%, best " f"{100 * S['rev_mae'] / min(S[('real_time', m, 'mae')] for m in METHODS):.0f}%") if a.csv: with open(a.csv, "w", encoding="utf-8", newline="") as f: w = csv.DictWriter(f, fieldnames=list(rows[0]), lineterminator="\n") w.writeheader() w.writerows(rows) print(f"\nwrote {a.csv} ({len(rows)} rows)") if __name__ == "__main__": sys.stdout.reconfigure(encoding="utf-8") main()