Prerequisite refactor: - Consolidate duplicate _to_dicts into shared obb_utils.to_list - Add fetch_historical and first_or_empty helpers to obb_utils Phase 1 - Local computation (no provider risk): - Group I: 12 technical indicators (ATR, ADX, Stoch, OBV, Ichimoku, Donchian, Aroon, CCI, Keltner, Fibonacci, A/D, Volatility Cones) - Group J: Sortino, Omega ratios + rolling stats (variance, stdev, mean, skew, kurtosis, quantile via generic endpoint) - Group H: ECB currency reference rates Phase 2 - FRED/Federal Reserve providers: - Group C: 10 fixed income endpoints (treasury rates, yield curve, auctions, TIPS, EFFR, SOFR, HQM, commercial paper, spot rates, spreads) - Group D: 11 economy endpoints (CPI, GDP, unemployment, PCE, money measures, CLI, HPI, FRED search, balance of payments, Fed holdings, FOMC documents) - Group E: 5 survey endpoints (Michigan, SLOOS, NFP, Empire State, BLS search) Phase 3 - SEC/stockgrid/FINRA providers: - Group B: 4 equity fundamental endpoints (management, dividends, SEC filings, company search) - Group A: 4 shorts/dark pool endpoints (short volume, FTD, short interest, OTC dark pool) - Group F: 3 index/ETF enhanced (S&P 500 multiples, index constituents, ETF N-PORT) Phase 4 - Regulators: - Group G: 5 regulatory endpoints (COT report, COT search, SEC litigation, institution search, CIK mapping) Security hardening: - Service-layer allowlists for all getattr dynamic dispatch - Regex validation on date, country, security_type, form_type params - Exception handling in fetch_historical - Callable guard on rolling stat dispatch Total: 32 existing + 67 new = 99 endpoints, all free providers.
84 lines
2.3 KiB
Python
84 lines
2.3 KiB
Python
"""Macro economic data via OpenBB FRED provider."""
|
|
|
|
import asyncio
|
|
import logging
|
|
from typing import Any
|
|
|
|
from openbb import obb
|
|
|
|
from obb_utils import to_list
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
PROVIDER = "fred"
|
|
|
|
# Key FRED series IDs
|
|
SERIES = {
|
|
"fed_funds_rate": "FEDFUNDS",
|
|
"us_10y_treasury": "DGS10",
|
|
"us_2y_treasury": "DGS2",
|
|
"cpi_yoy": "CPIAUCSL",
|
|
"unemployment_rate": "UNRATE",
|
|
"gdp_growth": "A191RL1Q225SBEA",
|
|
"sp500": "SP500",
|
|
"vix": "VIXCLS",
|
|
}
|
|
|
|
|
|
async def get_series(
|
|
series_id: str, limit: int = 10, latest: bool = False,
|
|
) -> list[dict[str, Any]]:
|
|
"""Get a FRED time series by ID."""
|
|
try:
|
|
fetch_limit = limit if not latest else None
|
|
kwargs: dict[str, Any] = {
|
|
"symbol": series_id,
|
|
"provider": PROVIDER,
|
|
}
|
|
if fetch_limit is not None:
|
|
kwargs["limit"] = fetch_limit
|
|
result = await asyncio.to_thread(
|
|
obb.economy.fred_series,
|
|
**kwargs,
|
|
)
|
|
items = to_list(result)
|
|
items = [
|
|
{**item, "date": str(item["date"])}
|
|
if "date" in item and not isinstance(item["date"], str)
|
|
else item
|
|
for item in items
|
|
]
|
|
if latest:
|
|
items = items[-limit:]
|
|
return items
|
|
except Exception:
|
|
logger.warning("Failed to fetch FRED series %s", series_id, exc_info=True)
|
|
return []
|
|
|
|
|
|
async def get_macro_overview() -> dict[str, Any]:
|
|
"""Get a summary of key macro indicators."""
|
|
tasks = {
|
|
name: get_series(series_id, limit=1, latest=True)
|
|
for name, series_id in SERIES.items()
|
|
}
|
|
results = await asyncio.gather(*tasks.values(), return_exceptions=True)
|
|
|
|
overview: dict[str, Any] = {}
|
|
for (name, series_id), result in zip(SERIES.items(), results):
|
|
if isinstance(result, BaseException):
|
|
logger.warning("Failed to fetch %s: %s", name, result)
|
|
overview[name] = None
|
|
elif result and len(result) > 0:
|
|
entry = result[-1]
|
|
# FRED returns values keyed by series ID, not "value"
|
|
value = entry.get(series_id) or entry.get("value")
|
|
overview[name] = {
|
|
"value": value,
|
|
"date": str(entry.get("date", "")),
|
|
}
|
|
else:
|
|
overview[name] = None
|
|
|
|
return overview
|