CoolFace
Apppublic

Celtic29/YC-FinSight

sourceHugging Facemitupdated 4mo agoView on Hugging Face
0likes
App README

YC FinSight

An AI-powered U.S. stock analysis tool by YC Intelligence, built with a Retrieval-Augmented Generation (RAG) pipeline. Look up any stock's price history and analyst ratings, then ask the AI for a grounded buy/hold/sell analysis — all in one place.


Architecture

┌─────────────────────────────────────────────────────┐
│                     frontend/                        │
│         Next.js 14 · TypeScript · Tailwind           │
│              GSAP + ScrollTrigger                    │
│                                                      │
│   Landing Page → Stock Lookup → AI Chat              │
└──────────────────────┬──────────────────────────────┘
                       │ HTTP (fetch / axios)
┌──────────────────────▼──────────────────────────────┐
│                     backend/                         │
│              Flask · Python 3.10                     │
│                                                      │
│  POST /assistant   →  RAG (FAISS + Gemini)           │
│  GET  /stock       →  Yahoo Finance (price + ratings)│
└─────────────────────────────────────────────────────┘

The frontend and backend are fully decoupled. Flask serves only JSON API responses — no HTML templates. Next.js owns all UI, routing, and animations.


Tech Stack

LayerTechnology
Frontend FrameworkNext.js 14 (App Router) + TypeScript
StylingTailwind CSS + shadcn/ui
AnimationsGSAP + ScrollTrigger
ChartsRecharts
Backend APIFlask + Flask-CORS
LLMGoogle Gemini 2.0 Flash
Embedding Modelall-MiniLM-L6-v2 (Sentence Transformers)
Vector StoreFAISS
Stock DataYahoo Finance (yfinance)
DatabaseMongoDB Atlas (TLS/X.509 auth)

How the RAG System Works

RAG (Retrieval-Augmented Generation) gives the LLM access to up-to-date, domain-specific knowledge without retraining. This project implements it in three stages:

1. Ingestion & Embedding (Offline Pipeline)

Yahoo Finance scraper
        ↓
  MongoDB Atlas
  (stock_data collection)
        ↓
  training_embedding.py
  (exports all documents → data/output.json)
        ↓
  embedding.py
  (encodes each article with all-MiniLM-L6-v2,
   builds a FAISS index, saves to faiss_db/)
  • —training_embedding.py connects to MongoDB via TLS certificate, fetches all scraped news articles, and dumps them to data/output.json.
  • —embedding.py reads the JSON, attaches metadata (title, date, company) to each document, encodes article content using SentenceTransformerEmbeddings, and saves a binary FAISS index (american-stock-fun.faiss + american-stock-fun.pkl).
  • —crontab.sh schedules the full pipeline to run automatically, keeping the vector store fresh.

2. Retrieval (At Query Time)

When a user sends a message from the Next.js frontend:

  1. 1.Frontend POSTs { message } to Flask /assistant.
  2. 2.stock_assistant.py loads the pre-built FAISS index from faiss_db/.
  3. 3.Encodes the query with all-MiniLM-L6-v2 and performs cosine similarity search, retrieving the top-5 most relevant articles with scores.

3. Augmentation & Generation

  1. 1.Retrieved titles, content, and scores are formatted into a context block.
  2. 2.A system prompt defines the role: "You are a professional analyst specializing in the U.S. stock market..."
  3. 3.The combined prompt (role + context + user query) is sent to Gemini 2.0 Flash.
  4. 4.Gemini returns a concise analysis (≤ 200 words) with a buy/sell/hold stance grounded in the retrieved news.
User query (Next.js)
    ↓  POST /assistant
FAISS similarity search (top-5 articles)
    ↓
Prompt = role_description + retrieved_info + user_query
    ↓
Gemini 2.0 Flash
    ↓
JSON { text: "..." }  →  Next.js chat UI

Query filtering: greetings return "Hello, user"; off-topic inputs are rejected; queries are matched against US market keywords (NASDAQ, NYSE, S&P 500, Dow Jones), ticker regex, and a list of 50 known companies.


Project Structure

YC-FinSight/
│
├── backend/                          # Flask micro-API (Python)
│   ├── app.py                        # Entry point — API routes only, no templates
│   ├── stock_assistant.py            # RAG: FAISS retrieval + Gemini generation
│   ├── yahoofinance.py               # Yahoo Finance: 1yr price history + analyst ratings
│   ├── members.py                    # User registration (SHA-256 + email verification)
│   ├── embedding.py                  # One-time: builds FAISS index from output.json
│   ├── training_embedding.py         # One-time: exports MongoDB → data/output.json
│   ├── requirements.txt
│   ├── Dockerfile
│   ├── crontab.sh                    # Schedules data refresh pipeline
│   ├── scrap_cert.pem                # MongoDB TLS certificate (never commit)
│   ├── config.ini                    # Gemini API key for local dev (never commit)
│   ├── faiss_db/
│   │   ├── american-stock-fun.faiss  # Vector index (~976 KB)
│   │   └── american-stock-fun.pkl    # Metadata + text store (~3.4 MB)
│   └── data/
│       └── output.json               # Stock news documents
│
└── frontend/                         # Next.js app (TypeScript)
    ├── app/
    │   ├── layout.tsx                # Root layout (fonts, global providers)
    │   ├── page.tsx                  # Landing page (GSAP scroll animations)
    │   ├── stock/
    │   │   └── page.tsx              # Stock lookup: price chart + analyst ratings
    │   └── chat/
    │       └── page.tsx              # AI chat interface (RAG)
    ├── components/
    │   ├── ui/                       # shadcn/ui base components
    │   ├── StockChart.tsx            # Recharts price line chart
    │   ├── RatingsChart.tsx          # Recharts doughnut for buy/hold/sell
    │   ├── ChatBox.tsx               # Chat UI — sends to Flask /assistant
    │   └── animations/               # GSAP scroll animation wrappers
    ├── lib/
    │   └── api.ts                    # Typed fetch helpers for Flask endpoints
    ├── public/                       # Static assets (logo, images)
    ├── package.json
    ├── tailwind.config.ts
    └── tsconfig.json

Backend API Endpoints

MethodRouteDescription
POST/assistantRAG chat — body: { message: string } → { text: string }
GET/stockYahoo Finance — query: ?symbol=NVDA → { ratings, stock_data }
POST/login/registerUser registration — body: { username, email, password }

Local Development

Backend

bash
cd backend
pip install -r requirements.txt
# create config.ini with your Gemini API key
python app.py
# runs on http://localhost:7860

Frontend

bash
cd frontend
npm install
npm run dev
# runs on http://localhost:3000

Set NEXT_PUBLIC_API_URL=http://localhost:7860 in frontend/.env.local.


HuggingFace Spaces Deployment

The backend/ is deployed as a Docker Space at huggingface.co/spaces/Celtic29/YC-FinSight.

Add GEMINI_API_KEY as a Space Secret — the app reads it via os.environ with config.ini as a local fallback.


Example Chat

User:  What is the outlook for NVIDIA stock?

Bot:   Based on recent reports, NVIDIA continues to demonstrate strong momentum
       driven by surging AI chip demand. The company's data center revenue has
       shown consecutive quarters of record growth. Analyst consensus leans
       bullish, with price targets ranging $130–$160. Key risks include export
       restrictions on advanced chips to China and potential demand softening in
       the consumer GPU segment. Recommendation: BUY on dips, with a mid-term
       target of $150.

Security Notes

  • —config.ini and scrap_cert.pem are in .gitignore — never commit them.
  • —Use HuggingFace Space Secrets or environment variables for all API keys in production.
  • —User passwords are hashed with SHA-256 + salt before storage.

License

MIT