summaryrefslogtreecommitdiff
path: root/backend/app/services
diff options
context:
space:
mode:
authorTyler Hoang <tyler@tylerhoang.xyz>2026-05-18 22:43:16 -0700
committerTyler Hoang <tyler@tylerhoang.xyz>2026-05-18 22:43:16 -0700
commit52635efd7d435b091b4f13897511ca8e2c48f0b9 (patch)
tree4d98b268502c6aa7c8988957d6e41dffd319534d /backend/app/services
parentacb628932215338b7971f3051b1e5d89e58573a1 (diff)
fix: add no-key fallback for sector ratio benchmarks
Diffstat (limited to 'backend/app/services')
-rw-r--r--backend/app/services/data_service.py61
1 files changed, 38 insertions, 23 deletions
diff --git a/backend/app/services/data_service.py b/backend/app/services/data_service.py
index ab06723..f913ec5 100644
--- a/backend/app/services/data_service.py
+++ b/backend/app/services/data_service.py
@@ -830,8 +830,6 @@ def compute_sector_ratio_benchmarks(symbol: str) -> dict[str, float]:
"""Median TTM ratio benchmarks from same-sector peers (FMP-backed when available)."""
sym = normalize_symbol(symbol)
fmp_key = os.getenv("FMP_API_KEY")
- if not fmp_key:
- return {}
info = get_company_info(sym)
sector_raw = info.get("sector") if isinstance(info, dict) else None
@@ -843,27 +841,44 @@ def compute_sector_ratio_benchmarks(symbol: str) -> dict[str, float]:
return {}
peer_symbols: list[str] = []
- try:
- with httpx.Client(timeout=3.5) as client:
- res = client.get(
- "https://financialmodelingprep.com/api/v3/stock-screener",
- params={
- "sector": sector,
- "isEtf": "false",
- "isActivelyTrading": "true",
- "limit": 12,
- "apikey": fmp_key,
- },
- )
- rows = res.json()
- if isinstance(rows, list):
- for row in rows:
- psym = normalize_symbol((row or {}).get("symbol"))
- if not psym or psym == sym:
- continue
- peer_symbols.append(psym)
- except Exception:
- return {}
+ if fmp_key:
+ try:
+ with httpx.Client(timeout=3.5) as client:
+ res = client.get(
+ "https://financialmodelingprep.com/api/v3/stock-screener",
+ params={
+ "sector": sector,
+ "isEtf": "false",
+ "isActivelyTrading": "true",
+ "limit": 12,
+ "apikey": fmp_key,
+ },
+ )
+ rows = res.json()
+ if isinstance(rows, list):
+ for row in rows:
+ psym = normalize_symbol((row or {}).get("symbol"))
+ if not psym or psym == sym:
+ continue
+ peer_symbols.append(psym)
+ except Exception:
+ peer_symbols = []
+
+ # No-key or FMP failure fallback: search by sector term, then filter by exact sector.
+ if not peer_symbols:
+ try:
+ candidates = search_tickers(sector)
+ except Exception:
+ candidates = []
+ target_sector = sector.lower()
+ for row in candidates[:24]:
+ psym = normalize_symbol((row or {}).get("symbol"))
+ if not psym or psym == sym:
+ continue
+ pinfo = get_company_info(psym)
+ psector = str((pinfo or {}).get("sector") or "").strip().lower()
+ if psector and psector == target_sector:
+ peer_symbols.append(psym)
if not peer_symbols:
return {}