REST API wrapping OpenBB SDK for stock data, sentiment analysis, technical indicators, macro data, and rule-based portfolio analysis. - Stock data via yfinance (quote, profile, metrics, financials, historical, news) - News sentiment via Alpha Vantage (per-article, per-ticker scores) - Analyst data via Finnhub (recommendations, insider trades, upgrades) - Macro data via FRED (Fed rate, CPI, GDP, unemployment, treasury yields) - Technical indicators via openbb-technical (RSI, MACD, SMA, EMA, Bollinger) - Rule-based portfolio analysis engine (BUY_MORE/HOLD/SELL) - Stock discovery (gainers, losers, active, undervalued, growth) - 102 tests, all passing
209 lines
6.4 KiB
Python
209 lines
6.4 KiB
Python
import functools
|
|
import logging
|
|
from collections.abc import Awaitable, Callable
|
|
from typing import ParamSpec, TypeVar
|
|
|
|
from fastapi import APIRouter, HTTPException, Path, Query
|
|
|
|
from mappers import (
|
|
discover_items_from_list,
|
|
metrics_from_dict,
|
|
profile_from_dict,
|
|
quote_from_dict,
|
|
)
|
|
from models import (
|
|
SYMBOL_PATTERN,
|
|
ApiResponse,
|
|
FinancialsResponse,
|
|
HistoricalBar,
|
|
NewsItem,
|
|
PortfolioRequest,
|
|
PortfolioResponse,
|
|
SummaryResponse,
|
|
)
|
|
import openbb_service
|
|
import analysis_service
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
router = APIRouter(prefix="/api/v1")
|
|
|
|
P = ParamSpec("P")
|
|
R = TypeVar("R")
|
|
|
|
|
|
def _validate_symbol(symbol: str) -> str:
|
|
if not SYMBOL_PATTERN.match(symbol):
|
|
raise HTTPException(status_code=400, detail="Invalid symbol format")
|
|
return symbol.upper()
|
|
|
|
|
|
def _safe(fn: Callable[P, Awaitable[R]]) -> Callable[P, Awaitable[R]]:
|
|
"""Decorator to catch OpenBB errors and return 502."""
|
|
@functools.wraps(fn)
|
|
async def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
|
|
try:
|
|
return await fn(*args, **kwargs)
|
|
except HTTPException:
|
|
raise
|
|
except Exception:
|
|
logger.exception("Upstream data error")
|
|
raise HTTPException(
|
|
status_code=502,
|
|
detail="Data provider error. Check server logs.",
|
|
)
|
|
return wrapper # type: ignore[return-value]
|
|
|
|
|
|
# --- Stock Data ---
|
|
|
|
|
|
@router.get("/stock/{symbol}/quote", response_model=ApiResponse)
|
|
@_safe
|
|
async def stock_quote(symbol: str = Path(..., min_length=1, max_length=20)):
|
|
"""Get current quote for a stock."""
|
|
symbol = _validate_symbol(symbol)
|
|
data = await openbb_service.get_quote(symbol)
|
|
return ApiResponse(data=quote_from_dict(symbol, data).model_dump())
|
|
|
|
|
|
@router.get("/stock/{symbol}/profile", response_model=ApiResponse)
|
|
@_safe
|
|
async def stock_profile(symbol: str = Path(..., min_length=1, max_length=20)):
|
|
"""Get company profile."""
|
|
symbol = _validate_symbol(symbol)
|
|
data = await openbb_service.get_profile(symbol)
|
|
return ApiResponse(data=profile_from_dict(symbol, data).model_dump())
|
|
|
|
|
|
@router.get("/stock/{symbol}/metrics", response_model=ApiResponse)
|
|
@_safe
|
|
async def stock_metrics(symbol: str = Path(..., min_length=1, max_length=20)):
|
|
"""Get key financial metrics (PE, PB, ROE, etc.)."""
|
|
symbol = _validate_symbol(symbol)
|
|
data = await openbb_service.get_metrics(symbol)
|
|
return ApiResponse(data=metrics_from_dict(symbol, data).model_dump())
|
|
|
|
|
|
@router.get("/stock/{symbol}/financials", response_model=ApiResponse)
|
|
@_safe
|
|
async def stock_financials(symbol: str = Path(..., min_length=1, max_length=20)):
|
|
"""Get income statement, balance sheet, and cash flow."""
|
|
symbol = _validate_symbol(symbol)
|
|
data = await openbb_service.get_financials(symbol)
|
|
return ApiResponse(data=FinancialsResponse(**data).model_dump())
|
|
|
|
|
|
@router.get("/stock/{symbol}/historical", response_model=ApiResponse)
|
|
@_safe
|
|
async def stock_historical(
|
|
symbol: str = Path(..., min_length=1, max_length=20),
|
|
days: int = Query(default=365, ge=1, le=3650),
|
|
):
|
|
"""Get historical price data."""
|
|
symbol = _validate_symbol(symbol)
|
|
data = await openbb_service.get_historical(symbol, days=days)
|
|
bars = [
|
|
HistoricalBar(
|
|
date=str(item.get("date", "")),
|
|
open=item.get("open"),
|
|
high=item.get("high"),
|
|
low=item.get("low"),
|
|
close=item.get("close"),
|
|
volume=item.get("volume"),
|
|
).model_dump()
|
|
for item in data
|
|
]
|
|
return ApiResponse(data=bars)
|
|
|
|
|
|
@router.get("/stock/{symbol}/news", response_model=ApiResponse)
|
|
@_safe
|
|
async def stock_news(symbol: str = Path(..., min_length=1, max_length=20)):
|
|
"""Get recent company news."""
|
|
symbol = _validate_symbol(symbol)
|
|
data = await openbb_service.get_news(symbol)
|
|
news = [
|
|
NewsItem(
|
|
title=item.get("title"),
|
|
url=item.get("url"),
|
|
date=str(item.get("date", "")),
|
|
source=item.get("source"),
|
|
).model_dump()
|
|
for item in data
|
|
]
|
|
return ApiResponse(data=news)
|
|
|
|
|
|
@router.get("/stock/{symbol}/summary", response_model=ApiResponse)
|
|
@_safe
|
|
async def stock_summary(symbol: str = Path(..., min_length=1, max_length=20)):
|
|
"""Get aggregated stock data: quote + profile + metrics + financials."""
|
|
symbol = _validate_symbol(symbol)
|
|
data = await openbb_service.get_summary(symbol)
|
|
summary = SummaryResponse(
|
|
quote=quote_from_dict(symbol, data.get("quote", {})),
|
|
profile=profile_from_dict(symbol, data.get("profile", {})),
|
|
metrics=metrics_from_dict(symbol, data.get("metrics", {})),
|
|
financials=FinancialsResponse(
|
|
**data.get("financials", {"symbol": symbol})
|
|
),
|
|
)
|
|
return ApiResponse(data=summary.model_dump())
|
|
|
|
|
|
# --- Portfolio Analysis ---
|
|
|
|
|
|
@router.post("/portfolio/analyze", response_model=ApiResponse)
|
|
@_safe
|
|
async def portfolio_analyze(request: PortfolioRequest):
|
|
"""Analyze portfolio holdings with rule-based engine."""
|
|
result: PortfolioResponse = await analysis_service.analyze_portfolio(
|
|
request.holdings
|
|
)
|
|
return ApiResponse(data=result.model_dump())
|
|
|
|
|
|
# --- Discovery ---
|
|
|
|
|
|
@router.get("/discover/gainers", response_model=ApiResponse)
|
|
@_safe
|
|
async def discover_gainers():
|
|
"""Get top gainers (US market)."""
|
|
data = await openbb_service.get_gainers()
|
|
return ApiResponse(data=discover_items_from_list(data))
|
|
|
|
|
|
@router.get("/discover/losers", response_model=ApiResponse)
|
|
@_safe
|
|
async def discover_losers():
|
|
"""Get top losers (US market)."""
|
|
data = await openbb_service.get_losers()
|
|
return ApiResponse(data=discover_items_from_list(data))
|
|
|
|
|
|
@router.get("/discover/active", response_model=ApiResponse)
|
|
@_safe
|
|
async def discover_active():
|
|
"""Get most active stocks (US market)."""
|
|
data = await openbb_service.get_active()
|
|
return ApiResponse(data=discover_items_from_list(data))
|
|
|
|
|
|
@router.get("/discover/undervalued", response_model=ApiResponse)
|
|
@_safe
|
|
async def discover_undervalued():
|
|
"""Get undervalued large cap stocks."""
|
|
data = await openbb_service.get_undervalued()
|
|
return ApiResponse(data=discover_items_from_list(data))
|
|
|
|
|
|
@router.get("/discover/growth", response_model=ApiResponse)
|
|
@_safe
|
|
async def discover_growth():
|
|
"""Get growth tech stocks."""
|
|
data = await openbb_service.get_growth()
|
|
return ApiResponse(data=discover_items_from_list(data))
|