Files
gold-gate/scripts/live/gold_gate_monitor.py
T
2026-08-12 16:40:55 -07:00

189 lines
6.6 KiB
Python

"""Weekly real-yield gate monitor for GLD.
The monitor reports the current long-only and long/short states. It does not
calculate or report future review dates.
Usage:
python scripts/live/gold_gate_monitor.py
Refresh GLD from EODHD and DFII20 from FRED, then print the latest
weekly gold gate state.
python scripts/live/gold_gate_monitor.py --no-refresh
Use cached series only (offline / quick check).
"""
import argparse
import logging
import sys
from datetime import date
from io import StringIO
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent.parent)) # noqa: E402
import pandas as pd # noqa: E402
import requests # noqa: E402
from src.data.eodhd_client import EODHDClient # noqa: E402
from src.gates.gold_real_yield import compute_weekly_real_yield_gate # noqa: E402
logging.basicConfig(level=logging.WARNING, format="%(message)s")
_ASSET = "GLD.US"
_REAL_YIELD_SERIES = "DFII20"
_REAL_YIELD_LABEL = "20Y TIPS real yield"
_FRED_GRAPH_URL = "https://fred.stlouisfed.org/graph/fredgraph.csv?id={series_id}"
_FRED_CACHE_DIR = Path("data/raw/fred_graph")
# ---------------------------------------------------------------------------
# Data
# ---------------------------------------------------------------------------
def load_gld_daily(refresh: bool) -> pd.DataFrame:
"""Load GLD daily adjusted close. Extends cache via EODHD when refresh is true."""
client = EODHDClient()
extend_to = date.today().isoformat() if refresh else None
df = client.get_eod_prices(_ASSET, extend_cache_to=extend_to)
df = df.sort_values("date").reset_index(drop=True)
df["date"] = pd.to_datetime(df["date"])
df["adjusted_close"] = df["adjusted_close"].astype(float)
return df[["date", "adjusted_close"]]
def _fred_cache_path(series_id: str) -> Path:
return _FRED_CACHE_DIR / f"{series_id}.csv"
def _parse_fred_graph_csv(text: str, series_id: str) -> pd.Series:
raw = pd.read_csv(StringIO(text))
raw.columns = [str(c).strip() for c in raw.columns]
date_col = next((c for c in ("DATE", "observation_date", "date") if c in raw.columns), None)
if date_col is None or series_id not in raw.columns:
raise ValueError(f"Unexpected FRED CSV columns for {series_id}: {list(raw.columns)}")
raw[date_col] = pd.to_datetime(raw[date_col])
raw[series_id] = pd.to_numeric(raw[series_id], errors="coerce")
series = raw.set_index(date_col)[series_id].sort_index().dropna()
series.index = pd.to_datetime(series.index)
series.index.name = "date"
series.name = "real_yield_pct"
return series
def load_fred_graph_series(series_id: str, refresh: bool) -> pd.Series:
"""Load a FRED graph CSV series with a raw CSV cache layer."""
cache_path = _fred_cache_path(series_id)
if not refresh and not cache_path.is_file():
raise FileNotFoundError(
f"FRED cache missing for {series_id}: {cache_path}. Run without --no-refresh first."
)
text: str
if refresh:
try:
url = _FRED_GRAPH_URL.format(series_id=series_id)
resp = requests.get(url, timeout=30)
resp.raise_for_status()
text = resp.text
cache_path.parent.mkdir(parents=True, exist_ok=True)
cache_path.write_text(text, encoding="utf-8")
except Exception as exc: # noqa: BLE001
if not cache_path.is_file():
raise
print(
f"WARNING: FRED refresh failed for {series_id} ({exc}). Falling back to cache.",
file=sys.stderr,
)
text = cache_path.read_text(encoding="utf-8")
else:
text = cache_path.read_text(encoding="utf-8")
return _parse_fred_graph_csv(text, series_id)
def load_real_yield_daily(refresh: bool) -> pd.Series:
"""Load the 20Y TIPS real-yield series used by the live weekly gold gate."""
return load_fred_graph_series(_REAL_YIELD_SERIES, refresh=refresh)
# ---------------------------------------------------------------------------
# Output
# ---------------------------------------------------------------------------
def _latest_gld_row(daily: pd.DataFrame, today: pd.Timestamp) -> pd.Series:
eligible = daily[daily["date"] <= today].sort_values("date")
if eligible.empty:
eligible = daily.sort_values("date")
if eligible.empty:
raise ValueError("GLD daily series is empty")
return eligible.iloc[-1]
def format_report(daily: pd.DataFrame, real_yield: pd.Series, today: pd.Timestamp) -> str:
gate = compute_weekly_real_yield_gate(real_yield, daily["date"], today)
last_gld = _latest_gld_row(daily, today)
last_real_yield_date = pd.Timestamp(real_yield.dropna().sort_index().index[-1])
bar = "=" * 82
lines = [
"",
bar,
f"GOLD REAL-YIELD GATE MONITOR - {date.today().isoformat()}",
bar,
f"Asset : {_ASSET} @ {float(last_gld['adjusted_close']):.2f} "
f"({pd.Timestamp(last_gld['date']).date()})",
f"Signal source : {_REAL_YIELD_SERIES} ({_REAL_YIELD_LABEL}, FRED)",
"",
f"Real yield : {gate['prev_real_yield']:.2f}% -> {gate['real_yield']:.2f}% "
f"({gate['delta_bp']:+.1f} bp)",
f"Gate rule : LONG GOLD when the weekly change <= +{gate['threshold_bp']:.0f} bp",
"",
f"{'Profile':<12} {'Action':<11} {'Interpretation':<40}",
f"{'Long-only':<12} {gate['long_only_state']:<11} " f"{'Hold GLD or sit in cash':<40}",
f"{'Long/short':<12} {gate['long_short_state']:<11} " f"{'Hold GLD or short gold':<40}",
"",
f"DFII20 latest : {last_real_yield_date.date()}",
bar,
]
return "\n".join(lines)
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
def parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(description="Weekly real-yield gold gate monitor")
p.add_argument(
"--no-refresh",
action="store_true",
help="Use cached GLD and DFII20 series only (offline / quick check)",
)
return p.parse_args()
def main() -> None:
args = parse_args()
refresh = not args.no_refresh
try:
daily = load_gld_daily(refresh)
except Exception as exc: # noqa: BLE001
if refresh:
print(f"WARNING: GLD refresh failed ({exc}). Falling back to cache.", file=sys.stderr)
daily = load_gld_daily(refresh=False)
else:
raise
real_yield = load_real_yield_daily(refresh)
today = pd.Timestamp(date.today())
print(format_report(daily, real_yield, today))
if __name__ == "__main__":
main()