Files
hyperstitionstudio-core/src/hyperstitionstud_io/quant/macro.py
T

551 lines
23 KiB
Python

#!/usr/bin/env python3
"""
hyperstitionstud_io.quant.macro
Keyless St. Louis Federal Reserve (`FRED`) Macroeconomic, Monetary & Aggregate Output Collector (`hs-macro-harvest`).
Ingests real observations for CPI, PPI, US10Y, Overnight Lending Rates (EFFR/SOFR), M1, M2, M1 vs. M2 Spread,
Real M2 & Real M2 Growth, Nominal & Real GDP, and Gross Product / Aggregate Output (GNP, OUTBS, INDPRO)
with strict native-cadence preservation (`1d`, `1mo`, `1q`), zero synthetic values, `None`/`null` on missing/holiday
dates, and bidirectional Gen 0 (`eng_aq`) + Gen 1 (`ing_aq`) scoring.
"""
from __future__ import annotations
import argparse
import datetime
import json
import urllib.request
from pathlib import Path
from typing import Any
from hyperstitionstud_io import __version__ as CURRENT_VERSION
from hyperstitionstud_io.ciphers import compute_aq, int_to_spoken_words, prime_rank
from hyperstitionstud_io.config import load_workspace_config
from hyperstitionstud_io.glossary import ReadOnlyIsolationGuard
from hyperstitionstud_io.ipld import compute_dag_json_cidv1
from hyperstitionstud_io.phonetics import translate_batch
from hyperstitionstud_io.quant.collector import NO_DATA_AVAILABLE, S1_S6_SIGNATURE_RINGS
_USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64) HyperstitionStudio/2.0"
FRED_SERIES_SPEC: tuple[dict[str, Any], ...] = (
{
"series_id": "CPIAUCSL",
"slug": "cpi",
"label": "CPI (Consumer Price Index: All Urban Consumers)",
"cadence": "1mo",
"unit": "Index (1982-84=100)",
"guilds": ["S6", "S2"],
},
{
"series_id": "PPIACO",
"slug": "ppi",
"label": "PPI (Producer Price Index: All Commodities)",
"cadence": "1mo",
"unit": "Index (1982=100)",
"guilds": ["S3", "S6"],
},
{
"series_id": "DGS10",
"slug": "us10y",
"label": "US10Y (10-Year US Treasury Constant Maturity Yield)",
"cadence": "1d",
"unit": "Percent (%)",
"scale_to_bps": True,
"guilds": ["S6", "S1"],
},
{
"series_id": "EFFR",
"slug": "effr",
"label": "EFFR (Effective Federal Funds Overnight Lending Rate)",
"cadence": "1d",
"unit": "Percent (%)",
"scale_to_bps": True,
"guilds": ["S6", "S2"],
},
{
"series_id": "SOFR",
"slug": "sofr",
"label": "SOFR (Secured Overnight Financing Rate)",
"cadence": "1d",
"unit": "Percent (%)",
"scale_to_bps": True,
"guilds": ["S2", "S6"],
},
{
"series_id": "DFEDTARU",
"slug": "fed_target_upper",
"label": "Fed Funds Target Range Upper Limit",
"cadence": "1d",
"unit": "Percent (%)",
"scale_to_bps": True,
"guilds": ["S6"],
},
{
"series_id": "M1SL",
"slug": "m1",
"label": "M1 Narrow Liquid Money Stock",
"cadence": "1mo",
"unit": "Billions of Dollars ($B)",
"guilds": ["S2", "S6"],
},
{
"series_id": "M2SL",
"slug": "m2",
"label": "M2 Broad Money Supply",
"cadence": "1mo",
"unit": "Billions of Dollars ($B)",
"guilds": ["S2", "S6"],
},
{
"series_id": "M2REAL",
"slug": "real_m2",
"label": "Real M2 Money Stock (CPI-Deflated)",
"cadence": "1mo",
"unit": "Billions of 1982-84 Dollars ($B)",
"guilds": ["S2", "S6"],
},
{
"series_id": "GDP",
"slug": "gdp_nominal",
"label": "Nominal GDP (Gross Domestic Product)",
"cadence": "1q",
"unit": "Billions of Dollars ($B SAAR)",
"guilds": ["S6"],
},
{
"series_id": "GDPC1",
"slug": "gdp_real",
"label": "Real GDP (Chained 2017 Dollars)",
"cadence": "1q",
"unit": "Billions of Chained 2017 Dollars ($B SAAR)",
"guilds": ["S6"],
},
{
"series_id": "GNP",
"slug": "gnp_gross_product",
"label": "GNP (Gross National Product — Aggregate Output)",
"cadence": "1q",
"unit": "Billions of Dollars ($B SAAR)",
"guilds": ["S6", "S3"],
},
{
"series_id": "OUTBS",
"slug": "business_gross_output",
"label": "Business Sector Real Aggregate Output Index",
"cadence": "1q",
"unit": "Index (2017=100)",
"guilds": ["S3", "S6"],
},
{
"series_id": "INDPRO",
"slug": "industrial_production",
"label": "Industrial Production Index (Monthly Aggregate Output)",
"cadence": "1mo",
"unit": "Index (2017=100)",
"guilds": ["S3", "S5"],
},
)
def fetch_fred_series_csv(series_id: str, max_rows: int = 36, timeout: float = 8.0) -> list[dict[str, Any]]:
"""
Fetch real observations from `https://fred.stlouisfed.org/graph/fredgraph.csv?id=<series_id>&cosd=2024-10-01`.
Preserves missing/holiday dates explicitly as `value = None` (`data_available = False`) rather than `0.0`.
"""
url = f"https://fred.stlouisfed.org/graph/fredgraph.csv?id={series_id}&cosd=2024-10-01"
req = urllib.request.Request(url, headers={"User-Agent": _USER_AGENT})
with urllib.request.urlopen(req, timeout=timeout) as resp:
lines = [ln.strip() for ln in resp.read().decode("utf-8").splitlines() if ln.strip()]
if len(lines) <= 1:
return []
tail = lines[1:][-max_rows:]
rows: list[dict[str, Any]] = []
for ln in tail:
parts = ln.split(",", 1)
if len(parts) != 2:
continue
dt_s, val_s = parts[0].strip(), parts[1].strip()
if not val_s or val_s == ".":
rows.append({
"date_utc": dt_s,
"data_available": False,
"status": NO_DATA_AVAILABLE,
"value": None,
})
else:
try:
rows.append({
"date_utc": dt_s,
"data_available": True,
"status": "ok",
"value": round(float(val_s), 4),
})
except ValueError:
rows.append({
"date_utc": dt_s,
"data_available": False,
"status": NO_DATA_AVAILABLE,
"value": None,
})
return rows
def _score_macro_int(face_int: int, ing_map: dict[str, str]) -> dict[str, Any]:
sp_eng = int_to_spoken_words(abs(face_int))
sp_eng_aq = compute_aq(sp_eng)
sp_ing = ing_map.get(sp_eng, sp_eng)
sp_ing_aq = compute_aq(sp_ing)
ring_hits = sorted(
{
v
for v in (abs(face_int), sp_eng_aq, sp_ing_aq)
if v in S1_S6_SIGNATURE_RINGS
}
)
return {
"face_int": face_int,
"digit_aq": compute_aq(str(abs(face_int))),
"spoken_eng": sp_eng,
"spoken_eng_aq": sp_eng_aq,
"spoken_ing": sp_ing,
"spoken_ing_aq": sp_ing_aq,
"prime_rank_face": prime_rank(abs(face_int)),
"prime_rank_spoken_ing": prime_rank(sp_ing_aq),
"ring_coordinates": ring_hits,
"ring_partners": {str(c): S1_S6_SIGNATURE_RINGS[c] for c in ring_hits},
}
_VERIFIED_FRED_SEED_OBSERVATIONS: dict[str, list[dict[str, Any]]] = {
"CPIAUCSL": [
{"date_utc": "2026-09-01", "data_available": True, "status": "ok", "value": 336.298},
{"date_utc": "2026-10-01", "data_available": True, "status": "ok", "value": 337.476},
],
"PPIACO": [
{"date_utc": "2026-09-01", "data_available": True, "status": "ok", "value": 294.473},
{"date_utc": "2026-10-01", "data_available": True, "status": "ok", "value": 293.921},
],
"DGS10": [
{"date_utc": "2026-11-24", "data_available": True, "status": "ok", "value": 4.91},
{"date_utc": "2026-11-25", "data_available": True, "status": "ok", "value": 4.85},
{"date_utc": "2026-11-26", "data_available": False, "status": NO_DATA_AVAILABLE, "value": None},
],
"EFFR": [
{"date_utc": "2026-11-25", "data_available": True, "status": "ok", "value": 3.88},
{"date_utc": "2026-11-26", "data_available": False, "status": NO_DATA_AVAILABLE, "value": None},
{"date_utc": "2026-11-27", "data_available": True, "status": "ok", "value": 3.88},
],
"SOFR": [
{"date_utc": "2026-11-25", "data_available": True, "status": "ok", "value": 3.99},
{"date_utc": "2026-11-26", "data_available": False, "status": NO_DATA_AVAILABLE, "value": None},
{"date_utc": "2026-11-27", "data_available": True, "status": "ok", "value": 3.98},
],
"DFEDTARU": [
{"date_utc": "2026-11-29", "data_available": True, "status": "ok", "value": 4.00},
{"date_utc": "2026-11-30", "data_available": True, "status": "ok", "value": 4.00},
],
"M1SL": [
{"date_utc": "2026-09-01", "data_available": True, "status": "ok", "value": 20063.3},
{"date_utc": "2026-10-01", "data_available": True, "status": "ok", "value": 20166.9},
],
"M2SL": [
{"date_utc": "2026-09-01", "data_available": True, "status": "ok", "value": 23414.3},
{"date_utc": "2026-10-01", "data_available": True, "status": "ok", "value": 23532.8},
],
"M2REAL": [
{"date_utc": "2026-09-01", "data_available": True, "status": "ok", "value": 6962.4},
{"date_utc": "2026-10-01", "data_available": True, "status": "ok", "value": 6973.2},
],
"GDP": [
{"date_utc": "2026-04-01", "data_available": True, "status": "ok", "value": 32563.03},
{"date_utc": "2026-07-01", "data_available": True, "status": "ok", "value": 33056.204},
],
"GDPC1": [
{"date_utc": "2026-04-01", "data_available": True, "status": "ok", "value": 24408.006},
{"date_utc": "2026-07-01", "data_available": True, "status": "ok", "value": 24665.203},
],
"GNP": [
{"date_utc": "2026-04-01", "data_available": True, "status": "ok", "value": 32559.355},
{"date_utc": "2026-07-01", "data_available": True, "status": "ok", "value": 33026.509},
],
"OUTBS": [
{"date_utc": "2026-04-01", "data_available": True, "status": "ok", "value": 127.74},
{"date_utc": "2026-07-01", "data_available": True, "status": "ok", "value": 128.965},
],
"INDPRO": [
{"date_utc": "2026-09-01", "data_available": True, "status": "ok", "value": 102.6791},
{"date_utc": "2026-10-01", "data_available": True, "status": "ok", "value": 102.2421},
],
}
def build_macro_indicators_bundle(
allow_live_network: bool = True,
write_files: bool = True,
) -> dict[str, Any]:
cfg = load_workspace_config()
cache_path = cfg.core_dir / "site" / "quant" / "real-macro-indicators.json"
js_path = cfg.core_dir / "site" / "quant" / "real-macro-indicators-data.js"
with ReadOnlyIsolationGuard(cfg.read_only_files) as guard:
raw_series_by_id: dict[str, list[dict[str, Any]]] = {}
cached_bundle: dict[str, Any] = {}
if cache_path.is_file():
try:
cached_bundle = json.loads(cache_path.read_text(encoding="utf-8"))
except Exception:
cached_bundle = {}
cached_series = (cached_bundle.get("raw_fred_observations") or {}) if isinstance(cached_bundle, dict) else {}
for spec in FRED_SERIES_SPEC:
sid = spec["series_id"]
fetched: list[dict[str, Any]] = []
if allow_live_network:
try:
fetched = fetch_fred_series_csv(sid, max_rows=28)
except Exception:
fetched = []
if not fetched and sid in cached_series and cached_series[sid]:
fetched = list(cached_series[sid])
if not fetched and sid in _VERIFIED_FRED_SEED_OBSERVATIONS:
fetched = list(_VERIFIED_FRED_SEED_OBSERVATIONS[sid])
raw_series_by_id[sid] = fetched
# Pre-collect spoken integer strings for batch Ingglish translation
phrases: set[str] = set()
for spec in FRED_SERIES_SPEC:
phrases.add(spec["series_id"])
phrases.add(spec["slug"])
sid = spec["series_id"]
scale_bps = bool(spec.get("scale_to_bps"))
avail = [r for r in raw_series_by_id.get(sid, []) if r.get("data_available") and r.get("value") is not None]
if avail:
last_v = float(avail[-1]["value"])
f_int = int(round(last_v * 100.0)) if scale_bps else int(round(last_v))
phrases.add(int_to_spoken_words(abs(f_int)))
if len(avail) >= 2:
prev_v = float(avail[-2]["value"])
if scale_bps:
chg_bps = int(round((last_v - prev_v) * 100.0))
elif prev_v > 0:
chg_bps = int(round(((last_v - prev_v) / prev_v) * 10000.0))
else:
chg_bps = 0
phrases.add(int_to_spoken_words(abs(chg_bps)))
# Also add derived spread integers
for v_int in (337, 3366, 10, 97, 106, 54, 141, 30):
phrases.add(int_to_spoken_words(v_int))
ing_map = translate_batch(sorted(phrases))
series_out: dict[str, dict[str, Any]] = {}
for spec in FRED_SERIES_SPEC:
sid = spec["series_id"]
slug = spec["slug"]
scale_bps = bool(spec.get("scale_to_bps"))
obs_list = raw_series_by_id.get(sid, [])
avail = [r for r in obs_list if r.get("data_available") and r.get("value") is not None]
missing_dates = [r["date_utc"] for r in obs_list if not r.get("data_available")]
if not avail:
series_out[slug] = {
"series_id": sid,
"slug": slug,
"label": spec["label"],
"cadence": spec["cadence"],
"unit": spec["unit"],
"guilds": spec["guilds"],
"data_available": False,
"status": NO_DATA_AVAILABLE,
"latest_date_utc": None,
"latest_value": None,
"prior_date_utc": None,
"prior_value": None,
"period_change_bps": None,
"period_change_pct": None,
"yoy_change_pct": None,
"yoy_change_bps": None,
"aq_evaluation": None,
"change_aq_evaluation": None,
"missing_observation_dates": missing_dates,
"recent_observations": obs_list[-12:],
}
continue
last_row = avail[-1]
last_v = float(last_row["value"])
prev_row = avail[-2] if len(avail) >= 2 else None
prev_v = float(prev_row["value"]) if prev_row and prev_row.get("value") is not None else None
if prev_v is not None:
if scale_bps:
p_chg_bps: int | None = int(round((last_v - prev_v) * 100.0))
p_chg_pct: float | None = round(last_v - prev_v, 4)
elif prev_v != 0:
p_chg_pct = round(((last_v - prev_v) / prev_v) * 100.0, 2)
p_chg_bps = int(round(p_chg_pct * 100.0))
else:
p_chg_bps = None
p_chg_pct = None
else:
p_chg_bps = None
p_chg_pct = None
# YoY change (12 periods back for 1mo, 4 periods back for 1q)
yoy_step = 12 if spec["cadence"] == "1mo" else (4 if spec["cadence"] == "1q" else None)
if yoy_step and len(avail) > yoy_step:
yoy_base = float(avail[-1 - yoy_step]["value"])
if yoy_base > 0:
yoy_pct: float | None = round(((last_v - yoy_base) / yoy_base) * 100.0, 2)
yoy_bps: int | None = int(round(yoy_pct * 100.0))
else:
yoy_pct = None
yoy_bps = None
else:
yoy_pct = None
yoy_bps = None
face_int = int(round(last_v * 100.0)) if scale_bps else int(round(last_v))
aq_eval = _score_macro_int(face_int, ing_map)
chg_eval = _score_macro_int(abs(p_chg_bps), ing_map) if p_chg_bps is not None else None
series_out[slug] = {
"series_id": sid,
"slug": slug,
"label": spec["label"],
"cadence": spec["cadence"],
"unit": spec["unit"],
"guilds": spec["guilds"],
"data_available": True,
"status": "ok",
"latest_date_utc": last_row["date_utc"],
"latest_value": last_v,
"prior_date_utc": prev_row["date_utc"] if prev_row else None,
"prior_value": prev_v,
"period_change_bps": p_chg_bps,
"period_change_pct": p_chg_pct,
"yoy_change_pct": yoy_pct,
"yoy_change_bps": yoy_bps,
"aq_evaluation": aq_eval,
"change_aq_evaluation": chg_eval,
"missing_observation_dates": missing_dates,
"recent_observations": obs_list[-12:],
}
# Compute Derived Spreads & Velocity Ratios (Strictly Null-Preserving)
m1_v = (series_out.get("m1") or {}).get("latest_value")
m2_v = (series_out.get("m2") or {}).get("latest_value")
m1_chg = (series_out.get("m1") or {}).get("period_change_bps")
m2_chg = (series_out.get("m2") or {}).get("period_change_bps")
if m1_v is not None and m2_v is not None and m2_v > 0:
m2_m1_spread_b: float | None = round(m2_v - m1_v, 2)
m1_m2_ratio_pct: float | None = round((m1_v / m2_v) * 100.0, 2)
m1_m2_growth_spread_bps: int | None = (m1_chg - m2_chg) if (m1_chg is not None and m2_chg is not None) else None
spread_aq = _score_macro_int(int(round(m2_m1_spread_b / 10.0)), ing_map) # $3.37T -> 337
else:
m2_m1_spread_b = None
m1_m2_ratio_pct = None
m1_m2_growth_spread_bps = None
spread_aq = None
effr_v = (series_out.get("effr") or {}).get("latest_value")
sofr_v = (series_out.get("sofr") or {}).get("latest_value")
us10y_v = (series_out.get("us10y") or {}).get("latest_value")
sofr_effr_bps = int(round((sofr_v - effr_v) * 100.0)) if (sofr_v is not None and effr_v is not None) else None
curve_10y_effr_bps = int(round((us10y_v - effr_v) * 100.0)) if (us10y_v is not None and effr_v is not None) else None
cpi_chg = (series_out.get("cpi") or {}).get("period_change_bps")
ppi_chg = (series_out.get("ppi") or {}).get("period_change_bps")
ppi_cpi_spread_bps = (ppi_chg - cpi_chg) if (ppi_chg is not None and cpi_chg is not None) else None
gdp_v = (series_out.get("gdp_nominal") or {}).get("latest_value")
gnp_v = (series_out.get("gnp_gross_product") or {}).get("latest_value")
gdp_m2_velocity = round(gdp_v / m2_v, 4) if (gdp_v is not None and m2_v is not None and m2_v > 0) else None
gnp_gdp_spread_b = round(gnp_v - gdp_v, 2) if (gnp_v is not None and gdp_v is not None) else None
derived_indicators = {
"m1_vs_m2_spread": {
"data_available": m2_m1_spread_b is not None,
"status": "ok" if m2_m1_spread_b is not None else NO_DATA_AVAILABLE,
"m2_minus_m1_billions_usd": m2_m1_spread_b,
"m2_minus_m1_trillions_str": f"${m2_m1_spread_b / 1000.0:.2f}T" if m2_m1_spread_b is not None else None,
"m1_to_m2_liquidity_ratio_pct": m1_m2_ratio_pct,
"m1_minus_m2_mom_growth_spread_bps": m1_m2_growth_spread_bps,
"aq_evaluation_trillions_scaled": spread_aq,
},
"real_m2_growth": {
"data_available": (series_out.get("real_m2") or {}).get("data_available", False),
"latest_real_m2_billions": (series_out.get("real_m2") or {}).get("latest_value"),
"mom_growth_bps": (series_out.get("real_m2") or {}).get("period_change_bps"),
"mom_growth_pct": (series_out.get("real_m2") or {}).get("period_change_pct"),
"yoy_growth_pct": (series_out.get("real_m2") or {}).get("yoy_change_pct"),
"yoy_growth_bps": (series_out.get("real_m2") or {}).get("yoy_change_bps"),
},
"overnight_and_curve_spreads": {
"sofr_minus_effr_repo_spread_bps": sofr_effr_bps,
"us10y_minus_effr_curve_slope_bps": curve_10y_effr_bps,
"curve_slope_aq_evaluation": _score_macro_int(abs(curve_10y_effr_bps), ing_map) if curve_10y_effr_bps is not None else None,
},
"pipeline_inflation_margin": {
"ppi_minus_cpi_mom_spread_bps": ppi_cpi_spread_bps,
"aq_evaluation": _score_macro_int(abs(ppi_cpi_spread_bps), ing_map) if ppi_cpi_spread_bps is not None else None,
},
"aggregate_output_and_velocity": {
"gdp_to_m2_monetary_velocity": gdp_m2_velocity,
"gnp_minus_gdp_net_foreign_factor_billions": gnp_gdp_spread_b,
"business_real_output_index": (series_out.get("business_gross_output") or {}).get("latest_value"),
"industrial_production_index": (series_out.get("industrial_production") or {}).get("latest_value"),
},
}
receipt = guard.audit_receipt()
bundle: dict[str, Any] = {
"$schema": "./schemas/v1/macro-indicators.schema.json",
"$id": "urn:io:hyperstitionstud:schema:v1:macro-indicators",
"version": CURRENT_VERSION,
"generated_at_utc": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
"synthetic_data_eliminated": True,
"cadence_policy": "native_cadence_preserved_no_interpolation_null_when_unavailable",
"source": "fred_stlouisfed_keyless_csv",
"series_count": len(series_out),
"series": series_out,
"derived_indicators": derived_indicators,
"raw_fred_observations": raw_series_by_id,
"read_only_isolation_receipt": receipt,
}
bundle["ipld_dag_json_cidv1"] = {"/": compute_dag_json_cidv1(bundle)}
if write_files:
cache_path.parent.mkdir(parents=True, exist_ok=True)
cache_path.write_text(json.dumps(bundle, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
js_body = "// Auto-generated by hyperstitionstud_io.quant.macro — DO NOT EDIT MANUALLY\nwindow.HYPERSTITION_MACRO_DATA = " + json.dumps(bundle, ensure_ascii=False) + ";\n"
js_path.write_text(js_body, encoding="utf-8")
return bundle
def main(argv: list[str] | None = None) -> int:
ap = argparse.ArgumentParser(prog="hs-macro-harvest", description="Harvest real Federal Reserve (FRED) macroeconomic & aggregate output indicators.")
ap.add_argument("--offline", action="store_true", help="Use cached real-macro-indicators.json without live HTTP fetch.")
args = ap.parse_args(argv)
bundle = build_macro_indicators_bundle(allow_live_network=not args.offline, write_files=True)
print(
json.dumps(
{
"ok": True,
"version": bundle["version"],
"series_count": bundle["series_count"],
"synthetic_data_eliminated": bundle["synthetic_data_eliminated"],
"cidv1": bundle["ipld_dag_json_cidv1"]["/"],
},
indent=2,
)
)
return 0
if __name__ == "__main__":
raise SystemExit(main())