refactor: address python review findings
- Move FRED credential registration to FastAPI lifespan (was fragile import-order-dependent side-effect) - Add noqa E402 annotations for imports after curl_cffi patch - Fix all return type hints: bare dict -> dict[str, Any] - Move yfinance import to module level (was inline in functions) - Fix datetime.now() -> datetime.now(tz=timezone.utc) in openbb_service - Add try/except error handling to Group B service functions - Fix dict mutation in relative_rotation (immutable pattern) - Extract _classify_rrg_quadrant helper function - Fix type builtin shadow in routes_economy (type -> gdp_type) - Fix falsy int guard (if year: -> if year is not None:) - Remove user input echo from error messages
This commit is contained in:
@@ -1,8 +1,9 @@
|
||||
import asyncio
|
||||
import logging
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any
|
||||
|
||||
import yfinance as yf
|
||||
from openbb import obb
|
||||
|
||||
from obb_utils import to_list, first_or_empty
|
||||
@@ -12,15 +13,15 @@ logger = logging.getLogger(__name__)
|
||||
PROVIDER = "yfinance"
|
||||
|
||||
|
||||
async def get_quote(symbol: str) -> dict:
|
||||
async def get_quote(symbol: str) -> dict[str, Any]:
|
||||
result = await asyncio.to_thread(
|
||||
obb.equity.price.quote, symbol, provider=PROVIDER
|
||||
)
|
||||
return first_or_empty(result)
|
||||
|
||||
|
||||
async def get_historical(symbol: str, days: int = 365) -> list[dict]:
|
||||
start = (datetime.now() - timedelta(days=days)).strftime("%Y-%m-%d")
|
||||
async def get_historical(symbol: str, days: int = 365) -> list[dict[str, Any]]:
|
||||
start = (datetime.now(tz=timezone.utc) - timedelta(days=days)).strftime("%Y-%m-%d")
|
||||
result = await asyncio.to_thread(
|
||||
obb.equity.price.historical,
|
||||
symbol,
|
||||
@@ -36,42 +37,42 @@ async def get_historical(symbol: str, days: int = 365) -> list[dict]:
|
||||
]
|
||||
|
||||
|
||||
async def get_profile(symbol: str) -> dict:
|
||||
async def get_profile(symbol: str) -> dict[str, Any]:
|
||||
result = await asyncio.to_thread(
|
||||
obb.equity.profile, symbol, provider=PROVIDER
|
||||
)
|
||||
return first_or_empty(result)
|
||||
|
||||
|
||||
async def get_metrics(symbol: str) -> dict:
|
||||
async def get_metrics(symbol: str) -> dict[str, Any]:
|
||||
result = await asyncio.to_thread(
|
||||
obb.equity.fundamental.metrics, symbol, provider=PROVIDER
|
||||
)
|
||||
return first_or_empty(result)
|
||||
|
||||
|
||||
async def get_income(symbol: str) -> list[dict]:
|
||||
async def get_income(symbol: str) -> list[dict[str, Any]]:
|
||||
result = await asyncio.to_thread(
|
||||
obb.equity.fundamental.income, symbol, provider=PROVIDER
|
||||
)
|
||||
return to_list(result)
|
||||
|
||||
|
||||
async def get_balance(symbol: str) -> list[dict]:
|
||||
async def get_balance(symbol: str) -> list[dict[str, Any]]:
|
||||
result = await asyncio.to_thread(
|
||||
obb.equity.fundamental.balance, symbol, provider=PROVIDER
|
||||
)
|
||||
return to_list(result)
|
||||
|
||||
|
||||
async def get_cash_flow(symbol: str) -> list[dict]:
|
||||
async def get_cash_flow(symbol: str) -> list[dict[str, Any]]:
|
||||
result = await asyncio.to_thread(
|
||||
obb.equity.fundamental.cash, symbol, provider=PROVIDER
|
||||
)
|
||||
return to_list(result)
|
||||
|
||||
|
||||
async def get_financials(symbol: str) -> dict:
|
||||
async def get_financials(symbol: str) -> dict[str, Any]:
|
||||
income, balance, cash_flow = await asyncio.gather(
|
||||
get_income(symbol),
|
||||
get_balance(symbol),
|
||||
@@ -87,8 +88,6 @@ async def get_financials(symbol: str) -> dict:
|
||||
|
||||
async def get_price_target(symbol: str) -> float | None:
|
||||
"""Get consensus analyst price target via yfinance."""
|
||||
import yfinance as yf
|
||||
|
||||
def _fetch() -> float | None:
|
||||
t = yf.Ticker(symbol)
|
||||
return t.info.get("targetMeanPrice")
|
||||
@@ -100,14 +99,14 @@ async def get_price_target(symbol: str) -> float | None:
|
||||
return None
|
||||
|
||||
|
||||
async def get_news(symbol: str) -> list[dict]:
|
||||
async def get_news(symbol: str) -> list[dict[str, Any]]:
|
||||
result = await asyncio.to_thread(
|
||||
obb.news.company, symbol, provider=PROVIDER
|
||||
)
|
||||
return to_list(result)
|
||||
|
||||
|
||||
async def get_summary(symbol: str) -> dict:
|
||||
async def get_summary(symbol: str) -> dict[str, Any]:
|
||||
quote, profile, metrics, financials = await asyncio.gather(
|
||||
get_quote(symbol),
|
||||
get_profile(symbol),
|
||||
@@ -122,45 +121,45 @@ async def get_summary(symbol: str) -> dict:
|
||||
}
|
||||
|
||||
|
||||
async def get_gainers() -> list[dict]:
|
||||
async def get_gainers() -> list[dict[str, Any]]:
|
||||
result = await asyncio.to_thread(
|
||||
obb.equity.discovery.gainers, provider=PROVIDER
|
||||
)
|
||||
return to_list(result)
|
||||
|
||||
|
||||
async def get_losers() -> list[dict]:
|
||||
async def get_losers() -> list[dict[str, Any]]:
|
||||
result = await asyncio.to_thread(
|
||||
obb.equity.discovery.losers, provider=PROVIDER
|
||||
)
|
||||
return to_list(result)
|
||||
|
||||
|
||||
async def get_active() -> list[dict]:
|
||||
async def get_active() -> list[dict[str, Any]]:
|
||||
result = await asyncio.to_thread(
|
||||
obb.equity.discovery.active, provider=PROVIDER
|
||||
)
|
||||
return to_list(result)
|
||||
|
||||
|
||||
async def get_undervalued() -> list[dict]:
|
||||
async def get_undervalued() -> list[dict[str, Any]]:
|
||||
result = await asyncio.to_thread(
|
||||
obb.equity.discovery.undervalued_large_caps, provider=PROVIDER
|
||||
)
|
||||
return to_list(result)
|
||||
|
||||
|
||||
async def get_growth() -> list[dict]:
|
||||
async def get_growth() -> list[dict[str, Any]]:
|
||||
result = await asyncio.to_thread(
|
||||
obb.equity.discovery.growth_tech, provider=PROVIDER
|
||||
)
|
||||
return to_list(result)
|
||||
|
||||
|
||||
async def get_upgrades_downgrades(symbol: str, limit: int = 20) -> list[dict]:
|
||||
async def get_upgrades_downgrades(
|
||||
symbol: str, limit: int = 20,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Get analyst upgrades/downgrades via yfinance."""
|
||||
import yfinance as yf
|
||||
|
||||
def _fetch() -> list[dict[str, Any]]:
|
||||
t = yf.Ticker(symbol)
|
||||
df = t.upgrades_downgrades
|
||||
@@ -187,32 +186,54 @@ async def get_upgrades_downgrades(symbol: str, limit: int = 20) -> list[dict]:
|
||||
# --- Equity Fundamentals Extended (Group B) ---
|
||||
|
||||
|
||||
async def get_management(symbol: str) -> list[dict]:
|
||||
async def get_management(symbol: str) -> list[dict[str, Any]]:
|
||||
"""Get executive team info (name, title, compensation)."""
|
||||
result = await asyncio.to_thread(
|
||||
obb.equity.fundamental.management, symbol, provider=PROVIDER
|
||||
)
|
||||
return to_list(result)
|
||||
try:
|
||||
result = await asyncio.to_thread(
|
||||
obb.equity.fundamental.management, symbol, provider=PROVIDER
|
||||
)
|
||||
return to_list(result)
|
||||
except Exception:
|
||||
logger.warning("Management failed for %s", symbol, exc_info=True)
|
||||
return []
|
||||
|
||||
|
||||
async def get_dividends(symbol: str) -> list[dict]:
|
||||
async def get_dividends(symbol: str) -> list[dict[str, Any]]:
|
||||
"""Get historical dividend records."""
|
||||
result = await asyncio.to_thread(
|
||||
obb.equity.fundamental.dividends, symbol, provider=PROVIDER
|
||||
)
|
||||
return to_list(result)
|
||||
try:
|
||||
result = await asyncio.to_thread(
|
||||
obb.equity.fundamental.dividends, symbol, provider=PROVIDER
|
||||
)
|
||||
return to_list(result)
|
||||
except Exception:
|
||||
logger.warning("Dividends failed for %s", symbol, exc_info=True)
|
||||
return []
|
||||
|
||||
|
||||
async def get_filings(symbol: str, form_type: str | None = None) -> list[dict]:
|
||||
async def get_filings(
|
||||
symbol: str, form_type: str | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Get SEC filings (10-K, 10-Q, 8-K, etc.)."""
|
||||
kwargs: dict[str, Any] = {"symbol": symbol, "provider": "sec"}
|
||||
if form_type:
|
||||
kwargs["type"] = form_type
|
||||
result = await asyncio.to_thread(obb.equity.fundamental.filings, **kwargs)
|
||||
return to_list(result)
|
||||
try:
|
||||
kwargs: dict[str, Any] = {"symbol": symbol, "provider": "sec"}
|
||||
if form_type is not None:
|
||||
kwargs["type"] = form_type
|
||||
result = await asyncio.to_thread(
|
||||
obb.equity.fundamental.filings, **kwargs
|
||||
)
|
||||
return to_list(result)
|
||||
except Exception:
|
||||
logger.warning("Filings failed for %s", symbol, exc_info=True)
|
||||
return []
|
||||
|
||||
|
||||
async def search_company(query: str) -> list[dict]:
|
||||
async def search_company(query: str) -> list[dict[str, Any]]:
|
||||
"""Search for companies by name."""
|
||||
result = await asyncio.to_thread(obb.equity.search, query, provider="sec")
|
||||
return to_list(result)
|
||||
try:
|
||||
result = await asyncio.to_thread(
|
||||
obb.equity.search, query, provider="sec"
|
||||
)
|
||||
return to_list(result)
|
||||
except Exception:
|
||||
logger.warning("Company search failed for %s", query, exc_info=True)
|
||||
return []
|
||||
|
||||
Reference in New Issue
Block a user