Skip to content

mr-anvesh/vibeathon

Repository files navigation

🧠📈 Zerodha Portfolio News Alert System

A sophisticated FastAPI-based web application that provides real-time stock news analysis and portfolio alerts using AI/LLM integration.

🌟 Features

  • 🔐 Secure Authentication - JWT-based user authentication
  • 🔗 Zerodha Integration - Connect your Kite portfolio via MCP
  • 📰 Smart News Aggregation - Fetch relevant news using GNews API
  • 🧠 AI-Powered Analysis - LLM-based sentiment and impact analysis via Groq
  • Real-time Processing - Pathway streaming for live news monitoring
  • 📬 Multi-channel Notifications - Email, Telegram, and WhatsApp alerts
  • 📊 Portfolio Management - Track your stocks and their performance
  • ⚙️ Customizable Settings - Configure notification preferences and thresholds

🛠️ Tech Stack

  • Backend: FastAPI with async/await
  • Streaming: Pathway for real-time data processing
  • AI/LLM: Groq API for news impact analysis
  • Database: Airtable for data storage
  • Authentication: JWT with bcrypt password hashing
  • News API: GNews.io for financial news
  • Broker Integration: Zerodha Kite Connect API
  • Notifications: SMTP (email) and Telegram Bot API

🚀 Quick Start

Prerequisites

  • Python 3.8+
  • Virtual environment (recommended)
  • API keys for required services (see Configuration section)

Installation

  1. Clone and setup the project:
cd /Users/anveshmishra/Developer/Vibeathon
python -m venv venv
source venv/bin/activate  # On macOS/Linux
pip install -r requirements.txt
  1. Configure environment variables:
cp .env.example .env
# Edit .env with your API keys and configuration
  1. Run the test suite:
python test_setup.py
  1. Start the application:
python main.py

The application will be available at http://localhost:8000

⚙️ Configuration

Required API Keys

Create accounts and obtain API keys for the following services:

1. Zerodha Kite Connect

  • Sign up at Kite Connect
  • Create an app to get API key and secret
  • Add to .env:
    KITE_API_KEY=your-kite-api-key
    KITE_API_SECRET=your-kite-api-secret
    

2. GNews API

  • Register at GNews.io
  • Get your free API key
  • Add to .env:
    GNEWS_API_KEY=your-gnews-api-key
    

3. Groq API

  • Sign up at Groq
  • Get your API key for LLM access
  • Add to .env:
    GROQ_API_KEY=your-groq-api-key
    

4. Airtable

  • Create account at Airtable
  • Create a base with tables: Users, Portfolios, NewsAlerts, Settings
  • Generate a personal access token (API keys are deprecated)
  • Add to .env:
    AIRTABLE_BASE_ID=your-airtable-base-id
    AIRTABLE_ACCESS_TOKEN=your-airtable-access-token
    

5. Email Configuration (Optional)

For email notifications:

SMTP_SERVER=smtp.gmail.com
SMTP_PORT=587
SMTP_USERNAME=your-email@gmail.com
SMTP_PASSWORD=your-app-password

6. Telegram Bot (Optional)

  • Create a bot via @BotFather
  • Add to .env:
    TELEGRAM_BOT_TOKEN=your-telegram-bot-token
    

Environment Variables

Complete .env configuration:

# JWT Settings
# Environment Variables
JWT_SECRET_KEY=your-super-secret-jwt-key-change-this-in-production
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30

# Zerodha MCP Server
ZERODHA_MCP_SERVER_URL=https://mcp.kite.trade/sse

# API Keys
GNEWS_API_KEY=your-gnews-api-key
GROQ_API_KEY=your-groq-api-key
AIRTABLE_BASE_ID=your-airtable-base-id
AIRTABLE_ACCESS_TOKEN=your-airtable-access-token

# Email Configuration
SMTP_SERVER=smtp.gmail.com
SMTP_PORT=587
SMTP_USERNAME=your-email@gmail.com
SMTP_PASSWORD=your-app-password

# Telegram
TELEGRAM_BOT_TOKEN=your-telegram-bot-token

# Application
DEBUG=True
HOST=0.0.0.0
PORT=8000

📋 API Endpoints

Authentication

  • POST /register - Register new user
  • POST /token - Login and get access token
  • GET /users/me - Get current user profile

Portfolio Management

  • GET /kite/login-url - Get Kite Connect login URL
  • POST /kite/connect - Connect Kite account
  • GET /portfolio - Get user portfolio
  • POST /portfolio/refresh - Refresh portfolio data

News & Analysis

  • GET /news - Get news for portfolio stocks
  • GET /news/analyze - Analyze news impact on portfolio
  • GET /alerts - Get user's news alerts

Settings

  • GET /settings - Get notification settings
  • POST /settings - Update notification settings

Utilities

  • POST /test/notification - Send test notification
  • GET /health - Health check endpoint
  • GET / - Home page
  • GET /docs - Interactive API documentation

🔄 User Flow

  1. Registration & Authentication

    • Register account via /register
    • Login to get JWT token via /token
  2. Connect Zerodha Account

    • Get Kite login URL via /kite/login-url
    • Complete Kite OAuth flow
    • Connect account via /kite/connect
  3. Portfolio Setup

    • Fetch portfolio via /portfolio
    • System automatically monitors your stocks
  4. News Monitoring

    • Pathway service continuously fetches news
    • LLM analyzes impact on your stocks
    • Notifications sent based on your preferences
  5. Manage Settings

    • Configure notification methods
    • Set impact thresholds
    • Exclude specific stocks

🧪 Testing

Run the comprehensive test suite:

python test_setup.py

This will test:

  • Module imports
  • Service initialization
  • FastAPI app setup
  • Configuration validation
  • Model creation

🚀 Deployment

Development

python main.py
# or
uvicorn main:app --reload --host 0.0.0.0 --port 8000

Production

# Update .env for production
DEBUG=False
JWT_SECRET_KEY=your-very-secure-production-key

# Run with Gunicorn
pip install gunicorn
gunicorn main:app -w 4 -k uvicorn.workers.UvicornWorker --bind 0.0.0.0:8000

📊 Architecture

┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│   FastAPI App   │    │  Pathway Stream  │    │  External APIs  │
│                 │    │                  │    │                 │
│ • Auth Routes   │◄──►│ • News Monitor   │◄──►│ • GNews API     │
│ • Portfolio API │    │ • LLM Analysis   │    │ • Groq LLM      │
│ • Settings API  │    │ • Notifications  │    │ • Kite Connect  │
└─────────────────┘    └──────────────────┘    └─────────────────┘
         │                        │                        │
         ▼                        ▼                        ▼
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│    Airtable     │    │  Notification    │    │   Telegram/     │
│                 │    │    Services      │    │     Email       │
│ • Users         │    │                  │    │                 │
│ • Portfolios    │    │ • Email SMTP     │    │ • Real-time     │
│ • Alerts        │    │ • Telegram Bot   │    │   Delivery      │
│ • Settings      │    │ • WhatsApp (TBD) │    │                 │
└─────────────────┘    └──────────────────┘    └─────────────────┘

🛡️ Security Features

  • JWT Authentication - Secure token-based auth
  • Password Hashing - bcrypt for password security
  • Input Validation - Pydantic model validation
  • Rate Limiting - Built-in request throttling
  • Environment Variables - Secure configuration management
  • CORS Protection - Configurable cross-origin requests

🔧 Customization

Adding New Stock Exchanges

Edit news_service.py to add mappings for different exchanges:

def _get_company_names(self, symbol: str) -> List[str]:
    symbol_mapping = {
        # Add your exchange symbols here
        "YOUR_SYMBOL": ["Company Name", "Alternative Name"],
    }

Custom LLM Prompts

Modify prompts in llm_service.py for different analysis styles:

def _create_analysis_prompt(self, news_item: NewsItem, user_stocks: List[str]) -> str:
    # Customize your analysis prompt here

Notification Templates

Update notification templates in notifications.py:

# Customize email/telegram message formats
html_body = f"""
<!-- Your custom HTML template -->
"""

📈 Monitoring & Logs

The application includes comprehensive logging:

  • Application logs - FastAPI request/response logs
  • Service logs - Individual service operation logs
  • Error tracking - Detailed error logging with context
  • Performance metrics - Response time monitoring

Check logs in the console output or configure file logging as needed.

🤝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new features
  5. Submit a pull request

📄 License

This project is for educational and personal use. Make sure to comply with all API terms of service when using in production.

🆘 Support

  • Documentation: Visit /docs endpoint for interactive API docs
  • Health Check: Use /health endpoint to verify system status
  • Test Notifications: Use /test/notification to verify alert delivery

🚨 Important Notes

  1. API Limits: Be aware of rate limits for external APIs
  2. Market Hours: Consider Indian market hours (9:15 AM - 3:30 PM IST)
  3. Data Accuracy: News analysis is AI-generated and should not be the sole basis for investment decisions
  4. Security: Always use HTTPS in production and secure your API keys
  5. Compliance: Ensure compliance with financial data regulations in your jurisdiction

Happy Trading! 📈

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages