135 lines
4.3 KiB
Python
135 lines
4.3 KiB
Python
"""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()
|