Initial public release

This commit is contained in:
kwyvern-gitea
2026-08-12 16:40:51 -07:00
commit ce064d5462
14 changed files with 1769 additions and 0 deletions
View File
+134
View File
@@ -0,0 +1,134 @@
"""Fetch CBOE Volatility Index (VIX) daily closes from EODHD.
Source: EODHD ``VIX.INDX`` — index series (same instrument as FRED's VIXCLS).
Why EODHD instead of FRED:
FRED's VIXCLS publishes with a ~2 business-day lag, which means the live
signal pipeline running on day T sees VIX through T-3 at best. That stale
VIX poisons the US asymmetric gate state at T-1/T (NaN gate_exposure), and
the multi-region orchestrator then aborts on the next gated region that
happens to be empty. EODHD publishes the VIX close within minutes of the
4:15pm ET print, so we always have a same-day bar by the time the signal
runs.
Output: ``data/processed/vix_daily.parquet``
- index: ``date`` (DatetimeIndex)
- column: ``vix_close`` (float64)
Freshness check (replaces the file-mtime trap in fetch_vix_fred.py):
Skips the network fetch only if the existing parquet's *most recent data
row* is ``>= today`` (i.e., today's close already on disk). A file written
yesterday with stale contents is NOT considered fresh. ``--force`` bypasses
the check.
Run from project root:
.venv/Scripts/python.exe scripts/data/fetch_vix_eodhd.py [--force]
"""
from __future__ import annotations
import argparse
import logging
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent.parent)) # noqa: E402
import pandas as pd
from src.data.eodhd_client import EODHDClient, EODHDError
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s — %(message)s",
datefmt="%Y-%m-%dT%H:%M:%S",
)
logger = logging.getLogger("fetch_vix_eodhd")
_EODHD_SYMBOL = "VIX.INDX"
_OUT_PATH = Path("data/processed/vix_daily.parquet")
def _parquet_has_todays_bar(path: Path) -> bool:
"""Return True iff the parquet exists and its latest row is dated >= today."""
if not path.is_file():
return False
try:
df = pd.read_parquet(path)
except Exception as exc: # noqa: BLE001
logger.warning("Existing parquet unreadable (%s); will refetch", exc)
return False
if df.empty:
return False
last_dt = pd.to_datetime(df.index.max())
today = pd.Timestamp.today().normalize()
return last_dt >= today
def fetch_vix(force: bool = False) -> pd.DataFrame:
"""Download VIX.INDX from EODHD and write to parquet.
Returns the resulting DataFrame (date index, vix_close column).
"""
if not force and _parquet_has_todays_bar(_OUT_PATH):
df = pd.read_parquet(_OUT_PATH)
logger.info(
"Cache already has today's bar; skipping fetch. %d rows, %s -> %s",
len(df), df.index.min().date(), df.index.max().date(),
)
return df
logger.info("Fetching %s from EODHD (use_cache=False) ...", _EODHD_SYMBOL)
client = EODHDClient()
raw = client.get_eod_prices(_EODHD_SYMBOL, use_cache=False)
if "date" not in raw.columns or "adjusted_close" not in raw.columns:
raise ValueError(
f"Unexpected EODHD response columns: {list(raw.columns)}"
)
raw["date"] = pd.to_datetime(raw["date"])
raw["adjusted_close"] = pd.to_numeric(raw["adjusted_close"], errors="coerce")
df = (
raw.rename(columns={"adjusted_close": "vix_close"})
[["date", "vix_close"]]
.set_index("date")
.sort_index()
.dropna(subset=["vix_close"])
)
df.index.name = "date"
_OUT_PATH.parent.mkdir(parents=True, exist_ok=True)
df.to_parquet(_OUT_PATH)
logger.info(
"VIX saved -> %s (%d rows, %s to %s, latest close=%.2f)",
_OUT_PATH, len(df), df.index.min().date(), df.index.max().date(),
float(df["vix_close"].iloc[-1]),
)
return df
def parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(description="Fetch VIX.INDX daily closes from EODHD")
p.add_argument(
"--force",
action="store_true",
help="Force re-fetch even when today's bar is already on disk",
)
return p.parse_args()
def main() -> None:
args = parse_args()
try:
fetch_vix(force=args.force)
except EODHDError as exc:
logger.error("EODHD fetch failed for %s: %s", _EODHD_SYMBOL, exc)
sys.exit(1)
except Exception as exc: # noqa: BLE001
logger.error("Unexpected error: %s", exc)
sys.exit(1)
if __name__ == "__main__":
main()
+249
View File
@@ -0,0 +1,249 @@
"""Multi-region VIX-p95 breach monitor for the KWPF Momentum gates.
Shows current gate state + next-session breach threshold for every gated
region (US/EU/JP). Pure end-of-day workflow.
US source : VIX (EODHD VIX.INDX, scripts/data/fetch_vix_eodhd.py)
EU source : V2TX (EODHD .INDX, src/data/eodhd_client.py)
JP source : Nikkei VI (Nikkei official CSV, src/data/nikkei_vi_fetcher.py)
CA is not gated (informational region only) — omitted from the monitor.
Threshold math mirrors production gate exactly:
vix_above_p95 = rolling.rank(pct=True) > 0.95 on 252d window
→ tomorrow's close must exceed the 13th-largest of the prior 251 values.
Output is one compact table with the current state for each region.
Usage:
.venv/Scripts/python.exe scripts/live/vix_breach_monitor.py
Refreshes all 3 sources, then reports.
.venv/Scripts/python.exe scripts/live/vix_breach_monitor.py --no-refresh
Uses cached parquets only (offline / quick check).
.venv/Scripts/python.exe scripts/live/vix_breach_monitor.py --region US
Only show one region (helpful when one source is being investigated).
"""
import argparse
import logging
import sys
from datetime import date
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent.parent)) # noqa: E402
import pandas as pd # noqa: E402
from scripts.data.fetch_vix_eodhd import _OUT_PATH as VIX_CACHE_PATH # noqa: E402
from scripts.data.fetch_vix_eodhd import fetch_vix # noqa: E402
from src.data.eodhd_client import EODHDClient # noqa: E402
from src.data.nikkei_vi_fetcher import fetch_and_cache_nikkei_vi # noqa: E402
logging.basicConfig(level=logging.WARNING, format="%(message)s")
_WINDOW = 252
_PCTILE = 0.95
# For n=252, pct_rank > 0.95 implies rank > 239.4, rank >= 240, and a top-13 position.
_TOP_N_TRIGGER = 13
_NIKKEI_VI_CACHE = Path("data/processed/nikkei_vi_daily.parquet")
_REGION_ORDER = ("US", "EU", "JP")
_REGION_SOURCES = {
"US": "VIX (EODHD)",
"EU": "VSTOXX (EODHD)",
"JP": "Nikkei VI (Nikkei)",
}
# ---------------------------------------------------------------------------
# Per-region data loaders
# ---------------------------------------------------------------------------
def load_us_vix(refresh: bool) -> pd.Series:
"""Load US VIX series. Refreshes from EODHD when refresh=True."""
if refresh:
try:
fetch_vix(force=True)
except Exception as exc: # noqa: BLE001
print(f"WARNING: US VIX refresh failed ({exc}). Using cached parquet.",
file=sys.stderr)
if not VIX_CACHE_PATH.is_file():
try:
fetch_vix(force=False)
except Exception as exc: # noqa: BLE001
raise RuntimeError(
f"US VIX cache not found at {VIX_CACHE_PATH} and fetch failed: {exc}"
) from exc
df = pd.read_parquet(VIX_CACHE_PATH)
return pd.Series(
df["vix_close"].values,
index=pd.to_datetime(df.index),
).sort_index()
def load_eu_v2tx(refresh: bool) -> pd.Series:
"""Load EU V2TX series. Refreshes from EODHD via extend_cache_to when refresh=True."""
client = EODHDClient()
extend_to = date.today().isoformat() if refresh else None
df = client.get_eod_prices("V2TX.INDX", extend_cache_to=extend_to)
df = df.sort_values("date").reset_index(drop=True)
return pd.Series(
df["adjusted_close"].values,
index=pd.to_datetime(df["date"]),
).sort_index().astype(float).dropna()
def load_jp_nikkei_vi(refresh: bool) -> pd.Series:
"""Load JP Nikkei VI series. Refreshes from Nikkei official CSV when refresh=True."""
if refresh:
try:
fetch_and_cache_nikkei_vi()
except Exception as exc: # noqa: BLE001
print(f"WARNING: JP Nikkei VI refresh failed ({exc}). Using cached parquet.",
file=sys.stderr)
if not _NIKKEI_VI_CACHE.is_file():
try:
fetch_and_cache_nikkei_vi()
except Exception as exc: # noqa: BLE001
raise RuntimeError(
f"JP Nikkei VI cache not found at {_NIKKEI_VI_CACHE} and fetch failed: {exc}"
) from exc
df = pd.read_parquet(_NIKKEI_VI_CACHE)
return pd.Series(
df["nikkei_vi_close"].values,
index=pd.to_datetime(df.index),
).sort_index()
_LOADERS = {
"US": load_us_vix,
"EU": load_eu_v2tx,
"JP": load_jp_nikkei_vi,
}
# ---------------------------------------------------------------------------
# Region-independent threshold math that exactly matches the production gate
# ---------------------------------------------------------------------------
def compute_breach(vol_close: pd.Series, window: int = _WINDOW) -> dict:
"""Return current state + tomorrow's breach threshold for a vol series.
Production gate fires when `rolling.rank(pct=True) > 0.95` on the trailing
`window` days. For window=252 the trigger is the top 13 by rank, so
tomorrow's close must strictly exceed the 13th-largest of the prior 251.
"""
if len(vol_close) < window:
raise ValueError(f"Need >= {window} closes; got {len(vol_close)}")
last_close = float(vol_close.iloc[-1])
last_date = vol_close.index[-1]
current_window = vol_close.iloc[-window:]
current_rank_pct = float(current_window.rank(pct=True).iloc[-1])
is_currently_breached = current_rank_pct > _PCTILE
prior_251 = vol_close.iloc[-(window - 1):]
threshold_tomorrow = float(prior_251.sort_values(ascending=False).iloc[_TOP_N_TRIGGER - 1])
threshold_today = float(current_window.sort_values(ascending=False).iloc[_TOP_N_TRIGGER - 1])
return {
"last_date": last_date,
"last_close": last_close,
"is_currently_breached": is_currently_breached,
"threshold_today": threshold_today,
"threshold_tomorrow": threshold_tomorrow,
"headroom_points": threshold_tomorrow - last_close,
"headroom_pct": (
100.0 * (threshold_tomorrow - last_close) / last_close if last_close > 0 else float("nan")
),
}
# ---------------------------------------------------------------------------
# Output
# ---------------------------------------------------------------------------
def format_state(result: dict) -> str:
return "RISK-OFF" if result["is_currently_breached"] else "SAFE"
def format_headroom(result: dict) -> str:
if result["is_currently_breached"]:
drop = result["threshold_today"] - result["last_close"]
drop_pct = 100.0 * drop / result["last_close"]
return f"{drop:+.2f} ({drop_pct:+.1f}% to release)"
return f"+{result['headroom_points']:.2f} (+{result['headroom_pct']:.1f}%)"
def format_report(region_results: dict[str, dict | Exception]) -> str:
bar = "=" * 78
lines = [
"",
bar,
f"MULTI-REGION VIX BREACH MONITOR — {date.today().isoformat()}",
bar,
f"{'Region':<7} {'Source':<22} {'Last':>8} {'p95':>8} {'State':<10} {'Headroom':<22}",
]
for region, result in region_results.items():
source = _REGION_SOURCES.get(region, "?")
if isinstance(result, Exception):
lines.append(f"{region:<7} {source:<22} {'ERROR':>8} {'—':>8} {'ERR':<10} {str(result)[:22]}")
continue
last_close = result["last_close"]
thr = result["threshold_today"]
state = format_state(result)
headroom = format_headroom(result)
date_str = result["last_date"].strftime("%m-%d")
lines.append(
f"{region:<7} {source:<22} {last_close:>8.2f} {thr:>8.2f} {state:<10} {headroom:<22} ({date_str})"
)
lines.append(bar)
return "\n".join(lines)
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
def parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(description="Multi-region VIX p95 breach monitor")
p.add_argument(
"--no-refresh", action="store_true",
help="Skip live data refreshes and use cached parquets (offline / quick check)",
)
p.add_argument(
"--region", choices=("US", "EU", "JP"), default=None,
help="Only show one region (default: all three)",
)
return p.parse_args()
def main() -> None:
args = parse_args()
refresh = not args.no_refresh
regions = (args.region,) if args.region else _REGION_ORDER
region_results: dict[str, dict | Exception] = {}
for region in regions:
loader = _LOADERS[region]
try:
series = loader(refresh)
result = compute_breach(series)
except Exception as exc: # noqa: BLE001
region_results[region] = exc
continue
region_results[region] = result
print(format_report(region_results))
if __name__ == "__main__":
main()