Spaces:
Sleeping
Sleeping
Charan S commited on
Commit Β·
8d4d0bb
1
Parent(s): 14673f9
feat: added filing module
Browse filesFiles changed (15)
- backend/api/routes/stocks.py+27-1
- backend/graph/finora_graph.py+4-1
- backend/graph/nodes/filings_rag_node.pyAdded+79
- backend/graph/nodes/fusion_node.py+35-1
- backend/graph/state.py+1
- backend/main.py+4-4
- backend/rag/ingestion/filings.py+31-21
- backend/rag/yahoo_client.py+165-38
- backend/scripts/build_universe.py+40-108
- backend/scripts/eval_rag.py+22-21
- backend/scripts/ingest_filings.pyAdded+96
- backend/scripts/ingest_historical.py+6-8
- backend/scripts/ingest_news.py+4-7
- requirements-dev.txt+9-10
- requirements.txt+47-23
7 unmodified lines89101112131454 unmodified lines69707172737425 unmodified lines100101102103104105105 unmodified lines21121221321421521626 unmodified lines2432442452462472487 unmodified linesfrom backend.api.middleware.rate_limit import limiterfrom backend.rag.ingestion.universe import universefrom backend.rag.yahoo_client import fetch_company_info, fetch_fundamentals, fetch_news, fetch_ohlcv, fetch_quote, fetch_sector_etfslog = structlog.get_logger()router = APIRouter(tags=["stocks"])54 unmodified linesreturn_pct: floatprice: float | None = Noneclass StockDetail(BaseModel):ticker: str25 unmodified linesnews_rag: list[NewsItem]historical_signals: list[HistoricalSignal]similar_stocks: list[SimilarStock] = []_SECTORS_CACHE: tuple[list[dict], float] | None = None105 unmodified linesexcept Exception:pass # Qdrant unavailable or ticker not in historical corpusac = fund.get("analyst_consensus", {}) or {}consensus = AnalystConsensus(buy=int(ac.get("buy") or 0),26 unmodified lines"ohlcv_7d": ohlcv_7d,"news_rag": news_rag,"historical_signals": historical_signals,}loop = asyncio.get_running_loop()7 unmodified lines89101112131454 unmodified lines6970717273747576777879808125 unmodified lines107108109110111112113105 unmodified lines21922022122222322422522622722822923023123223323423523623723823924024126 unmodified lines2682692702712722732747 unmodified linesfrom backend.api.middleware.rate_limit import limiterfrom backend.rag.ingestion.universe import universefrom backend.rag.yahoo_client import fetch_company_info, fetch_fundamentals, fetch_news, fetch_ohlcv, fetch_quote, fetch_sector_etfs, fetch_filingslog = structlog.get_logger()router = APIRouter(tags=["stocks"])54 unmodified linesreturn_pct: floatprice: float | None = Noneclass FilingItem(BaseModel):ticker: strform: strfiling_date: straccession_number: strdocument: strurl: strclass StockDetail(BaseModel):ticker: str25 unmodified linesnews_rag: list[NewsItem]historical_signals: list[HistoricalSignal]similar_stocks: list[SimilarStock] = []filings: list[FilingItem] = []_SECTORS_CACHE: tuple[list[dict], float] | None = None105 unmodified linesexcept Exception:pass # Qdrant unavailable or ticker not in historical corpusfilings: list[FilingItem] = []try:raw_filings = fetch_filings(yf_ticker)for f in raw_filings:filings.append(FilingItem(ticker=display_ticker,form=f.get("form", ""),filing_date=f.get("filing_date", f.get("date", "")),accession_number=f.get("accession_number", ""),document=f.get("document", ""),url=f.get("url", ""),))except Exception as exc:log.warning("filings_fetch_failed", ticker=yf_ticker, error=str(exc))filings = []ac = fund.get("analyst_consensus", {}) or {}consensus = AnalystConsensus(buy=int(ac.get("buy") or 0),26 unmodified lines"ohlcv_7d": ohlcv_7d,"news_rag": news_rag,"historical_signals": historical_signals,"filings": filings,}loop = asyncio.get_running_loop()
20 unmodified lines21222324252613 unmodified lines4041424344451 unmodified line4748495051523 unmodified lines5657585960616220 unmodified linesfrom backend.graph.nodes.fundamentals_node import fundamentals_nodefrom backend.graph.nodes.historical_rag_node import historical_rag_nodefrom backend.graph.nodes.intent_classifier import intent_classifier_nodefrom backend.graph.nodes.news_rag_node import news_rag_nodefrom backend.graph.nodes.realtime_node import realtime_nodefrom backend.graph.nodes.response_node import response_node13 unmodified linesnews_rag_node(state),historical_rag_node(state),fundamentals_node(state),]results = await asyncio.gather(*tasks, return_exceptions=True)1 unmodified line"realtime_context": None,"news_chunks": [],"historical_chunks": [],"fundamental_data": None,"sector_context": None,"retrieval_scores": {},3 unmodified lineslog.error("parallel_retrieval_branch_failed", error=str(r))continuefor key, val in r.items():if key in ("news_chunks", "historical_chunks"):merged[key] = merged.get(key, []) + (val or [])elif key == "retrieval_scores":merged["retrieval_scores"].update(val or {})20 unmodified lines2122232425262713 unmodified lines414243444546471 unmodified line495051525354553 unmodified lines5960616263646520 unmodified linesfrom backend.graph.nodes.fundamentals_node import fundamentals_nodefrom backend.graph.nodes.historical_rag_node import historical_rag_nodefrom backend.graph.nodes.intent_classifier import intent_classifier_nodefrom backend.graph.nodes.filings_rag_node import filings_rag_nodefrom backend.graph.nodes.news_rag_node import news_rag_nodefrom backend.graph.nodes.realtime_node import realtime_nodefrom backend.graph.nodes.response_node import response_node13 unmodified linesnews_rag_node(state),historical_rag_node(state),fundamentals_node(state),filings_rag_node(state),]results = await asyncio.gather(*tasks, return_exceptions=True)1 unmodified line"realtime_context": None,"news_chunks": [],"historical_chunks": [],"filings_chunks": [],"fundamental_data": None,"sector_context": None,"retrieval_scores": {},3 unmodified lineslog.error("parallel_retrieval_branch_failed", error=str(r))continuefor key, val in r.items():if key in ("news_chunks", "historical_chunks", "filings_chunks"):merged[key] = merged.get(key, []) + (val or [])elif key == "retrieval_scores":merged["retrieval_scores"].update(val or {})
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879"""Filings RAG node β deep fundamental context from SEC 10-K / 10-Q."""
from __future__ import annotations
import structlogimport asyncio
from backend.graph.state import FiNoraStatefrom backend.rag.pipeline import run_rag_branchfrom backend.rag.retrieval.router import RetrievalBranch
log = structlog.get_logger()
_BRANCH = RetrievalBranch( intent="filings", collection="filings", use_hyde=True, # filings benefit from abstraction description="SEC 10-K, 10-Q filings β risks, MD&A, financial disclosures", allow_global_fallback=False,)
_TOP_K = 5
def _rewrite_query(query: str) -> str: """ Light steering β forces retrieval toward high-value sections without breaking user intent. """ return ( f"{query} " "management discussion analysis risks growth strategy revenue margins guidance" )
async def filings_rag_node(state: FiNoraState) -> dict: """ SEC filings retrieval for stock-level context. """
query = state["query"] ticker = state.get("ticker", "")
rewritten_query = _rewrite_query(query)
loop = asyncio.get_running_loop() result = await loop.run_in_executor( None, run_rag_branch, rewritten_query, ticker, _BRANCH, )
chunks = [ { "text": ch.text, "score": ch.score, **ch.metadata, } for ch in result.chunks[:_TOP_K] ]
scores = result.retrieval_scores
log.info( "filings_rag_done", ticker=ticker, chunks=len(chunks), scores=scores, )
return { "filings_chunks": chunks, "retrieval_scores": { **state.get("retrieval_scores", {}), "filings": scores, }, }162 unmodified lines1631641651661671682 unmodified lines171172173174175176161 unmodified lines33833934034134234334434534686 unmodified lines43343443543643743819 unmodified lines45845946046146246378 unmodified lines542543544545546547162 unmodified linesreturn " | ".join(parts) if parts else "[LIMITED FUNDAMENTAL DATA]"def _compute_insight_flags(state: FiNoraState) -> list[str]:"""Pre-compute interpretive signals grounded in data β no hallucination possible."""2 unmodified linesfd = state.get("fundamental_data") or {}sym = _currency_sym(state.get("currency", "USD"))# Volume anomalyvol = rt.get("volume")avg_vol = rt.get("avg_volume_30d")161 unmodified linesstrong_signals += 1has_news = bool(state.get("news_chunks"))has_historical = bool(state.get("historical_chunks"))has_fundamentals = bool(fd)data_sources = sum([bool(rt), has_news, has_historical, has_fundamentals])if strong_signals >= 3 and data_sources >= 3:return "high"86 unmodified linesscore += 0.3if state.get("news_chunks"):score += 0.3if state.get("historical_chunks"):score += 0.25if state.get("fundamental_data"):19 unmodified linesrt_section = _fmt_realtime(rt, currency)news_section = _fmt_chunks(state.get("news_chunks", []), "NEWS")# Historical: prefer deep RAG chunks (historical_rag_node) when intent fired,# otherwise use always-available patterns fetched alongside realtime data78 unmodified lines{news_section}{hist_section}{chr(10) + sector_section if sector_section else ""}"""162 unmodified lines1631641651661671681691701711721731741751761771781791801811821832 unmodified lines186187188189190191192193194195196197198199200201202203204161 unmodified lines36636736836937037137237337437586 unmodified lines46246346446546646746846919 unmodified lines48949049149249349449578 unmodified lines574575576577578579580581162 unmodified linesreturn " | ".join(parts) if parts else "[LIMITED FUNDAMENTAL DATA]"def _fmt_filings(chunks: list[dict]) -> str:if not chunks:return "[NO FILINGS DATA]"lines = [f"[FILINGS CONTEXT β {len(chunks)} excerpts]"]for i, ch in enumerate(chunks[:4], 1):form = ch.get("filing_type", "")period = ch.get("period", "")text = ch.get("text", "")[:400]lines.append(f"[{i}] {form} ({period}): {text}")return "\n".join(lines)def _compute_insight_flags(state: FiNoraState) -> list[str]:"""Pre-compute interpretive signals grounded in data β no hallucination possible."""2 unmodified linesfd = state.get("fundamental_data") or {}sym = _currency_sym(state.get("currency", "USD"))filings = state.get("filings_chunks", [])if filings:recent_forms = {ch.get("filing_type", "") for ch in filings}if any(f in ("10-K", "10-Q", "Annual Report", "Quarterly Results") for f in recent_forms):flags.append("Recent earnings/financial filings available β includes official performance disclosures")elif any(f in ("8-K", "Corporate Action") for f in recent_forms):flags.append("Recent corporate event filings detected β may indicate material business updates")else:flags.append("Recent company filings available β includes primary disclosures and management commentary")# Volume anomalyvol = rt.get("volume")avg_vol = rt.get("avg_volume_30d")161 unmodified linesstrong_signals += 1has_news = bool(state.get("news_chunks"))has_filings = bool(state.get("filings_chunks"))has_historical = bool(state.get("historical_chunks"))has_fundamentals = bool(fd)data_sources = sum([bool(rt), has_news, has_filings, has_historical, has_fundamentals])if strong_signals >= 3 and data_sources >= 3:return "high"86 unmodified linesscore += 0.3if state.get("news_chunks"):score += 0.3if state.get("filings_chunks"):score += 0.35if state.get("historical_chunks"):score += 0.25if state.get("fundamental_data"):19 unmodified linesrt_section = _fmt_realtime(rt, currency)news_section = _fmt_chunks(state.get("news_chunks", []), "NEWS")filings_section = _fmt_filings(state.get("filings_chunks", []))# Historical: prefer deep RAG chunks (historical_rag_node) when intent fired,# otherwise use always-available patterns fetched alongside realtime data78 unmodified lines{news_section}{filings_section}{hist_section}{chr(10) + sector_section if sector_section else ""}"""
26 unmodified lines27282930313226 unmodified lines# Retrieval outputs (parallel branches append β operator.add merges lists)realtime_context: dict | Nonenews_chunks: Annotated[list[dict], operator.add]historical_chunks: Annotated[list[dict], operator.add]fundamental_data: dict | Nonesector_context: dict | None # sector ETF performance + similar stocks26 unmodified lines2728293031323326 unmodified lines# Retrieval outputs (parallel branches append β operator.add merges lists)realtime_context: dict | Nonenews_chunks: Annotated[list[dict], operator.add]filings_chunks: list[dict]historical_chunks: Annotated[list[dict], operator.add]fundamental_data: dict | Nonesector_context: dict | None # sector ETF performance + similar stocks
28 unmodified lines2930313233343536373828 unmodified linesdef _warm_yahoo_session() -> None:"""Prime curl_cffi session cookies + crumb before first real request."""try:from backend.rag.yahoo_client import _warm_session, _get_crumb_warm_session("AAPL")_warm_session("AAPL")crumb = _get_crumb()log.info("yahoo_session_warmed", crumb_ok=bool(crumb))except Exception as exc:log.warning("yahoo_warm_failed", error=str(exc))28 unmodified lines2930313233343536373828 unmodified linesdef _warm_yahoo_session() -> None:"""Prime curl_cffi session cookies + crumb before first real request."""try:from backend.rag.yahoo_client import _warm_session, _get_valid_crumbticker = "AAPL"_warm_session(ticker)crumb = _get_valid_crumb(ticker)log.info("yahoo_session_warmed", crumb_ok=bool(crumb))except Exception as exc:log.warning("yahoo_warm_failed", error=str(exc))
24 unmodified lines2526272829303132333435363738394041424344454647484950515253545543 unmodified lines991001011021031041051061071086 unmodified lines1151161171181191201211225 unmodified lines12812913013113213313413513613713813924 unmodified lines_EDGAR_BASE = "https://data.sec.gov"_HEADERS = {"User-Agent": os.getenv("SEC_EDGAR_USER_AGENT", "contact@finora.app")}_FORM_TYPES = {"10-K", "10-Q"}def _get_cik(ticker: str) -> str | None:"""Look up SEC CIK number for a ticker."""try:resp = requests.get(f"{_EDGAR_BASE}/submissions/",params={"action": "getcompany", "company": ticker, "type": "10-K", "dateb": "", "owner": "include"},headers=_HEADERS,timeout=10,)# Use the company tickers JSON instead β faster and reliabletickers_resp = requests.get("https://www.sec.gov/files/company_tickers.json",headers=_HEADERS,timeout=10,)tickers_resp.raise_for_status()data = tickers_resp.json()for entry in data.values():if entry.get("ticker", "").upper() == ticker.upper():return str(entry["cik_str"]).zfill(10)except Exception as exc:log.error("edgar_cik_lookup_failed", ticker=ticker, error=str(exc))return Nonedef _get_recent_filings(cik: str, max_filings: int = 3) -> list[dict]:43 unmodified linestext = re.sub(r"&[a-z]+;", " ", text)text = re.sub(r"\s{3,}", "\n\n", text)# Take middle section (skip boilerplate headers/footers)words = text.split()if len(words) > 2000:text = " ".join(words[200:8000]) # ~7800 words of substantive contentreturn text.strip()except Exception as exc:6 unmodified linesclient: QdrantClient | None = None,max_filings: int = 2,) -> int:# Only US tickers β NIFTY 50 uses Indian exchanges, no SEC filingsif ticker.endswith(".NS") or ticker.endswith(".BSE"):return 0c = client or get_client()5 unmodified linesreturn 0filings = _get_recent_filings(cik, max_filings)if not filings:return 0total_chunks = 0for filing in filings:time.sleep(0.5) # SEC fair use: no hammeringtext = _fetch_filing_text(filing["cik"], filing["accession"], filing["primary_doc"])if len(text) < 500:continue24 unmodified lines25262728293031323334353637383940414243444546474849505152535455565758596043 unmodified lines1041051061071081091101111126 unmodified lines1191201211221231241251261271281295 unmodified lines13513613713813914014114214314414514614714814924 unmodified lines_EDGAR_BASE = "https://data.sec.gov"_HEADERS = {"User-Agent": os.getenv("SEC_EDGAR_USER_AGENT", "contact@finora.app")}_FORM_TYPES = {"10-K", "10-Q"}_SEC_MAP = Nonedef _load_sec_map():global _SEC_MAPif _SEC_MAP:return _SEC_MAPtry:resp = requests.get("https://www.sec.gov/files/company_tickers.json",headers=_HEADERS,timeout=10,)resp.raise_for_status()data = resp.json()_SEC_MAP = {entry["ticker"].upper(): str(entry["cik_str"]).zfill(10)for entry in data.values()}return _SEC_MAPexcept Exception as exc:log.error("sec_map_failed", error=str(exc))return {}def _get_cik(ticker: str) -> str | None:sec_map = _load_sec_map()return sec_map.get(ticker.upper())def _get_recent_filings(cik: str, max_filings: int = 3) -> list[dict]:43 unmodified linestext = re.sub(r"&[a-z]+;", " ", text)text = re.sub(r"\s{3,}", "\n\n", text)words = text.split()if len(words) > 8000:text = " ".join(words[:8000])return text.strip()except Exception as exc:6 unmodified linesclient: QdrantClient | None = None,max_filings: int = 2,) -> int:log.info("filing_start", ticker=ticker)# Only US tickers β NIFTY 50 uses Indian exchanges, no SEC filingsif ticker.endswith((".NS", ".BO")):return 0c = client or get_client()5 unmodified linesreturn 0filings = _get_recent_filings(cik, max_filings)log.info("filings_found", ticker=ticker, count=len(filings))if not filings:return 0total_chunks = 0for filing in filings:time.sleep(1)text = _fetch_filing_text(filing["cik"], filing["accession"], filing["primary_doc"])if len(text) < 500:continue
15 unmodified lines16171819202113 unmodified lines3536373839404142434445464748495051525398 unmodified lines15215315415515615715815916016116216316416516625 unmodified lines1921931941951961971981992002012022032048 unmodified lines2132142152162172182192202212222232242252262272282292302312322331 unmodified line2352362372382392402412423 unmodified lines2462472482492502512522532542552562572582592602612622635 unmodified lines26927027127227327427527627747 unmodified lines3253263273283293303316 unmodified lines33833934034134234334448 unmodified lines39339439515 unmodified linesimport pandas as pdimport structloglog = structlog.get_logger()try:13 unmodified lines_CRUMB_TTL = 3600 # secondsdef _get_crumb() -> str:global _crumb, _crumb_tsif _crumb and time.time() - _crumb_ts < _CRUMB_TTL:return _crumbtry:r = _session.get(f"{_BASE2}/v1/test/getcrumb", timeout=10)if r.status_code == 200 and r.text.strip():_crumb = r.text.strip()_crumb_ts = time.time()return _crumbexcept Exception as exc:log.warning("crumb_fetch_failed", error=str(exc))return ""def _warm_session(ticker: str) -> None:98 unmodified linesmeta = chart_result[0].get("meta", {})price = meta.get("regularMarketPrice")prev_close = meta.get("chartPreviousClose") or meta.get("previousClose")change = round(price - prev_close, 4) if price and prev_close else Nonepct_change = round(change / prev_close * 100, 2) if change and prev_close else None# Intraday OHLC from timestampsquote = chart_result[0].get("indicators", {}).get("quote", [{}])[0]opens = [v for v in (quote.get("open") or []) if v]highs = [v for v in (quote.get("high") or []) if v]lows = [v for v in (quote.get("low") or []) if v]volumes = [v for v in (quote.get("volume") or []) if v]return {"ticker": ticker,25 unmodified lines"""if not _AVAILABLE:return []try:import datetime as _dtimport xml.etree.ElementTree as _ET# Build locale-aware queryis_india = ticker.endswith((".NS", ".BO"))base = ticker.replace(".NS", "").replace(".BO", "")if is_india:query = f"{base} NSE stock India"params = {"q": query, "hl": "en-IN", "gl": "IN", "ceid": "IN:en"}8 unmodified linesroot = _ET.fromstring(r.content)items = root.findall(".//item")[:count]results: list[dict] = []for item in items:title = item.findtext("title", "")link = item.findtext("link", "")source = item.findtext("source", "Google News")pub_date = item.findtext("pubDate", "")description = item.findtext("description", "")# Parse date: "Fri, 24 Apr 2026 07:30:00 GMT"try:dt = _dt.datetime.strptime(pub_date[:16].strip(), "%a, %d %b %Y")date_str = dt.strftime("%Y-%m-%d")except Exception:date_str = pub_date[:10]results.append({"text": f"{title}. {description}".strip(". ") if description else title,"url": link,"title": title,"source": source,1 unmodified line"ticker": ticker,"live": True,})log.info("news_rss_ok", ticker=ticker, count=len(results))return resultsexcept Exception as exc:log.warning("news_fetch_failed", ticker=ticker, error=str(exc))return []3 unmodified linesdef fetch_fundamentals(ticker: str) -> dict:"""PE, EPS, margins, analyst consensus via quoteSummary API."""if not _AVAILABLE:return {"ticker": ticker, "error": "curl_cffi unavailable"}try:# Warm session + get crumb on first call_warm_session(ticker)crumb = _get_crumb()except Exception as exc:log.warning("fundamentals_session_failed", ticker=ticker, error=str(exc))return {"ticker": ticker, "error": str(exc)}modules = "summaryDetail,financialData,defaultKeyStatistics,recommendationTrend"params: dict = {"modules": modules}if crumb:params["crumb"] = crumb5 unmodified linestimeout=15,)data = r.json()result = data.get("quoteSummary", {}).get("result", [])if not result:return {"ticker": ticker}item = result[0]sd = item.get("summaryDetail", {})47 unmodified linesreturn {}try:_warm_session(ticker)crumb = _get_crumb()params: dict = {"modules": "assetProfile"}if crumb:params["crumb"] = crumb6 unmodified linesresult = data.get("quoteSummary", {}).get("result", [])if not result:return {}ap = result[0].get("assetProfile", {})if not ap:return {}return {48 unmodified linesexcept Exception:continuereturn results15 unmodified lines16171819202122232413 unmodified lines383940414243444546474849505152535455565758596061626364656698 unmodified lines16516616716816917017117217317417517617717817918018118218325 unmodified lines2092102112122132142152162172182192202212228 unmodified lines2312322332342352362372382392402412422432442452462472482492502512522532541 unmodified line2562572582592602612622632642653 unmodified lines2692702712722732742752762772782792802812822832842852862872882892902915 unmodified lines29729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732847 unmodified lines3763773783793803813826 unmodified lines38939039139239339439539639739839948 unmodified lines44844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152215 unmodified linesimport pandas as pdimport structlogimport threading_crumb_lock = threading.Lock()log = structlog.get_logger()try:13 unmodified lines_CRUMB_TTL = 3600 # secondsdef _get_valid_crumb(ticker: str) -> str:global _crumb, _crumb_tsif _crumb and time.time() - _crumb_ts < _CRUMB_TTL:return _crumbwith _crumb_lock:# double-check inside lockif _crumb and time.time() - _crumb_ts < _CRUMB_TTL:return _crumb_warm_session(ticker)try:r = _session.get(f"{_BASE2}/v1/test/getcrumb", timeout=10)if r.status_code == 200 and r.text.strip():_crumb = r.text.strip()_crumb_ts = time.time()return _crumbexcept Exception as exc:log.warning("crumb_fetch_failed", error=str(exc))raise RuntimeError("Failed to obtain Yahoo crumb")def _warm_session(ticker: str) -> None:98 unmodified linesmeta = chart_result[0].get("meta", {})price = meta.get("regularMarketPrice")prev_close = meta.get("chartPreviousClose") or meta.get("previousClose")if price is not None and prev_close is not None:change = round(price - prev_close, 4)pct_change = round(change / prev_close * 100, 2)else:change = Nonepct_change = None# Intraday OHLC from timestampsquote = chart_result[0].get("indicators", {}).get("quote", [{}])[0]opens = [v for v in (quote.get("open") or []) if v is not None]highs = [v for v in (quote.get("high") or []) if v is not None]lows = [v for v in (quote.get("low") or []) if v is not None]volumes = [v for v in (quote.get("volume") or []) if v is not None]return {"ticker": ticker,25 unmodified lines"""if not _AVAILABLE:return []try:import xml.etree.ElementTree as _ETfrom email.utils import parsedate_to_datetimeis_india = ticker.endswith((".NS", ".BO"))base = ticker.replace(".NS", "").replace(".BO", "")if is_india:query = f"{base} NSE stock India"params = {"q": query, "hl": "en-IN", "gl": "IN", "ceid": "IN:en"}8 unmodified linesroot = _ET.fromstring(r.content)items = root.findall(".//item")[:count]results: list[dict] = []for item in items:title = item.findtext("title", "") or ""link = item.findtext("link", "") or ""source = item.findtext("source", "Google News") or "Google News"pub_date = item.findtext("pubDate", "") or ""description = item.findtext("description", "") or ""try:dt = parsedate_to_datetime(pub_date)date_str = dt.strftime("%Y-%m-%d")except Exception:date_str = pub_date[:10] if pub_date else Noneresults.append({"text": f"{title}. {description}".strip(". "),"url": link,"title": title,"source": source,1 unmodified line"ticker": ticker,"live": True,})log.info("news_rss_ok", ticker=ticker, count=len(results))return resultsexcept Exception as exc:log.warning("news_fetch_failed", ticker=ticker, error=str(exc))return []3 unmodified linesdef fetch_fundamentals(ticker: str) -> dict:"""PE, EPS, margins, analyst consensus via quoteSummary API."""global _crumbif not _AVAILABLE:return {"ticker": ticker, "error": "curl_cffi unavailable"}for attempt in range(2):try:crumb = _get_valid_crumb(ticker)breakexcept Exception as exc:log.warning("crumb_retry", ticker=ticker, error=str(exc))_crumb = Noneif attempt == 1:return {"ticker": ticker, "error": "crumb init failed"}modules = "summaryDetail,financialData,defaultKeyStatistics,recommendationTrend,assetProfile,summaryProfile,price,quoteType"params: dict = {"modules": modules}if crumb:params["crumb"] = crumb5 unmodified linestimeout=15,)data = r.json()result = (data.get("quoteSummary") or {}).get("result") or []result = [r for r in result if r]if not result:log.warning("empty_fundamentals", ticker=ticker)_crumb = None_warm_session(ticker)try:crumb = _get_valid_crumb(ticker)params["crumb"] = crumbr = _session.get(f"{_BASE1}/v10/finance/quoteSummary/{ticker}",params=params,timeout=15,)data = r.json()result = data.get("quoteSummary", {}).get("result", [])except Exception as exc:log.warning("fundamentals_retry_failed", ticker=ticker, error=str(exc))return {"ticker": ticker, "error": "retry failed"}if not result:return {"ticker": ticker, "error": "no data after retry"}item = result[0]sd = item.get("summaryDetail", {})47 unmodified linesreturn {}try:_warm_session(ticker)crumb = _get_valid_crumb(ticker)params: dict = {"modules": "assetProfile"}if crumb:params["crumb"] = crumb6 unmodified linesresult = data.get("quoteSummary", {}).get("result", [])if not result:return {}ap = (result[0].get("assetProfile")or result[0].get("summaryProfile")or {})if not ap:return {}return {48 unmodified linesexcept Exception:continuereturn results# ββ SEC Filings (EDGAR) ββββββββββββββββββββββββββββββββββββββββββββββββdef fetch_filings(ticker: str, count: int = 10) -> list[dict]:"""Fetch latest SEC filings (10-K, 10-Q, 8-K etc.) from EDGAR for a ticker.Works via company CIK lookup β filings feed."""if not _AVAILABLE:return []try:import jsonimport xml.etree.ElementTree as ETheaders = {"User-Agent": "FinoraAI/1.0 (contact: support@finora.ai)"}# 1. Get ticker β CIK mappingmapping_url = "https://www.sec.gov/files/company_tickers.json"r = _session.get(mapping_url, headers=headers, timeout=15)if r.status_code != 200:return []data = r.json()cik = Noneticker = ticker.upper()for _, v in data.items():if v.get("ticker", "").upper() == ticker:cik = str(v.get("cik_str")).zfill(10)breakif not cik:return []# 2. Pull filings feedfeed_url = f"https://data.sec.gov/submissions/CIK{cik}.json"r = _session.get(feed_url, headers=headers, timeout=15)if r.status_code != 200:return []filings = r.json().get("filings", {}).get("recent", {})forms = filings.get("form", [])dates = filings.get("filingDate", [])accession = filings.get("accessionNumber", [])primary_docs = filings.get("primaryDocument", [])results = []for i in range(min(count, len(forms))):results.append({"ticker": ticker,"form": forms[i],"filing_date": dates[i],"accession_number": accession[i],"document": primary_docs[i],"url": f"https://www.sec.gov/Archives/edgar/data/{int(cik)}/{accession[i].replace('-', '')}/{primary_docs[i]}",})return resultsexcept Exception as exc:log.warning("filings_fetch_failed", ticker=ticker, error=str(exc))return []
1 unmodified line23456784 unmodified lines131415161718192040 unmodified lines6162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761 unmodified line"""Fetch S&P 500 + NIFTY 50 tickers and write data/universe/stocks.json.Run once before starting the backend:python scripts/build_universe.py"""import io4 unmodified linesimport requests# backend/data/universe/stocks.json β committed to git, baked into Docker imageOUTPUT = Path(__file__).parent.parent / "data" / "universe" / "stocks.json"OUTPUT.parent.mkdir(parents=True, exist_ok=True)_HEADERS = {40 unmodified linesdef fetch_nifty50() -> list[dict]:print("Fetching NIFTY 50 from Wikipedia...")url = "https://en.wikipedia.org/wiki/NIFTY_50"try:tables = _html_tables(url)# Find the table that has a ticker/symbol columndf = Nonefor t in tables:cols = [str(c).lower() for c in t.columns]if any("symbol" in c or "ticker" in c for c in cols):df = tbreakif df is None:raise ValueError("No NIFTY 50 table found")col_map = {str(c).lower(): c for c in df.columns}sym_col = next((col_map[c] for c in col_map if "symbol" in c or "ticker" in c), None)name_col = next((col_map[c] for c in col_map if "company" in c or "name" in c or "stock" in c), None)sect_col = next((col_map[c] for c in col_map if "sector" in c or "industry" in c), None)stocks = []for _, row in df.iterrows():ticker = str(row[sym_col]).strip() if sym_col else ""name = str(row[name_col]).strip() if name_col else tickersector = str(row[sect_col]).strip() if sect_col else ""if not ticker or ticker == "nan":continueyf_ticker = f"{ticker}.NS"stocks.append({"ticker": ticker,"yf_ticker": yf_ticker,"name": name,"exchange": "NSE","sector": sector,"country": "IN","currency": "INR",})print(f" NIFTY 50: {len(stocks)} stocks")return stocksexcept Exception as exc:print(f" WARNING: NIFTY 50 fetch failed ({exc}), using hardcoded fallback")return _nifty50_fallback()def _nifty50_fallback() -> list[dict]:entries = [("RELIANCE", "Reliance Industries", "Energy"),("TCS", "Tata Consultancy Services", "Information Technology"),("HDFCBANK", "HDFC Bank", "Financial Services"),("INFY", "Infosys", "Information Technology"),("HINDUNILVR", "Hindustan Unilever", "FMCG"),("ICICIBANK", "ICICI Bank", "Financial Services"),("KOTAKBANK", "Kotak Mahindra Bank", "Financial Services"),("SBIN", "State Bank of India", "Financial Services"),("BHARTIARTL", "Bharti Airtel", "Telecom"),("ITC", "ITC Limited", "FMCG"),("BAJFINANCE", "Bajaj Finance", "Financial Services"),("LT", "Larsen & Toubro", "Construction"),("HCLTECH", "HCL Technologies", "Information Technology"),("ASIANPAINT", "Asian Paints", "Materials"),("AXISBANK", "Axis Bank", "Financial Services"),("MARUTI", "Maruti Suzuki India", "Automobile"),("SUNPHARMA", "Sun Pharmaceutical", "Healthcare"),("TITAN", "Titan Company", "Consumer Discretionary"),("ULTRACEMCO", "UltraTech Cement", "Materials"),("NESTLEIND", "Nestle India", "FMCG"),("WIPRO", "Wipro", "Information Technology"),("ADANIENT", "Adani Enterprises", "Industrials"),("ADANIPORTS", "Adani Ports & SEZ", "Industrials"),("BAJAJFINSV", "Bajaj Finserv", "Financial Services"),("BPCL", "Bharat Petroleum", "Energy"),("CIPLA", "Cipla", "Healthcare"),("COALINDIA", "Coal India", "Energy"),("DIVISLAB", "Divi's Laboratories", "Healthcare"),("DRREDDY", "Dr. Reddy's Laboratories", "Healthcare"),("EICHERMOT", "Eicher Motors", "Automobile"),("GRASIM", "Grasim Industries", "Materials"),("HDFCLIFE", "HDFC Life Insurance", "Financial Services"),("HEROMOTOCO", "Hero MotoCorp", "Automobile"),("HINDALCO", "Hindalco Industries", "Materials"),("INDUSINDBK", "IndusInd Bank", "Financial Services"),("JSWSTEEL", "JSW Steel", "Materials"),("M&M", "Mahindra & Mahindra", "Automobile"),("NTPC", "NTPC", "Utilities"),("ONGC", "Oil & Natural Gas Corporation", "Energy"),("POWERGRID", "Power Grid Corporation", "Utilities"),("SBILIFE", "SBI Life Insurance", "Financial Services"),("SHREECEM", "Shree Cement", "Materials"),("TATACONSUM", "Tata Consumer Products", "FMCG"),("TATAMOTORS", "Tata Motors", "Automobile"),("TATASTEEL", "Tata Steel", "Materials"),("TECHM", "Tech Mahindra", "Information Technology"),("TRENT", "Trent", "Consumer Discretionary"),("UPL", "UPL", "Materials"),("VEDL", "Vedanta", "Materials"),("ZOMATO", "Zomato", "Consumer Discretionary"),]return [{"ticker": t,"yf_ticker": f"{t}.NS","name": n,"exchange": "NSE","sector": s,"country": "IN","currency": "INR",}for t, n, s in entries]def build() -> None:sp500 = fetch_sp500()1 unmodified line23456784 unmodified lines1314151617181920212240 unmodified lines636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081 unmodified line"""Fetch S&P 500 + NIFTY 50 tickers and write data/universe/stocks.json.Run once before starting the backend:python backend/scripts/build_universe.py"""import io4 unmodified linesimport requestsROOT = Path(__file__).resolve().parents[2]sys.path.insert(0, str(ROOT))OUTPUT = ROOT / "backend" / "data" / "universe" / "stocks.json"OUTPUT.parent.mkdir(parents=True, exist_ok=True)_HEADERS = {40 unmodified linesdef fetch_nifty50() -> list[dict]:print("Fetching NIFTY 50 from Wikipedia...")tables = _html_tables("https://en.wikipedia.org/wiki/NIFTY_50")df = Nonefor t in tables:cols = [str(c).lower() for c in t.columns]if any("symbol" in c or "ticker" in c for c in cols):df = tbreakif df is None:raise RuntimeError("No NIFTY 50 table found on Wikipedia")col_map = {str(c).lower(): c for c in df.columns}sym_col = next((col_map[c] for c in col_map if "symbol" in c or "ticker" in c), None)name_col = next((col_map[c] for c in col_map if "company" in c or "name" in c or "stock" in c), None)sect_col = next((col_map[c] for c in col_map if "sector" in c or "industry" in c), None)if sym_col is None or name_col is None:raise RuntimeError("NIFTY 50 table missing required columns")stocks = []for _, row in df.iterrows():ticker = str(row[sym_col]).strip()name = str(row[name_col]).strip()sector = str(row[sect_col]).strip() if sect_col else ""if not ticker or ticker.lower() == "nan":continuestocks.append({"ticker": ticker,"yf_ticker": f"{ticker}.NS","name": name,"exchange": "NSE","sector": sector,"country": "IN","currency": "INR",})print(f" NIFTY 50: {len(stocks)} stocks")return stocksdef build() -> None:sp500 = fetch_sp500()
2 unmodified lines34567891011121314151617181920212223242526272829303132333435363738396 unmodified lines464748495051527 unmodified lines6061626364656667686970717273747576777879808182832 unmodified linesRAGAS evaluation suite for Finora RAG pipeline.Usage:python scripts/eval_rag.py --tickers AAPL MSFT NVDA RELIANCE.NSpython scripts/eval_rag.py --tickers AAPL --collection historical --n 10python scripts/eval_rag.py --tickers AAPL --output backend/data/eval_results/ragas_20260424.json"""from __future__ import annotationsimport argparseimport jsonimport sysfrom pathlib import PathROOT = Path(__file__).resolve().parents[2]BACKEND = ROOT / "backend"sys.path.insert(0, str(BACKEND))from dotenv import load_dotenvload_dotenv(ROOT / ".env")def main() -> None:parser = argparse.ArgumentParser(description="Run RAGAS eval on Finora RAG pipeline")parser.add_argument("--tickers", nargs="+", required=True, help="Tickers to evaluate")parser.add_argument("--collection", default="news", choices=["news", "historical", "filings"],help="Qdrant collection to sample from (default: news)")parser.add_argument("--n", type=int, default=5, help="QA pairs per ticker (default: 5)")parser.add_argument("--output", type=str, default=None, help="Path to write JSON results")args = parser.parse_args()print(f"Generating synthetic QA dataset for: {args.tickers}")from backend.rag.evaluation.synthetic import generate_synthetic_datasetqa_pairs = generate_synthetic_dataset(tickers=args.tickers,collection_key=args.collection,6 unmodified linessys.exit(1)print("\nRunning RAGAS evaluation...")from backend.rag.evaluation.ragas_eval import TARGETS, run_ragas_evalreport = run_ragas_eval(qa_pairs, tickers=args.tickers)if "error" in report:7 unmodified linesprint(f" {metric:<25} {result['score']:.4f} (target {target_label}) {status}")print(f"\nOverall: {'PASS β' if report.get('overall_pass') else 'FAIL β'}")import datetimereport["run_at"] = datetime.datetime.utcnow().isoformat() + "Z"report["tickers"] = args.tickers# Always save latest.json for /api/eval/latest endpointlatest_path = Path(__file__).parent.parent / "data" / "eval_results" / "latest.json"latest_path.parent.mkdir(parents=True, exist_ok=True)with open(latest_path, "w") as f:json.dump(report, f, indent=2)print(f"Latest results saved β {latest_path}")if args.output:out_path = Path(args.output)out_path.parent.mkdir(parents=True, exist_ok=True)with open(out_path, "w") as f:json.dump({"qa_pairs": qa_pairs, "report": report}, f, indent=2)print(f"Results saved β {out_path}")if __name__ == "__main__":main()2 unmodified lines3456789101112131415161718192021222324252627282930313233343536373839404142434445466 unmodified lines5354555657587 unmodified lines666768697071727374757677787980818283842 unmodified linesRAGAS evaluation suite for Finora RAG pipeline.Usage:python backend/scripts/eval_rag.py --tickers AAPL MSFT NVDA RELIANCE.NSpython backend/scripts/eval_rag.py --tickers AAPL --collection historical --n 10python backend/scripts/eval_rag.py --tickers AAPL --output backend/data/eval_results/ragas_20260424.json"""from __future__ import annotationsimport argparseimport datetime as dtimport jsonimport sysfrom pathlib import PathROOT = Path(__file__).resolve().parents[2]sys.path.insert(0, str(ROOT))from dotenv import load_dotenvload_dotenv(ROOT / ".env")DEFAULT_LATEST = ROOT / "backend" / "data" / "eval_results" / "latest.json"def main() -> None:parser = argparse.ArgumentParser(description="Run RAGAS eval on Finora RAG pipeline")parser.add_argument("--tickers", nargs="+", required=True, help="Tickers to evaluate")parser.add_argument("--collection",default="news",choices=["news", "historical", "filings"],help="Qdrant collection to sample from (default: news)",)parser.add_argument("--n", type=int, default=5, help="QA pairs per ticker (default: 5)")parser.add_argument("--output", type=str, default=None, help="Path to write JSON results")args = parser.parse_args()from backend.rag.evaluation.synthetic import generate_synthetic_datasetfrom backend.rag.evaluation.ragas_eval import run_ragas_evalprint(f"Generating synthetic QA dataset for: {args.tickers}")qa_pairs = generate_synthetic_dataset(tickers=args.tickers,collection_key=args.collection,6 unmodified linessys.exit(1)print("\nRunning RAGAS evaluation...")report = run_ragas_eval(qa_pairs, tickers=args.tickers)if "error" in report:7 unmodified linesprint(f" {metric:<25} {result['score']:.4f} (target {target_label}) {status}")print(f"\nOverall: {'PASS β' if report.get('overall_pass') else 'FAIL β'}")report["run_at"] = dt.datetime.utcnow().isoformat() + "Z"report["tickers"] = args.tickersDEFAULT_LATEST.parent.mkdir(parents=True, exist_ok=True)DEFAULT_LATEST.write_text(json.dumps(report, indent=2))print(f"Latest results saved β {DEFAULT_LATEST}")if args.output:out_path = Path(args.output)out_path.parent.mkdir(parents=True, exist_ok=True)out_path.write_text(json.dumps({"qa_pairs": qa_pairs, "report": report}, indent=2))print(f"Results saved β {out_path}")if __name__ == "__main__":main()
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596#!/usr/bin/env python3"""Seed US SEC filings (10-K, 10-Q) into Qdrant (finora_filings collection).
Usage: python backend/scripts/ingest_filings.py --tickers AAPL MSFT NVDA python backend/scripts/ingest_filings.py --all python backend/scripts/ingest_filings.py --limit 20"""
import argparseimport jsonimport sysimport timefrom pathlib import Path
ROOT = Path(__file__).resolve().parents[2]sys.path.insert(0, str(ROOT))
from dotenv import load_dotenvload_dotenv(ROOT / ".env")
from backend.rag.ingestion.collections import ensure_collections, get_clientfrom backend.rag.ingestion.filings import ingest_ticker
UNIVERSE_PATH = ROOT / "backend" / "data" / "universe" / "stocks.json"
HEADERS = { "User-Agent": "Finora Research (finora@example.com)"}
# ββ Load universe βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def load_universe(): if not UNIVERSE_PATH.exists(): print("ERROR: Universe missing. Run build_universe.py") sys.exit(1) return json.load(open(UNIVERSE_PATH))
# ββ Main ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def main(): parser = argparse.ArgumentParser(description="Ingest SEC filings into Qdrant") parser.add_argument("--tickers", nargs="+") parser.add_argument("--all", action="store_true") parser.add_argument("--limit", type=int, help="Limit number of tickers") parser.add_argument("--delay", type=float, default=1.0)
args = parser.parse_args()
if not args.tickers and not args.all: parser.print_help() sys.exit(1)
client = get_client() ensure_collections(client)
universe = load_universe()
# Filter US stocks only us_stocks = [s for s in universe if not s["ticker"].endswith((".NS", ".BO"))]
ticker_map = {s["ticker"].upper(): s for s in us_stocks}
stocks = ( us_stocks if args.all else [ticker_map.get(t.upper(), {"ticker": t}) for t in (args.tickers or [])] )
if args.limit: stocks = stocks[:args.limit]
print(f"Ingesting filings for {len(stocks)} stocks...\n")
success = 0
for s in stocks: ticker = s["ticker"]
n = ingest_ticker(ticker, client)
if n > 0: print(f"{ticker}: {n} chunks") success += 1 else: print(f"{ticker}: no filings")
time.sleep(args.delay)
print(f"\nDone. Successful: {success}/{len(stocks)}")
if __name__ == "__main__": main()2 unmodified lines345678910112 unmodified lines1415161718192021221 unmodified line24252627282930312 unmodified linesSeed 20yr OHLCV data into Qdrant (finora_historical collection).Usage:python scripts/ingest_historical.py --tickers AAPL MSFT NVDA RELIANCE.NS --years 20python scripts/ingest_historical.py --all --years 20python scripts/ingest_historical.py --tickers AAPL --years 5"""import argparse2 unmodified linesfrom pathlib import PathROOT = Path(__file__).resolve().parents[2]BACKEND = ROOT / "backend"sys.path.insert(0, str(BACKEND))from dotenv import load_dotenvload_dotenv(ROOT / ".env")1 unmodified linefrom backend.rag.ingestion.collections import ensure_collections, get_clientfrom backend.rag.ingestion.historical import ingest_ticker, ingest_universeUNIVERSE_PATH = Path(__file__).parent.parent / "data" / "universe" / "stocks.json"def load_universe() -> list[dict]:if not UNIVERSE_PATH.exists():2 unmodified lines34567891011122 unmodified lines151617181920211 unmodified line232425262728292 unmodified linesSeed 20yr OHLCV data into Qdrant (finora_historical collection).Usage:python backend/scripts/ingest_historical.py --tickers AAPL MSFT NVDA RELIANCE.NS --years 20python backend/scripts/ingest_historical.py --all --years 20python backend/scripts/ingest_historical.py --tickers AAPL --years 5python backend/scripts/ingest_historical.py --tickers ZBRA ZBH ZTS --years 5 (For Test Purpose Only!)"""import argparse2 unmodified linesfrom pathlib import PathROOT = Path(__file__).resolve().parents[2]sys.path.insert(0, str(ROOT))from dotenv import load_dotenvload_dotenv(ROOT / ".env")1 unmodified linefrom backend.rag.ingestion.collections import ensure_collections, get_clientfrom backend.rag.ingestion.historical import ingest_ticker, ingest_universeUNIVERSE_PATH = ROOT / "backend" / "data" / "universe" / "stocks.json"def load_universe() -> list[dict]:if not UNIVERSE_PATH.exists():
2 unmodified lines3456789102 unmodified lines1314151617181920211 unmodified line23242526272829302 unmodified linesSeed news corpus into Qdrant (finora_news collection) via NewsAPI.Usage:python scripts/ingest_news.py --tickers AAPL MSFT NVDA RELIANCE --days 7python scripts/ingest_news.py --all --days 3"""import argparse2 unmodified linesfrom pathlib import PathROOT = Path(__file__).resolve().parents[2]BACKEND = ROOT / "backend"sys.path.insert(0, str(BACKEND))from dotenv import load_dotenvload_dotenv(ROOT / ".env")1 unmodified linefrom backend.rag.ingestion.collections import ensure_collections, get_clientfrom backend.rag.ingestion.news import ingest_ticker, ingest_universeUNIVERSE_PATH = Path(__file__).parent.parent / "data" / "universe" / "stocks.json"def load_universe() -> list[dict]:if not UNIVERSE_PATH.exists():2 unmodified lines3456789102 unmodified lines131415161718191 unmodified line212223242526272 unmodified linesSeed news corpus into Qdrant (finora_news collection) via NewsAPI.Usage:python backend/scripts/ingest_news.py --tickers AAPL MSFT NVDA RELIANCE --days 7python backend/scripts/ingest_news.py --all --days 3"""import argparse2 unmodified linesfrom pathlib import PathROOT = Path(__file__).resolve().parents[2]sys.path.insert(0, str(ROOT))from dotenv import load_dotenvload_dotenv(ROOT / ".env")1 unmodified linefrom backend.rag.ingestion.collections import ensure_collections, get_clientfrom backend.rag.ingestion.news import ingest_ticker, ingest_universeUNIVERSE_PATH = ROOT / "backend" / "data" / "universe" / "stocks.json"def load_universe() -> list[dict]:if not UNIVERSE_PATH.exists():
1234567891011121314151617181920212223242526# =============================================================================# FINORA BACKEND β Development / Evaluation Dependencies# Install AFTER requirements.txt: pip install -r requirements-dev.txt# These are NOT installed in HuggingFace (production).# =============================================================================-r requirements.txt# MCP server (standalone process β separate from FastAPI)# NOTE: fastmcp requires mcp SDK which pulls starlette>=0.49, incompatible# with fastapi 0.115. Install in a SEPARATE venv for MCP server only.# fastmcp==1.0# Evaluationragas==0.2.5datasets==3.1.0# Testingpytest==8.3.3pytest-asyncio==0.24.0pytest-cov==5.0.0# Linting / formattingruff==0.7.1black==24.10.0mypy==1.13.012345678910111213141516171819202122232425# =============================================================================# FINORA BACKEND β DEVELOPMENT / EVALUATION STACK# =============================================================================-r requirements.txt# -----------------------# Evaluation (RAG quality, agents)# -----------------------ragas==0.2.5datasets==3.1.0# -----------------------# Testing# -----------------------pytest==8.3.3pytest-asyncio==0.24.0pytest-cov==5.0.0# -----------------------# Linting / formatting / typing# -----------------------ruff==0.7.1black==24.10.0mypy==1.13.0
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970# =============================================================================# FINORA BACKEND β Production Dependencies# For HuggingFace deployment. Dev/eval/MCP tools are in requirements-dev.txt.# =============================================================================# Web frameworkfastapi==0.115.0uvicorn[standard]==0.30.6python-multipart==0.0.9httpx>=0.27.0,<0.28.0# Validationpydantic==2.9.2pydantic-settings==2.5.2# Rate limitingslowapi==0.1.9# LLM β Groqgroq==0.11.0# Agent graphlanggraph==0.2.55langgraph-checkpoint==2.0.6# RAG / LangChainlangchain==0.3.7langchain-community==0.3.7langchain-groq==0.2.1langchain-qdrant==0.2.0langsmith==0.1.147# Vector storeqdrant-client==1.11.3# Reranker β Cohere primary, BAAI/bge-reranker-base local fallbackcohere==5.11.4# Embeddings + local reranker fallback (HuggingFace)sentence-transformers==3.2.1transformers==4.46.3torch==2.4.1# Sparse retrievalrank-bm25==0.2.2# Fuzzy searchrapidfuzz==3.10.1# Financial data β all fetching via curl_cffi Chrome TLS impersonation (no API key needed)curl_cffi==0.15.0polygon-api-client==1.14.2pandas==2.2.3lxml==5.3.0html5lib==1.1# Newsnewsapi-python==0.2.7# SEC filingsunstructured==0.15.14requests==2.32.3# Schedulingapscheduler==3.10.4# Loggingstructlog==24.4.0python-dotenv==1.0.1openai>=1.0.012345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394# =============================================================================# FINORA BACKEND β PRODUCTION DEPENDENCIES (CLEAN LOCKED STACK)# =============================================================================# -----------------------# Web Framework# -----------------------fastapi==0.115.0uvicorn[standard]==0.30.6python-multipart==0.0.9# -----------------------# HTTP Core (IMPORTANT: version aligned to avoid urllib3 warnings)# -----------------------httpx==0.27.2requests==2.32.3urllib3==2.2.2charset-normalizer==3.3.2chardet==5.2.0# -----------------------# Validation# -----------------------pydantic==2.9.2pydantic-settings==2.5.2# -----------------------# Rate limiting# -----------------------slowapi==0.1.9# -----------------------# LLM / Agent Stack# -----------------------groq==0.11.0openai==1.40.0langgraph==0.2.55langgraph-checkpoint==2.0.6langchain==0.3.7langchain-community==0.3.7langchain-groq==0.2.1langchain-qdrant==0.2.0langsmith==0.1.147# -----------------------# Vector DB# -----------------------qdrant-client==1.11.3# -----------------------# Reranking / Embeddings# -----------------------cohere==5.11.4sentence-transformers==3.2.1transformers==4.46.3torch==2.4.1# -----------------------# Retrieval# -----------------------rank-bm25==0.2.2rapidfuzz==3.10.1# -----------------------# Financial Data (core engine)# -----------------------curl_cffi==0.15.0pandas==2.2.3lxml==5.3.0html5lib==1.1# -----------------------# Scheduling# -----------------------apscheduler==3.10.4# -----------------------# News# -----------------------newsapi-python==0.2.7polygon-api-client==1.14.2# -----------------------# SEC / parsing# -----------------------unstructured==0.15.14# -----------------------# Logging / env# -----------------------structlog==24.4.0python-dotenv==1.0.1
backend/api/routes/stocks.py+27-1
backend/graph/finora_graph.py+4-1
backend/graph/nodes/filings_rag_node.pyAdded+79
backend/graph/nodes/fusion_node.py+35-1
backend/graph/state.py+1
backend/main.py+4-4
backend/rag/ingestion/filings.py+31-21
backend/rag/yahoo_client.py+165-38
backend/scripts/build_universe.py+40-108
backend/scripts/eval_rag.py+22-21
backend/scripts/ingest_filings.pyAdded+96
backend/scripts/ingest_historical.py+6-8
backend/scripts/ingest_news.py+4-7
requirements-dev.txt+9-10
requirements.txt+47-23