PolyHedra / src /polyhedra /services /options_data.py
yf176
fix(options): preserve Yahoo auth errors and add dated chain fallback
c342958
Raw History Blame Contribute Delete
10.2 kB
"""Options data provider surface for quant agents.
This module uses already-declared project dependencies only. It normalizes
available ETF option-chain data for agents, but it does not infer trade flow
direction or make strategy decisions.
"""
from __future__ import annotations
import math
from dataclasses import asdict, dataclass, field
from datetime import UTC, datetime
from typing import Any
from polyhedra.services.error_sanitizer import sanitize_error_text
ETF_OPTIONS_MARKETS: frozenset[str] = frozenset({"SPY", "QQQ", "GLD"})
@dataclass(frozen=True)
class OptionContract:
"""Normalized option-chain row used by OptionsFlowWatcher."""
provider: str
retrieved_at: str
symbol: str
expiration: str
strike: float | None
option_type: str
bid: float | None
ask: float | None
last: float | None
volume: int | None
open_interest: int | None
implied_volatility: float | None
source_delay_or_entitlement_note: str
contract_symbol: str = ""
def to_dict(self) -> dict[str, Any]:
return asdict(self)
@dataclass(frozen=True)
class OptionsDataSnapshot:
"""Result of an options-chain fetch for one symbol."""
symbol: str
provider: str
retrieved_at: str
status: str
note: str
expirations_checked: list[str] = field(default_factory=list)
contracts: list[OptionContract] = field(default_factory=list)
def to_dict(self) -> dict[str, Any]:
data = asdict(self)
data["contracts"] = [contract.to_dict() for contract in self.contracts]
return data
class YFinanceOptionsDataProvider:
"""Fetch delayed ETF option chains through the existing yfinance dependency."""
provider = "yfinance"
entitlement_note = (
"yfinance/Yahoo Finance options chain; free delayed data surface. "
"Trade-side, sweep, block, and opening/closing metadata unavailable."
)
def __init__(self, max_expirations: int = 2, max_contracts_per_side: int = 25) -> None:
self.max_expirations = max(1, max_expirations)
self.max_contracts_per_side = max(1, max_contracts_per_side)
def fetch(self, symbol: str) -> OptionsDataSnapshot:
symbol = symbol.strip().upper()
retrieved_at = datetime.now(tz=UTC).isoformat()
if symbol not in ETF_OPTIONS_MARKETS:
return OptionsDataSnapshot(
symbol=symbol,
provider=self.provider,
retrieved_at=retrieved_at,
status="not_applicable",
note="BTC and non-ETF markets do not use this ETF options surface by default.",
)
try:
import yfinance as yf
except Exception as exc:
return OptionsDataSnapshot(
symbol=symbol,
provider=self.provider,
retrieved_at=retrieved_at,
status="unavailable",
note=f"yfinance is not available in this runtime: {exc}",
)
last_error: Exception | None = None
empty_status = "unavailable"
empty_note = "yfinance returned no option expirations after retry."
for _attempt in range(2):
try:
# Yahoo occasionally returns an empty expiration list for a valid ETF.
# A fresh Ticker retries that transient response without changing providers.
ticker = yf.Ticker(symbol)
expirations = list(getattr(ticker, "options", []) or [])
if not expirations:
empty_status, empty_note = self._empty_expirations_diagnostic(ticker, symbol)
if empty_status == "error":
return OptionsDataSnapshot(
symbol=symbol,
provider=self.provider,
retrieved_at=retrieved_at,
status=empty_status,
note=empty_note,
)
continue
checked = expirations[: self.max_expirations]
contracts: list[OptionContract] = []
for expiration in checked:
chain = ticker.option_chain(expiration)
contracts.extend(
self._contracts_from_frame(
symbol,
expiration,
"call",
chain.calls,
retrieved_at,
)
)
contracts.extend(
self._contracts_from_frame(
symbol,
expiration,
"put",
chain.puts,
retrieved_at,
)
)
return OptionsDataSnapshot(
symbol=symbol,
provider=self.provider,
retrieved_at=retrieved_at,
status="ok" if contracts else "unavailable",
note=(
self.entitlement_note
if contracts
else "Provider returned empty option-chain tables."
),
expirations_checked=checked,
contracts=contracts,
)
except Exception as exc:
last_error = exc
if last_error is not None:
return OptionsDataSnapshot(
symbol=symbol,
provider=self.provider,
retrieved_at=retrieved_at,
status="error",
note=f"Options provider fetch failed after retry: {last_error}",
)
return OptionsDataSnapshot(
symbol=symbol,
provider=self.provider,
retrieved_at=retrieved_at,
status=empty_status,
note=empty_note,
)
@staticmethod
def _empty_expirations_diagnostic(ticker: Any, symbol: str) -> tuple[str, str]:
"""Inspect the same Yahoo response yfinance silently maps to empty options."""
fallback = "yfinance returned no option expirations after retry; Yahoo response unknown."
try:
from yfinance.base import _BASE_URL_
response = ticker._data.get(url=f"{_BASE_URL_}/v7/finance/options/{symbol}")
status_code = response.status_code
try:
body = response.json()
except (TypeError, ValueError):
body = {}
option_chain = body.get("optionChain", {}) if isinstance(body, dict) else {}
finance = body.get("finance", {}) if isinstance(body, dict) else {}
error = option_chain.get("error") if isinstance(option_chain, dict) else None
if error is None and isinstance(finance, dict):
error = finance.get("error")
if isinstance(error, dict):
code = str(error.get("code") or "UNKNOWN")[:80]
description = str(error.get("description") or "")[:160]
return "error", f"Yahoo options HTTP {status_code}: {code}; {description}"
if status_code >= 400:
body_excerpt = sanitize_error_text(getattr(response, "text", ""), limit=160)
detail = f" Response: {body_excerpt}" if body_excerpt else " No response body."
return "error", f"Yahoo options HTTP {status_code};{detail}"
if isinstance(option_chain, dict) and not option_chain.get("result"):
return "unavailable", f"Yahoo options HTTP {status_code} returned no optionChain.result."
return "error", (
f"yfinance returned no expirations, but diagnostic Yahoo HTTP {status_code} "
"contained an option result."
)
except Exception as exc:
return "unavailable", f"{fallback} Diagnostic failed: {type(exc).__name__}."
def _contracts_from_frame(
self,
symbol: str,
expiration: str,
option_type: str,
frame: Any,
retrieved_at: str,
) -> list[OptionContract]:
if frame is None:
return []
try:
records = frame.to_dict("records")
except Exception:
return []
def activity_score(row: dict[str, Any]) -> float:
volume = _clean_int(row.get("volume")) or 0
open_interest = _clean_int(row.get("openInterest")) or 0
return volume + open_interest * 0.1
rows = sorted(records, key=activity_score, reverse=True)[: self.max_contracts_per_side]
contracts: list[OptionContract] = []
for row in rows:
contracts.append(
OptionContract(
provider=self.provider,
retrieved_at=retrieved_at,
symbol=symbol,
expiration=expiration,
strike=_clean_float(row.get("strike")),
option_type=option_type,
bid=_clean_float(row.get("bid")),
ask=_clean_float(row.get("ask")),
last=_clean_float(row.get("lastPrice")),
volume=_clean_int(row.get("volume")),
open_interest=_clean_int(row.get("openInterest")),
implied_volatility=_clean_float(row.get("impliedVolatility")),
source_delay_or_entitlement_note=self.entitlement_note,
contract_symbol=str(row.get("contractSymbol") or ""),
)
)
return contracts
def _clean_float(value: Any) -> float | None:
try:
numeric = float(value)
except (TypeError, ValueError):
return None
if math.isnan(numeric) or math.isinf(numeric):
return None
return numeric
def _clean_int(value: Any) -> int | None:
try:
numeric = float(value)
except (TypeError, ValueError):
return None
if math.isnan(numeric) or math.isinf(numeric):
return None
return int(numeric)