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
+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()