feat: integrate quantitative, calendar, market data endpoints
Add 3 new service layers and route modules: - quantitative_service: Sharpe ratio, CAPM, normality tests, unit root tests - calendar_service: earnings/dividends/IPO/splits calendars, estimates, SEC ownership - market_service: ETF, index, crypto, forex, options, futures data Total endpoints: 50. All use free providers (yfinance, SEC). Update README with comprehensive endpoint documentation.
This commit is contained in:
181
market_service.py
Normal file
181
market_service.py
Normal file
@@ -0,0 +1,181 @@
|
||||
"""Market data: ETFs, indices, crypto, currencies, and derivatives."""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from openbb import obb
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
PROVIDER = "yfinance"
|
||||
|
||||
|
||||
# --- ETF ---
|
||||
|
||||
|
||||
async def get_etf_info(symbol: str) -> dict[str, Any]:
|
||||
"""Get ETF profile/info."""
|
||||
try:
|
||||
result = await asyncio.to_thread(obb.etf.info, symbol, provider=PROVIDER)
|
||||
items = _to_list(result)
|
||||
return items[0] if items else {}
|
||||
except Exception:
|
||||
logger.warning("ETF info failed for %s", symbol, exc_info=True)
|
||||
return {}
|
||||
|
||||
|
||||
async def get_etf_historical(symbol: str, days: int = 365) -> list[dict[str, Any]]:
|
||||
"""Get ETF price history."""
|
||||
start = (datetime.now() - timedelta(days=days)).strftime("%Y-%m-%d")
|
||||
try:
|
||||
result = await asyncio.to_thread(
|
||||
obb.etf.historical, symbol, start_date=start, provider=PROVIDER
|
||||
)
|
||||
return _to_list(result)
|
||||
except Exception:
|
||||
logger.warning("ETF historical failed for %s", symbol, exc_info=True)
|
||||
return []
|
||||
|
||||
|
||||
async def search_etf(query: str) -> list[dict[str, Any]]:
|
||||
"""Search for ETFs by name or keyword."""
|
||||
try:
|
||||
result = await asyncio.to_thread(obb.etf.search, query)
|
||||
return _to_list(result)
|
||||
except Exception:
|
||||
logger.warning("ETF search failed for %s", query, exc_info=True)
|
||||
return []
|
||||
|
||||
|
||||
# --- Index ---
|
||||
|
||||
|
||||
async def get_available_indices() -> list[dict[str, Any]]:
|
||||
"""List available market indices."""
|
||||
try:
|
||||
result = await asyncio.to_thread(obb.index.available, provider=PROVIDER)
|
||||
return _to_list(result)
|
||||
except Exception:
|
||||
logger.warning("Available indices failed", exc_info=True)
|
||||
return []
|
||||
|
||||
|
||||
async def get_index_historical(symbol: str, days: int = 365) -> list[dict[str, Any]]:
|
||||
"""Get index price history."""
|
||||
start = (datetime.now() - timedelta(days=days)).strftime("%Y-%m-%d")
|
||||
try:
|
||||
result = await asyncio.to_thread(
|
||||
obb.index.price.historical, symbol, start_date=start, provider=PROVIDER
|
||||
)
|
||||
return _to_list(result)
|
||||
except Exception:
|
||||
logger.warning("Index historical failed for %s", symbol, exc_info=True)
|
||||
return []
|
||||
|
||||
|
||||
# --- Crypto ---
|
||||
|
||||
|
||||
async def get_crypto_historical(symbol: str, days: int = 365) -> list[dict[str, Any]]:
|
||||
"""Get cryptocurrency price history."""
|
||||
start = (datetime.now() - timedelta(days=days)).strftime("%Y-%m-%d")
|
||||
try:
|
||||
result = await asyncio.to_thread(
|
||||
obb.crypto.price.historical, symbol, start_date=start, provider=PROVIDER
|
||||
)
|
||||
return _to_list(result)
|
||||
except Exception:
|
||||
logger.warning("Crypto historical failed for %s", symbol, exc_info=True)
|
||||
return []
|
||||
|
||||
|
||||
async def search_crypto(query: str) -> list[dict[str, Any]]:
|
||||
"""Search for cryptocurrencies."""
|
||||
try:
|
||||
result = await asyncio.to_thread(obb.crypto.search, query)
|
||||
return _to_list(result)
|
||||
except Exception:
|
||||
logger.warning("Crypto search failed for %s", query, exc_info=True)
|
||||
return []
|
||||
|
||||
|
||||
# --- Currency ---
|
||||
|
||||
|
||||
async def get_currency_historical(
|
||||
symbol: str, days: int = 365
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Get forex price history (e.g., EURUSD)."""
|
||||
start = (datetime.now() - timedelta(days=days)).strftime("%Y-%m-%d")
|
||||
try:
|
||||
result = await asyncio.to_thread(
|
||||
obb.currency.price.historical, symbol, start_date=start, provider=PROVIDER
|
||||
)
|
||||
return _to_list(result)
|
||||
except Exception:
|
||||
logger.warning("Currency historical failed for %s", symbol, exc_info=True)
|
||||
return []
|
||||
|
||||
|
||||
# --- Derivatives ---
|
||||
|
||||
|
||||
async def get_options_chains(symbol: str) -> list[dict[str, Any]]:
|
||||
"""Get options chain data for a symbol."""
|
||||
try:
|
||||
result = await asyncio.to_thread(
|
||||
obb.derivatives.options.chains, symbol, provider=PROVIDER
|
||||
)
|
||||
return _to_list(result)
|
||||
except Exception:
|
||||
logger.warning("Options chains failed for %s", symbol, exc_info=True)
|
||||
return []
|
||||
|
||||
|
||||
async def get_futures_historical(
|
||||
symbol: str, days: int = 365
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Get futures price history."""
|
||||
start = (datetime.now() - timedelta(days=days)).strftime("%Y-%m-%d")
|
||||
try:
|
||||
result = await asyncio.to_thread(
|
||||
obb.derivatives.futures.historical, symbol, start_date=start, provider=PROVIDER
|
||||
)
|
||||
return _to_list(result)
|
||||
except Exception:
|
||||
logger.warning("Futures historical failed for %s", symbol, exc_info=True)
|
||||
return []
|
||||
|
||||
|
||||
async def get_futures_curve(symbol: str) -> list[dict[str, Any]]:
|
||||
"""Get futures term structure/curve."""
|
||||
try:
|
||||
result = await asyncio.to_thread(
|
||||
obb.derivatives.futures.curve, symbol, provider=PROVIDER
|
||||
)
|
||||
return _to_list(result)
|
||||
except Exception:
|
||||
logger.warning("Futures curve failed for %s", symbol, exc_info=True)
|
||||
return []
|
||||
|
||||
|
||||
def _to_list(result: Any) -> list[dict[str, Any]]:
|
||||
"""Convert OBBject result to list of dicts."""
|
||||
if result is None or result.results is None:
|
||||
return []
|
||||
items = result.results
|
||||
if not isinstance(items, list):
|
||||
items = [items]
|
||||
out = []
|
||||
for item in items:
|
||||
if hasattr(item, "model_dump"):
|
||||
d = item.model_dump()
|
||||
else:
|
||||
d = vars(item) if vars(item) else {}
|
||||
for k, v in d.items():
|
||||
if hasattr(v, "isoformat"):
|
||||
d[k] = v.isoformat()
|
||||
out.append(d)
|
||||
return out
|
||||
Reference in New Issue
Block a user