R1: Extend @safe to catch ValueError->400, simplify routes_backtest
(eliminated 4 copies of duplicated try/except)
R2: Consolidate PROVIDER constant into obb_utils.py (single source)
R3: Add days_ago() helper to obb_utils.py, replace 8+ duplications
R4: Extract Reddit/ApeWisdom into reddit_service.py from finnhub_service
R5: Fix missing top-level import asyncio in finnhub_service
R6: (deferred - sentiment logic extraction is a larger change)
All 561 tests passing.
216 lines
6.4 KiB
Python
216 lines
6.4 KiB
Python
"""Market data: ETFs, indices, crypto, currencies, and derivatives."""
|
|
|
|
import asyncio
|
|
import logging
|
|
from datetime import datetime, timezone, timedelta
|
|
from typing import Any
|
|
|
|
from openbb import obb
|
|
|
|
from obb_utils import to_list, days_ago, PROVIDER
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
# --- 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 = days_ago(days)
|
|
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 = days_ago(days)
|
|
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 = days_ago(days)
|
|
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 = days_ago(days)
|
|
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 = days_ago(days)
|
|
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 []
|
|
|
|
|
|
# --- Currency Reference Rates (Group H) ---
|
|
|
|
|
|
async def get_currency_reference_rates() -> list[dict[str, Any]]:
|
|
"""Get ECB reference exchange rates for major currencies."""
|
|
try:
|
|
result = await asyncio.to_thread(
|
|
obb.currency.reference_rates, provider="ecb"
|
|
)
|
|
return to_list(result)
|
|
except Exception:
|
|
logger.warning("Currency reference rates failed", exc_info=True)
|
|
return []
|
|
|
|
|
|
# --- Index Enhanced (Group F) ---
|
|
|
|
|
|
async def get_sp500_multiples(series_name: str = "pe_ratio") -> list[dict[str, Any]]:
|
|
"""Get historical S&P 500 valuation multiples (PE, Shiller PE, P/B, etc.)."""
|
|
try:
|
|
result = await asyncio.to_thread(
|
|
obb.index.sp500_multiples, series_name=series_name, provider="multpl"
|
|
)
|
|
return to_list(result)
|
|
except Exception:
|
|
logger.warning("SP500 multiples failed for %s", series_name, exc_info=True)
|
|
return []
|
|
|
|
|
|
async def get_index_constituents(symbol: str) -> list[dict[str, Any]]:
|
|
"""Get index member stocks with sector and price data."""
|
|
try:
|
|
result = await asyncio.to_thread(
|
|
obb.index.constituents, symbol, provider="cboe"
|
|
)
|
|
return to_list(result)
|
|
except Exception:
|
|
logger.warning("Index constituents failed for %s", symbol, exc_info=True)
|
|
return []
|
|
|
|
|
|
async def get_etf_nport(symbol: str) -> list[dict[str, Any]]:
|
|
"""Get detailed ETF holdings from SEC N-PORT filings."""
|
|
try:
|
|
result = await asyncio.to_thread(
|
|
obb.etf.nport_disclosure, symbol, provider="sec"
|
|
)
|
|
return to_list(result)
|
|
except Exception:
|
|
logger.warning("ETF N-PORT failed for %s", symbol, exc_info=True)
|
|
return []
|