Skip to content

MyNameIsTarun/sip

Repository files navigation

Stock Intelligence Platform (SIP)

An AI-powered personal stock analysis tool that brings together real-time financial data, technical indicators, and investment frameworks from classic finance books (Graham, Lynch, Greenblatt) to deliver structured, book-backed analysis on any NSE/BSE or US stock. Every verdict comes with a plain-English explanation of the reasoning, framework scores across five dimensions, target price, stop-loss, and a curated news summary — all through a clean, chat-style interface running entirely on your own machine.

SIP is designed for a single user running locally. Cost is a first-class concern: a built-in budget manager enforces a configurable monthly LLM spend limit (default $8/month), automatically downgrades to a faster/cheaper model when usage climbs past 80%, and hard-blocks further calls at the limit — so your API bill can never surprise you.


Prerequisites

Requirement Version
Python 3.11+
Node.js 20+
Docker + Docker Compose 24+ (for containerised setup)

API keys required:


Quick Start (Docker — recommended)

# 1. Clone and enter the project
git clone <repo-url>
cd sip

# 2. Create your .env from the template
cp .env.example .env

# 3. Fill in your API keys in .env
#    ANTHROPIC_API_KEY=sk-ant-...
#    ALPHA_VANTAGE_KEY=...
#    FINNHUB_KEY=...

# 4. Build and start both services
docker-compose up --build

# App will be available at:
#   Frontend: http://localhost:5173
#   Backend API: http://localhost:8000
#   API docs:    http://localhost:8000/api/docs

To stop: docker-compose down

To persist data between restarts the sip_data Docker volume stores all cache, usage tracking, and your portfolio/watchlist files automatically.


Development Setup (without Docker)

Backend

cd backend

# Create a virtual environment
python -m venv .venv
source .venv/bin/activate      # Windows: .venv\Scripts\activate

# Install dependencies
pip install -r requirements.txt

# Copy and fill in env
cp ../.env.example ../.env
# Edit .env with your API keys

# Start the FastAPI server (hot-reload)
uvicorn backend.main:app --reload --port 8000

Frontend

cd frontend

# Install dependencies
npm install

# Start the Vite dev server (proxies /api/ to localhost:8000)
npm run dev
# → http://localhost:5173

Both servers must be running simultaneously during development.


How to Use the App

Analysing a Stock

  1. Open http://localhost:5173
  2. Type your question in the search bar, e.g.:
    • "Analyze RELIANCE.NS for long-term investment"
    • "Is INFY.NS overbought right now?"
    • "Compare HDFCBANK.NS vs ICICIBANK.NS"
  3. Select an intent chip (Deep Analysis, Quick Check, Compare, Sector Scan, Portfolio) or let the classifier auto-detect intent
  4. Hit Analyse — results typically arrive in 5–15 seconds

Reading the Analysis Card

┌───────────────────────────────────────────┐
│ TICKER — Company Name   [VERDICT BADGE]   │
│ Exchange | Sector | Market Cap            │
├─────────┬──────┬──────┬────────┬──────────┤
│  Price  │  P/E │  P/B │  RSI   │  ROE     │
├─────────┴──────┴──────┴────────┴──────────┤
│ [Graham] [Lynch] [Technical] [News/Macro] │  ← Tabs
├───────────────────────────────────────────┤
│  Plain-English Summary                    │
├───────────────────────────────────────────┤
│  ✅ Key Positives    ⚠️  Key Risks       │
├───────────────────────────────────────────┤
│  Target: ₹X  |  Stop Loss: ₹X             │
└───────────────────────────────────────────┘

Hover over any technical term (RSI, MACD, P/E, etc.) for a plain-English tooltip definition.

Portfolio Tracking

  • Add a holding: Settings → Portfolio → Add (ticker, quantity, buy price, date)
  • View P&L: Portfolio table shows live current price, unrealised gain/loss
  • Portfolio Review: Click "Review Portfolio" to get an LLM-powered rebalancing suggestion

Watchlist & Screener

  • Add tickers to your watchlist from the Settings panel
  • Use the Screener to filter your watchlist by criteria (P/E < 20, ROE > 15, etc.)

Budget Indicator

A persistent banner in the top bar shows your monthly LLM spend:

Colour Meaning
Hidden Normal (0–60%)
Amber Warning (60–80%)
Orange Budget Mode — Haiku model active (80–95%)
Red Near limit (95–99%)
Red (full-width) Hard stop — no more LLM calls this month (≥100%)

You can reset or adjust the limit in .envMONTHLY_SPEND_LIMIT_USD.


Knowledge Base Population

The investment framework (Graham, Lynch, Greenblatt, Fisher, O'Neil, Damodaran) is stored in backend/knowledge_base.txt. The placeholder is functional but produces generic output. For best results, follow the extraction guide:

→ docs/KNOWLEDGE_BASE_GUIDE.md

This guide walks you through uploading each book PDF to Claude.ai and pasting the structured extracts into knowledge_base.txt. No book content is committed to this repo.


Supported Tickers

Market Format Example
NSE India SYMBOL.NS RELIANCE.NS
BSE India SYMBOL.BO RELIANCE.BO
US stocks SYMBOL AAPL, MSFT

The app also resolves informal names: typing "Infosys" or "Reliance" will automatically resolve to the correct ticker via the 5-layer entity resolver.


Running Tests

# All tests with coverage report
pytest tests/ --cov=backend --cov-report=html --cov-report=term-missing -v

# Unit tests only (fast, no network)
pytest tests/unit/ -v

# Security tests
pytest tests/security/ -v

# E2E tests (mocked APIs, no real cost)
pytest tests/e2e/ -v

Security Scans

# Static analysis (aim: zero HIGH issues)
bandit -r backend/ --severity-level medium -f json -o reports/bandit_report.json

# Dependency vulnerabilities
safety check -r backend/requirements.txt

# Frontend dependency audit
npm audit --audit-level=moderate --prefix frontend/

Production Deployment

For public-facing deployment with SSL:

# 1. Point your domain's DNS to the server

# 2. Obtain SSL certificates
certbot certonly --standalone -d yourdomain.com

# 3. Set CORS_ORIGINS in .env
CORS_ORIGINS=https://yourdomain.com

# 4. Start with production overrides
docker-compose -f docker-compose.yml -f docker-compose.prod.yml up -d --build

See docker-compose.prod.yml and frontend/nginx.prod.conf for full TLS, HSTS, CSP, and rate-limiting configuration. Update the server_name and certificate paths in nginx.prod.conf for your domain.


Troubleshooting

"Analysis failed. Please try again."

  • Check docker-compose logs backend for the root cause
  • Verify ANTHROPIC_API_KEY is valid and has credits
  • The budget may be exhausted — check ~/.sip/usage.json or the budget banner

"Could not fetch data for TICKER"

  • yfinance may be rate-limited or the ticker does not exist
  • For Indian stocks, always use the .NS (NSE) or .BO (BSE) suffix
  • Wait 60 seconds and retry — yfinance caches are per-session

Docker: port already in use

# Change the host port mapping in docker-compose.yml
ports:
  - "8001:8000"   # backend
  - "3000:80"     # frontend

Cache is stale

  • Settings → Clear Cache (in the app)
  • Or manually: rm -rf ~/.sip/cache/

Budget exhausted mid-month

# Edit ~/.sip/usage.json and reset month_cost to 0
# (or increase MONTHLY_SPEND_LIMIT_USD in .env and restart)

Expected Monthly Cost

Usage Pattern Est. Monthly Cost
5 deep analyses/day ~$3–4
10 quick checks/day + 2 deep/day ~$2–3
Heavy use (50 queries/day) $7–8 (hard stop at $8)

The default MONTHLY_SPEND_LIMIT_USD=8.00 keeps you safely under $10/month. Haiku (auto-activated at 80% budget) costs ~5× less than Sonnet, so budget mode extends your capacity significantly.


Project Structure

sip/
├── backend/           ← FastAPI app (Python 3.11)
│   ├── main.py        ← App entry point, middleware, routers
│   ├── config.py      ← Settings via pydantic-settings
│   ├── routers/       ← HTTP route handlers
│   ├── services/      ← LLM engine, data fetchers, classifiers
│   ├── utils/         ← Cache, validators, formatters
│   └── knowledge_base.txt  ← Investment framework system prompt
├── frontend/          ← React 18 + Vite + Tailwind
│   └── src/
│       ├── components/ ← UI components
│       └── api/        ← Axios API client
├── tests/             ← pytest test suite (unit, integration, e2e, security)
├── docs/              ← Architecture, API spec, testing plan
└── docker-compose.yml ← Development stack

Security

SIP is built security-first — see docs/SECURITY_PLAN.md for the full threat model. Key measures:

  • All user input validated through strict allowlist regex before any processing
  • LLM prompts always wrap user text in <user_query>...</user_query> delimiters
  • System prompt loaded from disk, never from user input
  • Rate limiting on all endpoints (slowapi)
  • No secrets in logs or API responses
  • Docker runs as non-root user (sipuser, uid 1001)
  • SSRF prevention: only screener.in may be fetched by the scraper

Built with Claude Code | Powered by Anthropic Claude

About

AI-powered personal stock analysis tool. Combines real-time financial data, technical indicators, and live news with classical investment frameworks (Graham, Lynch, Greenblatt) via Claude. Local-hosted, cost-optimized (<$8/month), Python + React.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors