refactor: fix code review issues across routes and services

- Extract shared route_utils.py (validate_symbol, safe decorator)
  removing duplication from 6 route files
- Extract shared obb_utils.py (to_list, extract_single, safe_last)
  removing duplication from calendar_service and market_service
- Fix _to_list dict mutation during iteration (use comprehension)
- Fix double vars() call and live __dict__ mutation risk
- Fix route ordering: /etf/search and /crypto/search now registered
  before /{symbol} path params to prevent shadowing
- Add date format validation (YYYY-MM-DD pattern) on calendar routes
- Use timezone-aware datetime.now(tz=timezone.utc) in all services
- Add explicit type annotation for asyncio.gather results
This commit is contained in:
Yaojia Wang
2026-03-09 10:56:21 +01:00
parent 507194397e
commit 003c1d6ffc
12 changed files with 271 additions and 428 deletions

View File

@@ -2,11 +2,13 @@
import asyncio
import logging
from datetime import datetime, timedelta
from datetime import datetime, timezone, timedelta
from typing import Any
from openbb import obb
from obb_utils import to_list
logger = logging.getLogger(__name__)
PROVIDER = "yfinance"
@@ -19,7 +21,7 @@ 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)
items = to_list(result)
return items[0] if items else {}
except Exception:
logger.warning("ETF info failed for %s", symbol, exc_info=True)
@@ -28,12 +30,12 @@ async def get_etf_info(symbol: str) -> dict[str, Any]:
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")
start = (datetime.now(tz=timezone.utc) - 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)
return to_list(result)
except Exception:
logger.warning("ETF historical failed for %s", symbol, exc_info=True)
return []
@@ -43,7 +45,7 @@ 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)
return to_list(result)
except Exception:
logger.warning("ETF search failed for %s", query, exc_info=True)
return []
@@ -56,7 +58,7 @@ 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)
return to_list(result)
except Exception:
logger.warning("Available indices failed", exc_info=True)
return []
@@ -64,12 +66,12 @@ async def get_available_indices() -> list[dict[str, Any]]:
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")
start = (datetime.now(tz=timezone.utc) - 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)
return to_list(result)
except Exception:
logger.warning("Index historical failed for %s", symbol, exc_info=True)
return []
@@ -80,12 +82,12 @@ async def get_index_historical(symbol: str, days: int = 365) -> list[dict[str, A
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")
start = (datetime.now(tz=timezone.utc) - 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)
return to_list(result)
except Exception:
logger.warning("Crypto historical failed for %s", symbol, exc_info=True)
return []
@@ -95,7 +97,7 @@ 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)
return to_list(result)
except Exception:
logger.warning("Crypto search failed for %s", query, exc_info=True)
return []
@@ -108,12 +110,12 @@ 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")
start = (datetime.now(tz=timezone.utc) - 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)
return to_list(result)
except Exception:
logger.warning("Currency historical failed for %s", symbol, exc_info=True)
return []
@@ -128,7 +130,7 @@ async def get_options_chains(symbol: str) -> list[dict[str, Any]]:
result = await asyncio.to_thread(
obb.derivatives.options.chains, symbol, provider=PROVIDER
)
return _to_list(result)
return to_list(result)
except Exception:
logger.warning("Options chains failed for %s", symbol, exc_info=True)
return []
@@ -138,12 +140,12 @@ 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")
start = (datetime.now(tz=timezone.utc) - 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)
return to_list(result)
except Exception:
logger.warning("Futures historical failed for %s", symbol, exc_info=True)
return []
@@ -155,27 +157,7 @@ async def get_futures_curve(symbol: str) -> list[dict[str, Any]]:
result = await asyncio.to_thread(
obb.derivatives.futures.curve, symbol, provider=PROVIDER
)
return _to_list(result)
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