"""fredgraph-csv-parameters.py - FRED's keyless CSV URL (fredgraph.csv) tested one parameter at a time. What it does: sends the fixed list of requests in PROBES to https://fred.stlouisfed.org/graph/fredgraph.csv?, one every 3 seconds (FRED's robots.txt asks for a 1-second crawl delay, ALFRED's for 2), saves every response byte for byte as /.csv plus an index /probes.json (URL, HTTP status, content type, bytes, sha256, UTC fetch time), then reads the saved files and prints what each parameter did, with the checks that prove it (for example: a monthly average recomputed from the daily file, a change column recomputed from the level column). Run : python code/fredgraph-csv-parameters.py --download DIR # live: fetch, save, then report python code/fredgraph-csv-parameters.py --offline DIR # report from a saved run only add --csv datasets/fredgraph-csv-parameters.csv to write the one-row-per-request summary. Inputs : public-domain series only: DGS10, DGS2 and T10Y2Y (Board of Governors H.15 / FRED), PAYEMS (BLS), GDPC1 (BEA), CPIAUCSL (BLS). Cite each as https://fred.stlouisfed.org/series/ with the fetch date. Notes : fredgraph.csv has no published reference page; the results describe what the endpoint did on the day of the run, nothing more. User-Agent: an honest research string with no personal contact. Needs : Python 3.13 standard library only. """ from __future__ import annotations import argparse import csv import datetime as dt import hashlib import io import json import math import statistics import sys import time import urllib.error import urllib.request from pathlib import Path BASE = "https://fred.stlouisfed.org/graph/fredgraph.csv?" UA = "prismdatalab-research/1.0 (site research; robots-first)" # name -> query string. The order is the order of the table in the article. PROBES = { "plain": "id=DGS10", "cosd": "id=DGS10&cosd=2026-01-01", "coed": "id=DGS10&coed=1962-12-31", "window": "id=DGS10&cosd=2026-01-01&coed=2026-03-31", "reversed": "id=DGS10&cosd=2026-03-31&coed=2026-01-01", "cosd_nodash": "id=DGS10&cosd=20260101", "fq_m": "id=DGS10&cosd=2025-01-01&coed=2025-12-31&fq=Monthly", "fq_m_avg": "id=DGS10&cosd=2025-01-01&coed=2025-12-31&fq=Monthly&fam=avg", "fq_m_eop": "id=DGS10&cosd=2025-01-01&coed=2025-12-31&fq=Monthly&fam=eop", "fq_m_sum": "id=DGS10&cosd=2025-01-01&coed=2025-12-31&fq=Monthly&fam=sum", "fq_w": "id=DGS10&cosd=2026-01-01&coed=2026-03-31&fq=Weekly,%20Ending%20Friday&fam=avg", "fq_a": "id=DGS10&cosd=2016-01-01&coed=2025-12-31&fq=Annual&fam=avg", "fq_up": "id=GDPC1&cosd=2025-01-01&fq=Monthly", "fq_bad": "id=DGS10&cosd=2026-01-01&coed=2026-03-31&fq=Fortnightly", "tr_chg": "id=PAYEMS&cosd=2025-01-01&coed=2025-12-01&transformation=chg", "tr_pch": "id=CPIAUCSL&cosd=2025-01-01&coed=2025-12-01&transformation=pch", "tr_pc1": "id=CPIAUCSL&cosd=2025-01-01&coed=2025-12-01&transformation=pc1", "tr_log": "id=CPIAUCSL&cosd=2025-01-01&coed=2025-12-01&transformation=log", "tr_bad": "id=CPIAUCSL&cosd=2025-01-01&coed=2025-12-01&transformation=xyz", "cpi_level": "id=CPIAUCSL&cosd=2024-01-01&coed=2025-12-01", "payems_level": "id=PAYEMS&cosd=2024-12-01&coed=2025-12-01", "fgst_chg": "id=PAYEMS&cosd=2025-01-01&coed=2025-12-01&fgst=chg", "vintage": "id=PAYEMS&cosd=2026-01-01&vintage_date=2026-09-04", "payems_2026": "id=PAYEMS&cosd=2026-01-01", "multi": "id=DGS10,DGS2&cosd=2026-09-01&coed=2026-09-30", "multi_cosd": "id=DGS10,PAYEMS&cosd=2026-09-01,2025-01-01&coed=2026-09-30,2025-03-01", "multi_paired": "id=DGS10,DGS2&cosd=2026-09-01,2025-01-01&coed=2026-09-30,2025-01-31", "mixed_freq": "id=DGS10,PAYEMS&cosd=2026-09-01&coed=2026-09-30", "fml": "id=DGS10,DGS2&cosd=2026-09-01&coed=2026-09-30&fml=a-b", "t10y2y": "id=T10Y2Y&cosd=2026-09-01&coed=2026-09-30", "lower": "id=dgs10&cosd=2026-09-01&coed=2026-09-30", "bad_id": "id=NOTASERIES123", # the same vintage asked of ALFRED, the archive that does honour vintage_date (robots.txt: Crawl-delay 2) "alfred_0904": "https://alfred.stlouisfed.org/graph/alfredgraph.csv?id=PAYEMS&cosd=2026-01-01&vintage_date=2026-09-04", } def url_of(qs: str) -> str: return qs if qs.startswith("https://") else BASE + qs # ------------------------------------------------------------------ fetch --- def download(out: Path) -> None: out.mkdir(parents=True, exist_ok=True) idx_path = out / "probes.json" idx = json.loads(idx_path.read_text(encoding="utf-8")) if idx_path.exists() else {} for name, qs in PROBES.items(): if name in idx: continue url = url_of(qs) req = urllib.request.Request(url, headers={"User-Agent": UA, "Accept": "text/csv,*/*"}) try: with urllib.request.urlopen(req, timeout=120) as r: st, ct, body = r.status, r.headers.get("Content-Type"), r.read() except urllib.error.HTTPError as e: st, ct, body = e.code, e.headers.get("Content-Type"), e.read() (out / f"{name}.csv").write_bytes(body) idx[name] = {"url": url, "status": st, "content_type": ct, "bytes": len(body), "sha256": hashlib.sha256(body).hexdigest(), "user_agent": UA, "fetched_utc": dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")} idx_path.write_text(json.dumps(idx, indent=1), encoding="utf-8") print(f" {name}: HTTP {st}, {len(body):,} bytes", file=sys.stderr) time.sleep(3) # ------------------------------------------------------------------- read --- class Resp: def __init__(self, d: Path, name: str, meta: dict): self.name, self.meta = name, meta raw = (d / f"{name}.csv").read_bytes() if hashlib.sha256(raw).hexdigest() != meta["sha256"]: sys.exit(f"{name}: saved file does not match its sha256 in probes.json") self.members: dict[str, str] = {} if raw[:2] == b"PK": import zipfile z = zipfile.ZipFile(io.BytesIO(raw)) self.members = {n: z.read(n).decode("utf-8") for n in z.namelist()} self.text = "" if self.members else raw.decode("utf-8", "replace") self.is_csv = self.text.startswith("observation_date") rows = list(csv.reader(io.StringIO(self.text))) if self.is_csv else [] self.header = rows[0] if rows else [] self.rows = [r for r in rows[1:] if r] def col(self, i: int = 1) -> dict[str, float | None]: return {r[0]: (None if r[i] in (".", "") else float(r[i])) for r in self.rows} @property def span(self) -> str: return f"{self.rows[0][0]} to {self.rows[-1][0]}" if self.rows else "no rows" def close(a: float, b: float, tol: float) -> bool: return a is not None and b is not None and abs(a - b) <= tol def report(d: Path, csv_out: Path | None) -> None: idx = json.loads((d / "probes.json").read_text(encoding="utf-8")) R = {n: Resp(d, n, idx[n]) for n in PROBES} fetched = sorted(m["fetched_utc"] for m in idx.values()) print(f"{len(R)} requests, fetched {fetched[0]} to {fetched[-1]} UTC\n") find: dict[str, str] = {} plain = R["plain"] daily = plain.col() n_dot = sum(1 for r in plain.rows if r[1] == ".") n_empty = sum(1 for r in plain.rows if r[1] == "") find["plain"] = (f"{len(plain.rows):,} rows, {plain.span}; {n_empty:,} empty values, {n_dot:,} written as '.'; " f"{plain.meta['bytes']:,} bytes") for n in ("cosd", "coed", "window", "reversed", "cosd_nodash"): r = R[n] same_plain = r.meta["sha256"] == plain.meta["sha256"] find[n] = f"{len(r.rows):,} rows, {r.span}" + ("; identical to the plain file" if same_plain else "") # frequency aggregation, recomputed from the plain daily file by_month: dict[str, list[float]] = {} for k, v in daily.items(): if "2025-01-01" <= k <= "2025-12-31" and v is not None: by_month.setdefault(k[:7], []).append(v) avg = {m: statistics.fmean(v) for m, v in by_month.items()} eop = {m: v[-1] for m, v in by_month.items()} tot = {m: math.fsum(v) for m, v in by_month.items()} for n, ref, label in (("fq_m", avg, "mean"), ("fq_m_avg", avg, "mean"), ("fq_m_eop", eop, "last value"), ("fq_m_sum", tot, "sum")): got = {k[:7]: v for k, v in R[n].col().items()} ok = sum(1 for m in ref if close(got.get(m), ref[m], 0.00501)) find[n] = f"{len(R[n].rows)} rows; {ok} of {len(ref)} months equal the daily {label} (to the 2 decimals printed)" w = R["fq_w"] ok_full, odd = 0, [] for k, v in w.col().items(): end = dt.date.fromisoformat(k) week = [(end - dt.timedelta(days=i)).isoformat() for i in range(6, -1, -1)] full = [daily[d] for d in week if daily.get(d) is not None] clip = [daily[d] for d in week if daily.get(d) is not None and "2026-01-01" <= d <= "2026-03-31"] if full and close(v, statistics.fmean(full), 0.00501): ok_full += 1 else: how = "the in-window days only" if clip and close(v, statistics.fmean(clip), 0.00501) else "neither" odd.append(f"{k} = {how}") first_wk = dt.date.fromisoformat(w.rows[0][0]).strftime("%A") if w.rows else "-" find["fq_w"] = (f"{len(w.rows)} rows, {w.span}, all dated on {first_wk}s; {ok_full} of {len(w.rows)} equal the mean " f"of the seven days ending on the row's date" + (f"; {', '.join(odd)}" if odd else "")) a = R["fq_a"] yr: dict[str, list[float]] = {} for k, v in daily.items(): if "2016-01-01" <= k <= "2025-12-31" and v is not None: yr.setdefault(k[:4], []).append(v) ok_a = sum(1 for k, v in a.col().items() if close(v, statistics.fmean(yr[k[:4]]), 0.00501)) find["fq_a"] = f"{len(a.rows)} rows, {a.span}; {ok_a} of {len(a.rows)} equal the calendar-year daily mean" up = R["fq_up"] find["fq_up"] = (f"HTTP {up.meta['status']}; " + (f"{len(up.rows)} rows, {up.span}, header {up.header}" if up.is_csv else f"not a CSV ({up.meta['bytes']:,} bytes)")) fb = R["fq_bad"] find["fq_bad"] = (f"HTTP {fb.meta['status']}; " + (f"{len(fb.rows)} rows, {fb.span}" + ("; identical to the window request" if fb.meta["sha256"] == R["window"].meta["sha256"] else "") if fb.is_csv else f"not a CSV ({fb.meta['bytes']:,} bytes)")) # transformations, recomputed from level requests pay = R["payems_level"].col() cpi = R["cpi_level"].col() months25 = [f"2025-{m:02d}-01" for m in range(1, 13)] def prev(k: str, n: int) -> str: y, m = int(k[:4]), int(k[5:7]) - n while m < 1: m += 12 y -= 1 return f"{y:04d}-{m:02d}-01" def check(n: str, f) -> str: got = R[n].col() pairs = [(got.get(k), f(k)) for k in months25] usable = [(g, e) for g, e in pairs if g is not None and e is not None] ok = sum(1 for g, e in usable if close(g, e, 0.0051 if abs(e) < 50 else 0.51)) return f"header {R[n].header[1] if len(R[n].header) > 1 else '-'}; {ok} of {len(usable)} months match" def safe(fn): def g(k): try: return fn(k) except (TypeError, ZeroDivisionError): return None return g find["tr_chg"] = check("tr_chg", safe(lambda k: pay[k] - pay[prev(k, 1)])) + " the level differences" find["tr_pch"] = check("tr_pch", safe(lambda k: 100 * (cpi[k] / cpi[prev(k, 1)] - 1))) + " 100*(x/x[-1]-1)" find["tr_pc1"] = check("tr_pc1", safe(lambda k: 100 * (cpi[k] / cpi[prev(k, 12)] - 1))) + " 100*(x/x[-12]-1)" find["tr_log"] = (check("tr_log", safe(lambda k: round(math.log(cpi[k]), 1))) + " ln(x) rounded to 1 dp; " + check("tr_log", safe(lambda k: math.log(cpi[k]))).split("; ")[1] + " unrounded ln(x)") tb = R["tr_bad"] lvl25 = {k: v for k, v in cpi.items() if k >= "2025-01-01"} same_lvl = tb.is_csv and all(close(tb.col().get(k), v, 1e-9) for k, v in lvl25.items() if v is not None) find["tr_bad"] = (f"HTTP {tb.meta['status']}; header {tb.header}; " + ("the plain levels" if same_lvl else "not the plain levels")) fg = R["fgst_chg"] pay25 = {k: v for k, v in pay.items() if k >= "2025-01-01"} fg_lvl = fg.is_csv and all(close(fg.col().get(k), v, 1e-9) for k, v in pay25.items() if v is not None) same_chg = fg.is_csv and fg.col() == R["tr_chg"].col() find["fgst_chg"] = (f"header {fg.header}; " + ("ignored: the plain levels" if fg_lvl else ("the transformation=chg values under the plain header" if same_chg else "changed the values"))) find["cpi_level"] = f"{len(R['cpi_level'].rows)} rows, {R['cpi_level'].span}; " + ( "blank: " + ", ".join(k[:7] for k, x in cpi.items() if x is None) if None in cpi.values() else "no blanks") find["payems_level"] = f"{len(R['payems_level'].rows)} rows, {R['payems_level'].span} (reference for chg)" find["payems_2026"] = f"{len(R['payems_2026'].rows)} rows, {R['payems_2026'].span} (today's file, for the vintage test)" # vintage_date on fredgraph, compared with today's file and with ALFRED's copy of that vintage v, now, alf = R["vintage"].col(), R["payems_2026"].col(), R["alfred_0904"].col(1) same_now = R["vintage"].meta["sha256"] == R["payems_2026"].meta["sha256"] dif_alf = [k for k in v if k in alf and v[k] != alf[k]] find["vintage"] = (f"header {R['vintage'].header}; {len(v)} rows to {R['vintage'].rows[-1][0] if v else '-'}; " + ("byte-identical to the same request without vintage_date; " if same_now else "") + f"differs from ALFRED's 2026-09-04 vintage in {len(dif_alf)} month(s)" + (": " + ", ".join(f"{k[:7]} {v[k]:,.0f} vs {alf[k]:,.0f}" for k in dif_alf) if dif_alf else "") + f"; ALFRED's vintage ends {R['alfred_0904'].rows[-1][0][:7]}, fredgraph's {R['vintage'].rows[-1][0][:7]}") find["alfred_0904"] = f"header {R['alfred_0904'].header}; {len(alf)} rows, {R['alfred_0904'].span}" def multi_desc(r: Resp) -> str: if r.members: parts = [] for n_, txt in r.members.items(): if n_.endswith(".csv"): rr = [x for x in csv.reader(io.StringIO(txt)) if x] parts.append(f"{n_} ({rr[0][1]}, {len(rr) - 1} rows, {rr[1][0]} to {rr[-1][0]})") else: parts.append(n_) return f"a ZIP archive ({r.meta['content_type']}) holding " + ", ".join(parts) cols = [r.col(i) for i in range(1, len(r.header))] fill = [f"{h} {sum(1 for x in c.values() if x is not None):,} values, " f"{min((k for k, x in c.items() if x is not None), default='-')} to " f"{max((k for k, x in c.items() if x is not None), default='-')}" for h, c in zip(r.header[1:], cols)] return f"one CSV, {len(r.rows):,} rows, {r.span}; " + "; ".join(fill) for n in ("multi", "multi_cosd", "multi_paired", "mixed_freq"): find[n] = multi_desc(R[n]) fm, t = R["fml"], R["t10y2y"].col() d10, d2 = R["multi"].col(1), R["multi"].col(2) sept = [k for k in t if t[k] is not None and d10.get(k) is not None and d2.get(k) is not None] eq = sum(1 for k in sept if close(round(d10[k] - d2[k], 2), t[k], 0.005)) find["fml"] = (("ignored: byte-identical to the request without fml" if fm.meta["sha256"] == R["multi"].meta["sha256"] else f"header {fm.header}; {len(fm.rows):,} rows") + f" (for the record, DGS10 minus DGS2 equals T10Y2Y on {eq} of {len(sept)} September days)") find["t10y2y"] = f"{len(R['t10y2y'].rows)} rows, {R['t10y2y'].span}" lo = R["lower"] find["lower"] = f"HTTP {lo.meta['status']}; header {lo.header}; {len(lo.rows)} rows" bi = R["bad_id"] find["bad_id"] = (f"HTTP {bi.meta['status']}, {bi.meta['content_type']}, {bi.meta['bytes']:,} bytes; " + ("a CSV" if bi.is_csv else f"starts {bi.text[:40]!r}")) print("| request | HTTP | first line | finding |") print("|---|---|---|---|") out_rows = [] for n, qs in PROBES.items(): r = R[n] first = r.text.splitlines()[0][:60] if r.text else ("(zip) " + ", ".join(r.members) if r.members else "") print(f"| `{qs}` | {r.meta['status']} | `{first}` | {find[n]} |") out_rows.append({"name": n, "query": qs, "http_status": r.meta["status"], "content_type": r.meta["content_type"], "bytes": r.meta["bytes"], "sha256": r.meta["sha256"], "fetched_utc": r.meta["fetched_utc"], "header": "|".join(r.header), "rows": len(r.rows), "first_date": r.rows[0][0] if r.rows else "", "last_date": r.rows[-1][0] if r.rows else "", "finding": find[n]}) if csv_out: with open(csv_out, "w", encoding="utf-8", newline="") as f: wr = csv.DictWriter(f, fieldnames=list(out_rows[0]), lineterminator="\n") wr.writeheader() wr.writerows(out_rows) print(f"\nwrote {csv_out} ({len(out_rows)} rows)") def main() -> None: ap = argparse.ArgumentParser() g = ap.add_mutually_exclusive_group(required=True) g.add_argument("--download", type=Path, help="fetch every probe into DIR (cached), then report") g.add_argument("--offline", type=Path, help="report from a saved DIR") ap.add_argument("--csv", type=Path) a = ap.parse_args() if a.download: download(a.download) report(a.download or a.offline, a.csv) if __name__ == "__main__": sys.stdout.reconfigure(encoding="utf-8") main()