File size: 10,248 Bytes
3a1a713 c342958 3a1a713 a4757bc c342958 a4757bc c342958 a4757bc 3a1a713 a4757bc 3a1a713 a4757bc 3a1a713 a4757bc 3a1a713 a4757bc 3a1a713 a4757bc c342958 a4757bc 3a1a713 00896f8 c342958 00896f8 c342958 00896f8 c342958 00896f8 c342958 00896f8 3a1a713 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 | """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)
|