diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..748dea7b74fdf56f55f9b8cf0f396c8b44183c72 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,26 @@ +__pycache__/ +*.pyc +*.pyo +*.pyd + +.venv/ +venv/ +env/ + +data/hf_cache/ +data/qdrant/ +data/bm25_index/ + +.git/ +.gitignore + +*.log +logs/ + +.env +.venv + +finora-frontend/ +node_modules/ + +.DS_Store diff --git a/.env.example b/.env.example new file mode 100644 index 0000000000000000000000000000000000000000..1864acd406347e48c7c8c4fce270bd93d97cd827 --- /dev/null +++ b/.env.example @@ -0,0 +1,81 @@ +# ============================================================================= +# FINORA BACKEND — Environment Variables Template +# Copy this file to .env and fill in your values: cp .env.example .env +# Production: set all these in HuggingFace Secrets instead of this file +# ============================================================================= + +# ── LLM: Groq ──────────────────────────────────────────────────────────────── +# https://console.groq.com → Create API Key +GROQ_API_KEY=your_groq_api_key_here +GROQ_MODEL_PRIMARY=llama-3.3-70b-versatile +GROQ_MODEL_FAST=llama-3.1-8b-instant +GROQ_MAX_TOKENS=2048 +GROQ_TEMPERATURE=0.1 + +# ── Observability: LangSmith ────────────────────────────────────────────────── +# https://smith.langchain.com → Settings → API Keys +LANGCHAIN_API_KEY=your_langsmith_api_key_here +LANGCHAIN_PROJECT=finora-prod +LANGCHAIN_TRACING_V2=true +LANGCHAIN_ENDPOINT=https://api.smith.langchain.com + +# ── Vector Store: Qdrant Cloud ──────────────────────────────────────────────── +# https://cloud.qdrant.io → Create free cluster → copy URL and API key +QDRANT_URL=https://your-cluster-id.us-east-1-1.aws.cloud.qdrant.io +QDRANT_API_KEY=your_qdrant_api_key_here +QDRANT_COLLECTION_NEWS=finora_news +QDRANT_COLLECTION_HISTORICAL=finora_historical +QDRANT_COLLECTION_FILINGS=finora_filings + +# ── Reranker: Cohere ────────────────────────────────────────────────────────── +# https://dashboard.cohere.com → API Keys (free tier available) +# Falls back to local BAAI/bge-reranker-base if Cohere fails or rate-limits +COHERE_API_KEY=your_cohere_api_key_here +RERANKER_PROVIDER=cohere + +# ── Market Data ─────────────────────────────────────────────────────────────── +# Polygon.io: https://polygon.io/dashboard (free: 5 calls/min) +POLYGON_API_KEY=your_polygon_api_key_here +# NewsAPI: https://newsapi.org/register (free: 100 req/day) +NEWSAPI_KEY=your_newsapi_key_here + +# ── Embeddings: HuggingFace (local, no API key needed) ─────────────────────── +EMBEDDING_MODEL=sentence-transformers/all-MiniLM-L6-v2 +RERANKER_MODEL=BAAI/bge-reranker-base +HF_HOME=./data/hf_cache + +# ── SEC EDGAR (no key — fair use requires a user agent) ────────────────────── +SEC_EDGAR_USER_AGENT=YourName contact@youremail.com + +# ── RAG Configuration ───────────────────────────────────────────────────────── +RAG_TOP_K=8 +RAG_OVER_RETRIEVE_FACTOR=2 +RAG_HYDE_ENABLED=true +RAG_RERANKER_ENABLED=true +RAG_HYBRID_ALPHA=0.6 +RAG_MMR_LAMBDA=0.6 +RAG_DEDUP_THRESHOLD=0.92 + +# ── Guardrails ──────────────────────────────────────────────────────────────── +GUARDRAILS_ENABLED=true +GUARDRAILS_MODE=strict +DISCLAIMER_LOCALE=IN +GUARDRAILS_LOG_BLOCKED=true + +# ── Application ─────────────────────────────────────────────────────────────── +BACKEND_PORT=7860 +BACKEND_HOST=0.0.0.0 +ENV=development +LOG_LEVEL=INFO +CORS_ORIGINS=http://localhost:3000,https://your-app.vercel.app +SCHEDULER_ENABLED=false + +# ── Rate Limiting ───────────────────────────────────────────────────────────── +RATE_LIMIT_PER_MINUTE=20 +RATE_LIMIT_PER_HOUR=200 +MAX_QUERY_LENGTH=500 +MAX_CONVERSATION_TURNS=50 + +# ── Ingestion Scheduler ─────────────────────────────────────────────────────── +NEWS_INGEST_INTERVAL_MINUTES=15 +HISTORICAL_UPDATE_INTERVAL_HOURS=24 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..46ac101367aabcf0bf541b283944ed26030f6a93 --- /dev/null +++ b/.gitignore @@ -0,0 +1,22 @@ +# virtual environment +.venv/ +venv/ +.env/ + +# Python cache +__pycache__/ +*.pyc + +# HF / ML caches +data/ +data/hf_cache/ +data/qdrant/ +data/bm25_index/ + +# logs +*.log +logs/ + +# env files (IMPORTANT) +.env +finora-backend/.env diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3be90444fca1489e2a9baa89278e221a85532b1f --- /dev/null +++ b/Dockerfile @@ -0,0 +1,25 @@ +FROM python:3.11-slim + +WORKDIR /app + +RUN apt-get update && apt-get install -y --no-install-recommends \ + curl \ + build-essential \ + git \ + && rm -rf /var/lib/apt/lists/* + +COPY requirements.txt . + +RUN pip install --no-cache-dir -r requirements.txt + +ENV HF_HOME=/tmp/hf_cache +ENV TRANSFORMERS_CACHE=/tmp/hf_cache +ENV SENTENCE_TRANSFORMERS_HOME=/tmp/hf_cache + +ENV PYTHONPATH=/app/backend + +COPY . . + +EXPOSE 7860 + +CMD ["uvicorn", "backend.main:app", "--host", "0.0.0.0", "--port", "7860"] diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ef2ce4979850867df2289116c23bdfcd70dc9027 --- /dev/null +++ b/README.md @@ -0,0 +1,17 @@ +--- +title: Finora Backend +emoji: 🐳 +colorFrom: purple +colorTo: gray +sdk: docker +app_port: 7860 +--- + +# Finora Backend (FastAPI + RAG + ML Stack) + +Production-grade financial AI backend with: +- Intent classification (LLM + rules) +- RAG (news, historical, filings) +- Qdrant vector search +- Groq LLM inference +- HuggingFace embeddings diff --git a/backend/__init__.py b/backend/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/backend/api/__init__.py b/backend/api/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/backend/api/middleware/__init__.py b/backend/api/middleware/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/backend/api/middleware/guardrails.py b/backend/api/middleware/guardrails.py new file mode 100644 index 0000000000000000000000000000000000000000..365d505d15ffc83be8a3d0729bb73065fcf944a6 --- /dev/null +++ b/backend/api/middleware/guardrails.py @@ -0,0 +1,38 @@ +""" +Financial guardrails FastAPI middleware — request-level content policy enforcement. + +Runs before the route handler to reject clearly non-financial queries +without spending Groq tokens on the graph-level classifier. +""" +from __future__ import annotations + +import re + +from fastapi import Request, Response +from fastapi.responses import JSONResponse +from starlette.middleware.base import BaseHTTPMiddleware + +_HARD_BLOCK_PATTERNS = [ + re.compile(r"\b(hack|exploit|malware|phishing|ransomware)\b", re.I), + re.compile(r"\b(credit card number|cvv|ssn|social security)\b", re.I), +] + +_CHAT_PATH = "/api/chat" + + +class FinancialGuardrailMiddleware(BaseHTTPMiddleware): + async def dispatch(self, request: Request, call_next): + if request.method == "POST" and request.url.path == _CHAT_PATH: + try: + body = await request.json() + query = body.get("query", "") + for pattern in _HARD_BLOCK_PATTERNS: + if pattern.search(query): + return JSONResponse( + status_code=400, + content={"detail": "Query violates content policy."}, + ) + except Exception: + pass # malformed JSON handled downstream + + return await call_next(request) diff --git a/backend/api/middleware/rate_limit.py b/backend/api/middleware/rate_limit.py new file mode 100644 index 0000000000000000000000000000000000000000..9757a8fc51b12e4686967e8ad9e310fe82a5151b --- /dev/null +++ b/backend/api/middleware/rate_limit.py @@ -0,0 +1,12 @@ +import os + +from slowapi import Limiter +from slowapi.util import get_remote_address + +limiter = Limiter( + key_func=get_remote_address, + default_limits=[ + f"{os.getenv('RATE_LIMIT_PER_MINUTE', '20')}/minute", + f"{os.getenv('RATE_LIMIT_PER_HOUR', '200')}/hour", + ], +) diff --git a/backend/api/routes/__init__.py b/backend/api/routes/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/backend/api/routes/chat.py b/backend/api/routes/chat.py new file mode 100644 index 0000000000000000000000000000000000000000..432d7b48dee248b067c0996102c18b370172a35f --- /dev/null +++ b/backend/api/routes/chat.py @@ -0,0 +1,330 @@ +import json +import os +import re +import uuid +from typing import AsyncIterator + +import structlog +from fastapi import APIRouter, Request +from fastapi.responses import StreamingResponse +from pydantic import BaseModel, Field + +from backend.api.middleware.rate_limit import limiter +from backend.graph.nodes.response_cache import cache_key as _resp_cache_key, get_cached as _resp_get_cached, is_volatile_query as _resp_is_volatile +from backend.rag.ingestion.universe import universe + +log = structlog.get_logger() +router = APIRouter(tags=["chat"]) + + +def _parse_chart_timeframe(query: str) -> tuple[str, str, str]: + """ + Returns (range_str, interval, label) for fetch_ohlcv based on query text. + Handles standard timeframes, custom day counts, and date ranges. + """ + q = query.lower() + + # Custom date range: "from 2025-01-01 to 2025-03-31" or "from jan 1 to mar 31" + date_range = re.search( + r"from\s+(\d{4}-\d{2}-\d{2})\s+to\s+(\d{4}-\d{2}-\d{2})", q + ) + if date_range: + # Yahoo doesn't support arbitrary date ranges via range_str easily; + # fall back to period calculation + from datetime import date + try: + start = date.fromisoformat(date_range.group(1)) + end = date.fromisoformat(date_range.group(2)) + days = (end - start).days + if days <= 7: + return (f"{days}d", "5m", f"{days}D") + elif days <= 90: + return (f"{days}d", "1d", f"{days}D") + else: + return (f"{days}d", "1wk", f"{days}D") + except ValueError: + pass + + # Custom N days: "20 days", "45 days", "past 10 days" + n_days = re.search(r"(\d+)\s*day", q) + if n_days: + d = int(n_days.group(1)) + d = max(1, min(d, 365)) + interval = "5m" if d == 1 else "1d" if d <= 90 else "1wk" + return (f"{d}d", interval, f"{d}D") + + # N weeks + n_weeks = re.search(r"(\d+)\s*week", q) + if n_weeks: + w = int(n_weeks.group(1)) + w = max(1, min(w, 52)) + days = w * 7 + interval = "30m" if w == 1 else "1d" + return (f"{days}d", interval, f"{w}W") + + # N months + n_months = re.search(r"(\d+)\s*month", q) + if n_months: + m = int(n_months.group(1)) + m = max(1, min(m, 60)) + interval = "1d" if m <= 6 else "1wk" + return (f"{m}mo", interval, f"{m}M") + + # N years + n_years = re.search(r"(\d+)\s*year", q) + if n_years: + y = int(n_years.group(1)) + y = max(1, min(y, 20)) + interval = "1wk" if y <= 5 else "1mo" + return (f"{y}y", interval, f"{y}Y") + + # Named timeframes + if any(x in q for x in ("intraday", "today", "1d", "1 day", "one day", + "suddenly", "crashing", "crashed", "surging", "surged", + "dropped", "spiked", "right now", "happening now")): + return ("1d", "5m", "1D") + if any(x in q for x in ("this week", "1w", "1 week", "one week", "past week", "7 day")): + return ("5d", "30m", "1W") + if any(x in q for x in ("3m", "3 month", "three month", "quarter", "quarterly")): + return ("3mo", "1d", "3M") + if any(x in q for x in ("6m", "6 month", "six month", "half year")): + return ("6mo", "1d", "6M") + if any(x in q for x in ("1y", "1 year", "one year", "past year", "this year", "ytd", "annual")): + return ("1y", "1wk", "1Y") + if any(x in q for x in ("3y", "3 year", "three year")): + return ("3y", "1wk", "3Y") + if any(x in q for x in ("5y", "5 year", "five year")): + return ("5y", "1wk", "5Y") + if any(x in q for x in ("all time", "all-time", "max", "20 year", "full history")): + return ("20y", "1mo", "ALL") + + # Default: 1 month + return ("1mo", "1d", "1M") + +MAX_CONVERSATION_TURNS = int(os.getenv("MAX_CONVERSATION_TURNS", "50")) + + +class ConversationTurn(BaseModel): + role: str + content: str + + +class ChatRequest(BaseModel): + query: str = Field(..., max_length=500) + ticker: str = Field(default="") + conversation_history: list[ConversationTurn] = Field(default_factory=list) + session_id: str = Field(default_factory=lambda: str(uuid.uuid4())) + user_mode: str = Field(default="insight", pattern="^(insight|trader)$") + + +def _sse(event: dict) -> str: + return f"data: {json.dumps(event)}\n\n" + + +async def _stream_graph(req: ChatRequest) -> AsyncIterator[str]: + from backend.graph.finora_graph import graph + + # Resolve yf_ticker from universe (e.g. TCS → TCS.NS, RELIANCE → RELIANCE.NS) + entry = universe.get_by_ticker(req.ticker) if req.ticker else None + yf_ticker = entry.get("yf_ticker", req.ticker) if entry else req.ticker + + initial_state = { + "query": req.query, + "ticker": req.ticker, + "yf_ticker": yf_ticker, + "company_name": entry.get("name", req.ticker) if entry else req.ticker, + "currency": entry.get("currency", "USD") if entry else "USD", + "user_mode": req.user_mode, + "session_id": req.session_id, + "conversation_history": [t.model_dump() for t in req.conversation_history], + "intents": [], + "guardrail_flags": [], + "guardrail_blocked": False, + "realtime_context": None, + "news_chunks": [], + "historical_chunks": [], + "fundamental_data": None, + "sector_context": None, + "fused_context": "", + "response": "", + "citations": [], + "confidence_score": 0.0, + "disclaimer_text": "", + "trace_id": str(uuid.uuid4())[:8], + "retrieval_scores": {}, + } + + # Per-request unique thread_id — prevents MemorySaver from accumulating + # operator.add fields (news_chunks, historical_chunks) across invocations. + # Conversation history is passed explicitly in initial_state, so nothing is lost. + trace_id = initial_state["trace_id"] + config = {"configurable": {"thread_id": f"{req.session_id}:{req.ticker}:{trace_id}"}} + + try: + yield _sse({"type": "status", "message": "Analyzing query..."}) + + # Early cache bypass — skip entire graph if response is cached + # Uses TTL-only check (no price data yet); price-based invalidation runs in response_node + if req.ticker and not _resp_is_volatile(req.query): + _key = _resp_cache_key(req.ticker, req.query, req.user_mode) + _cached_text = _resp_get_cached(_key, current_pct=None) + if _cached_text: + log.info("early_cache_hit", ticker=req.ticker, session=req.session_id) + yield _sse({"type": "guardrail", "status": "allowed"}) + yield _sse({"type": "intent", "intents": []}) + sentences = _cached_text.split(". ") + for i, sent in enumerate(sentences): + content = sent + (". " if i < len(sentences) - 1 else "") + yield _sse({"type": "token", "content": content}) + yield _sse({"type": "done", "trace_id": trace_id, "confidence": 0.0, "cached": True}) + return + + # Stream graph events node-by-node + async for event in graph.astream(initial_state, config=config): + node_name = next(iter(event)) + node_output = event[node_name] + + if node_name == "guardrail_check": + blocked = node_output.get("guardrail_blocked", False) + yield _sse({"type": "guardrail", "status": "blocked" if blocked else "allowed"}) + if blocked: + response = node_output.get("response", "") + disclaimer = node_output.get("disclaimer_text", "") + yield _sse({"type": "token", "content": response}) + if disclaimer: + yield _sse({"type": "disclaimer", "text": disclaimer}) + yield _sse({"type": "done", "trace_id": req.session_id[:8], "confidence": 0.0}) + return + + elif node_name == "intent_classifier": + intents = node_output.get("intents", []) + yield _sse({"type": "intent", "intents": intents}) + + elif node_name == "parallel_retrieval": + news_n = len(node_output.get("news_chunks") or []) + hist_n = len(node_output.get("historical_chunks") or []) + has_rt = node_output.get("realtime_context") is not None + yield _sse({ + "type": "retrieving", + "status": "done", + "news_chunks": news_n, + "historical_chunks": hist_n, + "realtime": has_rt, + }) + + elif node_name == "response_node": + response = node_output.get("response", "") + # Stream sentence-by-sentence for smooth rendering + sentences = response.split(". ") + for i, sent in enumerate(sentences): + content = sent + (". " if i < len(sentences) - 1 else "") + yield _sse({"type": "token", "content": content}) + + # Final state — emit citations, disclaimer, done + final = await graph.aget_state(config) + final_vals = final.values if final else {} + + # Shared intent + keyword context for gating visual/news output + _active_intents = set(final_vals.get("intents") or []) + _query_words = set(req.query.lower().split()) + + _news_intents = {"news"} + _news_keywords = {"news", "why", "drop", "rise", "fell", "rally", "crash", "surge", + "spike", "decline", "moved", "sliding", "today", "week", "recent", + "latest", "reported", "announced", "earnings", "results", "catalyst"} + _should_cite = bool( + _active_intents & _news_intents + or _query_words & _news_keywords + ) + + citations = final_vals.get("citations", []) + if citations and _should_cite: + yield _sse({"type": "citation", "sources": citations}) + + disclaimer = final_vals.get("disclaimer_text", "") + if disclaimer: + yield _sse({"type": "disclaimer", "text": disclaimer}) + + # Emit 30-day price chart only when visually meaningful + _chart_intents = {"real_time", "historical"} + _chart_keywords = {"chart", "price", "movement", "trend", "performance", "summarize", + "visualize", "graph", "history", "drop", "rise", "fell", "rally", + "crash", "surge", "spike", "decline", "week", "month", "year", + "today", "yesterday", "52", "high", "low", "range"} + _should_chart = bool( + _active_intents & _chart_intents + or _query_words & _chart_keywords + ) + if yf_ticker and _should_chart: + try: + import asyncio as _asyncio + from backend.rag.yahoo_client import fetch_ohlcv as _fetch_ohlcv + currency = initial_state.get("currency", "USD") + + range_str, interval, label = _parse_chart_timeframe(req.query) + + def _get_bars(): + df = _fetch_ohlcv(yf_ticker, range_str=range_str, interval=interval) + if df.empty: + return [] + bars = [] + for dt, row in df.iterrows(): + try: + date_str = str(dt) if interval in ("5m", "30m") else str(dt.date()) + bars.append({ + "date": date_str, + "open": round(float(row["Open"]), 4), + "high": round(float(row["High"]), 4), + "low": round(float(row["Low"]), 4), + "close": round(float(row["Close"]), 4), + }) + except Exception: + continue + return bars + + loop = _asyncio.get_event_loop() + bars = await loop.run_in_executor(None, _get_bars) + if bars: + yield _sse({ + "type": "chart_data", + "ticker": req.ticker, + "currency": currency, + "label": label, + "bars": bars, + }) + except Exception as chart_exc: + log.debug("chart_data_fetch_failed", error=str(chart_exc)) + + confidence = final_vals.get("confidence_score", 0.0) + trace_id = final_vals.get("trace_id", req.session_id[:8]) + from backend.observability.langsmith_url import get_project_url + langsmith_url = get_project_url() + yield _sse({ + "type": "done", + "trace_id": trace_id, + "confidence": confidence, + "langsmith_url": langsmith_url, + }) + + except Exception as exc: + log.error("graph_stream_failed", session=req.session_id, error=str(exc)) + yield _sse({"type": "error", "message": "An error occurred processing your query."}) + yield _sse({"type": "done", "trace_id": req.session_id[:8], "confidence": 0.0}) + + +@router.post("/chat") +@limiter.limit("20/minute") +async def chat(request: Request, body: ChatRequest) -> StreamingResponse: + if len(body.conversation_history) > MAX_CONVERSATION_TURNS: + body.conversation_history = body.conversation_history[-MAX_CONVERSATION_TURNS:] + + log.info("chat_request", session=body.session_id, ticker=body.ticker, query_len=len(body.query)) + + return StreamingResponse( + _stream_graph(body), + media_type="text/event-stream", + headers={ + "Cache-Control": "no-cache", + "X-Accel-Buffering": "no", + }, + ) diff --git a/backend/api/routes/health.py b/backend/api/routes/health.py new file mode 100644 index 0000000000000000000000000000000000000000..137bf557bf2eab22b9efaad6879340c7a5cc5b22 --- /dev/null +++ b/backend/api/routes/health.py @@ -0,0 +1,116 @@ +import json +import os +from pathlib import Path + +import structlog +from fastapi import APIRouter +from pydantic import BaseModel + +from backend.rag.ingestion.universe import universe + +log = structlog.get_logger() +router = APIRouter(tags=["health"]) + +_LANGSMITH_PROJECT = os.getenv("LANGCHAIN_PROJECT", "finora-prod") +_EVAL_PATH = Path(__file__).parent.parent.parent / "data" / "eval_results" / "latest.json" + + +class HealthResponse(BaseModel): + status: str + qdrant: str + groq: str + langsmith: str + langsmith_url: str + universe_size: int + + +class EvalMetric(BaseModel): + score: float + target: float + passed: bool + delta: float | None = None + + +class EvalResponse(BaseModel): + overall_pass: bool + scores: dict[str, float] + results: dict[str, EvalMetric] + run_at: str | None = None + tickers: list[str] = [] + n_pairs: int | None = None + + +@router.get("/health", response_model=HealthResponse) +async def health() -> HealthResponse: + qdrant_status = "unconfigured" + groq_status = "unconfigured" + langsmith_status = "unconfigured" + langsmith_url = f"https://smith.langchain.com/projects/{_LANGSMITH_PROJECT}" + + if os.getenv("QDRANT_URL") and os.getenv("QDRANT_API_KEY"): + try: + from qdrant_client import QdrantClient + client = QdrantClient( + url=os.getenv("QDRANT_URL"), + api_key=os.getenv("QDRANT_API_KEY"), + timeout=3, + ) + client.get_collections() + qdrant_status = "connected" + except Exception as exc: + log.warning("qdrant_health_failed", error=str(exc)) + qdrant_status = "error" + + if os.getenv("GROQ_API_KEY"): + try: + from groq import Groq + groq_client = Groq(api_key=os.getenv("GROQ_API_KEY")) + groq_client.chat.completions.create( + model="llama-3.1-8b-instant", + messages=[{"role": "user", "content": "ping"}], + max_tokens=1, + ) + groq_status = "connected" + except Exception as exc: + log.warning("groq_health_failed", error=str(exc)) + groq_status = "error" + + if os.getenv("LANGCHAIN_API_KEY"): + langsmith_status = "configured" + + return HealthResponse( + status="ok", + qdrant=qdrant_status, + groq=groq_status, + langsmith=langsmith_status, + langsmith_url=langsmith_url, + universe_size=len(universe.stocks), + ) + + +@router.get("/eval/latest", response_model=EvalResponse) +async def eval_latest() -> EvalResponse: + """Return most recent RAGAS evaluation results from disk.""" + if not _EVAL_PATH.exists(): + return EvalResponse( + overall_pass=False, + scores={}, + results={}, + run_at=None, + ) + try: + data = json.loads(_EVAL_PATH.read_text()) + return EvalResponse( + overall_pass=data.get("overall_pass", False), + scores=data.get("scores", {}), + results={ + k: EvalMetric(**v) + for k, v in data.get("results", {}).items() + }, + tickers=data.get("tickers", []), + n_pairs=data.get("n_pairs"), + run_at=data.get("run_at"), + ) + except Exception as exc: + log.warning("eval_read_failed", error=str(exc)) + return EvalResponse(overall_pass=False, scores={}, results={}, run_at=None) diff --git a/backend/api/routes/stocks.py b/backend/api/routes/stocks.py new file mode 100644 index 0000000000000000000000000000000000000000..b5e269e58ca93290b299ea61674860b729ba5829 --- /dev/null +++ b/backend/api/routes/stocks.py @@ -0,0 +1,382 @@ +import asyncio +import time +from typing import Any + +import structlog +from fastapi import APIRouter, HTTPException, Query, Request +from pydantic import BaseModel + +from backend.api.middleware.rate_limit import limiter +from backend.rag.ingestion.universe import universe +from backend.rag.yahoo_client import fetch_company_info, fetch_fundamentals, fetch_news, fetch_ohlcv, fetch_quote, fetch_sector_etfs + +log = structlog.get_logger() +router = APIRouter(tags=["stocks"]) + + +class StockSearchResult(BaseModel): + ticker: str + name: str + exchange: str + sector: str + country: str + currency: str + yf_ticker: str + + +class AnalystConsensus(BaseModel): + buy: int + hold: int + sell: int + avg_target: float | None + + +class OHLCVBar(BaseModel): + date: str + open: float + high: float + low: float + close: float + volume: int + + +class NewsItem(BaseModel): + text: str + title: str + source: str + published_at: str + url: str + + +class HistoricalSignal(BaseModel): + text: str + event_type: str + date_range: str + return_pct: float | None + + +class SimilarStock(BaseModel): + ticker: str + name: str + sector: str + exchange: str + currency: str + + +class SectorData(BaseModel): + sector: str + etf: str + return_pct: float + price: float | None = None + + +class StockDetail(BaseModel): + ticker: str + name: str + exchange: str + currency: str + sector: str | None + industry: str | None + country: str | None + city: str | None + website: str | None + full_time_employees: int | None + business_summary: str | None + beta: float | None + dividend_yield: float | None + price: float | None + change: float | None + pct_change: float | None + volume: int | None + avg_volume_30d: int | None + market_cap: int | None + pe: float | None + forward_pe: float | None + eps: float | None + week_52_high: float | None + week_52_low: float | None + analyst_consensus: AnalystConsensus | None + ohlcv_7d: list[OHLCVBar] + news_rag: list[NewsItem] + historical_signals: list[HistoricalSignal] + similar_stocks: list[SimilarStock] = [] + + +_SECTORS_CACHE: tuple[list[dict], float] | None = None +_SECTORS_TTL = 300.0 # 5 minutes + + +def _get_similar_stocks(current_ticker: str, sector: str | None, limit: int = 5) -> list[SimilarStock]: + if not sector: + return [] + all_stocks = universe.search("", limit=10000) + similar = [ + SimilarStock( + ticker=s["ticker"], + name=s["name"], + sector=s.get("sector", ""), + exchange=s.get("exchange", ""), + currency=s.get("currency", "USD"), + ) + for s in all_stocks + if s.get("sector", "").lower() == sector.lower() + and s["ticker"] != current_ticker + ] + return similar[:limit] + + +def _safe_float(val: Any) -> float | None: + try: + v = float(val) + return None if v != v else v + except (TypeError, ValueError): + return None + + +def _safe_int(val: Any) -> int | None: + try: + v = float(val) + return None if v != v else int(v) + except (TypeError, ValueError): + return None + + +async def _fetch_detail(yf_ticker: str, display_ticker: str) -> dict[str, Any]: + def _blocking() -> dict[str, Any]: + try: + quote = fetch_quote(yf_ticker) + except Exception: + quote = {} + try: + fund = fetch_fundamentals(yf_ticker) + except Exception: + fund = {} + try: + company = fetch_company_info(yf_ticker) + except Exception: + company = {} + + # 7-day daily OHLCV + ohlcv_7d: list[OHLCVBar] = [] + try: + df = fetch_ohlcv(yf_ticker, days=7, interval="1d") + if not df.empty: + for dt, row in df.tail(7).iterrows(): + ohlcv_7d.append(OHLCVBar( + date=str(dt.date()), + open=round(float(row["Open"]), 4), + high=round(float(row["High"]), 4), + low=round(float(row["Low"]), 4), + close=round(float(row["Close"]), 4), + volume=int(row["Volume"]), + )) + except Exception: + pass + + # Live news via Google News RSS + news_rag: list[NewsItem] = [] + try: + raw_news = fetch_news(yf_ticker, count=5) + for n in raw_news: + news_rag.append(NewsItem( + text=n.get("text", n.get("title", "")), + title=n.get("title", ""), + source=n.get("source", ""), + published_at=n.get("published_at", ""), + url=n.get("url", ""), + )) + except Exception as exc: + log.warning("news_fetch_failed", ticker=yf_ticker, error=str(exc)) + + # Historical signals from Qdrant (best-effort, silent fail) + historical_signals: list[HistoricalSignal] = [] + try: + from backend.rag.retrieval.hybrid import hybrid_search + from backend.rag.ingestion.collections import collection_name + chunks = hybrid_search( + query=f"{display_ticker} historical price patterns", + ticker=display_ticker, + collection=collection_name("historical"), + limit=4, + allow_global_fallback=False, + ) + for ch in chunks: + meta = ch.metadata + historical_signals.append(HistoricalSignal( + text=ch.text, + event_type=meta.get("event_type", "price_event"), + date_range=meta.get("date_range", meta.get("start_date", "")), + return_pct=_safe_float(meta.get("return_pct")), + )) + except Exception: + pass # Qdrant unavailable or ticker not in historical corpus + + ac = fund.get("analyst_consensus", {}) or {} + consensus = AnalystConsensus( + buy=int(ac.get("buy") or 0), + hold=int(ac.get("hold") or 0), + sell=int(ac.get("sell") or 0), + avg_target=_safe_float(ac.get("avg_target")), + ) + + return { + "price": _safe_float(quote.get("price")), + "change": _safe_float(quote.get("change")), + "pct_change": _safe_float(quote.get("pct_change")), + "volume": _safe_int(quote.get("volume")), + "avg_volume_30d": _safe_int(quote.get("avg_volume_3m")) or _safe_int(fund.get("avg_volume_3m")), + "market_cap": _safe_int(fund.get("market_cap")) or _safe_int(quote.get("market_cap")), + "pe": _safe_float(fund.get("pe")), + "forward_pe": _safe_float(fund.get("forward_pe")), + "eps": _safe_float(fund.get("eps")), + "week_52_high": _safe_float(fund.get("week_52_high")), + "week_52_low": _safe_float(fund.get("week_52_low")), + "beta": _safe_float(fund.get("beta")), + "dividend_yield": _safe_float(fund.get("dividend_yield")), + "industry": company.get("industry") or fund.get("industry"), + "country": company.get("country") or fund.get("country"), + "city": company.get("city") or fund.get("city"), + "website": company.get("website") or fund.get("website"), + "full_time_employees": _safe_int(company.get("full_time_employees") or fund.get("full_time_employees")), + "business_summary": company.get("business_summary") or fund.get("business_summary"), + "analyst_consensus": consensus, + "ohlcv_7d": ohlcv_7d, + "news_rag": news_rag, + "historical_signals": historical_signals, + } + + loop = asyncio.get_running_loop() + return await loop.run_in_executor(None, _blocking) + + +@router.get("/sectors", response_model=list[SectorData]) +@limiter.limit("30/minute") +async def get_sectors(request: Request) -> list[SectorData]: + global _SECTORS_CACHE + now = time.monotonic() + if _SECTORS_CACHE and (now - _SECTORS_CACHE[1]) < _SECTORS_TTL: + return [SectorData(**s) for s in _SECTORS_CACHE[0]] + + loop = asyncio.get_running_loop() + raw = await loop.run_in_executor(None, fetch_sector_etfs) + _SECTORS_CACHE = (raw, now) + return [SectorData(**s) for s in raw] + + +@router.get("/search", response_model=list[StockSearchResult]) +@limiter.limit("60/minute") +async def search_stocks( + request: Request, + q: str = Query("", max_length=100), + limit: int = Query(10, ge=1, le=50), +) -> list[StockSearchResult]: + results = universe.search(q, limit=limit) + return [ + StockSearchResult( + ticker=s["ticker"], + name=s["name"], + exchange=s.get("exchange", ""), + sector=s.get("sector", ""), + country=s.get("country", ""), + currency=s.get("currency", "USD"), + yf_ticker=s.get("yf_ticker", s["ticker"]), + ) + for s in results + ] + + +@router.get("/{ticker}", response_model=StockDetail) +@limiter.limit("30/minute") +async def get_stock(request: Request, ticker: str) -> StockDetail: + entry = universe.get_by_ticker(ticker) + if not entry: + raise HTTPException(status_code=404, detail=f"Ticker '{ticker}' not in universe") + + yf_ticker = entry.get("yf_ticker", ticker) + data: dict[str, Any] = { + "price": None, "change": None, "pct_change": None, + "volume": None, "avg_volume_30d": None, "market_cap": None, + "pe": None, "forward_pe": None, "eps": None, + "week_52_high": None, "week_52_low": None, + "beta": None, "dividend_yield": None, + "industry": None, "country": None, "city": None, + "website": None, "full_time_employees": None, "business_summary": None, + "analyst_consensus": AnalystConsensus(buy=0, hold=0, sell=0, avg_target=None), + "ohlcv_7d": [], "news_rag": [], "historical_signals": [], + } + try: + data = await _fetch_detail(yf_ticker, entry["ticker"]) + except Exception as exc: + log.warning("yahoo_fetch_failed", ticker=yf_ticker, error=str(exc)) + + sector = entry.get("sector") + similar = _get_similar_stocks(entry["ticker"], sector) + + return StockDetail( + ticker=entry["ticker"], + name=entry["name"], + exchange=entry.get("exchange", ""), + currency=entry.get("currency", "USD"), + sector=sector, + similar_stocks=similar, + **data, + ) + + +# Timeframe → (yahoo_range, yahoo_interval) +_TIMEFRAME_MAP: dict[str, tuple[str, str]] = { + "1D": ("1d", "5m"), + "1W": ("5d", "30m"), + "1M": ("1mo", "1d"), + "3M": ("3mo", "1d"), + "6M": ("6mo", "1d"), + "1Y": ("1y", "1wk"), + "3Y": ("3y", "1wk"), + "5Y": ("5y", "1wk"), + "ALL": ("20y", "1mo"), +} + + +class OHLCVResponse(BaseModel): + ticker: str + range: str + interval: str + bars: list[OHLCVBar] + + +@router.get("/{ticker}/ohlcv", response_model=OHLCVResponse) +@limiter.limit("60/minute") +async def get_ohlcv( + request: Request, + ticker: str, + range: str = Query("1M", pattern="^(1D|1W|1M|3M|6M|1Y|3Y|5Y|ALL)$"), +) -> OHLCVResponse: + entry = universe.get_by_ticker(ticker) + if not entry: + raise HTTPException(status_code=404, detail=f"Ticker '{ticker}' not in universe") + + yf_ticker = entry.get("yf_ticker", ticker) + yahoo_range, interval = _TIMEFRAME_MAP.get(range, ("1mo", "1d")) + + def _blocking() -> list[OHLCVBar]: + df = fetch_ohlcv(yf_ticker, interval=interval, range_str=yahoo_range) + bars: list[OHLCVBar] = [] + if df.empty: + return bars + for dt, row in df.iterrows(): + try: + bars.append(OHLCVBar( + date=str(dt) if range == "1D" else str(dt.date()), + open=round(float(row["Open"]), 4), + high=round(float(row["High"]), 4), + low=round(float(row["Low"]), 4), + close=round(float(row["Close"]), 4), + volume=int(row["Volume"]), + )) + except Exception: + continue + return bars + + loop = asyncio.get_running_loop() + bars = await loop.run_in_executor(None, _blocking) + return OHLCVResponse(ticker=ticker, range=range, interval=interval, bars=bars) diff --git a/backend/finora_mcp/__init__.py b/backend/finora_mcp/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/backend/finora_mcp/server.py b/backend/finora_mcp/server.py new file mode 100644 index 0000000000000000000000000000000000000000..7aa2a1db4d59c7a90d7c1ca883593eceba2e81e3 --- /dev/null +++ b/backend/finora_mcp/server.py @@ -0,0 +1,43 @@ +""" +Finora FastMCP server — stdio transport. + +Run from repo root: + cd backend && python -m finora_mcp.server + +Tools exposed: + get_realtime_quote, search_historical_rag, search_news_rag, + get_fundamentals, screen_stocks, get_stock_universe +""" +from __future__ import annotations + +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +BACKEND = ROOT / "backend" + +sys.path.insert(0, str(BACKEND)) + +from dotenv import load_dotenv +load_dotenv(ROOT / ".env") + +from fastmcp import FastMCP + +from finora_mcp.tools.fundamentals import get_fundamentals +from finora_mcp.tools.historical import search_historical_rag +from finora_mcp.tools.news import search_news_rag +from finora_mcp.tools.quote import get_realtime_quote +from finora_mcp.tools.screener import get_stock_universe, screen_stocks + +mcp = FastMCP("finora-mcp") + +mcp.tool()(get_realtime_quote) +mcp.tool()(search_historical_rag) +mcp.tool()(search_news_rag) +mcp.tool()(get_fundamentals) +mcp.tool()(screen_stocks) +mcp.tool()(get_stock_universe) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/backend/finora_mcp/tools/__init__.py b/backend/finora_mcp/tools/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/backend/finora_mcp/tools/fundamentals.py b/backend/finora_mcp/tools/fundamentals.py new file mode 100644 index 0000000000000000000000000000000000000000..076dc41e1042a52190594ca7d74283352c545b84 --- /dev/null +++ b/backend/finora_mcp/tools/fundamentals.py @@ -0,0 +1,9 @@ +"""MCP tool: get_fundamentals — PE, EPS, revenue, margins, analyst consensus.""" +from __future__ import annotations + +from backend.rag.yahoo_client import fetch_fundamentals + + +def get_fundamentals(ticker: str) -> dict: + """PE, EPS, revenue, margins, debt, analyst consensus, price targets.""" + return fetch_fundamentals(ticker) diff --git a/backend/finora_mcp/tools/historical.py b/backend/finora_mcp/tools/historical.py new file mode 100644 index 0000000000000000000000000000000000000000..2a6a8953e8745646bf58ba78736c4e10a0764d79 --- /dev/null +++ b/backend/finora_mcp/tools/historical.py @@ -0,0 +1,26 @@ +"""MCP tool: search_historical_rag — semantic + BM25 hybrid over 20yr OHLCV event chunks.""" +from __future__ import annotations + + +def search_historical_rag(ticker: str, query: str, years: int = 20, top_k: int = 5) -> list[dict]: + """Semantic + BM25 hybrid search over 20yr OHLCV event chunks. Reranked results.""" + from backend.rag.pipeline import run_rag_branch + + results = run_rag_branch( + query=query, + ticker=ticker, + collection_key="historical", + use_hyde=True, + top_k=top_k, + ) + return [ + { + "text": r.text, + "ticker": r.metadata.get("ticker"), + "date_range": r.metadata.get("date_range"), + "event_type": r.metadata.get("event_type"), + "return_pct": r.metadata.get("return_pct"), + "score": round(r.score, 4) if r.score else None, + } + for r in results + ] diff --git a/backend/finora_mcp/tools/news.py b/backend/finora_mcp/tools/news.py new file mode 100644 index 0000000000000000000000000000000000000000..4dabe6c7ae16f20c986ab2084a234ffec94f5b87 --- /dev/null +++ b/backend/finora_mcp/tools/news.py @@ -0,0 +1,27 @@ +"""MCP tool: search_news_rag — hybrid search over news + SEC filings.""" +from __future__ import annotations + + +def search_news_rag(ticker: str, query: str, days: int = 30, top_k: int = 8) -> list[dict]: + """Hybrid search over news + SEC filings. Reranked, deduplicated.""" + from backend.rag.pipeline import run_rag_branch + + results = run_rag_branch( + query=query, + ticker=ticker, + collection_key="news", + use_hyde=True, + top_k=top_k, + ) + return [ + { + "text": r.text, + "ticker": r.metadata.get("ticker"), + "source": r.metadata.get("source"), + "published_at": r.metadata.get("published_at"), + "url": r.metadata.get("url"), + "sentiment_score": r.metadata.get("sentiment_score"), + "score": round(r.score, 4) if r.score else None, + } + for r in results + ] diff --git a/backend/finora_mcp/tools/quote.py b/backend/finora_mcp/tools/quote.py new file mode 100644 index 0000000000000000000000000000000000000000..613d4c5affd024867ea57f8118779fd41e38275b --- /dev/null +++ b/backend/finora_mcp/tools/quote.py @@ -0,0 +1,9 @@ +"""MCP tool: get_realtime_quote — live price, volume, intraday OHLC.""" +from __future__ import annotations + +from backend.rag.yahoo_client import fetch_quote + + +def get_realtime_quote(ticker: str) -> dict: + """Live price, volume, intraday OHLC, market status. Works for US + Indian stocks.""" + return fetch_quote(ticker) diff --git a/backend/finora_mcp/tools/screener.py b/backend/finora_mcp/tools/screener.py new file mode 100644 index 0000000000000000000000000000000000000000..0ebc6730518c6e71fc01fc220c4cbc7913b01d41 --- /dev/null +++ b/backend/finora_mcp/tools/screener.py @@ -0,0 +1,63 @@ +"""MCP tool: screen_stocks + get_stock_universe.""" +from __future__ import annotations + +from typing import Optional + + +def screen_stocks( + sector: Optional[str] = None, + min_pe: Optional[float] = None, + max_pe: Optional[float] = None, + country: Optional[str] = None, + limit: int = 20, +) -> list[dict]: + """Screen S&P 500 + NIFTY 50 universe by criteria.""" + from backend.rag.ingestion.universe import StockUniverse + from backend.rag.yahoo_client import fetch_fundamentals + + u = StockUniverse() + stocks = u.stocks + + if sector: + stocks = [s for s in stocks if (s.get("sector") or "").lower() == sector.lower()] + if country: + stocks = [s for s in stocks if (s.get("country") or "").lower() == country.lower()] + + if (min_pe is not None or max_pe is not None) and stocks: + filtered = [] + for s in stocks[:50]: + try: + fund = fetch_fundamentals(s.get("yf_ticker", s["ticker"])) + pe = fund.get("pe") + if pe is None: + continue + if min_pe is not None and pe < min_pe: + continue + if max_pe is not None and pe > max_pe: + continue + filtered.append({**s, "pe": round(pe, 2)}) + if len(filtered) >= limit: + break + except Exception: + continue + return filtered + + return [ + {"ticker": s["ticker"], "name": s.get("name"), "sector": s.get("sector"), + "country": s.get("country"), "exchange": s.get("exchange")} + for s in stocks[:limit] + ] + + +def get_stock_universe(query: Optional[str] = None, limit: int = 10) -> list[dict]: + """Fuzzy search ~555 stocks by name or ticker.""" + from backend.rag.ingestion.universe import StockUniverse + + u = StockUniverse() + results = u.search(query, limit=limit) if query else u.stocks[:limit] + return [ + {"ticker": s["ticker"], "name": s.get("name"), "sector": s.get("sector"), + "country": s.get("country"), "exchange": s.get("exchange"), + "yf_ticker": s.get("yf_ticker", s["ticker"])} + for s in results + ] diff --git a/backend/graph/__init__.py b/backend/graph/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/backend/graph/finora_graph.py b/backend/graph/finora_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..e648c66e4a4e7c08740614e7faf4be7a2833f587 --- /dev/null +++ b/backend/graph/finora_graph.py @@ -0,0 +1,96 @@ +""" +Finora LangGraph StateGraph. + +Topology: + guardrail_check → [blocked → END | allowed → intent_classifier] + intent_classifier → parallel_retrieval (asyncio.gather over all needed branches) + parallel_retrieval → fusion_node → response_node → END + +Note: parallel_retrieval is a single async node that fans out internally via +asyncio.gather — simpler and more reliable than graph-level fan-out for this use case. +""" +from __future__ import annotations + +import asyncio + +import structlog +from langgraph.checkpoint.memory import MemorySaver +from langgraph.graph import END, StateGraph + +from backend.graph.nodes.fusion_node import fusion_node +from backend.graph.nodes.fundamentals_node import fundamentals_node +from backend.graph.nodes.historical_rag_node import historical_rag_node +from backend.graph.nodes.intent_classifier import intent_classifier_node +from backend.graph.nodes.news_rag_node import news_rag_node +from backend.graph.nodes.realtime_node import realtime_node +from backend.graph.nodes.response_node import response_node +from backend.graph.state import FiNoraState +from backend.guardrails.classifier import guardrail_check_node, route_after_guardrail + +log = structlog.get_logger() + + +async def parallel_retrieval_node(state: FiNoraState) -> dict: + """ + Fan-out: runs all applicable retrieval branches concurrently via asyncio.gather. + Merges results back into state. + """ + tasks = [ + realtime_node(state), + news_rag_node(state), + historical_rag_node(state), + fundamentals_node(state), + ] + results = await asyncio.gather(*tasks, return_exceptions=True) + + merged: dict = { + "realtime_context": None, + "news_chunks": [], + "historical_chunks": [], + "fundamental_data": None, + "sector_context": None, + "retrieval_scores": {}, + } + for r in results: + if isinstance(r, Exception): + log.error("parallel_retrieval_branch_failed", error=str(r)) + continue + for 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 {}) + elif val is not None: + merged[key] = val + + return merged + + +def _build_graph() -> StateGraph: + builder = StateGraph(FiNoraState) + + builder.add_node("guardrail_check", guardrail_check_node) + builder.add_node("intent_classifier", intent_classifier_node) + builder.add_node("parallel_retrieval", parallel_retrieval_node) + builder.add_node("fusion_node", fusion_node) + builder.add_node("response_node", response_node) + + builder.set_entry_point("guardrail_check") + + builder.add_conditional_edges( + "guardrail_check", + route_after_guardrail, + {"blocked": END, "allowed": "intent_classifier"}, + ) + + builder.add_edge("intent_classifier", "parallel_retrieval") + builder.add_edge("parallel_retrieval", "fusion_node") + builder.add_edge("fusion_node", "response_node") + builder.add_edge("response_node", END) + + return builder + + +# Compiled graph — shared across all requests +_checkpointer = MemorySaver() +graph = _build_graph().compile(checkpointer=_checkpointer) diff --git a/backend/graph/nodes/__init__.py b/backend/graph/nodes/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/backend/graph/nodes/fundamentals_node.py b/backend/graph/nodes/fundamentals_node.py new file mode 100644 index 0000000000000000000000000000000000000000..978bc18645378144b5f4f558104b7e2a7a3eae29 --- /dev/null +++ b/backend/graph/nodes/fundamentals_node.py @@ -0,0 +1,131 @@ +"""Fundamentals node — Yahoo Finance quoteSummary via curl_cffi.""" +from __future__ import annotations + +import asyncio +import time + +import structlog + +from backend.graph.state import FiNoraState +from backend.rag.yahoo_client import fetch_fundamentals, fetch_sector_etfs + +log = structlog.get_logger() + +_FUNDAMENTALS_CACHE: dict[str, tuple[dict, float]] = {} +_SECTOR_CACHE: tuple[list[dict], float] | None = None +_CACHE_TTL = 300.0 # 5 minutes + + +def _get_cached_fundamentals(yf_ticker: str) -> dict | None: + entry = _FUNDAMENTALS_CACHE.get(yf_ticker) + if entry and (time.monotonic() - entry[1]) < _CACHE_TTL: + return entry[0] + return None + + +def _set_cached_fundamentals(yf_ticker: str, data: dict) -> None: + _FUNDAMENTALS_CACHE[yf_ticker] = (data, time.monotonic()) + + +def _get_similar_stocks(ticker: str, sector: str | None) -> list[dict]: + if not sector: + return [] + try: + from backend.rag.ingestion.universe import universe + all_stocks = universe.search("", limit=10000) + similar = [ + {"ticker": s["ticker"], "name": s["name"], + "sector": s.get("sector", ""), "exchange": s.get("exchange", ""), + "currency": s.get("currency", "USD")} + for s in all_stocks + if s.get("sector", "").lower() == sector.lower() and s["ticker"] != ticker + ] + return similar[:8] + except Exception: + return [] + + +def _fetch_sector_context(ticker: str, sector: str | None) -> dict: + global _SECTOR_CACHE + now = time.monotonic() + + etfs: list[dict] = [] + if _SECTOR_CACHE and (now - _SECTOR_CACHE[1]) < _CACHE_TTL: + etfs = _SECTOR_CACHE[0] + else: + try: + etfs = fetch_sector_etfs() + _SECTOR_CACHE = (etfs, now) + except Exception: + etfs = [] + + similar = _get_similar_stocks(ticker, sector) + + # Find the ETF for this stock's sector + sector_etf: dict | None = None + if sector: + for etf in etfs: + if etf.get("sector", "").lower() == sector.lower(): + sector_etf = etf + break + + return { + "sector": sector, + "sector_etf": sector_etf, + "all_sector_etfs": etfs, + "similar_stocks": similar, + } + + +async def fundamentals_node(state: FiNoraState) -> dict: + intents = state.get("intents", []) + has_fundamental = "fundamental" in intents + has_comparative = "comparative" in intents + + if not has_fundamental and not has_comparative: + return {"fundamental_data": None, "sector_context": None} + + ticker = state.get("ticker", "") + yf_ticker = state.get("yf_ticker", ticker) + if not ticker: + return {"fundamental_data": None, "sector_context": None} + + result: dict = {"fundamental_data": None, "sector_context": None} + + # Fetch fundamentals if needed + if has_fundamental: + cached = _get_cached_fundamentals(yf_ticker) + if cached: + log.debug("fundamentals_cache_hit", ticker=ticker) + result["fundamental_data"] = cached + else: + loop = asyncio.get_running_loop() + data = await loop.run_in_executor(None, fetch_fundamentals, yf_ticker) + data["ticker"] = ticker + _set_cached_fundamentals(yf_ticker, data) + log.info("fundamentals_node_done", ticker=ticker, yf_ticker=yf_ticker, pe=data.get("pe")) + result["fundamental_data"] = data + + # Fetch sector context if comparative intent present + if has_comparative: + # Get sector from fundamentals data or state + fd = result.get("fundamental_data") or {} + sector = fd.get("sector") or state.get("sector") + + # If no fundamentals fetched yet, get sector from universe + if not sector: + try: + from backend.rag.ingestion.universe import universe + entry = universe.get_by_ticker(ticker) + sector = (entry or {}).get("sector") + except Exception: + sector = None + + loop = asyncio.get_running_loop() + sector_ctx = await loop.run_in_executor(None, _fetch_sector_context, ticker, sector) + result["sector_context"] = sector_ctx + log.info("sector_context_fetched", ticker=ticker, sector=sector, + similar_count=len(sector_ctx.get("similar_stocks", [])), + etfs_count=len(sector_ctx.get("all_sector_etfs", []))) + + return result diff --git a/backend/graph/nodes/fusion_node.py b/backend/graph/nodes/fusion_node.py new file mode 100644 index 0000000000000000000000000000000000000000..bf6fd0d9f2d452371cd7356dc2dbeeb036346eec --- /dev/null +++ b/backend/graph/nodes/fusion_node.py @@ -0,0 +1,595 @@ +"""Fusion node — assembles structured data context for the response LLM.""" +from __future__ import annotations + +import os + +import structlog + +from backend.graph.state import FiNoraState +from backend.guardrails.disclaimers import get_disclaimer + +log = structlog.get_logger() + +_SUMMARY_TRIGGERS = { + "summarize", "summary", "explain", "overview", "what's happening", + "whats happening", "tell me about", "breakdown", "analyse", "analyze", + "give me a", "what do you think", "how is", "how's", +} + + +def _is_summary_query(query: str) -> bool: + q = query.lower().strip() + return any(trigger in q for trigger in _SUMMARY_TRIGGERS) + + +def _currency_sym(currency: str) -> str: + return "₹" if currency == "INR" else "$" + + +def _fmt_realtime(rt: dict | None, currency: str = "USD") -> str: + if not rt or not rt.get("price"): + return "[REAL-TIME DATA UNAVAILABLE]" + sym = _currency_sym(currency) + ticker = rt.get("ticker", "") + price = rt.get("price") + change = rt.get("change") + pct = rt.get("pct_change") + vol = rt.get("volume") + avg_vol = rt.get("avg_volume_30d") + vol_ratio = round(vol / avg_vol, 1) if vol and avg_vol else None + + lines = [f"{ticker}: {sym}{price:.2f} ({pct:+.2f}%)" if price and pct else f"{ticker}: {sym}{price}"] + if change: + lines.append(f"Change: {sym}{change:+.4f}") + if vol_ratio is not None: + lines.append(f"Volume: {vol:,} ({vol_ratio}x 30d avg)") + w52h = rt.get("week_52_high") + w52l = rt.get("week_52_low") + if w52h and w52l: + lines.append(f"52W Range: {sym}{w52l:.2f} - {sym}{w52h:.2f}") + + return "\n".join(lines) + + +def _fmt_historical_patterns(patterns: list[dict]) -> str: + """Format always-available historical patterns fetched alongside realtime data.""" + if not patterns: + return "" + top = patterns[:2] + lines = [f"[HISTORICAL PATTERNS — {len(top)} events]"] + for i, p in enumerate(top, 1): + parts = [f"[{i}]"] + if p.get("event_type"): + parts.append(p["event_type"].replace("_", " ").title()) + if p.get("date_range"): + parts.append(f"({p['date_range']})") + if p.get("return_pct") is not None: + parts.append(f"fwd return: {p['return_pct']:+.1f}%") + if p.get("text"): + parts.append(f"— {p['text'][:120]}") + lines.append(" ".join(parts)) + return "\n".join(lines) + + +_CHUNK_TEXT_LIMIT = int(os.getenv("RAG_CHUNK_TEXT_LIMIT", "400")) +_MAX_NEWS_CHUNKS = int(os.getenv("RAG_MAX_NEWS_CHUNKS", "4")) +_MAX_HIST_CHUNKS = int(os.getenv("RAG_MAX_HIST_CHUNKS", "3")) + + +def _fmt_chunks(chunks: list[dict], label: str, max_chunks: int = _MAX_NEWS_CHUNKS) -> str: + if not chunks: + return f"[NO {label.upper()} DATA]" + lines = [f"[{label.upper()} - {min(len(chunks), max_chunks)} sources]"] + for i, ch in enumerate(chunks[:max_chunks], 1): + source = ch.get("source", ch.get("url", "unknown")) + date = ch.get("published_at", ch.get("start_date", ch.get("date_range", ""))) + text = ch.get("text", "")[:_CHUNK_TEXT_LIMIT] + lines.append(f"[{i}] {source} ({date}): {text}") + return "\n".join(lines) + + +def _fmt_sector_context(sc: dict | None, currency: str = "USD") -> str: + if not sc: + return "" + sym = _currency_sym(currency) + lines = [] + + sector = sc.get("sector") + etf = sc.get("sector_etf") + if sector: + header = f"[SECTOR CONTEXT — {sector}]" + if etf: + pct = etf.get("return_pct", 0) + price = etf.get("price") + etf_name = etf.get("etf", "") + price_str = f" ({sym}{price:.2f})" if price else "" + header += f"\nSector ETF ({etf_name}){price_str}: {pct:+.2f}% today" + lines.append(header) + + all_etfs = sc.get("all_sector_etfs", []) + if all_etfs: + sorted_etfs = sorted(all_etfs, key=lambda x: x.get("return_pct", 0), reverse=True) + etf_parts = [ + f"{e['sector']} ({e['etf']}): {e.get('return_pct', 0):+.2f}%" + for e in sorted_etfs[:6] + ] + lines.append("Sector performance today:\n" + "\n".join(etf_parts)) + + similar = sc.get("similar_stocks", []) + if similar: + sim_parts = [ + f"- {s['ticker']} ({s['exchange']}): {s['name']}" + for s in similar[:6] + ] + lines.append(f"Similar stocks in {sector or 'sector'}:\n" + "\n".join(sim_parts)) + + return "\n".join(lines) + + +def _fmt_fundamentals(fd: dict | None, currency: str = "USD") -> str: + if not fd: + return "[FUNDAMENTAL DATA UNAVAILABLE]" + sym = _currency_sym(currency) + parts: list[str] = [] + if fd.get("pe"): + parts.append(f"PE: {fd['pe']:.1f}") + if fd.get("forward_pe"): + parts.append(f"Forward PE: {fd['forward_pe']:.1f}") + if fd.get("eps"): + parts.append(f"EPS: {sym}{fd['eps']:.2f}") + if fd.get("analyst_target"): + parts.append(f"Analyst target: {sym}{fd['analyst_target']:.2f}") + if fd.get("recommendation"): + parts.append(f"Consensus: {fd['recommendation'].upper()}") + if fd.get("profit_margins"): + parts.append(f"Net margin: {fd['profit_margins']*100:.1f}%") + if fd.get("beta"): + parts.append(f"Beta: {fd['beta']:.2f}") + if fd.get("revenue"): + parts.append(f"Revenue: {sym}{fd['revenue']/1e9:.1f}B") + if fd.get("market_cap"): + mc = fd["market_cap"] + mc_str = f"{sym}{mc/1e12:.2f}T" if mc >= 1e12 else f"{sym}{mc/1e9:.1f}B" + parts.append(f"Mkt Cap: {mc_str}") + + consensus = fd.get("analyst_consensus") or {} + buy = consensus.get("buy", 0) or 0 + hold = consensus.get("hold", 0) or 0 + sell = consensus.get("sell", 0) or 0 + if buy or hold or sell: + total = buy + hold + sell + buy_pct = round(buy / total * 100) if total else 0 + parts.append(f"Analysts: {buy} Buy / {hold} Hold / {sell} Sell ({buy_pct}% bullish)") + + return " | ".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.""" + flags: list[str] = [] + rt = state.get("realtime_context") or {} + fd = state.get("fundamental_data") or {} + sym = _currency_sym(state.get("currency", "USD")) + + # Volume anomaly + vol = rt.get("volume") + avg_vol = rt.get("avg_volume_30d") + if vol and avg_vol and avg_vol > 0: + vol_z = vol / avg_vol + if vol_z >= 2.5: + flags.append(f"Volume spike: {vol_z:.1f}x 30-day average — unusual institutional activity likely") + elif vol_z <= 0.4: + flags.append("Volume well below average — low conviction move, may not be sustained") + + # PE interpretation + pe = fd.get("pe") + fpe = fd.get("forward_pe") + if pe and pe > 0: + if pe > 40: + flags.append(f"PE of {pe:.1f} — premium valuation, priced for high earnings growth expectations") + elif pe < 12: + flags.append(f"PE of {pe:.1f} — below typical market average, may signal undervaluation or elevated risk") + if fpe and fpe > 0: + ratio = fpe / pe + if ratio < 0.80: + flags.append( + f"Forward PE ({fpe:.1f}) significantly below trailing ({pe:.1f}) — " + "earnings growth expected ahead" + ) + elif ratio > 1.20: + flags.append( + f"Forward PE ({fpe:.1f}) above trailing ({pe:.1f}) — " + "earnings expected to slow or decline" + ) + + # 52W range position + price = rt.get("price") + w52h = rt.get("week_52_high") or fd.get("week_52_high") + w52l = rt.get("week_52_low") or fd.get("week_52_low") + if price and w52h and w52l and w52h > w52l: + pos_pct = ((price - w52l) / (w52h - w52l)) * 100 + if pos_pct >= 95: + flags.append(f"Near 52-week high ({sym}{w52h:.2f}) — potential resistance zone") + elif pos_pct <= 5: + flags.append(f"Near 52-week low ({sym}{w52l:.2f}) — potential support zone") + elif pos_pct >= 75: + flags.append(f"Upper quartile of 52-week range ({pos_pct:.0f}% from low) — relative strength") + elif pos_pct <= 25: + flags.append(f"Lower quartile of 52-week range ({pos_pct:.0f}% from low) — relative weakness") + + # Analyst consensus + consensus = fd.get("analyst_consensus") or {} + buy = consensus.get("buy", 0) or 0 + hold = consensus.get("hold", 0) or 0 + sell = consensus.get("sell", 0) or 0 + total = buy + hold + sell + if total >= 3: + buy_pct = buy / total + if buy_pct >= 0.75: + flags.append(f"Strong buy consensus: {round(buy_pct*100)}% of {total} analysts rate Buy") + elif buy_pct <= 0.25: + flags.append(f"Weak buy consensus: only {round(buy_pct*100)}% of {total} analysts rate Buy") + + # Price vs analyst target + target = fd.get("analyst_target") or (consensus.get("avg_target") if consensus else None) + if price and target and target > 0: + upside = ((target - price) / price) * 100 + if upside >= 15: + flags.append(f"Analyst target ({sym}{target:.2f}) implies {upside:.0f}% upside from current price") + elif upside <= -10: + flags.append(f"Current price {abs(upside):.0f}% above consensus analyst target ({sym}{target:.2f})") + + # Profit margin + margin = fd.get("profit_margins") + if margin is not None: + if margin >= 0.25: + flags.append(f"High net margin of {margin*100:.1f}% — strong pricing power or operational efficiency") + elif margin < 0.05: + flags.append(f"Thin net margin of {margin*100:.1f}% — highly sensitive to cost pressures") + + # Beta + beta = fd.get("beta") + if beta is not None: + if beta >= 1.5: + flags.append(f"High beta ({beta:.2f}) — moves significantly more than the broader market") + elif beta <= 0.5: + flags.append(f"Low beta ({beta:.2f}) — defensive stock with low market correlation") + + return flags + + +def _compute_narrative_hint(state: FiNoraState) -> str: + """Single most important signal — used to anchor the opening narrative sentence.""" + rt = state.get("realtime_context") or {} + fd = state.get("fundamental_data") or {} + + pct = rt.get("pct_change") + vol = rt.get("volume") + avg_vol = rt.get("avg_volume_30d") + price = rt.get("price") + w52h = rt.get("week_52_high") + w52l = rt.get("week_52_low") + consensus = (fd.get("analyst_consensus") or {}) + buy = consensus.get("buy", 0) or 0 + hold = consensus.get("hold", 0) or 0 + sell = consensus.get("sell", 0) or 0 + total = buy + hold + sell + + # Priority order: large price move > volume spike > 52W extreme > consensus + if pct is not None and abs(pct) >= 3.0: + direction = "sharp_upward_move" if pct > 0 else "sharp_downward_move" + return direction + + if vol and avg_vol and avg_vol > 0 and (vol / avg_vol) >= 2.5: + return "high_volume_move" + + if price and w52h and w52l and w52h > w52l: + pos = (price - w52l) / (w52h - w52l) + if pos >= 0.95: + return "near_52w_high" + if pos <= 0.05: + return "near_52w_low" + + if total >= 3: + if buy / total >= 0.75: + return "analyst_strongly_bullish" + if buy / total <= 0.25: + return "analyst_bearish" + + if pct is not None: + if pct >= 1.0: + return "mild_upward_move" + if pct <= -1.0: + return "mild_downward_move" + + return "consolidating" + + +def _compute_confidence_level(state: FiNoraState) -> str: + """Derived confidence: how strongly do signals agree?""" + rt = state.get("realtime_context") or {} + fd = state.get("fundamental_data") or {} + + strong_signals = 0 + + pct = rt.get("pct_change") + if pct is not None and abs(pct) >= 2.0: + strong_signals += 1 + + vol = rt.get("volume") + avg_vol = rt.get("avg_volume_30d") + if vol and avg_vol and avg_vol > 0 and (vol / avg_vol) >= 2.0: + strong_signals += 1 + + price = rt.get("price") + w52h = rt.get("week_52_high") + w52l = rt.get("week_52_low") + if price and w52h and w52l and w52h > w52l: + pos = (price - w52l) / (w52h - w52l) + if pos >= 0.85 or pos <= 0.15: + strong_signals += 1 + + consensus = (fd.get("analyst_consensus") or {}) + buy = consensus.get("buy", 0) or 0 + hold = consensus.get("hold", 0) or 0 + sell = consensus.get("sell", 0) or 0 + total = buy + hold + sell + if total >= 3 and (buy / total >= 0.70 or buy / total <= 0.30): + strong_signals += 1 + + has_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" + if strong_signals >= 1 and data_sources >= 2: + return "medium" + return "low" + + +def _compute_conflict(state: FiNoraState) -> tuple[bool, str]: + """Detect meaningful signal conflicts — price vs analyst, short vs long-term.""" + rt = state.get("realtime_context") or {} + fd = state.get("fundamental_data") or {} + + pct = rt.get("pct_change") + consensus = (fd.get("analyst_consensus") or {}) + buy = consensus.get("buy", 0) or 0 + hold = consensus.get("hold", 0) or 0 + sell = consensus.get("sell", 0) or 0 + total = buy + hold + sell + + price = rt.get("price") + w52h = rt.get("week_52_high") + w52l = rt.get("week_52_low") + + # Price falling but analysts strongly bullish + if pct is not None and pct <= -2.0 and total >= 3 and buy / total >= 0.65: + return True, "price_down_but_analyst_bullish" + + # Price rising sharply but analysts mostly bearish/hold + if pct is not None and pct >= 2.0 and total >= 3 and (hold + sell) / total >= 0.65: + return True, "price_up_but_analyst_cautious" + + # Near 52W low but strong buy consensus + if price and w52h and w52l and w52h > w52l and total >= 3: + pos = (price - w52l) / (w52h - w52l) + if pos <= 0.15 and buy / total >= 0.65: + return True, "near_52w_low_but_analyst_bullish" + + # Near 52W high but analyst target below current price + target = fd.get("analyst_target") or (consensus.get("avg_target") if consensus else None) + if price and target and w52h and w52l and w52h > w52l: + pos = (price - w52l) / (w52h - w52l) + if pos >= 0.85 and target < price: + return True, "near_52w_high_but_target_below_price" + + return False, "" + + +def _compute_price_trend(rt: dict | None, fd: dict | None) -> dict[str, str]: + signals: dict[str, str] = {} + if not rt: + return signals + + pct = rt.get("pct_change") + if pct is not None: + if pct >= 2.0: + signals["short_term"] = f"Upward (+{pct:.1f}% today)" + elif pct <= -2.0: + signals["short_term"] = f"Downward ({pct:.1f}% today)" + else: + signals["short_term"] = f"Flat ({pct:+.1f}% today)" + + price = rt.get("price") + w52h = rt.get("week_52_high") + w52l = rt.get("week_52_low") + if price and w52h and w52l and w52h > w52l: + pos = (price - w52l) / (w52h - w52l) + if pos >= 0.7: + signals["long_term"] = "Near 52-week high — longer-term uptrend" + elif pos <= 0.3: + signals["long_term"] = "Near 52-week low — longer-term downtrend or consolidation" + else: + signals["long_term"] = "Mid-range of 52-week band" + + beta = (fd or {}).get("beta") + if beta is not None: + if beta >= 1.3: + signals["volatility"] = f"High ({beta:.2f} beta) — amplified market moves" + elif beta <= 0.7: + signals["volatility"] = f"Low ({beta:.2f} beta) — defensive, dampened moves" + else: + signals["volatility"] = f"Moderate ({beta:.2f} beta)" + + return signals + + +def _compute_confidence(state: FiNoraState) -> float: + score = 0.0 + if state.get("realtime_context") and state["realtime_context"].get("price"): + score += 0.3 + if state.get("news_chunks"): + score += 0.3 + if state.get("historical_chunks"): + score += 0.25 + if state.get("fundamental_data"): + score += 0.15 + return min(round(score, 2), 1.0) + + +def _build_data_context(state: FiNoraState) -> str: + """Pure data context — no behavioral instructions. Used as the user message.""" + ticker = state.get("ticker", "") + company_name = state.get("company_name") or ticker + currency = state.get("currency") or "USD" + history = state.get("conversation_history", []) + + rt = state.get("realtime_context") + fd = state.get("fundamental_data") + insight_flags = _compute_insight_flags(state) + trend = _compute_price_trend(rt, fd) + narrative_hint = _compute_narrative_hint(state) + confidence_level = _compute_confidence_level(state) + has_conflict, conflict_reason = _compute_conflict(state) + uncertainty_flag = confidence_level == "low" or (has_conflict and confidence_level != "high") + + rt_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 data + rag_hist = state.get("historical_chunks", []) + if rag_hist: + hist_section = _fmt_chunks(rag_hist, "HISTORICAL PATTERN", max_chunks=_MAX_HIST_CHUNKS) + else: + # Always-available fallback: fetched in realtime_node concurrently + rt_patterns = (rt or {}).get("historical_patterns", []) + hist_section = _fmt_historical_patterns(rt_patterns) + + fund_section = _fmt_fundamentals(fd, currency) + sector_section = _fmt_sector_context(state.get("sector_context"), currency) + + flags_text = "\n".join(f"- {f}" for f in insight_flags[:4]) if insight_flags else "No significant flags." + trend_text = "\n".join( + f"- {k.replace('_', ' ').title()}: {v}" for k, v in trend.items() + ) if trend else "Trend data unavailable." + + conv_section = "" + if history: + recent = history[-4:] + conv_lines = [f"{m['role'].upper()}: {m['content'][:200]}" for m in recent] + conv_section = "[CONVERSATION HISTORY]\n" + "\n".join(conv_lines) + "\n\n" + + # Translate internal labels → natural language before sending to LLM + # This prevents label leakage ("dominant signal suggests", "uncertainty flag") + _HINT_TO_NL = { + "sharp_downward_move": "The stock is experiencing a sharp decline today.", + "sharp_upward_move": "The stock is surging sharply today.", + "high_volume_move": "Unusually high trading volume is the dominant signal today.", + "near_52w_high": "The stock is trading near its 52-week high.", + "near_52w_low": "The stock is trading near its 52-week low.", + "analyst_strongly_bullish": "Analyst consensus is strongly bullish.", + "analyst_bearish": "Analyst consensus is leaning bearish.", + "mild_upward_move": "The stock is seeing a mild upward move today.", + "mild_downward_move": "The stock is seeing a mild decline today.", + "consolidating": "No strong directional signal is present — the stock is consolidating.", + } + market_context = _HINT_TO_NL.get(narrative_hint, "Market context is unclear.") + + _CONFIDENCE_TO_POSTURE = { + "high": "Be direct. State conclusions without hedging.", + "medium": "Be measured. Use 'data shows' or 'current price action shows' — not 'suggests' or 'indicates'.", + "low": "Be cautious. Avoid directional conclusions. Acknowledge limited signal clearly.", + } + response_posture = _CONFIDENCE_TO_POSTURE.get(confidence_level, "Be cautious. Avoid strong conclusions.") + + if uncertainty_flag: + response_posture += " No strong signal — do not construct a directional narrative." + + if has_conflict: + _CONFLICT_NL = { + "price_down_but_analyst_bullish": "Price is declining but analyst consensus is bullish — name this divergence explicitly.", + "price_up_but_analyst_cautious": "Price is rising but analysts are cautious — name this divergence explicitly.", + "near_52w_low_but_analyst_bullish": "Stock is near 52-week lows but analysts rate it bullish — name this divergence explicitly.", + "near_52w_high_but_target_below_price":"Stock is near 52-week highs but analyst target is below current price — name this divergence explicitly.", + } + conflict_text = _CONFLICT_NL.get(conflict_reason, f"Signal divergence detected: {conflict_reason.replace('_', ' ')}.") + else: + conflict_text = "" + + return f"""{conv_section}STOCK: {company_name} ({ticker}) | Currency: {currency} + +[MARKET CONTEXT — anchor your opening sentence here] +{market_context} +{f"[SIGNAL DIVERGENCE — acknowledge this in your narrative]{chr(10)}{conflict_text}" if conflict_text else ""} +[RESPONSE POSTURE] +{response_posture} + +[REAL-TIME DATA] +{rt_section} + +[INSIGHT FLAGS] +{flags_text} + +[TREND SIGNALS] +{trend_text} + +[FUNDAMENTALS] +{fund_section} + +{news_section} + +{hist_section} +{chr(10) + sector_section if sector_section else ""}""" + + +def fusion_node(state: FiNoraState) -> dict: + query = state["query"] + ticker = state.get("ticker", "") + is_summary = _is_summary_query(query) + + data_context = _build_data_context(state) + + if is_summary: + task = ( + "TASK: Explain what is happening with this stock right now, " + "as if the user just opened the stock dashboard. " + "Use the structured output format from your instructions." + ) + else: + task = f"QUESTION: {query}" + + fused = f"{data_context}\n\n{task}" + + confidence = _compute_confidence(state) + disclaimer = get_disclaimer(os.getenv("DISCLAIMER_LOCALE", "IN")) + + citations: list[dict] = [] + for ch in (state.get("news_chunks") or [])[:5]: + if ch.get("url"): + citations.append({ + "url": ch["url"], + "title": ch.get("title", ""), + "source": ch.get("source", ""), + "time": ch.get("published_at", ""), + }) + + log.info( + "fusion_done", + ticker=ticker, + mode="summary" if is_summary else "focused", + user_mode=state.get("user_mode", "insight"), + confidence=confidence, + news=len(state.get("news_chunks") or []), + historical=len(state.get("historical_chunks") or []), + ) + + return { + "fused_context": fused, + "confidence_score": confidence, + "disclaimer_text": disclaimer, + "citations": citations, + } diff --git a/backend/graph/nodes/historical_rag_node.py b/backend/graph/nodes/historical_rag_node.py new file mode 100644 index 0000000000000000000000000000000000000000..25bb52a76ff7d7ad363920045cb1fc50eee1e77d --- /dev/null +++ b/backend/graph/nodes/historical_rag_node.py @@ -0,0 +1,41 @@ +"""Historical RAG node — HyDE → hybrid retrieval → rerank → dedup → append to historical_chunks.""" +from __future__ import annotations + +import structlog + +from backend.graph.state import FiNoraState +from backend.rag.pipeline import run_rag_branch +from backend.rag.retrieval.router import RetrievalBranch + +log = structlog.get_logger() + +_BRANCH = RetrievalBranch( + intent="historical", + collection="historical", + use_hyde=True, + description="20yr OHLCV event patterns, earnings history, technicals", + allow_global_fallback=True, +) + + +async def historical_rag_node(state: FiNoraState) -> dict: + if "historical" not in state.get("intents", []): + return {"historical_chunks": []} + + query = state["query"] + ticker = state.get("ticker", "") + + import asyncio + loop = asyncio.get_running_loop() + result = await loop.run_in_executor(None, run_rag_branch, query, ticker, _BRANCH) + + chunks = [ + {"text": ch.text, "score": ch.score, **ch.metadata} + for ch in result.chunks + ] + scores = result.retrieval_scores + log.info("historical_rag_done", ticker=ticker, chunks=len(chunks), scores=scores) + return { + "historical_chunks": chunks, + "retrieval_scores": {**state.get("retrieval_scores", {}), "historical": scores}, + } diff --git a/backend/graph/nodes/intent_classifier.py b/backend/graph/nodes/intent_classifier.py new file mode 100644 index 0000000000000000000000000000000000000000..9d9f2e43bf1db5bef4351a77a2d9f3dcd508706b --- /dev/null +++ b/backend/graph/nodes/intent_classifier.py @@ -0,0 +1,102 @@ +""" +Intent classification node — llama-3.1-8b-instant (~200ms). +Classifies query into one or more intents that drive graph fan-out. +""" +from __future__ import annotations + +import json +import os +import uuid + +import structlog +from groq import Groq + +from backend.graph.state import FiNoraState, Intent + +log = structlog.get_logger() + +_MODEL = os.getenv("GROQ_MODEL_FAST", "llama-3.1-8b-instant") + +_SYSTEM = """\ +You are a financial query intent classifier. Classify the user query into one or more intents. + +Intents: +- real_time: live price, today's movement, current volume, intraday +- news: recent news, announcements, catalysts, analyst notes, press releases +- historical: past patterns, earnings history, 20yr comparison, technical patterns +- fundamental: PE, EPS, revenue, margins, balance sheet, valuation +- comparative: compare two stocks or sectors, sector performance, peers, similar stocks, competitors +- screener: find stocks matching criteria + +INCLUDE news for: "why", "what's driving", "catalyst", "reason", "what happened", "latest", "moving", "dropped", "surged", "crashed", "rally", explicit news requests +DO NOT include news for: pure fundamental queries (PE, EPS, revenue, valuation, margins), pure technical queries (RSI, MACD, support, resistance, moving average), basic price or volume lookups +INCLUDE comparative for: "sector", "peers", "similar stocks", "competitors", "how does it compare", "vs", "against", "sector performance", "industry peers", "sector heatmap" + +Examples: +- "Why did Apple drop today?" → ["real_time", "news", "historical"] +- "What is the PE ratio?" → ["fundamental"] +- "What's the RSI?" → ["real_time", "historical"] +- "Latest news on NVDA" → ["news"] +- "What's AAPL trading at?" → ["real_time"] +- "Compare AAPL and MSFT earnings" → ["fundamental", "historical", "comparative"] +- "How is the tech sector doing?" → ["real_time", "comparative"] +- "Show me similar stocks to AAPL" → ["comparative"] +- "Who are Apple's peers?" → ["comparative"] +- "How does AAPL compare to its sector?" → ["real_time", "fundamental", "comparative"] + +Return ONLY the JSON array, no explanation.""" + + +_SUMMARY_TRIGGERS = { + "summarize", "summary", "explain", "overview", "what's happening", + "whats happening", "tell me about", "breakdown", "analyse", "analyze", + "give me a", "what do you think", "how is", "how's", +} + +_ALL_INTENTS: list[Intent] = ["real_time", "fundamental", "news", "historical"] + + +def _is_summary_query(query: str) -> bool: + q = query.lower().strip() + return any(trigger in q for trigger in _SUMMARY_TRIGGERS) + + +def intent_classifier_node(state: FiNoraState) -> dict: + query = state["query"] + ticker = state.get("ticker", "") + trace_id = state.get("trace_id") or str(uuid.uuid4())[:8] + + # Summary queries always fire all 4 branches — need full data for narrative + if _is_summary_query(query): + log.info("intents_classified", query=query[:60], intents=_ALL_INTENTS, + trace_id=trace_id, reason="summary_shortcut") + return {"intents": _ALL_INTENTS, "trace_id": trace_id} + + try: + client = Groq(api_key=os.getenv("GROQ_API_KEY")) + prompt = f'Ticker context: {ticker}\nQuery: "{query}"' + + resp = client.chat.completions.create( + model=_MODEL, + messages=[ + {"role": "system", "content": _SYSTEM}, + {"role": "user", "content": prompt}, + ], + max_tokens=60, + temperature=0.0, + ) + raw = resp.choices[0].message.content or "[]" + + start = raw.find("[") + end = raw.rfind("]") + 1 + intents = json.loads(raw[start:end]) if start >= 0 else ["real_time"] + + valid = {"real_time", "news", "historical", "fundamental", "comparative", "screener"} + intents = [i for i in intents if i in valid] or ["real_time"] + + except Exception as exc: + log.warning("intent_classifier_failed", error=str(exc)) + intents = ["real_time"] + + log.info("intents_classified", query=query[:60], intents=intents, trace_id=trace_id) + return {"intents": intents, "trace_id": trace_id} diff --git a/backend/graph/nodes/news_rag_node.py b/backend/graph/nodes/news_rag_node.py new file mode 100644 index 0000000000000000000000000000000000000000..a9ed6e27bb54f43492c5e8f622abc86b52ca76f1 --- /dev/null +++ b/backend/graph/nodes/news_rag_node.py @@ -0,0 +1,72 @@ +"""News RAG node — live Google RSS (dashboard-parity) + Qdrant supplementary context.""" +from __future__ import annotations + +import asyncio + +import structlog + +from backend.graph.state import FiNoraState +from backend.rag.pipeline import run_rag_branch +from backend.rag.retrieval.router import RetrievalBranch + +log = structlog.get_logger() + +_BRANCH = RetrievalBranch( + intent="news", + collection="news", + use_hyde=False, + description="News articles, analyst reports, press releases", + allow_global_fallback=False, +) + +_TOP_K = 4 # Qdrant supplementary chunks (already capped in fusion) +_LIVE_COUNT = 5 # Google RSS headlines — same source as dashboard + + +async def news_rag_node(state: FiNoraState) -> dict: + if "news" not in state.get("intents", []) and "comparative" not in state.get("intents", []): + return {"news_chunks": []} + + query = state["query"] + ticker = state.get("ticker", "") + yf_ticker = state.get("yf_ticker", ticker) + + loop = asyncio.get_running_loop() + from backend.rag.yahoo_client import fetch_news + + # Always fetch live Google RSS first — same source the dashboard displays. + # This guarantees LLM sees the same headlines the user is looking at. + live_task = loop.run_in_executor(None, fetch_news, yf_ticker or ticker, _LIVE_COUNT) + rag_task = loop.run_in_executor(None, run_rag_branch, query, ticker, _BRANCH) + + live_news, result = await asyncio.gather(live_task, rag_task) + + # Qdrant chunks — supplementary historical/older context + qdrant_chunks = [ + {"text": ch.text, "score": ch.score, **ch.metadata} + for ch in result.chunks + ] + + # Deduplicate: drop Qdrant chunks whose title appears in live headlines + live_titles = {n.get("title", "").lower()[:60] for n in live_news} + qdrant_chunks = [ + ch for ch in qdrant_chunks + if ch.get("title", ch.get("text", ""))[:60].lower() not in live_titles + ] + + # Live RSS headlines first (highest priority = same as dashboard) + # Qdrant supplementary second + chunks = list(live_news) + qdrant_chunks + + scores = result.retrieval_scores + log.info( + "news_rag_done", + ticker=ticker, + live=len(live_news), + qdrant=len(qdrant_chunks), + total=len(chunks), + ) + return { + "news_chunks": chunks, + "retrieval_scores": {**state.get("retrieval_scores", {}), "news": scores}, + } diff --git a/backend/graph/nodes/realtime_node.py b/backend/graph/nodes/realtime_node.py new file mode 100644 index 0000000000000000000000000000000000000000..a3ebc4324df7d548b0e21e3afd736e31943149bc --- /dev/null +++ b/backend/graph/nodes/realtime_node.py @@ -0,0 +1,118 @@ +"""Real-time data node — Yahoo Finance v8 via curl_cffi Chrome TLS impersonation.""" +from __future__ import annotations + +import asyncio +import time + +import structlog + +from backend.graph.state import FiNoraState +from backend.rag.yahoo_client import fetch_ohlcv, fetch_quote + +log = structlog.get_logger() + +_PATTERNS_CACHE: dict[str, tuple[list[dict], float]] = {} +_PATTERNS_TTL = 300.0 # 5 minutes + + +def _fetch_historical_patterns(ticker: str) -> list[dict]: + """ + Fetch historical context from Qdrant — same query the dashboard uses — + so chat has historical data regardless of intent routing. + Returns up to 2 pattern chunks, empty list on any failure. Cached 5 min. + """ + cached = _PATTERNS_CACHE.get(ticker) + if cached and (time.monotonic() - cached[1]) < _PATTERNS_TTL: + log.debug("historical_patterns_cache_hit", ticker=ticker) + return cached[0] + + try: + from backend.rag.retrieval.hybrid import hybrid_search + from backend.rag.ingestion.collections import collection_name + chunks = hybrid_search( + query=f"{ticker} historical price patterns earnings volatility", + ticker=ticker, + collection=collection_name("historical"), + limit=2, + allow_global_fallback=False, + ) + results = [] + for ch in chunks: + meta = ch.metadata if hasattr(ch, "metadata") else {} + results.append({ + "text": ch.text if hasattr(ch, "text") else str(ch), + "event_type": meta.get("event_type", "price_event"), + "date_range": meta.get("date_range", meta.get("start_date", "")), + "return_pct": meta.get("return_pct"), + }) + _PATTERNS_CACHE[ticker] = (results, time.monotonic()) + return results + except Exception as exc: + log.debug("historical_patterns_fetch_skipped", ticker=ticker, error=str(exc)) + return [] + + +def _fetch_realtime(ticker: str) -> dict: + quote = fetch_quote(ticker) + + # 1d intraday bars (5m interval, last 12 bars for streaming chart) + df_intraday = fetch_ohlcv(ticker, days=1, interval="5m") + intraday: list[dict] = [] + if not df_intraday.empty: + for dt, row in df_intraday.tail(12).iterrows(): + intraday.append({ + "time": str(dt), + "close": round(float(row["Close"]), 4), + "volume": int(row["Volume"]), + }) + + # 30d daily bars for monthly price chart + df_30d = fetch_ohlcv(ticker, range_str="1mo", interval="1d") + monthly: list[dict] = [] + if not df_30d.empty: + for dt, row in df_30d.iterrows(): + monthly.append({ + "date": str(dt)[:10], + "close": round(float(row["Close"]), 4), + }) + + return { + "price": quote.get("price"), + "change": quote.get("change"), + "pct_change": quote.get("pct_change"), + "volume": quote.get("volume"), + "avg_volume_30d": quote.get("avg_volume_3m"), + "market_cap": quote.get("market_cap"), + "week_52_high": None, + "week_52_low": None, + "open": quote.get("open"), + "intraday": intraday, + "monthly": monthly, + } + + +async def realtime_node(state: FiNoraState) -> dict: + ticker = state.get("ticker", "") + yf_ticker = state.get("yf_ticker", ticker) + if not ticker: + return {"realtime_context": None} + + loop = asyncio.get_running_loop() + + # Fetch realtime + historical patterns concurrently + realtime_task = loop.run_in_executor(None, _fetch_realtime, yf_ticker) + historical_task = loop.run_in_executor(None, _fetch_historical_patterns, ticker) + + data, historical_patterns = await asyncio.gather(realtime_task, historical_task) + + data["ticker"] = ticker + # Always inject historical patterns — chat has parity with dashboard regardless of intent + data["historical_patterns"] = historical_patterns + + log.info( + "realtime_node_done", + ticker=ticker, + price=data.get("price"), + historical_patterns=len(historical_patterns), + ) + return {"realtime_context": data} diff --git a/backend/graph/nodes/response_cache.py b/backend/graph/nodes/response_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..86ed3d7de9a6b8e3daa3560a3420da3c05947665 --- /dev/null +++ b/backend/graph/nodes/response_cache.py @@ -0,0 +1,45 @@ +"""Shared response cache — imported by response_node and chat route for early bypass.""" +from __future__ import annotations + +import hashlib +import os +import time + +_RESPONSE_CACHE: dict[str, tuple[str, float | None, float]] = {} +_CACHE_TTL = float(os.getenv("RESPONSE_CACHE_TTL", "300")) +_CACHE_PRICE_THRESHOLD = float(os.getenv("RESPONSE_CACHE_PRICE_THRESHOLD", "2.0")) + +_VOLATILE_TERMS = frozenset({ + "right now", "just now", "breaking", "latest news", "happening now", + "this second", "live", "real time", "realtime", "right this moment", +}) + + +def cache_key(ticker: str, query: str, user_mode: str) -> str: + fingerprint = hashlib.sha256(query.lower().strip().encode()).hexdigest()[:12] + return f"{ticker}:{fingerprint}:{user_mode}" + + +def is_volatile_query(query: str) -> bool: + q = query.lower() + return any(term in q for term in _VOLATILE_TERMS) + + +def get_cached(key: str, current_pct: float | None = None) -> str | None: + """Return cached response if valid. current_pct=None skips price-based invalidation.""" + entry = _RESPONSE_CACHE.get(key) + if not entry: + return None + text, cached_pct, ts = entry + if (time.monotonic() - ts) > _CACHE_TTL: + del _RESPONSE_CACHE[key] + return None + if current_pct is not None and cached_pct is not None: + if abs(current_pct - cached_pct) >= _CACHE_PRICE_THRESHOLD: + del _RESPONSE_CACHE[key] + return None + return text + + +def set_cached(key: str, text: str, pct: float | None) -> None: + _RESPONSE_CACHE[key] = (text, pct, time.monotonic()) diff --git a/backend/graph/nodes/response_node.py b/backend/graph/nodes/response_node.py new file mode 100644 index 0000000000000000000000000000000000000000..8e2a43360b86184f47e8a39bb8412f1d8344346d --- /dev/null +++ b/backend/graph/nodes/response_node.py @@ -0,0 +1,193 @@ +"""Response node — Groq llama-3.3-70b with mode-aware output, response cache, and 8B fallback.""" +from __future__ import annotations + +import os + +import structlog +from groq import Groq + +from backend.graph.nodes.response_cache import cache_key, get_cached, is_volatile_query, set_cached +from backend.graph.state import FiNoraState +from backend.guardrails.output_filter import apply_output_guardrail + +log = structlog.get_logger() + +_GROQ_MODEL_PRIMARY = os.getenv("GROQ_MODEL_PRIMARY", "openai/gpt-oss-120b") +_GROQ_MODEL_FALLBACK = os.getenv("GROQ_MODEL_FAST", "llama-3.1-8b-instant") +_MAX_TOKENS = int(os.getenv("GROQ_MAX_TOKENS", "1200")) +_TEMPERATURE = float(os.getenv("GROQ_TEMPERATURE", "0.15")) + +_SYSTEM_INSIGHT = """You are Finora AI — a financial intelligence system. Behave like an analyst reading a dashboard, not a chatbot. + +STRICT RULES: +- Never hallucinate numbers. Ground every statement in provided data. +- Interpret metrics, don't restate them. High PE = premium valuation — say why it matters. +- Correct currency: INR for Indian stocks, USD for US stocks. Use company name, not ticker. +- No emojis. + +OPENING — NON-NEGOTIABLE: +- First sentence states what the stock is doing, grounded in [MARKET CONTEXT]. +- Never start with: "Based on", "According to", "The data shows". +- Good: "Apple is down 0.9% today with no strong momentum — markets appear to be waiting ahead of earnings." + +RESPONSE POSTURE: Follow [RESPONSE POSTURE] exactly — it controls certainty level. + +SIGNAL DIVERGENCE: If [SIGNAL DIVERGENCE] present, name it in one sentence. +- Good: "Price is down 2% but 78% of analysts rate Buy — the market may be discounting near-term noise." + +INTENSITY AWARENESS: +- Query uses strong language but data shows mild move → use contrast phrases: "no signs of heavy selling", "price action remains orderly", "no panic-driven volume" +- Data confirms sharp move → match intensity, be direct. +- Never reference the user's wording. Let data speak. + +BANNED WORDS: suggesting, indicating, implying, appears to, seems to, would suggest, dominant signal, uncertainty flag, MARKET CONTEXT, RESPONSE POSTURE, SIGNAL DIVERGENCE, "not X% as stated", "discrepancy", "does not match", "despite the", "as you mentioned", mixed signals, it depends + +HISTORICAL PATTERNS: If [HISTORICAL PATTERNS] present → reference at least one. Integrate naturally: "This mirrors [date] when the stock [outcome]." + +STYLE: 1-2 tight sentences per section. Each section adds new info. Expand where data is strong; omit where weak. +- [UNAVAILABLE] / [NO DATA] / [LIMITED] → skip that section entirely, no explanation. +- Low signal fallback: "No strong directional signal is present — the stock is consolidating." + +OUTPUT — summary queries: +## What's Happening +## Fundamentals +## Technical Trend +## Analyst Sentiment +## Recent Drivers +## Key Risks + +OUTPUT — focused queries: Answer directly. No headers. Max 100 words. + +For buy/sell queries: price action + analyst sentiment + top risk, then end with EXACTLY: +Consider consulting a financial advisor before making investment decisions.""" + +_SYSTEM_TRADER = """You are Finora AI — financial intelligence for active traders. Behave like a quant analyst at a trading desk — data-first, directional, precise. + +STRICT RULES: +- Never hallucinate numbers. Ground every statement in provided data. +- Be specific and directional. Correct currency: INR Indian, USD US. Company name, not ticker. +- No emojis. + +OPENING — NON-NEGOTIABLE: +- First sentence: stock action + explicit directional bias (bullish / bearish / neutral). +- Never start with: "Based on", "According to", "The data shows". +- Good: "Momentum is neutral — Apple is down 0.9% on below-average volume, consolidating ahead of earnings." + +RESPONSE POSTURE: Follow [RESPONSE POSTURE] exactly — controls certainty and directional strength. + +SIGNAL DIVERGENCE: If [SIGNAL DIVERGENCE] present, name it — most actionable signal for a trader. +- Good: "Price is down 2.4% but 78% of analysts rate Buy — this divergence may signal opportunity or analyst lag." + +INTENSITY AWARENESS: +- Query uses strong language but data shows mild move → contrast phrases: "no signs of heavy selling", "price action remains orderly", "no panic-driven volume" +- Data confirms sharp move → match intensity, be urgent. +- Never reference the user's wording. + +BANNED WORDS: suggesting, indicating, implying, appears to, seems to, would suggest, dominant signal, uncertainty flag, MARKET CONTEXT, RESPONSE POSTURE, SIGNAL DIVERGENCE, "not X% as stated", "discrepancy", "does not match", "despite the", "as you mentioned" + +HISTORICAL PATTERNS: If [HISTORICAL PATTERNS] present → reference at least one. "This setup mirrors [event] in [date] when the stock [return outcome]." + +STYLE: 1-2 tight sentences per section. Each section adds new info. Expand where data is strong. +- [UNAVAILABLE] / [NO DATA] / [LIMITED] → skip that section entirely. +- Low signal fallback: "No strong directional signal. Momentum is neutral — exercise caution." + +OUTPUT — summary queries: +## What's Happening +## Fundamentals +## Technical Trend +## Analyst Sentiment +## Recent Drivers +## Key Risks +## Signals That Matter (always include for trader mode) + +OUTPUT — focused queries: Answer directly. No headers. Max 150 words. Always state directional bias. + +For buy/sell queries: current signals + key risk, end with: +This is market intelligence, not financial advice — trading decisions rest with you. +NEVER give absolute directives ("you should buy", "go long now").""" + + +def _cache_key(ticker: str, query: str, user_mode: str) -> str: + fingerprint = hashlib.sha256(query.lower().strip().encode()).hexdigest()[:12] + return f"{ticker}:{fingerprint}:{user_mode}" + + +def _call_groq(client: Groq, model: str, system_prompt: str, fused_context: str) -> str: + resp = client.chat.completions.create( + model=model, + messages=[ + {"role": "system", "content": system_prompt}, + {"role": "user", "content": fused_context}, + ], + max_tokens=_MAX_TOKENS, + temperature=_TEMPERATURE, + ) + return resp.choices[0].message.content or "" + + +def response_node(state: FiNoraState) -> dict: + fused_context = state.get("fused_context", "") + confidence = state.get("confidence_score", 0.0) + disclaimer = state.get("disclaimer_text", "") + locale = os.getenv("DISCLAIMER_LOCALE", "IN") + user_mode = state.get("user_mode", "insight") + ticker = state.get("ticker", "") + query = state.get("query", "") + current_pct = (state.get("realtime_context") or {}).get("pct_change") + + if not fused_context: + return {"response": "I don't have enough data to answer that query."} + + system_prompt = _SYSTEM_TRADER if user_mode == "trader" else _SYSTEM_INSIGHT + + # Cache lookup — skip for volatile/live queries + cache_hit = False + text = "" + if ticker and query and not is_volatile_query(query): + key = cache_key(ticker, query, user_mode) + cached = get_cached(key, current_pct) + if cached: + log.info("response_cache_hit", ticker=ticker, user_mode=user_mode) + text = cached + cache_hit = True + + if not cache_hit: + client = Groq(api_key=os.getenv("GROQ_API_KEY")) + model_used = _GROQ_MODEL_PRIMARY + try: + text = _call_groq(client, _GROQ_MODEL_PRIMARY, system_prompt, fused_context) + except Exception as exc: + err_str = str(exc) + # 429 rate limit → fall back to 8B (separate TPD bucket on Groq free tier) + if "429" in err_str or "rate_limit" in err_str.lower(): + log.warning("groq_primary_rate_limited_falling_back_to_8b", error=err_str[:120]) + try: + text = _call_groq(client, _GROQ_MODEL_FALLBACK, system_prompt, fused_context) + model_used = _GROQ_MODEL_FALLBACK + except Exception as fallback_exc: + log.error("groq_fallback_also_failed", error=str(fallback_exc)) + text = "I encountered an error generating the analysis. Please try again." + else: + log.error("groq_generation_failed", error=err_str) + text = "I encountered an error generating the analysis. Please try again." + + # Cache successful primary-model responses only + if text and model_used == _GROQ_MODEL_PRIMARY and ticker and query and not is_volatile_query(query): + set_cached(cache_key(ticker, query, user_mode), text, current_pct) + + text = apply_output_guardrail( + response=text, + fused_context=fused_context, + confidence_score=confidence, + disclaimer_text=disclaimer, + locale=locale, + ) + + log.info( + "response_ok", + chars=len(text), + confidence=confidence, + cache_hit=cache_hit, + user_mode=user_mode, + ) + return {"response": text} diff --git a/backend/graph/state.py b/backend/graph/state.py new file mode 100644 index 0000000000000000000000000000000000000000..95af90e16897b9574aa752ddba4a22f0b162b358 --- /dev/null +++ b/backend/graph/state.py @@ -0,0 +1,43 @@ +from __future__ import annotations + +import operator +from typing import Annotated, Literal, TypedDict + + +Intent = Literal["real_time", "news", "historical", "fundamental", "comparative", "screener"] +UserMode = Literal["insight", "trader"] + + +class FiNoraState(TypedDict): + # Input + query: str + ticker: str # display ticker (e.g. "TCS", "RELIANCE") + yf_ticker: str # Yahoo Finance ticker (e.g. "TCS.NS", "RELIANCE.NS") + company_name: str # full company name (e.g. "Infosys Limited") + currency: str # ISO currency code (e.g. "INR", "USD") + user_mode: UserMode # "insight" (default) or "trader" + session_id: str + conversation_history: list[dict] + + # Routing + intents: list[Intent] + guardrail_flags: list[str] + guardrail_blocked: bool + + # Retrieval outputs (parallel branches append — operator.add merges lists) + realtime_context: dict | None + news_chunks: Annotated[list[dict], operator.add] + historical_chunks: Annotated[list[dict], operator.add] + fundamental_data: dict | None + sector_context: dict | None # sector ETF performance + similar stocks + + # Generation + fused_context: str + response: str + citations: list[dict] + confidence_score: float + disclaimer_text: str + + # Observability + trace_id: str + retrieval_scores: dict diff --git a/backend/guardrails/__init__.py b/backend/guardrails/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/backend/guardrails/classifier.py b/backend/guardrails/classifier.py new file mode 100644 index 0000000000000000000000000000000000000000..37bb4dc2e93cfd5777dce6d6ede909f1cc269c7a --- /dev/null +++ b/backend/guardrails/classifier.py @@ -0,0 +1,108 @@ +""" +Input guardrail — llama-3.1-8b-instant classifies query safety (~150ms). +First node in the LangGraph — blocks unsafe queries before any retrieval. +""" +from __future__ import annotations + +import json +import os + +import structlog +from groq import Groq + +from backend.graph.state import FiNoraState +from backend.guardrails.disclaimers import get_disclaimer + +log = structlog.get_logger() + +_MODEL = os.getenv("GROQ_MODEL_FAST", "llama-3.1-8b-instant") + +# Always blocked — regardless of user_mode +_ALWAYS_BLOCKED = { + "insider_trading_context", + "market_manipulation", + "tax_evasion_advice", + "specific_options_strategy", +} + +# Blocked in INSIGHT mode only — TRADER mode receives signal-based response instead +_INSIGHT_ONLY_BLOCKED = { + "direct_buy_sell_recommendation", + "personal_financial_planning", +} + +# Combined set for insight mode +_BLOCKED_INTENTS = _ALWAYS_BLOCKED | _INSIGHT_ONLY_BLOCKED + +_SYSTEM = """\ +You are a financial query safety classifier. +Classify the query intent as one of: +- allowed: fundamental_analysis, technical_analysis, news_analysis, historical_pattern, + sector_comparison, earnings_analysis, market_overview, screener, educational +- blocked: direct_buy_sell_recommendation, specific_options_strategy, insider_trading_context, + market_manipulation, personal_financial_planning, tax_evasion_advice + +Return JSON: {"intent": "", "blocked": true/false} +Return ONLY the JSON.""" + +_REDIRECT_MSG = ( + "I can't make specific investment recommendations, but I can pull what analysts " + "currently say about {ticker} and the key metrics to consider. " + "Want me to surface the consensus view and recent developments?" +) + + +def guardrail_check_node(state: FiNoraState) -> dict: + if os.getenv("GUARDRAILS_ENABLED", "true").lower() != "true": + return {"guardrail_blocked": False, "guardrail_flags": []} + + query = state["query"] + ticker = state.get("ticker", "the stock") + + user_mode = state.get("user_mode", "insight") + # In trader mode, buy/sell and personal planning queries are allowed through + # (response_node handles them with signal-based framing + risk disclosure) + blocked_set = _ALWAYS_BLOCKED if user_mode == "trader" else _BLOCKED_INTENTS + + try: + client = Groq(api_key=os.getenv("GROQ_API_KEY")) + resp = client.chat.completions.create( + model=_MODEL, + messages=[ + {"role": "system", "content": _SYSTEM}, + {"role": "user", "content": f"Query: {query}"}, + ], + max_tokens=60, + temperature=0.0, + ) + raw = resp.choices[0].message.content or "{}" + start, end = raw.find("{"), raw.rfind("}") + 1 + result = json.loads(raw[start:end]) if start >= 0 else {} + intent = result.get("intent", "allowed") + blocked = intent in blocked_set + except Exception as exc: + log.warning("guardrail_classifier_failed", error=str(exc)) + blocked = False + intent = "allowed" + + flags = [intent] if blocked else [] + log.info("guardrail_check", query=query[:60], blocked=blocked, intent=intent, user_mode=user_mode) + + if blocked: + redirect = _REDIRECT_MSG.format(ticker=ticker) + disclaimer = get_disclaimer(os.getenv("DISCLAIMER_LOCALE", "IN")) + return { + "guardrail_blocked": True, + "guardrail_flags": flags, + "response": redirect, + "disclaimer_text": disclaimer, + "fused_context": "", + "confidence_score": 0.0, + "citations": [], + } + + return {"guardrail_blocked": False, "guardrail_flags": flags} + + +def route_after_guardrail(state: FiNoraState) -> str: + return "blocked" if state.get("guardrail_blocked") else "allowed" diff --git a/backend/guardrails/disclaimers.py b/backend/guardrails/disclaimers.py new file mode 100644 index 0000000000000000000000000000000000000000..2201c694de53d36ebf32bbbee91cd411214c2716 --- /dev/null +++ b/backend/guardrails/disclaimers.py @@ -0,0 +1,20 @@ +from __future__ import annotations + +_DISCLAIMERS = { + "IN": ( + "⚠ For informational purposes only. Not financial advice. " + "Consult a SEBI-registered investment advisor before making decisions." + ), + "US": ( + "⚠ For informational purposes only. Not financial advice per SEC rules. " + "Consult a registered investment advisor." + ), + "GLOBAL": ( + "⚠ Informational only. Not investment advice. " + "Past performance does not guarantee future results." + ), +} + + +def get_disclaimer(locale: str = "IN") -> str: + return _DISCLAIMERS.get(locale.upper(), _DISCLAIMERS["GLOBAL"]) diff --git a/backend/guardrails/output_filter.py b/backend/guardrails/output_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..cd8232d668c7204e75493cd2adb3d3dda10e8608 --- /dev/null +++ b/backend/guardrails/output_filter.py @@ -0,0 +1,86 @@ +""" +Output guardrail pipeline — runs post-generation, pre-client. + +Steps: +1. Hallucination check: numbers/% in response verified against fused_context +2. PII scrub: regex over response for account numbers, personal identifiers +3. Confidence signal: if score < 0.6, inject moderate-confidence warning +4. Directional language: detected → inject disclaimer +""" +from __future__ import annotations + +import re + +import structlog + +from backend.guardrails.disclaimers import get_disclaimer + +log = structlog.get_logger() + +# Matches percentages and dollar/rupee amounts with optional sign +_NUMBER_RE = re.compile(r"[+-]?\d+(?:\.\d+)?%|[₹$]\s*\d[\d,.]+") + +# PII patterns: account numbers (10–18 digits), Aadhaar (XXXX XXXX XXXX), PAN +_PII_PATTERNS = [ + (re.compile(r"\b\d{10,18}\b"), "[ACCOUNT_REDACTED]"), + (re.compile(r"\b[A-Z]{5}\d{4}[A-Z]\b"), "[PAN_REDACTED]"), + (re.compile(r"\b\d{4}\s\d{4}\s\d{4}\b"), "[AADHAAR_REDACTED]"), +] + +_DIRECTIONAL_PHRASES = { + "will rise", "will fall", "will go up", "will go down", + "you should buy", "you should sell", "guaranteed", "certain to", + "definitely go up", "definitely go down", "sure to", +} + + +def _extract_numbers(text: str) -> list[str]: + return _NUMBER_RE.findall(text) + + +def _hallucination_check(response: str, fused_context: str) -> str: + """Log unverified numbers for observability. No user-facing annotation.""" + if not fused_context: + return response + context_numbers = set(_extract_numbers(fused_context)) + flagged = [n for n in _extract_numbers(response) if n not in context_numbers] + if flagged: + log.warning("hallucination_flag", unverified=flagged[:5]) + return response # no inline annotation — clean UX + + +def _scrub_pii(text: str) -> str: + for pattern, replacement in _PII_PATTERNS: + text = pattern.sub(replacement, text) + return text + + +def _has_directional_language(text: str) -> bool: + lower = text.lower() + return any(phrase in lower for phrase in _DIRECTIONAL_PHRASES) + + +def apply_output_guardrail( + response: str, + fused_context: str, + confidence_score: float, + disclaimer_text: str, + locale: str = "IN", +) -> str: + """Apply all output guardrails. Returns the final safe response string.""" + # Step 1: hallucination check + response = _hallucination_check(response, fused_context) + + # Step 2: PII scrub + response = _scrub_pii(response) + + # Step 3: confidence is tracked in SSE event — no inline annotation needed + + # Step 4: disclaimer ONLY when response contains directional language + # (otherwise it fires via the separate SSE "disclaimer" event once per session) + if _has_directional_language(response): + disclaimer = disclaimer_text or get_disclaimer(locale) + if disclaimer not in response: + response += f"\n\n{disclaimer}" + + return response diff --git a/backend/main.py b/backend/main.py new file mode 100644 index 0000000000000000000000000000000000000000..a62f17f004aff4f09534ed54bc3d1c1397c6e77d --- /dev/null +++ b/backend/main.py @@ -0,0 +1,93 @@ +import os +from contextlib import asynccontextmanager +from pathlib import Path + +import structlog +import uvicorn +from fastapi import FastAPI +from fastapi.middleware.cors import CORSMiddleware +from slowapi import _rate_limit_exceeded_handler +from slowapi.errors import RateLimitExceeded +from slowapi.middleware import SlowAPIMiddleware + +from dotenv import load_dotenv + +ROOT = Path(__file__).resolve().parents[1] +if os.getenv("ENV", "development") != "production": + load_dotenv(ROOT / ".env") + +EVAL_DIR = ROOT / "backend" / "data" / "eval_results" +EVAL_DIR.mkdir(parents=True, exist_ok=True) + +from backend.api.middleware.guardrails import FinancialGuardrailMiddleware +from backend.api.middleware.rate_limit import limiter +from backend.api.routes import chat, health, stocks +from backend.rag.ingestion.universe import universe + +log = structlog.get_logger() + +def _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)) + + +@asynccontextmanager +async def lifespan(app: FastAPI): + log.info("startup", universe_size=len(universe.stocks)) + + import asyncio + loop = asyncio.get_event_loop() + await loop.run_in_executor(None, _warm_yahoo_session) + + scheduler = None + if os.getenv("ENV", "development") == "production" or os.getenv("SCHEDULER_ENABLED", "false") == "true": + from backend.rag.ingestion.scheduler import start_scheduler + scheduler = start_scheduler() + + yield + + if scheduler: + from backend.rag.ingestion.scheduler import stop_scheduler + stop_scheduler() + + log.info("shutdown") + + +app = FastAPI(title="Finora API", version="1.0.0", lifespan=lifespan) + + +# ========================= Verify Backend Log (REMOVE LATER) ========================= +@app.get("/") +def root(): + return {"message": "Finora API is running"} + +cors_origins = os.getenv("CORS_ORIGINS", "http://localhost:3000").split(",") +app.add_middleware( + CORSMiddleware, + allow_origins=[o.strip() for o in cors_origins], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +app.state.limiter = limiter +app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler) +app.add_middleware(SlowAPIMiddleware) +app.add_middleware(FinancialGuardrailMiddleware) + +app.include_router(health.router, prefix="/api") +app.include_router(stocks.router, prefix="/api/stocks") +app.include_router(chat.router, prefix="/api") + + +if __name__ == "__main__": + port = int(os.getenv("PORT", "7860")) + uvicorn.run("backend.main:app", host="0.0.0.0", port=port) + diff --git a/backend/observability/__init__.py b/backend/observability/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/backend/observability/langsmith_client.py b/backend/observability/langsmith_client.py new file mode 100644 index 0000000000000000000000000000000000000000..9ca282550cb06dfa0d9b1a2ea7c3a54b95737f3c --- /dev/null +++ b/backend/observability/langsmith_client.py @@ -0,0 +1,66 @@ +""" +LangSmith tracing wrapper for all LangGraph runs. + +LangSmith auto-instruments via environment variables when: + LANGCHAIN_TRACING_V2=true + LANGCHAIN_API_KEY=ls__... + LANGCHAIN_PROJECT=finora-prod + +This module provides explicit trace helpers for non-graph code paths +(MCP tools, batch ingestion, eval) that don't run through LangGraph. +""" +from __future__ import annotations + +import os +from contextlib import contextmanager +from typing import Any, Generator + +import structlog + +log = structlog.get_logger() + +_TRACING_ENABLED = ( + os.getenv("LANGCHAIN_TRACING_V2", "false").lower() == "true" + and bool(os.getenv("LANGCHAIN_API_KEY")) +) + + +@contextmanager +def trace_run( + name: str, + run_type: str = "chain", + metadata: dict[str, Any] | None = None, +) -> Generator[Any, None, None]: + """Context manager that wraps a code block in a LangSmith trace span.""" + if not _TRACING_ENABLED: + yield None + return + + try: + from langsmith import trace as ls_trace + + with ls_trace(name=name, run_type=run_type, metadata=metadata or {}) as run: + yield run + except ImportError: + yield None + except Exception as exc: + log.warning("langsmith_trace_failed", name=name, error=str(exc)) + yield None + + +def log_retrieval_scores(run_id: str, scores: dict[str, float]) -> None: + """Attach retrieval scores as feedback to a LangSmith run.""" + if not _TRACING_ENABLED or not scores: + return + try: + from langsmith import Client as LSClient + + client = LSClient() + for key, value in scores.items(): + client.create_feedback( + run_id=run_id, + key=key, + score=value, + ) + except Exception as exc: + log.warning("langsmith_feedback_failed", error=str(exc)) diff --git a/backend/observability/langsmith_url.py b/backend/observability/langsmith_url.py new file mode 100644 index 0000000000000000000000000000000000000000..9f441ea5b72782ad4adb1ba9b79eaf0501d8f75a --- /dev/null +++ b/backend/observability/langsmith_url.py @@ -0,0 +1,64 @@ +"""Resolve the correct LangSmith project URL at startup and cache it.""" +from __future__ import annotations + +import os + +import structlog + +log = structlog.get_logger() + +_cached_url: str | None = None +_resolved = False + + +def get_project_url() -> str | None: + """ + Return the full LangSmith project URL. + Resolution order: + 1. Env vars LANGSMITH_ORG_ID + LANGSMITH_PROJECT_ID (fastest, no API call) + 2. LangSmith Client API (reads project by name, uses client._tenant_id) + 3. None if LANGCHAIN_API_KEY not set + Result is cached — API call happens at most once per process lifetime. + """ + global _cached_url, _resolved + if _resolved: + return _cached_url + + _resolved = True + api_key = os.getenv("LANGCHAIN_API_KEY") + if not api_key: + return None + + project_name = os.getenv("LANGCHAIN_PROJECT", "finora-prod") + + # Fast path — both IDs set explicitly in env + org_id = os.getenv("LANGSMITH_ORG_ID") + project_id = os.getenv("LANGSMITH_PROJECT_ID") + if org_id and project_id: + _cached_url = f"https://smith.langchain.com/o/{org_id}/projects/p/{project_id}" + log.info("langsmith_traced", url=_cached_url) + return _cached_url + + # Slow path — fetch from LangSmith API (once per process) + try: + from langsmith import Client + client = Client(api_key=api_key) + + project = client.read_project(project_name=project_name) + project_id = str(project.id) + + # _tenant_id is private but stable across SDK versions + resolved_org_id = org_id or str(getattr(client, "_tenant_id", None) or "") + + if resolved_org_id and project_id: + _cached_url = f"https://smith.langchain.com/o/{resolved_org_id}/projects/p/{project_id}" + elif project_id: + # Fallback: no org id available — link to project by name (less precise) + _cached_url = f"https://smith.langchain.com/projects/{project_name}" + + log.info("langsmith_url_resolved_from_api", url=_cached_url, project_id=project_id) + except Exception as exc: + log.warning("langsmith_url_resolution_failed", error=str(exc)) + _cached_url = None + + return _cached_url diff --git a/backend/observability/metrics.py b/backend/observability/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..0c5df2a3ff3e78a524ad9646911ccdf55f6d270f --- /dev/null +++ b/backend/observability/metrics.py @@ -0,0 +1,23 @@ +"""Prometheus metrics — optional, enabled via METRICS_ENABLED=true.""" +from __future__ import annotations + +import os + +_ENABLED = os.getenv("METRICS_ENABLED", "false").lower() == "true" + +if _ENABLED: + try: + from prometheus_client import Counter, Histogram, start_http_server + + chat_requests_total = Counter("finora_chat_requests_total", "Total chat requests") + chat_latency_seconds = Histogram("finora_chat_latency_seconds", "Chat end-to-end latency") + retrieval_chunks = Histogram( + "finora_retrieval_chunks", "Chunks retrieved per branch", + labelnames=["branch"], + ) + guardrail_blocks_total = Counter("finora_guardrail_blocks_total", "Guardrail blocked requests") + + def start_metrics_server(port: int = 9090) -> None: + start_http_server(port) + except ImportError: + pass diff --git a/backend/rag/__init__.py b/backend/rag/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/backend/rag/chunking/__init__.py b/backend/rag/chunking/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/backend/rag/chunking/financial.py b/backend/rag/chunking/financial.py new file mode 100644 index 0000000000000000000000000000000000000000..d6576750b5ab4a8b08674c87c3984c60b345123a --- /dev/null +++ b/backend/rag/chunking/financial.py @@ -0,0 +1,125 @@ +from __future__ import annotations + +from dataclasses import dataclass, field +from datetime import date +from typing import Any, Literal + +import numpy as np +import pandas as pd + +EventType = Literal["earnings_week", "macro_shock", "sector_rotation", "fed_meeting", "unusual_volume"] + + +@dataclass +class FinancialChunk: + text: str # embeddable summary_text + metadata: dict[str, Any] = field(default_factory=dict) + + +class FinancialEventChunker: + """ + Detects significant events in OHLCV data and creates 5-trading-day windows around each. + Each chunk is embedded via its LLM-generated summary_text. + """ + + VOLUME_Z_THRESHOLD = 2.0 + RETURN_THRESHOLD = 0.03 # 3% single-day move + WINDOW_DAYS = 5 # days before+after event + + def chunk(self, df: pd.DataFrame, ticker: str) -> list[FinancialChunk]: + """ + df: DataFrame with DatetimeIndex, columns [Open, High, Low, Close, Volume]. + Returns FinancialChunk list, one per detected event window. + """ + if df.empty or len(df) < 20: + return [] + + df = df.copy() + df["return_pct"] = df["Close"].pct_change() + vol_mean = df["Volume"].rolling(30, min_periods=10).mean() + vol_std = df["Volume"].rolling(30, min_periods=10).std().replace(0, 1) + df["volume_z"] = (df["Volume"] - vol_mean) / vol_std + + event_indices = self._detect_events(df) + chunks: list[FinancialChunk] = [] + seen_windows: set[int] = set() + + for idx in event_indices: + # 5-day window: 2 before, event, 2 after + start = max(0, idx - 2) + end = min(len(df), idx + 3) + + # Skip if this window overlaps a seen one + if any(i in seen_windows for i in range(start, end)): + continue + seen_windows.update(range(start, end)) + + window = df.iloc[start:end] + event_type = self._classify_event(df.iloc[idx]) + chunk = self._build_chunk(window, ticker, event_type, df.iloc[idx]) + chunks.append(chunk) + + return chunks + + def _detect_events(self, df: pd.DataFrame) -> list[int]: + events: list[int] = [] + for i in range(len(df)): + row = df.iloc[i] + ret = abs(row.get("return_pct", 0) or 0) + vol_z = row.get("volume_z", 0) or 0 + if (ret >= self.RETURN_THRESHOLD) or (vol_z >= self.VOLUME_Z_THRESHOLD): + events.append(i) + return events + + def _classify_event(self, row: pd.Series) -> EventType: + vol_z = row.get("volume_z", 0) or 0 + ret = row.get("return_pct", 0) or 0 + if vol_z >= 3.0 and abs(ret) >= 0.05: + return "earnings_week" + if abs(ret) >= 0.05: + return "macro_shock" + if vol_z >= self.VOLUME_Z_THRESHOLD: + return "unusual_volume" + return "sector_rotation" + + def _build_chunk( + self, + window: pd.DataFrame, + ticker: str, + event_type: EventType, + event_row: pd.Series, + ) -> FinancialChunk: + start_date = str(window.index[0].date()) if hasattr(window.index[0], "date") else str(window.index[0]) + end_date = str(window.index[-1].date()) if hasattr(window.index[-1], "date") else str(window.index[-1]) + + ret_pct = float(event_row.get("return_pct", 0) or 0) * 100 + vol_z = float(event_row.get("volume_z", 0) or 0) + close_start = float(window["Close"].iloc[0]) + close_end = float(window["Close"].iloc[-1]) + window_return = (close_end - close_start) / close_start * 100 if close_start else 0 + + summary = ( + f"{ticker} experienced a {event_type.replace('_', ' ')} event from {start_date} to {end_date}. " + f"On the event day, the stock moved {ret_pct:+.2f}% with volume {vol_z:+.1f}x the 30-day average. " + f"Over the 5-day window, {ticker} returned {window_return:+.2f}% " + f"(from ${close_start:.2f} to ${close_end:.2f})." + ) + + return FinancialChunk( + text=summary, + metadata={ + "ticker": ticker, + "event_type": event_type, + "date_range": f"{start_date}:{end_date}", + "start_date": start_date, + "end_date": end_date, + "return_pct": round(ret_pct, 4), + "volume_z_score": round(vol_z, 4), + "window_return_pct": round(window_return, 4), + "open": round(float(window["Open"].iloc[0]), 4), + "high": round(float(window["High"].max()), 4), + "low": round(float(window["Low"].min()), 4), + "close": round(float(window["Close"].iloc[-1]), 4), + "volume": int(window["Volume"].sum()), + }, + ) diff --git a/backend/rag/chunking/strategies.py b/backend/rag/chunking/strategies.py new file mode 100644 index 0000000000000000000000000000000000000000..b9aaba7385f1d7229423f87f5aa69064a015c452 --- /dev/null +++ b/backend/rag/chunking/strategies.py @@ -0,0 +1,124 @@ +from __future__ import annotations + +import re +from dataclasses import dataclass, field +from typing import Any + + +@dataclass +class Chunk: + text: str + metadata: dict[str, Any] = field(default_factory=dict) + + +class SlidingWindowChunker: + """ + Overlapping token-window chunker for news articles and analyst reports. + window=512 tokens, stride=128 tokens. + """ + + def __init__(self, window: int = 512, stride: int = 128) -> None: + self.window = window + self.stride = stride + + def _tokenize(self, text: str) -> list[str]: + return text.split() + + def chunk(self, text: str, metadata: dict[str, Any] | None = None) -> list[Chunk]: + meta = metadata or {} + tokens = self._tokenize(text) + chunks: list[Chunk] = [] + + start = 0 + while start < len(tokens): + end = min(start + self.window, len(tokens)) + chunk_text = " ".join(tokens[start:end]) + if len(chunk_text.strip()) > 50: + chunks.append(Chunk( + text=chunk_text, + metadata={**meta, "chunk_start_token": start, "chunk_end_token": end}, + )) + if end == len(tokens): + break + start += self.stride + + return chunks + + +class SemanticChunker: + """ + Boundary-detection chunker for SEC filings and earnings transcripts. + Splits on cosine similarity drops between adjacent sentence embeddings. + chunk size: 300-800 tokens (variable, topic-coherent). + """ + + def __init__(self, threshold: float = 0.75, min_tokens: int = 300, max_tokens: int = 800) -> None: + self.threshold = threshold + self.min_tokens = min_tokens + self.max_tokens = max_tokens + + def _split_sentences(self, text: str) -> list[str]: + sentences = re.split(r'(?<=[.!?])\s+', text.strip()) + return [s.strip() for s in sentences if len(s.strip()) > 20] + + def chunk(self, text: str, metadata: dict[str, Any] | None = None) -> list[Chunk]: + from backend.rag.embedder import get_embedder + import numpy as np + + meta = metadata or {} + sentences = self._split_sentences(text) + if not sentences: + return [] + + if len(sentences) <= 3: + return [Chunk(text=text, metadata=meta)] + + embedder = get_embedder() + embeddings = embedder.encode(sentences, normalize_embeddings=True, batch_size=32) + + # Detect boundary: cosine similarity drop between adjacent sentences + boundaries = [0] + current_tokens = len(sentences[0].split()) + + for i in range(1, len(sentences)): + sim = float(np.dot(embeddings[i - 1], embeddings[i])) + current_tokens += len(sentences[i].split()) + + is_boundary = ( + (sim < self.threshold and current_tokens >= self.min_tokens) + or current_tokens >= self.max_tokens + ) + if is_boundary: + boundaries.append(i) + current_tokens = 0 + + boundaries.append(len(sentences)) + + chunks: list[Chunk] = [] + for j in range(len(boundaries) - 1): + chunk_sentences = sentences[boundaries[j]:boundaries[j + 1]] + chunk_text = " ".join(chunk_sentences) + if len(chunk_text.strip()) > 100: + chunks.append(Chunk( + text=chunk_text, + metadata={**meta, "chunk_index": j}, + )) + + return chunks + + +class FixedTokenChunker: + """Simple fixed-size chunker, no overlap. Fallback for structured data.""" + + def __init__(self, size: int = 512) -> None: + self.size = size + + def chunk(self, text: str, metadata: dict[str, Any] | None = None) -> list[Chunk]: + meta = metadata or {} + tokens = text.split() + chunks: list[Chunk] = [] + for i in range(0, len(tokens), self.size): + chunk_text = " ".join(tokens[i:i + self.size]) + if chunk_text.strip(): + chunks.append(Chunk(text=chunk_text, metadata={**meta, "chunk_index": i // self.size})) + return chunks diff --git a/backend/rag/embedder.py b/backend/rag/embedder.py new file mode 100644 index 0000000000000000000000000000000000000000..97065d5517a0f3d95248d08b54fe325560dd0b8b --- /dev/null +++ b/backend/rag/embedder.py @@ -0,0 +1,22 @@ +import os +from functools import lru_cache + +import numpy as np + + +@lru_cache(maxsize=1) +def get_embedder(): + from sentence_transformers import SentenceTransformer + model = os.getenv("EMBEDDING_MODEL", "sentence-transformers/all-MiniLM-L6-v2") + return SentenceTransformer(model) + + +def embed(text: str) -> list[float]: + return get_embedder().encode(text, normalize_embeddings=True).tolist() + + +def embed_batch(texts: list[str]) -> list[list[float]]: + return get_embedder().encode(texts, normalize_embeddings=True, batch_size=32).tolist() + + +VECTOR_SIZE = 384 diff --git a/backend/rag/evaluation/__init__.py b/backend/rag/evaluation/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/backend/rag/evaluation/ragas_eval.py b/backend/rag/evaluation/ragas_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..bb60862a2a0d4a82d969ceccc6d838503e927496 --- /dev/null +++ b/backend/rag/evaluation/ragas_eval.py @@ -0,0 +1,147 @@ +""" +RAGAS evaluation runner for Finora RAG pipeline. + +Uses Groq llama-3.1-8b-instant (GROQ_MODEL_FAST) as the evaluation LLM +and all-MiniLM-L6-v2 (local HF) for embeddings — zero OpenAI dependency. + +Targets: + Faithfulness > 0.85 + Answer Relevance > 0.80 + Context Recall > 0.75 + Context Precision > 0.70 + +Usage: + from backend.rag.evaluation.ragas_eval import run_ragas_eval + results = run_ragas_eval(qa_pairs, tickers=["AAPL", "MSFT"]) +""" +from __future__ import annotations + +import os +import warnings +from typing import Any + +import structlog + +log = structlog.get_logger() + +TARGETS = { + "faithfulness": 0.85, + "answer_relevancy": 0.80, + "context_recall": 0.75, + "context_precision": 0.70, +} + + +def _build_llm(): + """Groq llama-3.1-8b-instant wrapped for RAGAS. + + Groq rejects n > 1. RAGAS passes n=3 via LangchainLLMWrapper.generate(n=3). + Subclass the wrapper itself to hard-cap n=1 at the exact call site. + """ + from langchain_groq import ChatGroq + from ragas.llms import LangchainLLMWrapper + + groq = ChatGroq( + model=os.getenv("GROQ_MODEL_FAST", "llama-3.1-8b-instant"), + api_key=os.getenv("GROQ_API_KEY"), + temperature=0.0, + max_tokens=512, + n=1, + ) + + return LangchainLLMWrapper(groq, bypass_n=True) + + +def _build_embeddings(): + """Local all-MiniLM-L6-v2 wrapped for RAGAS — no API key needed.""" + from langchain_community.embeddings import HuggingFaceEmbeddings + from ragas.embeddings import LangchainEmbeddingsWrapper + + return LangchainEmbeddingsWrapper(HuggingFaceEmbeddings( + model_name=os.getenv("EMBEDDING_MODEL", "sentence-transformers/all-MiniLM-L6-v2"), + cache_folder=os.getenv("HF_CACHE_DIR", "data/hf_cache"), + )) + + +def run_ragas_eval( + qa_pairs: list[dict], + tickers: list[str] | None = None, +) -> dict[str, Any]: + """ + Run RAGAS evaluation over QA pairs. + + qa_pairs schema: + [{"question": str, "answer": str, "contexts": list[str], "ground_truth": str}] + + Returns metrics dict with scores + pass/fail per metric. + """ + try: + from datasets import Dataset + from ragas import evaluate + from ragas.metrics import ( + answer_relevancy, + context_precision, + context_recall, + faithfulness, + ) + except ImportError as exc: + log.error("ragas_import_failed", error=str(exc)) + return {"error": "ragas / datasets not installed"} + + if not qa_pairs: + return {"error": "no QA pairs provided"} + + try: + llm = _build_llm() + embeddings = _build_embeddings() + except Exception as exc: + log.error("ragas_llm_build_failed", error=str(exc)) + return {"error": f"LLM/embeddings init failed: {exc}"} + + dataset = Dataset.from_list(qa_pairs) + + # Cap answer_relevancy to n=1 — Groq free tier can't handle n=3 sequential calls + answer_relevancy.n = 1 # type: ignore[attr-defined] + + metrics = [faithfulness, answer_relevancy, context_recall, context_precision] + + log.info("ragas_eval_start", pairs=len(qa_pairs), tickers=tickers) + + try: + with warnings.catch_warnings(): + warnings.simplefilter("ignore", DeprecationWarning) + result = evaluate( + dataset, + metrics=metrics, + llm=llm, + embeddings=embeddings, + raise_exceptions=False, + show_progress=True, + ) + # EvaluationResult is DataFrame-like — extract per-row scores then average + result_df = result.to_pandas() + metric_cols = [c for c in result_df.columns if c in TARGETS] + scores: dict[str, float] = result_df[metric_cols].mean().dropna().to_dict() + except Exception as exc: + log.error("ragas_eval_failed", error=str(exc)) + return {"error": str(exc)} + + report: dict[str, Any] = {"scores": scores, "results": {}} + for metric, target in TARGETS.items(): + score = scores.get(metric) + if score is None: + continue + report["results"][metric] = { + "score": round(score, 4), + "target": target, + "passed": score >= target, + "delta": round(score - target, 4), + } + + all_pass = all(r["passed"] for r in report["results"].values()) + report["overall_pass"] = all_pass + report["tickers"] = tickers or [] + report["n_pairs"] = len(qa_pairs) + + log.info("ragas_eval_complete", pass_all=all_pass, scores=scores) + return report diff --git a/backend/rag/evaluation/synthetic.py b/backend/rag/evaluation/synthetic.py new file mode 100644 index 0000000000000000000000000000000000000000..98e4208dd9b9ed2e57e4385354025a5b44835445 --- /dev/null +++ b/backend/rag/evaluation/synthetic.py @@ -0,0 +1,83 @@ +"""Generate synthetic QA pairs from Qdrant chunks for RAGAS evaluation.""" +from __future__ import annotations + +import os +import random + +import structlog +from groq import Groq + +log = structlog.get_logger() + +_SYSTEM = """\ +You are a financial analyst. Given a passage about a stock, generate one question +that can be answered from the passage and provide the answer. + +Return JSON: {"question": "...", "answer": "..."} +Return ONLY the JSON.""" + + +def generate_qa_pair(chunk_text: str, ticker: str) -> dict | None: + try: + client = Groq(api_key=os.getenv("GROQ_API_KEY")) + resp = client.chat.completions.create( + model=os.getenv("GROQ_MODEL_FAST", "llama-3.1-8b-instant"), + messages=[ + {"role": "system", "content": _SYSTEM}, + {"role": "user", "content": f"Ticker: {ticker}\n\nPassage:\n{chunk_text[:800]}"}, + ], + max_tokens=200, + temperature=0.3, + ) + import json + raw = resp.choices[0].message.content or "{}" + start, end = raw.find("{"), raw.rfind("}") + 1 + pair = json.loads(raw[start:end]) if start >= 0 else {} + if pair.get("question") and pair.get("answer"): + return { + "question": pair["question"], + "answer": pair["answer"], + "contexts": [chunk_text], + "ground_truth": pair["answer"], + } + except Exception as exc: + log.warning("synthetic_qa_failed", ticker=ticker, error=str(exc)) + return None + + +def generate_synthetic_dataset( + tickers: list[str], + collection_key: str = "news", + n_per_ticker: int = 5, +) -> list[dict]: + """Pull chunks from Qdrant + generate synthetic QA pairs via Groq.""" + from backend.rag.ingestion.collections import collection_name, get_client + + client = get_client() + col = collection_name(collection_key) + pairs: list[dict] = [] + + for ticker in tickers: + try: + from qdrant_client.models import FieldCondition, Filter, MatchValue + results, _ = client.scroll( + collection_name=col, + scroll_filter=Filter( + must=[FieldCondition(key="ticker", match=MatchValue(value=ticker))] + ), + limit=n_per_ticker * 3, + with_payload=True, + ) + chunks = [r.payload.get("text", "") for r in results if r.payload] + random.shuffle(chunks) + for chunk in chunks[:n_per_ticker]: + if not chunk: + continue + pair = generate_qa_pair(chunk, ticker) + if pair: + pairs.append(pair) + except Exception as exc: + log.error("synthetic_ticker_failed", ticker=ticker, error=str(exc)) + + log.info("synthetic_dataset_done", total=len(pairs)) + return pairs diff --git a/backend/rag/ingestion/__init__.py b/backend/rag/ingestion/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/backend/rag/ingestion/collections.py b/backend/rag/ingestion/collections.py new file mode 100644 index 0000000000000000000000000000000000000000..dcd89ee053e7e675cfaf70218b740463ac20a3e1 --- /dev/null +++ b/backend/rag/ingestion/collections.py @@ -0,0 +1,57 @@ +import os + +import structlog +from qdrant_client import QdrantClient +from qdrant_client.models import Distance, VectorParams, OptimizersConfigDiff, PayloadSchemaType + +from backend.rag.embedder import VECTOR_SIZE + +log = structlog.get_logger() + +COLLECTIONS = { + "finora_news": "QDRANT_COLLECTION_NEWS", + "finora_historical": "QDRANT_COLLECTION_HISTORICAL", + "finora_filings": "QDRANT_COLLECTION_FILINGS", +} + + +def get_client() -> QdrantClient: + url = os.getenv("QDRANT_URL") + api_key = os.getenv("QDRANT_API_KEY") + if not url: + raise RuntimeError("QDRANT_URL not set") + return QdrantClient(url=url, api_key=api_key, timeout=30) + + +def ensure_collections(client: QdrantClient | None = None) -> None: + """Create all three collections if they don't exist.""" + c = client or get_client() + existing = {col.name for col in c.get_collections().collections} + + for default_name, env_key in COLLECTIONS.items(): + name = os.getenv(env_key, default_name) + if name in existing: + log.info("collection_exists", name=name) + continue + c.create_collection( + collection_name=name, + vectors_config=VectorParams(size=VECTOR_SIZE, distance=Distance.COSINE), + optimizers_config=OptimizersConfigDiff(indexing_threshold=20_000), + ) + # Payload index required for ticker-filtered searches + c.create_payload_index( + collection_name=name, + field_name="ticker", + field_schema=PayloadSchemaType.KEYWORD, + ) + log.info("collection_created", name=name) + + +def collection_name(key: str) -> str: + """key: 'news' | 'historical' | 'filings'""" + env_map = { + "news": "QDRANT_COLLECTION_NEWS", + "historical": "QDRANT_COLLECTION_HISTORICAL", + "filings": "QDRANT_COLLECTION_FILINGS", + } + return os.getenv(env_map[key], f"finora_{key}") diff --git a/backend/rag/ingestion/filings.py b/backend/rag/ingestion/filings.py new file mode 100644 index 0000000000000000000000000000000000000000..d20b5ac152fdf1825154f61ae8158fa67d723c24 --- /dev/null +++ b/backend/rag/ingestion/filings.py @@ -0,0 +1,172 @@ +""" +Ingest SEC EDGAR 10-K / 10-Q filings → SemanticChunker → Qdrant (finora_filings). +No API key needed. User-Agent set per SEC fair use policy. +""" +from __future__ import annotations + +import os +import re +import time +import uuid + +import requests +import structlog +from qdrant_client import QdrantClient +from qdrant_client.models import PointStruct + +from backend.rag.chunking.strategies import SemanticChunker +from backend.rag.embedder import embed_batch +from backend.rag.ingestion.collections import collection_name, get_client + +log = structlog.get_logger() + +_chunker = SemanticChunker(threshold=0.75, min_tokens=300, max_tokens=800) + +_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 reliable + tickers_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 None + + +def _get_recent_filings(cik: str, max_filings: int = 3) -> list[dict]: + try: + resp = requests.get( + f"{_EDGAR_BASE}/submissions/CIK{cik}.json", + headers=_HEADERS, + timeout=15, + ) + resp.raise_for_status() + data = resp.json() + recent = data.get("filings", {}).get("recent", {}) + + forms = recent.get("form", []) + accessions = recent.get("accessionNumber", []) + dates = recent.get("filingDate", []) + primary_docs = recent.get("primaryDocument", []) + + filings = [] + for form, acc, dt, doc in zip(forms, accessions, dates, primary_docs): + if form in _FORM_TYPES and len(filings) < max_filings: + filings.append({ + "form": form, + "accession": acc.replace("-", ""), + "date": dt, + "primary_doc": doc, + "cik": cik, + }) + return filings + except Exception as exc: + log.error("edgar_filings_fetch_failed", cik=cik, error=str(exc)) + return [] + + +def _fetch_filing_text(cik: str, accession: str, primary_doc: str) -> str: + url = f"https://www.sec.gov/Archives/edgar/full-index/{cik[:4]}/{cik[4:]}" + # Direct document URL + filing_url = f"https://www.sec.gov/Archives/edgar/data/{int(cik)}/{accession}/{primary_doc}" + try: + resp = requests.get(filing_url, headers=_HEADERS, timeout=30) + resp.raise_for_status() + + # Strip HTML tags if present + text = resp.text + if "]+>", " ", text) + text = 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 content + + return text.strip() + except Exception as exc: + log.error("edgar_filing_download_failed", url=filing_url, error=str(exc)) + return "" + + +def ingest_ticker( + ticker: str, + client: QdrantClient | None = None, + max_filings: int = 2, +) -> int: + # Only US tickers — NIFTY 50 uses Indian exchanges, no SEC filings + if ticker.endswith(".NS") or ticker.endswith(".BSE"): + return 0 + + c = client or get_client() + col = collection_name("filings") + + cik = _get_cik(ticker) + if not cik: + log.warning("edgar_no_cik", ticker=ticker) + return 0 + + filings = _get_recent_filings(cik, max_filings) + if not filings: + return 0 + + total_chunks = 0 + for filing in filings: + time.sleep(0.5) # SEC fair use: no hammering + text = _fetch_filing_text(filing["cik"], filing["accession"], filing["primary_doc"]) + if len(text) < 500: + continue + + meta = { + "ticker": ticker, + "filing_type": filing["form"], + "period": filing["date"], + "cik": filing["cik"], + "accession": filing["accession"], + "source": "sec_edgar", + } + chunks = _chunker.chunk(text, metadata=meta) + if not chunks: + continue + + texts = [ch.text for ch in chunks] + vectors = embed_batch(texts) + + points = [ + PointStruct( + id=str(uuid.uuid5( + uuid.NAMESPACE_DNS, + f"{ticker}:{filing['accession']}:{i}", + )), + vector=vec, + payload={**ch.metadata, "text": ch.text, "data_type": "filing"}, + ) + for i, (ch, vec) in enumerate(zip(chunks, vectors)) + ] + + c.upsert(collection_name=col, points=points) + total_chunks += len(points) + log.info("filing_ingest_done", ticker=ticker, form=filing["form"], chunks=len(points)) + + return total_chunks diff --git a/backend/rag/ingestion/historical.py b/backend/rag/ingestion/historical.py new file mode 100644 index 0000000000000000000000000000000000000000..287db97a791e017e16c8da294daed5d2a432d6fe --- /dev/null +++ b/backend/rag/ingestion/historical.py @@ -0,0 +1,246 @@ +""" +Ingest OHLCV history → FinancialEventChunker → Qdrant (finora_historical). + +Primary source: Yahoo Finance v8 chart API via curl_cffi Chrome TLS impersonation. + - Works for ALL tickers: US, Indian (.NS), European, etc. + - No API key required. No IP blocks (TLS fingerprint bypasses bot detection). + - 20yr weekly history, adjusted close prices. + +Fallback: Polygon.io (US tickers, ~2yr free tier, requires POLYGON_API_KEY). +""" +from __future__ import annotations + +import asyncio +import os +import time +import uuid +from datetime import date, timedelta + +import pandas as pd +import structlog +from qdrant_client import QdrantClient +from qdrant_client.models import PointStruct + +from backend.rag.chunking.financial import FinancialEventChunker +from backend.rag.embedder import embed_batch +from backend.rag.ingestion.collections import collection_name, get_client + +log = structlog.get_logger() + +_chunker = FinancialEventChunker() + +# Shared curl_cffi session — Chrome TLS fingerprint impersonation +# This is what Yahoo Finance requires in 2024 to avoid 429/empty responses. +# Standard requests.Session only sends HTTP headers; Yahoo also checks TLS fingerprint. +try: + from curl_cffi import requests as cffi_requests + _cffi_session = cffi_requests.Session(impersonate="chrome124") + _CFFI_AVAILABLE = True +except ImportError: + _cffi_session = None + _CFFI_AVAILABLE = False + log.warning("curl_cffi_not_installed", hint="pip install curl_cffi") + + +# ── Yahoo Finance v8 chart API (primary, universal) ──────────────────────── + +def _fetch_ohlcv_yahoo(yf_ticker: str, years: int = 20) -> pd.DataFrame: + """ + Fetch weekly OHLCV via Yahoo Finance v8 chart API with curl_cffi TLS impersonation. + Works universally for US and Indian stocks. No API key needed. + """ + if not _CFFI_AVAILABLE or _cffi_session is None: + return pd.DataFrame() + + url = f"https://query1.finance.yahoo.com/v8/finance/chart/{yf_ticker}" + params = { + "range": f"{min(years, 20)}y", + "interval": "1wk", + "includePrePost": "false", + "events": "history", + } + + try: + r = _cffi_session.get(url, params=params, timeout=20) + if r.status_code != 200: + log.warning("yahoo_v8_http_error", ticker=yf_ticker, status=r.status_code) + return pd.DataFrame() + + data = r.json() + result = data.get("chart", {}).get("result", []) + if not result: + log.warning("yahoo_v8_no_result", ticker=yf_ticker) + return pd.DataFrame() + + chart = result[0] + timestamps = chart.get("timestamp", []) + if not timestamps: + return pd.DataFrame() + + quote = chart.get("indicators", {}).get("quote", [{}])[0] + adj_list = chart.get("indicators", {}).get("adjclose", [{}]) + adjclose = adj_list[0].get("adjclose", []) if adj_list else [] + + rows = [] + for i, ts in enumerate(timestamps): + close_val = adjclose[i] if i < len(adjclose) and adjclose[i] else ( + (quote.get("close") or [])[i] if i < len(quote.get("close") or []) else None + ) + if close_val is None: + continue + rows.append({ + "Open": (quote.get("open") or [None])[i] if i < len(quote.get("open") or []) else None, + "High": (quote.get("high") or [None])[i] if i < len(quote.get("high") or []) else None, + "Low": (quote.get("low") or [None])[i] if i < len(quote.get("low") or []) else None, + "Close": close_val, + "Volume": (quote.get("volume") or [0])[i] or 0 if i < len(quote.get("volume") or []) else 0, + }) + + if not rows: + return pd.DataFrame() + + idx = pd.to_datetime(timestamps[:len(rows)], unit="s", utc=True).tz_localize(None) + df = pd.DataFrame(rows, index=idx).dropna(subset=["Close"]) + log.info("yahoo_v8_fetch_ok", ticker=yf_ticker, rows=len(df)) + return df + + except Exception as exc: + log.warning("yahoo_v8_fetch_failed", ticker=yf_ticker, error=str(exc)) + return pd.DataFrame() + + +# ── Polygon.io fallback (US tickers, ~2yr free tier) ────────────────────── + +def _fetch_ohlcv_polygon(poly_ticker: str, years: int = 20) -> pd.DataFrame: + """Polygon.io fallback. Free tier: ~2yr lookback, 5 calls/min.""" + api_key = os.getenv("POLYGON_API_KEY", "") + if not api_key: + return pd.DataFrame() + + max_lookback = min(years, 2) + end_dt = date.today() + start_dt = end_dt - timedelta(days=max_lookback * 365) + + try: + from polygon import RESTClient + time.sleep(13) # Polygon free tier: 5 calls/min = 12s minimum gap + client = RESTClient(api_key=api_key) + aggs = list(client.get_aggs( + poly_ticker, 1, "week", + str(start_dt), str(end_dt), + limit=5000, adjusted=True, + )) + if not aggs: + return pd.DataFrame() + + rows = [ + { + "Date": pd.Timestamp.fromtimestamp(a.timestamp / 1000, tz="UTC").tz_localize(None), + "Open": a.open, "High": a.high, "Low": a.low, + "Close": a.close, "Volume": a.volume or 0, + } + for a in aggs + ] + df = pd.DataFrame(rows).set_index("Date").sort_index() + log.info("polygon_fetch_ok", ticker=poly_ticker, rows=len(df)) + return df + + except Exception as exc: + log.warning("polygon_fetch_failed", ticker=poly_ticker, error=str(exc)) + return pd.DataFrame() + + +# ── Main fetch: Yahoo primary → Polygon fallback ─────────────────────────── + +def _fetch_ohlcv(yf_ticker: str, years: int = 20) -> pd.DataFrame: + # Yahoo Finance v8 with Chrome TLS impersonation — works for all tickers + df = _fetch_ohlcv_yahoo(yf_ticker, years) + if not df.empty: + return df + + # Polygon fallback (US tickers only, 2yr max on free tier) + poly_ticker = yf_ticker.split(".")[0].upper() + log.info("yahoo_failed_trying_polygon", ticker=yf_ticker) + return _fetch_ohlcv_polygon(poly_ticker, years) + + +# ── Ingest functions ─────────────────────────────────────────────────────── + +def ingest_ticker( + ticker: str, + yf_ticker: str, + years: int = 20, + client: QdrantClient | None = None, +) -> int: + c = client or get_client() + col = collection_name("historical") + + log.info("historical_ingest_start", ticker=ticker, yf_ticker=yf_ticker) + + try: + df = _fetch_ohlcv(yf_ticker, years) + except Exception as exc: + log.error("historical_fetch_failed", ticker=ticker, error=str(exc)) + return 0 + + if df.empty: + log.warning("historical_empty", ticker=ticker) + return 0 + + # Flatten MultiIndex columns (yfinance sometimes returns these) + if hasattr(df.columns, "get_level_values"): + try: + df.columns = df.columns.get_level_values(0) + except Exception: + pass + + chunks = _chunker.chunk(df, ticker) + if not chunks: + log.warning("historical_no_events", ticker=ticker, rows=len(df)) + return 0 + + texts = [ch.text for ch in chunks] + vectors = embed_batch(texts) + + points = [ + PointStruct( + id=str(uuid.uuid5(uuid.NAMESPACE_DNS, f"{ticker}:{ch.metadata['date_range']}")), + vector=vec, + payload={**ch.metadata, "text": ch.text, "source": "historical_ohlcv"}, + ) + for ch, vec in zip(chunks, vectors) + ] + + c.upsert(collection_name=col, points=points) + log.info("historical_ingest_done", ticker=ticker, chunks=len(points)) + return len(points) + + +async def ingest_ticker_async(ticker: str, yf_ticker: str, years: int = 20) -> int: + loop = asyncio.get_running_loop() + return await loop.run_in_executor(None, ingest_ticker, ticker, yf_ticker, years) + + +def ingest_universe( + stocks: list[dict], + years: int = 20, + delay_seconds: float = 0.5, +) -> dict[str, int]: + """Sequential ingest. curl_cffi handles rate limiting gracefully.""" + client = get_client() + results: dict[str, int] = {} + total = len(stocks) + + for i, s in enumerate(stocks): + ticker = s["ticker"] + yf_ticker = s.get("yf_ticker", ticker) + log.info("historical_universe_progress", done=i, total=total, ticker=ticker) + try: + results[ticker] = ingest_ticker(ticker, yf_ticker, years, client) + except Exception as exc: + log.error("historical_universe_failed", ticker=ticker, error=str(exc)) + results[ticker] = 0 + if i < total - 1: + time.sleep(delay_seconds) + + return results diff --git a/backend/rag/ingestion/news.py b/backend/rag/ingestion/news.py new file mode 100644 index 0000000000000000000000000000000000000000..4320b84002549affd08e691e5ea875e27d7da6a9 --- /dev/null +++ b/backend/rag/ingestion/news.py @@ -0,0 +1,150 @@ +""" +Ingest news articles via NewsAPI → SlidingWindowChunker → Qdrant (finora_news). +""" +from __future__ import annotations + +import os +import time +import uuid +from datetime import datetime, timedelta, timezone + +import requests +import structlog +from qdrant_client import QdrantClient +from qdrant_client.models import PointStruct + +from backend.rag.chunking.strategies import SlidingWindowChunker +from backend.rag.embedder import embed_batch +from backend.rag.ingestion.collections import collection_name, get_client + +log = structlog.get_logger() + +_chunker = SlidingWindowChunker(window=512, stride=128) + +_NEWSAPI_BASE = "https://newsapi.org/v2/everything" +_RSS_SOURCES = [ + "reuters.com", + "bloomberg.com", + "ft.com", + "wsj.com", + "cnbc.com", + "businessinsider.com", +] + + +def _fetch_newsapi(ticker: str, company_name: str, days: int = 7) -> list[dict]: + api_key = os.getenv("NEWSAPI_KEY") + if not api_key: + log.warning("newsapi_key_missing") + return [] + + from_date = (datetime.now(timezone.utc) - timedelta(days=days)).strftime("%Y-%m-%d") + query = f'"{company_name}" OR "{ticker}"' + + try: + resp = requests.get( + _NEWSAPI_BASE, + params={ + "q": query, + "from": from_date, + "sortBy": "relevancy", + "language": "en", + "pageSize": 20, + "domains": ",".join(_RSS_SOURCES), + "apiKey": api_key, + }, + timeout=15, + ) + resp.raise_for_status() + return resp.json().get("articles", []) + except Exception as exc: + log.error("newsapi_fetch_failed", ticker=ticker, error=str(exc)) + return [] + + +def _article_to_text(article: dict) -> str: + parts = [] + if article.get("title"): + parts.append(article["title"]) + if article.get("description"): + parts.append(article["description"]) + if article.get("content"): + # NewsAPI free tier truncates at ~200 chars; use what we have + content = article["content"].replace("[+", "").split("[+")[0].strip() + if content: + parts.append(content) + return " ".join(parts) + + +def ingest_ticker( + ticker: str, + company_name: str, + days: int = 7, + client: QdrantClient | None = None, +) -> int: + c = client or get_client() + col = collection_name("news") + + articles = _fetch_newsapi(ticker, company_name, days) + if not articles: + log.warning("news_no_articles", ticker=ticker) + return 0 + + all_chunks = [] + for article in articles: + text = _article_to_text(article) + if len(text) < 100: + continue + + published_at = article.get("publishedAt", "") + source = article.get("source", {}).get("name", "unknown") + url = article.get("url", "") + + meta = { + "ticker": ticker, + "source": source, + "url": url, + "published_at": published_at, + "title": article.get("title", ""), + } + chunks = _chunker.chunk(text, metadata=meta) + all_chunks.extend(chunks) + + if not all_chunks: + return 0 + + texts = [ch.text for ch in all_chunks] + vectors = embed_batch(texts) + + points = [ + PointStruct( + id=str(uuid.uuid5( + uuid.NAMESPACE_DNS, + f"{ticker}:{ch.metadata.get('url','')}:{ch.metadata.get('chunk_start_token', i)}", + )), + vector=vec, + payload={**ch.metadata, "text": ch.text, "data_type": "news"}, + ) + for i, (ch, vec) in enumerate(zip(all_chunks, vectors)) + ] + + c.upsert(collection_name=col, points=points) + log.info("news_ingest_done", ticker=ticker, articles=len(articles), chunks=len(points)) + return len(points) + + +def ingest_universe(stocks: list[dict], days: int = 7) -> dict[str, int]: + client = get_client() + results: dict[str, int] = {} + + for stock in stocks: + ticker = stock["ticker"] + name = stock.get("name", ticker) + try: + results[ticker] = ingest_ticker(ticker, name, days=days, client=client) + except Exception as exc: + log.error("news_worker_failed", ticker=ticker, error=str(exc)) + results[ticker] = 0 + time.sleep(0.5) # NewsAPI free tier: 100 req/day + + return results diff --git a/backend/rag/ingestion/scheduler.py b/backend/rag/ingestion/scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..ff8425ccdcb5f897c906897ed62ebcdd086ccec0 --- /dev/null +++ b/backend/rag/ingestion/scheduler.py @@ -0,0 +1,86 @@ +""" +APScheduler jobs: news ingestion every 15 min, historical update every 24 hr. +Integrated into FastAPI lifespan. +""" +from __future__ import annotations + +import os + +import structlog +from apscheduler.schedulers.asyncio import AsyncIOScheduler +from apscheduler.triggers.interval import IntervalTrigger + +log = structlog.get_logger() + +_scheduler: AsyncIOScheduler | None = None + + +async def _run_news_ingest() -> None: + from backend.rag.ingestion.universe import universe + from backend.rag.ingestion import news as news_ingest + from backend.rag.ingestion.collections import ensure_collections + + stocks = [s for s in universe.stocks][:50] # Cap at 50 on scheduled runs + if not stocks: + return + + ensure_collections() + results = news_ingest.ingest_universe(stocks, days=1) + total = sum(results.values()) + log.info("scheduled_news_done", tickers=len(results), chunks=total) + + +async def _run_historical_update() -> None: + from backend.rag.ingestion.universe import universe + from backend.rag.ingestion import historical as hist_ingest + from backend.rag.ingestion.collections import ensure_collections + + # Daily update: only ingest recent 30 days of OHLCV + stocks = universe.stocks + if not stocks: + return + + ensure_collections() + # Use a subset to avoid overwhelming yfinance rate limits on daily runs + priority = [s for s in stocks if s["country"] in ("US",)][:20] + results = hist_ingest.ingest_universe(priority, years=1, max_workers=2) + total = sum(results.values()) + log.info("scheduled_historical_done", tickers=len(results), chunks=total) + + +def start_scheduler() -> AsyncIOScheduler: + global _scheduler + + news_interval = int(os.getenv("NEWS_INGEST_INTERVAL_MINUTES", "15")) + hist_interval = int(os.getenv("HISTORICAL_UPDATE_INTERVAL_HOURS", "24")) + + _scheduler = AsyncIOScheduler() + + _scheduler.add_job( + _run_news_ingest, + trigger=IntervalTrigger(minutes=news_interval), + id="news_ingest", + name="News RAG Ingest", + replace_existing=True, + misfire_grace_time=300, + ) + + _scheduler.add_job( + _run_historical_update, + trigger=IntervalTrigger(hours=hist_interval), + id="historical_update", + name="Historical OHLCV Update", + replace_existing=True, + misfire_grace_time=3600, + ) + + _scheduler.start() + log.info("scheduler_started", news_interval_min=news_interval, hist_interval_hr=hist_interval) + return _scheduler + + +def stop_scheduler() -> None: + global _scheduler + if _scheduler and _scheduler.running: + _scheduler.shutdown(wait=False) + log.info("scheduler_stopped") diff --git a/backend/rag/ingestion/universe.py b/backend/rag/ingestion/universe.py new file mode 100644 index 0000000000000000000000000000000000000000..998804a4fbf961e20f024b0531cf0475b0a103ca --- /dev/null +++ b/backend/rag/ingestion/universe.py @@ -0,0 +1,76 @@ +import json +import os +from pathlib import Path +from typing import Any + +import structlog +from rapidfuzz import fuzz, process + +log = structlog.get_logger() + +# parents[2] = backend/ (works for both local dev and Docker: /app/data/universe/) +_UNIVERSE_PATH = Path(__file__).parents[2] / "data" / "universe" / "stocks.json" + + +class StockUniverse: + def __init__(self) -> None: + self.stocks: list[dict[str, Any]] = [] + self._search_strings: list[str] = [] + self._load() + + def _load(self) -> None: + if not _UNIVERSE_PATH.exists(): + log.warning("universe_not_found", path=str(_UNIVERSE_PATH)) + return + with open(_UNIVERSE_PATH) as f: + self.stocks = json.load(f) + # Pre-build search strings: "AAPL Apple Inc Technology US" + self._search_strings = [ + f"{s['ticker']} {s['name']} {s.get('sector', '')} {s.get('country', '')}" + for s in self.stocks + ] + log.info("universe_loaded", count=len(self.stocks)) + + def search(self, query: str, limit: int = 10) -> list[dict[str, Any]]: + if not query or not self.stocks: + return self.stocks[:limit] + + q = query.strip() + q_up = q.upper() + q_low = q.lower() + scored: list[tuple[float, int]] = [] + + for i, stock in enumerate(self.stocks): + ticker = stock["ticker"].upper() + name_low = stock["name"].lower() + + if ticker == q_up: + score = 200.0 + elif ticker.startswith(q_up) and len(q_up) >= 2: + score = 170.0 + len(q_up) + else: + # ratio for ticker: avoids single-char 100% partial traps + ticker_score = fuzz.ratio(q_up, ticker) * 1.2 + # partial_ratio for name: finds query as substring + name_score = fuzz.partial_ratio(q_low, name_low) + score = max(ticker_score, name_score) + if score < 50: + continue + + scored.append((score, i)) + + scored.sort(key=lambda x: -x[0]) + return [self.stocks[i] for _, i in scored[:limit]] + + def get_by_ticker(self, ticker: str) -> dict[str, Any] | None: + ticker_upper = ticker.upper() + for s in self.stocks: + if s["ticker"].upper() == ticker_upper or s.get("yf_ticker", "").upper() == ticker_upper: + return s + return None + + def reload(self) -> None: + self._load() + + +universe = StockUniverse() diff --git a/backend/rag/pipeline.py b/backend/rag/pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..34cd7f9b5eab8658ab9c1a0e67cf9c649fdb2285 --- /dev/null +++ b/backend/rag/pipeline.py @@ -0,0 +1,144 @@ +""" +Master RAG orchestrator. +Called by LangGraph nodes to execute retrieval for a given intent + ticker. +""" +from __future__ import annotations + +import os +from dataclasses import dataclass, field +from typing import Any + +import structlog + +from backend.rag.ingestion.collections import collection_name, get_client +from backend.rag.retrieval.deduplication import deduplicate_and_diversify +from backend.rag.retrieval.hybrid import RetrievedChunk, hybrid_search +from backend.rag.retrieval.hyde import generate_hyde_embedding, should_use_hyde +from backend.rag.retrieval.reranker import rerank +from backend.rag.retrieval.router import RetrievalBranch, get_branches + +log = structlog.get_logger() + +TOP_K = int(os.getenv("RAG_TOP_K", "8")) +CANDIDATES = TOP_K * int(os.getenv("RAG_OVER_RETRIEVE_FACTOR", "2")) + + +@dataclass +class RAGResult: + chunks: list[RetrievedChunk] + collection: str + intent: str + hyde_used: bool + retrieval_scores: dict[str, Any] = field(default_factory=dict) + + +def run_rag_branch( + query: str, + ticker: str, + branch: RetrievalBranch, + top_k: int = TOP_K, +) -> RAGResult: + """Execute full RAG pipeline for one intent branch.""" + client = get_client() + col = collection_name(branch.collection) + + # HyDE: generate hypothetical doc embedding for abstract queries + hyde_used = branch.use_hyde and bool(os.getenv("RAG_HYDE_ENABLED", "false") == "true") + if hyde_used: + query_vector = generate_hyde_embedding(query) + else: + query_vector = None + + # Hybrid retrieval: BM25 + dense, RRF-fused + candidates = hybrid_search( + query=query, + ticker=ticker, + collection=col, + query_vector=query_vector, + client=client, + limit=CANDIDATES, + allow_global_fallback=branch.allow_global_fallback, + ) + + if not candidates: + log.debug("rag_no_candidates", ticker=ticker, intent=branch.intent, collection=col) + return RAGResult(chunks=[], collection=col, intent=branch.intent, hyde_used=hyde_used) + + # Reranking: Cohere → BAAI fallback + if os.getenv("RAG_RERANKER_ENABLED", "true") == "true": + reranked = rerank(query, candidates, top_k=top_k) + else: + reranked = candidates[:top_k] + + # Drop chunks below minimum relevance (Cohere 0–1 range only; BGE logits skipped) + # Fallback: if threshold wipes all results, keep top-2 — empty context is worse than low-score context + min_score = float(os.getenv("RAG_MIN_RELEVANCE_SCORE", "0.05")) + if reranked and 0.0 <= reranked[0].score <= 1.0: + filtered = [c for c in reranked if c.score >= min_score] + reranked = filtered if filtered else reranked[:2] + + # Deduplication + MMR diversity + final = deduplicate_and_diversify(query, reranked, top_k=top_k) + + scores = { + "candidates": len(candidates), + "after_rerank": len(reranked), + "after_dedup": len(final), + "top_score": final[0].score if final else 0.0, + } + log.info("rag_branch_done", ticker=ticker, intent=branch.intent, **scores) + + return RAGResult( + chunks=final, + collection=col, + intent=branch.intent, + hyde_used=hyde_used, + retrieval_scores=scores, + ) + + +def run_rag( + query: str, + ticker: str, + intents: list[str], + top_k: int = TOP_K, +) -> list[RAGResult]: + """ + Run all RAG branches for the given intents in sequence. + LangGraph handles parallel execution across graph nodes. + """ + branches = get_branches(intents) # type: ignore[arg-type] + results: list[RAGResult] = [] + + for branch in branches: + try: + result = run_rag_branch(query, ticker, branch, top_k=top_k) + results.append(result) + except Exception as exc: + log.error("rag_branch_failed", intent=branch.intent, ticker=ticker, error=str(exc)) + results.append(RAGResult( + chunks=[], + collection=collection_name(branch.collection), + intent=branch.intent, + hyde_used=False, + )) + + return results + + +def format_context(results: list[RAGResult]) -> str: + """Render retrieved chunks into the fusion prompt context string.""" + sections: list[str] = [] + for result in results: + if not result.chunks: + continue + label = result.intent.upper().replace("_", " ") + lines = [f"[{label} CONTEXT — {len(result.chunks)} sources]"] + for i, chunk in enumerate(result.chunks, 1): + meta = chunk.metadata + source = meta.get("source", meta.get("url", "unknown")) + date = meta.get("published_at", meta.get("start_date", "")) + lines.append(f"[{i}] {source} ({date}): {chunk.text}") + sections.append("\n".join(lines)) + + return "\n\n".join(sections) diff --git a/backend/rag/retrieval/__init__.py b/backend/rag/retrieval/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/backend/rag/retrieval/deduplication.py b/backend/rag/retrieval/deduplication.py new file mode 100644 index 0000000000000000000000000000000000000000..5eb19465ce7a1196b10b0fd8107fbd7cfab06b8d --- /dev/null +++ b/backend/rag/retrieval/deduplication.py @@ -0,0 +1,108 @@ +""" +Semantic deduplication + MMR (Maximal Marginal Relevance). + +Step 1: Remove near-duplicates (cosine similarity > 0.92). +Step 2: MMR — balance relevance (λ=0.6) vs diversity (1-λ=0.4). +""" +from __future__ import annotations + +import os + +import numpy as np + +from backend.rag.embedder import embed, embed_batch +from backend.rag.retrieval.hybrid import RetrievedChunk + +DEDUP_THRESHOLD = float(os.getenv("RAG_DEDUP_THRESHOLD", "0.92")) +MMR_LAMBDA = float(os.getenv("RAG_MMR_LAMBDA", "0.6")) + + +def _cosine(a: list[float], b: list[float]) -> float: + va, vb = np.array(a), np.array(b) + denom = np.linalg.norm(va) * np.linalg.norm(vb) + return float(np.dot(va, vb) / denom) if denom > 0 else 0.0 + + +def semantic_dedup( + chunks: list[RetrievedChunk], + threshold: float = DEDUP_THRESHOLD, +) -> list[RetrievedChunk]: + """Remove chunks whose text is >threshold cosine similar to an already-kept chunk.""" + if not chunks: + return [] + + texts = [ch.text for ch in chunks] + embeddings = embed_batch(texts) + + kept: list[RetrievedChunk] = [] + kept_embs: list[list[float]] = [] + + for chunk, emb in zip(chunks, embeddings): + is_dup = any(_cosine(emb, ke) >= threshold for ke in kept_embs) + if not is_dup: + kept.append(chunk) + kept_embs.append(emb) + + return kept + + +def mmr_select( + query: str, + chunks: list[RetrievedChunk], + lambda_: float = MMR_LAMBDA, + k: int | None = None, +) -> list[RetrievedChunk]: + """ + Maximal Marginal Relevance selection. + lambda_=0.6: 60% relevance weight, 40% diversity weight. + """ + if not chunks: + return [] + + top_k = k or len(chunks) + query_emb = np.array(embed(query)) + doc_embs = np.array(embed_batch([ch.text for ch in chunks])) + + # Relevance scores: cosine(query, doc) + norms = np.linalg.norm(doc_embs, axis=1, keepdims=True) + norms = np.where(norms == 0, 1, norms) + doc_embs_norm = doc_embs / norms + query_norm = query_emb / (np.linalg.norm(query_emb) or 1) + relevance = doc_embs_norm @ query_norm # shape: (n,) + + selected: list[int] = [] + remaining = list(range(len(chunks))) + + for _ in range(min(top_k, len(chunks))): + if not remaining: + break + + if not selected: + # Pick highest relevance first + best = max(remaining, key=lambda i: relevance[i]) + else: + # MMR score: λ·rel(i) - (1-λ)·max_sim(i, selected) + sel_embs = doc_embs_norm[selected] + scores = [] + for i in remaining: + sim_to_selected = float(np.max(doc_embs_norm[i] @ sel_embs.T)) + mmr_score = lambda_ * relevance[i] - (1 - lambda_) * sim_to_selected + scores.append((i, mmr_score)) + best = max(scores, key=lambda x: x[1])[0] + + selected.append(best) + remaining.remove(best) + + return [chunks[i] for i in selected] + + +def deduplicate_and_diversify( + query: str, + chunks: list[RetrievedChunk], + top_k: int, + dedup_threshold: float = DEDUP_THRESHOLD, + mmr_lambda: float = MMR_LAMBDA, +) -> list[RetrievedChunk]: + """Full dedup pipeline: semantic dedup → MMR select.""" + deduped = semantic_dedup(chunks, threshold=dedup_threshold) + return mmr_select(query, deduped, lambda_=mmr_lambda, k=top_k) diff --git a/backend/rag/retrieval/hybrid.py b/backend/rag/retrieval/hybrid.py new file mode 100644 index 0000000000000000000000000000000000000000..06fca69135b84f7a6da5639afc86aa92e5326404 --- /dev/null +++ b/backend/rag/retrieval/hybrid.py @@ -0,0 +1,155 @@ +""" +Hybrid retrieval: BM25 (sparse) + Qdrant (dense) fused via Reciprocal Rank Fusion. +BM25 is built on-the-fly from Qdrant scroll results filtered by ticker. +""" +from __future__ import annotations + +import os +from dataclasses import dataclass, field +from functools import lru_cache +from typing import Any + +import structlog +from qdrant_client import QdrantClient +from qdrant_client.models import Filter, FieldCondition, MatchValue +from rank_bm25 import BM25Okapi + +from backend.rag.embedder import embed +from backend.rag.ingestion.collections import get_client, collection_name + +log = structlog.get_logger() + +TOP_K = int(os.getenv("RAG_TOP_K", "8")) +OVER_RETRIEVE = int(os.getenv("RAG_OVER_RETRIEVE_FACTOR", "2")) +CANDIDATES = TOP_K * OVER_RETRIEVE # 16 by default +RRF_K = 60 + + +@dataclass +class RetrievedChunk: + id: str + text: str + score: float + metadata: dict[str, Any] = field(default_factory=dict) + + +def _ticker_filter(ticker: str) -> Filter: + return Filter(must=[FieldCondition(key="ticker", match=MatchValue(value=ticker))]) + + +def _scroll_collection(client: QdrantClient, col: str, ticker: str) -> list[dict]: + """Fetch chunks from a collection for BM25. ticker='' means no filter (global).""" + all_points: list[dict] = [] + offset = None + scroll_filter = _ticker_filter(ticker) if ticker else None + while True: + results, offset = client.scroll( + collection_name=col, + scroll_filter=scroll_filter, + limit=256, + offset=offset, + with_payload=True, + with_vectors=False, + ) + for r in results: + all_points.append({"id": str(r.id), "payload": r.payload or {}}) + if offset is None: + break + return all_points + + +def _rrf(ranked_lists: list[list[str]], k: int = RRF_K) -> list[tuple[str, float]]: + """Reciprocal Rank Fusion over lists of doc IDs.""" + scores: dict[str, float] = {} + for ranked in ranked_lists: + for rank, doc_id in enumerate(ranked): + scores[doc_id] = scores.get(doc_id, 0.0) + 1.0 / (k + rank + 1) + return sorted(scores.items(), key=lambda x: -x[1]) + + +def hybrid_search( + query: str, + ticker: str, + collection: str, + query_vector: list[float] | None = None, + client: QdrantClient | None = None, + limit: int = CANDIDATES, + allow_global_fallback: bool = False, +) -> list[RetrievedChunk]: + """ + BM25 + dense vector search, RRF-fused. + query_vector: pre-computed embedding (e.g. from HyDE). If None, embeds query. + allow_global_fallback: if True, retry without ticker filter when ticker yields no results. + Set False for news (unrelated articles worse than no context). + """ + c = client or get_client() + vec = query_vector if query_vector is not None else embed(query) + + # --- Dense retrieval (qdrant-client >=1.9 uses query_points, not search) --- + ticker_filter = _ticker_filter(ticker) if ticker else None + qr = c.query_points( + collection_name=collection, + query=vec, + query_filter=ticker_filter, + limit=limit, + with_payload=True, + ) + dense_results = qr.points + + # Fallback: only for collections where cross-ticker context is valid (e.g. historical) + if not dense_results and ticker and allow_global_fallback: + log.info("rag_ticker_fallback_global", ticker=ticker, collection=collection) + qr = c.query_points( + collection_name=collection, + query=vec, + limit=limit, + with_payload=True, + ) + dense_results = qr.points + dense_id_order = [str(r.id) for r in dense_results] + id_to_chunk: dict[str, RetrievedChunk] = { + str(r.id): RetrievedChunk( + id=str(r.id), + text=r.payload.get("text", "") if r.payload else "", + score=float(r.score), + metadata={k: v for k, v in (r.payload or {}).items() if k != "text"}, + ) + for r in dense_results + } + + # --- Sparse retrieval (BM25 over ticker corpus) --- + corpus_points = _scroll_collection(c, collection, ticker) + if not corpus_points and ticker and allow_global_fallback: + corpus_points = _scroll_collection(c, collection, "") # global fallback + + sparse_id_order: list[str] = [] + if corpus_points: + corpus_texts = [p["payload"].get("text", "") for p in corpus_points] + tokenized = [t.lower().split() for t in corpus_texts] + bm25 = BM25Okapi(tokenized) + scores = bm25.get_scores(query.lower().split()) + ranked_indices = sorted(range(len(scores)), key=lambda i: -scores[i]) + + for idx in ranked_indices[:limit]: + pt = corpus_points[idx] + doc_id = pt["id"] + sparse_id_order.append(doc_id) + if doc_id not in id_to_chunk: + id_to_chunk[doc_id] = RetrievedChunk( + id=doc_id, + text=pt["payload"].get("text", ""), + score=float(scores[idx]), + metadata={k: v for k, v in pt["payload"].items() if k != "text"}, + ) + + # --- RRF fusion --- + fused = _rrf([dense_id_order, sparse_id_order]) + + results: list[RetrievedChunk] = [] + for doc_id, rrf_score in fused[:limit]: + if doc_id in id_to_chunk: + chunk = id_to_chunk[doc_id] + chunk.score = rrf_score + results.append(chunk) + + return results diff --git a/backend/rag/retrieval/hyde.py b/backend/rag/retrieval/hyde.py new file mode 100644 index 0000000000000000000000000000000000000000..eb003ad417df5950809d991457a2266bf3a9cd42 --- /dev/null +++ b/backend/rag/retrieval/hyde.py @@ -0,0 +1,52 @@ +""" +HyDE — Hypothetical Document Embeddings. +Applied to HISTORICAL and NEWS intents with abstract queries. +Skipped for REAL_TIME. +""" +from __future__ import annotations + +import os + +import structlog +from groq import Groq + +from backend.rag.embedder import embed + +log = structlog.get_logger() + +_HYDE_MODEL = os.getenv("GROQ_MODEL_FAST", "llama-3.1-8b-instant") + +_HYDE_PROMPT = """\ +Generate a 2-sentence financial analyst note that would directly answer: "{query}" +Be specific: include data points, dates, percentages if possible. +Do not say "I don't know." Write as if you have access to market data.""" + + +def _get_groq() -> Groq: + return Groq(api_key=os.getenv("GROQ_API_KEY")) + + +def generate_hyde_embedding(query: str) -> list[float]: + """ + Generate a hypothetical document for the query, then embed it. + Falls back to embedding the raw query on any failure. + """ + try: + client = _get_groq() + resp = client.chat.completions.create( + model=_HYDE_MODEL, + messages=[{"role": "user", "content": _HYDE_PROMPT.format(query=query)}], + max_tokens=150, + temperature=0.3, + ) + hyde_doc = resp.choices[0].message.content or query + log.debug("hyde_generated", query_len=len(query), doc_len=len(hyde_doc)) + return embed(hyde_doc) + except Exception as exc: + log.warning("hyde_failed_fallback_to_query", error=str(exc)) + return embed(query) + + +def should_use_hyde(intent: str) -> bool: + """HyDE applies to historical and news intents, not real-time.""" + return intent in {"historical", "news", "fundamental", "comparative"} diff --git a/backend/rag/retrieval/reranker.py b/backend/rag/retrieval/reranker.py new file mode 100644 index 0000000000000000000000000000000000000000..7bf3611ac31c05a6848726fc7e360d7f70efc71e --- /dev/null +++ b/backend/rag/retrieval/reranker.py @@ -0,0 +1,87 @@ +""" +Cross-encoder reranking. +Primary: Cohere rerank-english-v3.0 (API) +Fallback: BAAI/bge-reranker-base (local HuggingFace) +""" +from __future__ import annotations + +import os +from functools import lru_cache + +import structlog + +from backend.rag.retrieval.hybrid import RetrievedChunk + +log = structlog.get_logger() + +TOP_K = int(os.getenv("RAG_TOP_K", "8")) +_COHERE_MODEL = "rerank-english-v3.0" + + +@lru_cache(maxsize=1) +def _get_bge_reranker(): + from sentence_transformers import CrossEncoder + model = os.getenv("RERANKER_MODEL", "BAAI/bge-reranker-base") + log.info("bge_reranker_loaded", model=model) + return CrossEncoder(model) + + +def _rerank_cohere(query: str, chunks: list[RetrievedChunk], top_k: int) -> list[RetrievedChunk]: + import cohere + api_key = os.getenv("COHERE_API_KEY") + if not api_key: + raise RuntimeError("COHERE_API_KEY not set") + + co = cohere.ClientV2(api_key=api_key) + response = co.rerank( + model=_COHERE_MODEL, + query=query, + documents=[ch.text for ch in chunks], + top_n=top_k, + ) + reranked: list[RetrievedChunk] = [] + for result in response.results: + chunk = chunks[result.index] + chunk.score = float(result.relevance_score) + reranked.append(chunk) + return reranked + + +def _rerank_bge(query: str, chunks: list[RetrievedChunk], top_k: int) -> list[RetrievedChunk]: + reranker = _get_bge_reranker() + pairs = [(query, ch.text) for ch in chunks] + scores = reranker.predict(pairs) + scored = sorted(zip(chunks, scores), key=lambda x: -float(x[1])) + result = [] + for chunk, score in scored[:top_k]: + chunk.score = float(score) + result.append(chunk) + return result + + +def rerank( + query: str, + chunks: list[RetrievedChunk], + top_k: int = TOP_K, +) -> list[RetrievedChunk]: + """ + Rerank chunks by relevance to query. + Tries Cohere first; falls back to BAAI/bge-reranker-base. + """ + if not chunks: + return [] + + provider = os.getenv("RERANKER_PROVIDER", "cohere").lower() + + if provider == "cohere": + try: + reranked = _rerank_cohere(query, chunks, top_k) + log.debug("reranker_cohere_ok", chunks_in=len(chunks), chunks_out=len(reranked)) + return reranked + except Exception as exc: + log.warning("cohere_rerank_failed_bge_fallback", error=str(exc)) + + # BGE fallback (or primary when RERANKER_PROVIDER=bge) + reranked = _rerank_bge(query, chunks, top_k) + log.debug("reranker_bge_ok", chunks_in=len(chunks), chunks_out=len(reranked)) + return reranked diff --git a/backend/rag/retrieval/router.py b/backend/rag/retrieval/router.py new file mode 100644 index 0000000000000000000000000000000000000000..3df4083f200799f767e626aec292f039a57b5ba7 --- /dev/null +++ b/backend/rag/retrieval/router.py @@ -0,0 +1,68 @@ +""" +Intent → retrieval branch mapping. +Maps each intent to: which collection, whether to use HyDE, retrieval config. +""" +from __future__ import annotations + +from dataclasses import dataclass +from typing import Literal + +Intent = Literal["real_time", "news", "historical", "fundamental", "comparative", "screener"] + + +@dataclass +class RetrievalBranch: + intent: Intent + collection: str # Qdrant collection key: 'news' | 'historical' | 'filings' + use_hyde: bool + description: str + allow_global_fallback: bool = False # historical OK; news must NOT return unrelated articles + + +_BRANCH_MAP: dict[str, RetrievalBranch] = { + "news": RetrievalBranch( + intent="news", + collection="news", + use_hyde=True, + description="News articles, analyst reports, press releases", + allow_global_fallback=False, + ), + "historical": RetrievalBranch( + intent="historical", + collection="historical", + use_hyde=True, + description="20yr OHLCV event patterns, earnings history, technicals", + allow_global_fallback=True, + ), + "fundamental": RetrievalBranch( + intent="fundamental", + collection="filings", + use_hyde=False, + description="SEC 10-K/10-Q filings, earnings transcripts", + allow_global_fallback=False, + ), + "comparative": RetrievalBranch( + intent="comparative", + collection="news", + use_hyde=True, + description="Cross-ticker or cross-sector comparison", + allow_global_fallback=False, + ), +} + +# Intents that skip RAG entirely (handled by live data nodes) +LIVE_ONLY_INTENTS = {"real_time", "screener"} + + +def get_branches(intents: list[Intent]) -> list[RetrievalBranch]: + """Return RAG branches for a set of intents, deduplicating collections.""" + seen_collections: set[str] = set() + branches: list[RetrievalBranch] = [] + for intent in intents: + if intent in LIVE_ONLY_INTENTS: + continue + branch = _BRANCH_MAP.get(intent) + if branch and branch.collection not in seen_collections: + branches.append(branch) + seen_collections.add(branch.collection) + return branches diff --git a/backend/rag/yahoo_client.py b/backend/rag/yahoo_client.py new file mode 100644 index 0000000000000000000000000000000000000000..30a607252bfc83efb748962ac12e425869b4f8aa --- /dev/null +++ b/backend/rag/yahoo_client.py @@ -0,0 +1,395 @@ +""" +Unified Yahoo Finance client using curl_cffi Chrome TLS impersonation. + +Replaces yfinance library for all data fetching. Works for all exchanges +(US, NSE India .NS, BSE .BO, LSE .L, etc.) without IP blocks. + +Session is a module-level singleton — one Chrome TLS session shared across +all requests. Cookie/crumb lifecycle managed automatically. +""" +from __future__ import annotations + +import os +import time +from functools import lru_cache + +import pandas as pd +import structlog + +log = structlog.get_logger() + +try: + from curl_cffi import requests as cffi_requests + _session = cffi_requests.Session(impersonate="chrome124") + _AVAILABLE = True +except ImportError: + _session = None + _AVAILABLE = False + log.error("curl_cffi_missing", fix="pip install curl_cffi") + +_BASE1 = "https://query1.finance.yahoo.com" +_BASE2 = "https://query2.finance.yahoo.com" + +_crumb: str | None = None +_crumb_ts: float = 0.0 +_CRUMB_TTL = 3600 # seconds + + +def _get_crumb() -> str: + global _crumb, _crumb_ts + if _crumb and time.time() - _crumb_ts < _CRUMB_TTL: + return _crumb + 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 _crumb + except Exception as exc: + log.warning("crumb_fetch_failed", error=str(exc)) + return "" + + +def _warm_session(ticker: str) -> None: + """One chart request primes session cookies; crumb then works.""" + try: + _session.get( + f"{_BASE1}/v8/finance/chart/{ticker}", + params={"range": "5d", "interval": "1d"}, + timeout=10, + ) + except Exception: + pass + + +# ── OHLCV ────────────────────────────────────────────────────────────────── + +def fetch_ohlcv( + ticker: str, + years: int = 20, + interval: str = "1wk", + days: int | None = None, + range_str: str | None = None, +) -> pd.DataFrame: + """OHLCV for any ticker. Pass range_str (e.g. '1mo','3mo','1y') or days for intraday.""" + if not _AVAILABLE: + return pd.DataFrame() + + url = f"{_BASE1}/v8/finance/chart/{ticker}" + if not range_str: + range_str = f"{days}d" if days else f"{min(years, 20)}y" + params = { + "range": range_str, + "interval": interval, + "includePrePost": "false", + "events": "history", + } + try: + r = _session.get(url, params=params, timeout=20) + if r.status_code != 200: + log.warning("ohlcv_http_error", ticker=ticker, status=r.status_code) + return pd.DataFrame() + + data = r.json() + chart_result = data.get("chart", {}).get("result", []) + if not chart_result: + return pd.DataFrame() + + chart = chart_result[0] + timestamps = chart.get("timestamp", []) + if not timestamps: + return pd.DataFrame() + + quote = chart.get("indicators", {}).get("quote", [{}])[0] + adj_list = chart.get("indicators", {}).get("adjclose", [{}]) + adjclose = adj_list[0].get("adjclose", []) if adj_list else [] + + rows = [] + for i, ts in enumerate(timestamps): + close_val = ( + adjclose[i] if i < len(adjclose) and adjclose[i] + else (quote.get("close") or [None])[i] if i < len(quote.get("close") or []) else None + ) + if close_val is None: + continue + rows.append({ + "Open": (quote.get("open") or [None])[i] if i < len(quote.get("open") or []) else None, + "High": (quote.get("high") or [None])[i] if i < len(quote.get("high") or []) else None, + "Low": (quote.get("low") or [None])[i] if i < len(quote.get("low") or []) else None, + "Close": close_val, + "Volume": (quote.get("volume") or [0])[i] or 0, + }) + + if not rows: + return pd.DataFrame() + + idx = pd.to_datetime(timestamps[: len(rows)], unit="s", utc=True).tz_localize(None) + return pd.DataFrame(rows, index=idx).dropna(subset=["Close"]) + + except Exception as exc: + log.warning("ohlcv_fetch_failed", ticker=ticker, error=str(exc)) + return pd.DataFrame() + + +# ── Real-time quote ──────────────────────────────────────────────────────── + +def fetch_quote(ticker: str) -> dict: + """Real-time price, change, volume from v8 chart (1d/2m interval).""" + if not _AVAILABLE: + return {"ticker": ticker, "error": "curl_cffi unavailable"} + + try: + r = _session.get( + f"{_BASE1}/v8/finance/chart/{ticker}", + params={"range": "1d", "interval": "2m", "includePrePost": "false"}, + timeout=15, + ) + data = r.json() + chart_result = data.get("chart", {}).get("result", []) + if not chart_result: + return {"ticker": ticker, "price": None} + + meta = 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 None + pct_change = round(change / prev_close * 100, 2) if change and prev_close else None + + # Intraday OHLC from timestamps + quote = 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, + "price": price, + "prev_close": prev_close, + "change": change, + "pct_change": pct_change, + "volume": sum(volumes) if volumes else meta.get("regularMarketVolume"), + "avg_volume_3m": meta.get("averageDailyVolume3Month"), + "market_cap": meta.get("marketCap"), + "open": opens[0] if opens else None, + "high": max(highs) if highs else None, + "low": min(lows) if lows else None, + "currency": meta.get("currency", "USD"), + "exchange": meta.get("exchangeName"), + "timestamp": meta.get("regularMarketTime"), + } + except Exception as exc: + log.warning("quote_fetch_failed", ticker=ticker, error=str(exc)) + return {"ticker": ticker, "error": str(exc)} + + +# ── Live news ───────────────────────────────────────────────────────────── + +def fetch_news(ticker: str, count: int = 8) -> list[dict]: + """ + Live news for a ticker via Google News RSS (no API key needed). + Handles both Indian (.NS / .BO) and US/global tickers. + """ + if not _AVAILABLE: + return [] + try: + import datetime as _dt + import xml.etree.ElementTree as _ET + + # Build locale-aware query + is_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"} + else: + query = f"{base} stock" + params = {"q": query, "hl": "en-US", "gl": "US", "ceid": "US:en"} + + r = _session.get("https://news.google.com/rss/search", params=params, timeout=10) + if r.status_code != 200: + log.warning("news_rss_error", ticker=ticker, status=r.status_code) + return [] + + root = _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, + "published_at": date_str, + "ticker": ticker, + "live": True, + }) + log.info("news_rss_ok", ticker=ticker, count=len(results)) + return results + except Exception as exc: + log.warning("news_fetch_failed", ticker=ticker, error=str(exc)) + return [] + + +# ── Fundamentals ─────────────────────────────────────────────────────────── + +def 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"] = crumb + + try: + r = _session.get( + f"{_BASE1}/v10/finance/quoteSummary/{ticker}", + params=params, + timeout=15, + ) + data = r.json() + result = data.get("quoteSummary", {}).get("result", []) + if not result: + return {"ticker": ticker} + + item = result[0] + sd = item.get("summaryDetail", {}) + fd = item.get("financialData", {}) + ks = item.get("defaultKeyStatistics", {}) + recs = item.get("recommendationTrend", {}).get("trend", []) + + buy = hold = sell = 0 + if recs: + r0 = recs[0] + buy = r0.get("strongBuy", 0) + r0.get("buy", 0) + hold = r0.get("hold", 0) + sell = r0.get("sell", 0) + r0.get("strongSell", 0) + + def _raw(d: dict, key: str): + v = d.get(key) + if isinstance(v, dict): + return v.get("raw") + return v + + return { + "ticker": ticker, + "pe": _raw(sd, "trailingPE"), + "forward_pe": _raw(sd, "forwardPE"), + "eps": _raw(ks, "trailingEps"), + "revenue": _raw(fd, "totalRevenue"), + "revenue_growth": _raw(fd, "revenueGrowth"), + "gross_margin": _raw(fd, "grossMargins"), + "operating_margin": _raw(fd, "operatingMargins"), + "net_margin": _raw(fd, "profitMargins"), + "debt_to_equity": _raw(fd, "debtToEquity"), + "current_ratio": _raw(fd, "currentRatio"), + "roe": _raw(fd, "returnOnEquity"), + "market_cap": _raw(sd, "marketCap"), + "avg_volume_3m": _raw(sd, "averageVolume"), + "dividend_yield": _raw(sd, "dividendYield"), + "beta": _raw(sd, "beta"), + "week_52_high": _raw(sd, "fiftyTwoWeekHigh"), + "week_52_low": _raw(sd, "fiftyTwoWeekLow"), + "analyst_consensus": {"buy": buy, "hold": hold, "sell": sell, + "avg_target": _raw(fd, "targetMeanPrice")}, + } + except Exception as exc: + log.warning("fundamentals_fetch_failed", ticker=ticker, error=str(exc)) + return {"ticker": ticker, "error": str(exc)} + + +def fetch_company_info(ticker: str) -> dict: + """Company profile: business summary, industry, country, employees, website.""" + if not _AVAILABLE: + return {} + try: + _warm_session(ticker) + crumb = _get_crumb() + params: dict = {"modules": "assetProfile"} + if crumb: + params["crumb"] = crumb + r = _session.get( + f"{_BASE1}/v10/finance/quoteSummary/{ticker}", + params=params, + timeout=12, + ) + data = r.json() + result = data.get("quoteSummary", {}).get("result", []) + if not result: + return {} + ap = result[0].get("assetProfile", {}) + if not ap: + return {} + return { + "industry": ap.get("industry"), + "country": ap.get("country"), + "city": ap.get("city"), + "website": ap.get("website"), + "full_time_employees": ap.get("fullTimeEmployees"), + "business_summary": ap.get("longBusinessSummary"), + } + except Exception as exc: + log.warning("company_info_fetch_failed", ticker=ticker, error=str(exc)) + return {} + + +# ── Sector ETF performance ───────────────────────────────────────────────── + +_SECTOR_ETFS: list[tuple[str, str]] = [ + ("XLK", "Technology"), + ("XLV", "Healthcare"), + ("XLF", "Financials"), + ("XLE", "Energy"), + ("XLY", "Consumer Disc."), + ("XLP", "Consumer Staples"), + ("XLB", "Materials"), + ("XLI", "Industrials"), + ("XLU", "Utilities"), + ("XLRE", "Real Estate"), + ("XLC", "Comm. Services"), + ("SOXX", "Semiconductors"), +] + + +def fetch_sector_etfs() -> list[dict]: + """ + Fetch daily % change for 12 US sector ETFs. + Returns [{sector, etf, return_pct, price}]. + """ + results = [] + for etf, label in _SECTOR_ETFS: + try: + q = fetch_quote(etf) + pct = q.get("pct_change") + price = q.get("price") + if pct is not None: + results.append({ + "sector": label, + "etf": etf, + "return_pct": round(float(pct), 2), + "price": round(float(price), 2) if price else None, + }) + except Exception: + continue + return results diff --git a/backend/scripts/build_universe.py b/backend/scripts/build_universe.py new file mode 100644 index 0000000000000000000000000000000000000000..7ea4e5db096af0704626aa7e45322a1eab778970 --- /dev/null +++ b/backend/scripts/build_universe.py @@ -0,0 +1,199 @@ +#!/usr/bin/env python3 +""" +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 io +import json +import sys +import time +from pathlib import Path + +import requests + +# backend/data/universe/stocks.json — committed to git, baked into Docker image +OUTPUT = Path(__file__).parent.parent / "data" / "universe" / "stocks.json" +OUTPUT.parent.mkdir(parents=True, exist_ok=True) + +_HEADERS = { + "User-Agent": ( + "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/124.0 Safari/537.36" + ), + "Accept-Language": "en-US,en;q=0.9", +} + + +def _html_tables(url: str) -> list: + import pandas as pd + resp = requests.get(url, headers=_HEADERS, timeout=30) + resp.raise_for_status() + return pd.read_html(io.StringIO(resp.text), header=0) + + +def fetch_sp500() -> list[dict]: + print("Fetching S&P 500 from Wikipedia...") + tables = _html_tables("https://en.wikipedia.org/wiki/List_of_S%26P_500_companies") + df = tables[0] + + stocks = [] + for _, row in df.iterrows(): + ticker = str(row.get("Symbol", row.get("Ticker symbol", ""))).strip().replace(".", "-") + name = str(row.get("Security", row.get("Company", ""))).strip() + sector = str(row.get("GICS Sector", row.get("Sector", ""))).strip() + if not ticker or not name: + continue + stocks.append({ + "ticker": ticker, + "yf_ticker": ticker, + "name": name, + "exchange": "NYSE/NASDAQ", + "sector": sector, + "country": "US", + "currency": "USD", + }) + + print(f" S&P 500: {len(stocks)} stocks") + return stocks + + +def 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 column + df = None + for 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 = t + break + if 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 ticker + sector = str(row[sect_col]).strip() if sect_col else "" + if not ticker or ticker == "nan": + continue + yf_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 stocks + + except 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() + time.sleep(1) + nifty50 = fetch_nifty50() + + # Deduplicate by yf_ticker + seen: set[str] = set() + all_stocks: list[dict] = [] + for s in sp500 + nifty50: + key = s["yf_ticker"].upper() + if key not in seen: + seen.add(key) + all_stocks.append(s) + + print(f"\nTotal universe: {len(all_stocks)} stocks") + OUTPUT.write_text(json.dumps(all_stocks, indent=2, ensure_ascii=False)) + print(f"Written → {OUTPUT}") + + +if __name__ == "__main__": + try: + build() + except Exception as exc: + print(f"ERROR: {exc}", file=sys.stderr) + sys.exit(1) diff --git a/backend/scripts/eval_rag.py b/backend/scripts/eval_rag.py new file mode 100644 index 0000000000000000000000000000000000000000..0630355d2407640c3aaac7c7c01b69e8d0847ee0 --- /dev/null +++ b/backend/scripts/eval_rag.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python3 +""" +RAGAS evaluation suite for Finora RAG pipeline. + +Usage: + python scripts/eval_rag.py --tickers AAPL MSFT NVDA RELIANCE.NS + python scripts/eval_rag.py --tickers AAPL --collection historical --n 10 + python scripts/eval_rag.py --tickers AAPL --output backend/data/eval_results/ragas_20260424.json +""" +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +BACKEND = ROOT / "backend" + +sys.path.insert(0, str(BACKEND)) + +from dotenv import load_dotenv +load_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_dataset + qa_pairs = generate_synthetic_dataset( + tickers=args.tickers, + collection_key=args.collection, + n_per_ticker=args.n, + ) + print(f"Generated {len(qa_pairs)} QA pairs") + + if not qa_pairs: + print("No QA pairs generated — check Qdrant data for these tickers.") + sys.exit(1) + + print("\nRunning RAGAS evaluation...") + from backend.rag.evaluation.ragas_eval import TARGETS, run_ragas_eval + report = run_ragas_eval(qa_pairs, tickers=args.tickers) + + if "error" in report: + print(f"Eval failed: {report['error']}") + sys.exit(1) + + print("\n── RAGAS Results ──────────────────────────") + for metric, result in report.get("results", {}).items(): + status = "✓ PASS" if result["passed"] else "✗ FAIL" + target_label = f"< {result['target']}" if metric == "noise_sensitivity" else f"> {result['target']}" + print(f" {metric:<25} {result['score']:.4f} (target {target_label}) {status}") + print(f"\nOverall: {'PASS ✓' if report.get('overall_pass') else 'FAIL ✗'}") + + import datetime + report["run_at"] = datetime.datetime.utcnow().isoformat() + "Z" + report["tickers"] = args.tickers + + # Always save latest.json for /api/eval/latest endpoint + latest_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() diff --git a/backend/scripts/ingest_historical.py b/backend/scripts/ingest_historical.py new file mode 100644 index 0000000000000000000000000000000000000000..bd518248de7ed9e7b4f8a3f7fa12153835556e94 --- /dev/null +++ b/backend/scripts/ingest_historical.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python3 +""" +Seed 20yr OHLCV data into Qdrant (finora_historical collection). + +Usage: + python scripts/ingest_historical.py --tickers AAPL MSFT NVDA RELIANCE.NS --years 20 + python scripts/ingest_historical.py --all --years 20 + python scripts/ingest_historical.py --tickers AAPL --years 5 +""" + +import argparse +import json +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +BACKEND = ROOT / "backend" + +sys.path.insert(0, str(BACKEND)) + +from dotenv import load_dotenv +load_dotenv(ROOT / ".env") + +from backend.rag.ingestion.collections import ensure_collections, get_client +from backend.rag.ingestion.historical import ingest_ticker, ingest_universe + +UNIVERSE_PATH = Path(__file__).parent.parent / "data" / "universe" / "stocks.json" + + +def load_universe() -> list[dict]: + if not UNIVERSE_PATH.exists(): + print(f"ERROR: Universe not found at {UNIVERSE_PATH}. Run build_universe.py first.") + sys.exit(1) + with open(UNIVERSE_PATH) as f: + return json.load(f) + + +def main() -> None: + parser = argparse.ArgumentParser(description="Ingest historical OHLCV into Qdrant") + parser.add_argument("--tickers", nargs="+", help="Tickers to ingest (e.g. AAPL MSFT RELIANCE.NS)") + parser.add_argument("--all", action="store_true", help="Ingest full universe (~553 tickers)") + parser.add_argument("--years", type=int, default=20, help="Years of history (default: 20)") + parser.add_argument("--delay", type=float, default=3.0, help="Seconds between tickers (default: 3)") + args = parser.parse_args() + + if not args.tickers and not args.all: + parser.print_help() + sys.exit(1) + + client = get_client() + print("Connected to Qdrant.") + ensure_collections(client) + print("Collections ready.") + + universe = load_universe() + ticker_map = {s["ticker"].upper(): s for s in universe} + ticker_map.update({s.get("yf_ticker", "").upper(): s for s in universe}) + + stocks = universe if args.all else [ + ticker_map.get(t.upper(), {"ticker": t, "yf_ticker": t, "name": t}) + for t in (args.tickers or []) + ] + + print(f"\nIngesting {len(stocks)} ticker(s) — {args.years}yr history...\n") + + if len(stocks) == 1: + s = stocks[0] + n = ingest_ticker(s["ticker"], s.get("yf_ticker", s["ticker"]), args.years, client) + print(f"{s['ticker']}: {n} chunks") + else: + results = ingest_universe(stocks, years=args.years, delay_seconds=args.delay) + total = sum(results.values()) + success = sum(1 for v in results.values() if v > 0) + print(f"\nDone: {success}/{len(stocks)} tickers, {total} total chunks") + failures = [t for t, v in results.items() if v == 0] + if failures: + print(f"Zero chunks (failed/delisted): {failures[:20]}") + + +if __name__ == "__main__": + main() diff --git a/backend/scripts/ingest_news.py b/backend/scripts/ingest_news.py new file mode 100644 index 0000000000000000000000000000000000000000..b70a50a5cdb669a0ec536d81f99e306cb5f637e0 --- /dev/null +++ b/backend/scripts/ingest_news.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python3 +""" +Seed news corpus into Qdrant (finora_news collection) via NewsAPI. + +Usage: + python scripts/ingest_news.py --tickers AAPL MSFT NVDA RELIANCE --days 7 + python scripts/ingest_news.py --all --days 3 +""" + +import argparse +import json +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +BACKEND = ROOT / "backend" + +sys.path.insert(0, str(BACKEND)) + +from dotenv import load_dotenv +load_dotenv(ROOT / ".env") + +from backend.rag.ingestion.collections import ensure_collections, get_client +from backend.rag.ingestion.news import ingest_ticker, ingest_universe + +UNIVERSE_PATH = Path(__file__).parent.parent / "data" / "universe" / "stocks.json" + + +def load_universe() -> list[dict]: + if not UNIVERSE_PATH.exists(): + print(f"ERROR: Universe not found. Run build_universe.py first.") + sys.exit(1) + with open(UNIVERSE_PATH) as f: + return json.load(f) + + +def main() -> None: + parser = argparse.ArgumentParser(description="Ingest news into Qdrant") + parser.add_argument("--tickers", nargs="+", help="Tickers to ingest") + parser.add_argument("--all", action="store_true", help="Ingest full universe (caution: 100 req/day limit)") + parser.add_argument("--days", type=int, default=7, help="Days of news history (default: 7)") + args = parser.parse_args() + + if not args.tickers and not args.all: + parser.print_help() + sys.exit(1) + + client = get_client() + print("Connected to Qdrant.") + ensure_collections(client) + print("Collections ready.") + + universe = load_universe() + ticker_map = {s["ticker"].upper(): s for s in universe} + + stocks = universe if args.all else [ + ticker_map.get(t.upper(), {"ticker": t, "yf_ticker": t, "name": t}) + for t in (args.tickers or []) + ] + + # NewsAPI free tier: 100 req/day. Each ticker = 1 request. + if len(stocks) > 90: + print(f"WARNING: {len(stocks)} tickers requested but NewsAPI free tier = 100 req/day.") + print("Capping at 90 to leave buffer.") + stocks = stocks[:90] + + print(f"\nIngesting news for {len(stocks)} ticker(s) — last {args.days} day(s)...\n") + + if len(stocks) == 1: + s = stocks[0] + n = ingest_ticker(s["ticker"], s.get("name", s["ticker"]), days=args.days, client=client) + print(f"{s['ticker']}: {n} chunks") + else: + results = ingest_universe(stocks, days=args.days) + total = sum(results.values()) + success = sum(1 for v in results.values() if v > 0) + print(f"\nDone: {success}/{len(stocks)} tickers, {total} total chunks") + + +if __name__ == "__main__": + main() diff --git a/requirements-dev.txt b/requirements-dev.txt new file mode 100644 index 0000000000000000000000000000000000000000..431cfc9a704cd301de52c3634019d894a2241a0e --- /dev/null +++ b/requirements-dev.txt @@ -0,0 +1,26 @@ +# ============================================================================= +# 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 + +# Evaluation +ragas==0.2.5 +datasets==3.1.0 + +# Testing +pytest==8.3.3 +pytest-asyncio==0.24.0 +pytest-cov==5.0.0 + +# Linting / formatting +ruff==0.7.1 +black==24.10.0 +mypy==1.13.0 diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..5c5ff880d483e7925f8584d5c6aefd397a4a3ffe --- /dev/null +++ b/requirements.txt @@ -0,0 +1,70 @@ +# ============================================================================= +# FINORA BACKEND — Production Dependencies +# For HuggingFace deployment. Dev/eval/MCP tools are in requirements-dev.txt. +# ============================================================================= + +# Web framework +fastapi==0.115.0 +uvicorn[standard]==0.30.6 +python-multipart==0.0.9 +httpx>=0.27.0,<0.28.0 + +# Validation +pydantic==2.9.2 +pydantic-settings==2.5.2 + +# Rate limiting +slowapi==0.1.9 + +# LLM — Groq +groq==0.11.0 + +# Agent graph +langgraph==0.2.55 +langgraph-checkpoint==2.0.6 + +# RAG / LangChain +langchain==0.3.7 +langchain-community==0.3.7 +langchain-groq==0.2.1 +langchain-qdrant==0.2.0 +langsmith==0.1.147 + +# Vector store +qdrant-client==1.11.3 + +# Reranker — Cohere primary, BAAI/bge-reranker-base local fallback +cohere==5.11.4 + +# Embeddings + local reranker fallback (HuggingFace) +sentence-transformers==3.2.1 +transformers==4.46.3 +torch==2.4.1 + +# Sparse retrieval +rank-bm25==0.2.2 + +# Fuzzy search +rapidfuzz==3.10.1 + +# Financial data — all fetching via curl_cffi Chrome TLS impersonation (no API key needed) +curl_cffi==0.15.0 +polygon-api-client==1.14.2 +pandas==2.2.3 +lxml==5.3.0 +html5lib==1.1 + +# News +newsapi-python==0.2.7 + +# SEC filings +unstructured==0.15.14 +requests==2.32.3 + +# Scheduling +apscheduler==3.10.4 + +# Logging +structlog==24.4.0 +python-dotenv==1.0.1 +openai>=1.0.0