Skip to content

NehaBhask/et-hackathon

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

3 Commits
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸš€ KUBERA - AI-Powered Stock Analysis Chatbot

Python 3.11+ FastAPI PostgreSQL License: MIT

KUBERA is an intelligent stock analysis chatbot specialized in Indian markets (NSE/BSE). Built with FastAPI, PostgreSQL, and OpenRouter (supporting multiple LLMs including Llama 3.3, Claude, GPT-4), it provides comprehensive stock analysis through AI-powered conversations.


🌍 Live Deployment

The application is fully deployed and available online:

  • Frontend Application: https://kubera-frontend-olive.vercel.app/
    (Deployed via Vercel)
  • Backend API: https://kubera007.duckdns.org | WebSocket: wss://kubera007.duckdns.org
    (Running on AWS EC2 t3.micro using Docker containerization. Mapped to EC2 IP 54.206.176.208 using DuckDNS to support secure HTTPS/WSS connections for Vercel compatibility).
  • Docker Image: Available on Docker Hub at tejascm/kubera-backend

πŸ“‹ Table of Contents


Features

Core Features

  • πŸ€– AI-Powered Chat: Real-time conversations powered by OpenRouter (Llama 3.3, Claude, GPT-4, etc.)
  • πŸ“Š Stock Analysis: Comprehensive analysis of NSE/BSE stocks
  • πŸ’Ό Portfolio Tracking: Track your investments with live price updates
  • πŸ“ˆ Technical Analysis: 45 MCP tools for in-depth analysis
  • 🎨 Visualizations: Beautiful charts and graphs via Plotly
  • πŸ“° News & Sentiment: Real-time market news and sentiment analysis

Authentication & Security

  • πŸ” 3-Step OTP Registration: Email-based verification
  • 🎫 JWT Authentication: Secure access and refresh tokens
  • πŸ”’ Password Security: Bcrypt hashing with strict requirements
  • πŸ”„ Session Management: Automatic token refresh

Rate Limiting

  • ⚑ 4-Level Fail-Fast System (DB-driven, configurable via Admin Panel):
    • Burst: 10 prompts/minute (default)
    • Per-Chat: 50 prompts/chat (default)
    • Hourly: 150 prompts/hour (default)
    • Daily: 1000 prompts/24 hours (default)
    • Whitelist: selected users bypass all limits
    • Per-user overrides: custom limits per user

Email Notifications

  • πŸ“§ 15+ Email Triggers:
    • Registration OTP
    • Password reset
    • Welcome email
    • Rate limit violation notifications
    • Portfolio reports (sent to all active users)
    • Account deactivation / reactivation (users & admins)
    • Security alerts

Admin Panel

  • πŸŽ›οΈ Complete System Management:
    • User management (activate/deactivate, user-specific rate overrides)
    • Super Admin role: manages regular admins (activate/deactivate admins)
    • Rate limit configuration β€” DB-driven, live without restarts
    • System control (start/stop/maintenance)
    • Analytics dashboard with role-aware pie charts
    • Admin activity logs

Background Jobs

  • ⏰ Automated Tasks:
    • Portfolio price updates (every 30 mins)
    • Daily/weekly/monthly reports
    • Cleanup jobs (OTPs, tokens)

Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                     CLIENT (Browser/App)                        β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                 β”‚                            β”‚
                 β”‚ REST API                   β”‚ WebSocket
                 β”‚                            β”‚
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                    FASTAPI APPLICATION                          β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚  β”‚                    API Endpoints (55)                      β”‚ β”‚
β”‚  β”‚  Auth (11) | User (7) | Portfolio (5) | Chat (5)           β”‚ β”‚
β”‚  β”‚        Admin (22) | Root (4) | WebSocket (1)               β”‚ β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚  β”‚                  Business Logic Layer                      β”‚ β”‚
β”‚  β”‚         Services | Validators | Formatters                 β”‚ β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚  β”‚                    MCP Integration                         β”‚ β”‚
β”‚  β”‚      LLM Orchestrator | Tool Handler | Client              β”‚ β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
             β”‚                  β”‚                  β”‚
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚    PostgreSQL       β”‚ β”‚ MCP Servers  β”‚ β”‚  Background Scheduler   β”‚
β”‚    (15 tables)      β”‚ β”‚ (5 servers)  β”‚ β”‚     (APScheduler)       β”‚
β”‚                     β”‚ β”‚ (45 tools)   β”‚ β”‚                         β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Tech Stack

Backend

Technology Version Purpose
FastAPI 0.109.0 Web Framework
Python 3.11+ Language
Uvicorn Latest ASGI Server
PostgreSQL 14+ Database
AsyncPG Latest Async PostgreSQL Driver

AI & LLM

Technology Purpose
OpenRouter LLM Gateway (multi-model)
Llama 3.3-70B Default LLM Model
LangChain LLM Orchestration
FastMCP MCP Protocol

Data & Finance

Technology Purpose
yfinance Stock Data
Pandas Data Processing
NumPy Numerical Computing
Plotly Interactive Charts
Matplotlib Static Charts

Authentication

Technology Purpose
python-jose JWT Tokens
passlib (bcrypt) Password Hashing
Pydantic Validation

Infrastructure

Technology Purpose
APScheduler Background Jobs
aiosmtplib Async Email
Docker Containerization
Supabase Chart Storage

Project Structure

kubera-backend/
β”œβ”€β”€ main.py                           # FastAPI app entry point
β”œβ”€β”€ app/
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ core/                         # Core configurations
β”‚   β”‚   β”œβ”€β”€ config.py                 # Settings & environment
β”‚   β”‚   β”œβ”€β”€ security.py               # Auth utilities
β”‚   β”‚   β”œβ”€β”€ database.py               # Database connection
β”‚   β”‚   β”œβ”€β”€ dependencies.py           # FastAPI dependencies
β”‚   β”‚   └── utils.py                  # Helper utilities
β”‚   β”œβ”€β”€ models/                       # Pydantic models
β”‚   β”‚   β”œβ”€β”€ user.py
β”‚   β”‚   β”œβ”€β”€ chat.py
β”‚   β”‚   β”œβ”€β”€ portfolio.py
β”‚   β”‚   β”œβ”€β”€ admin.py
β”‚   β”‚   β”œβ”€β”€ rate_limit.py
β”‚   β”‚   β”œβ”€β”€ email.py
β”‚   β”‚   └── system.py
β”‚   β”œβ”€β”€ schemas/                      # Request/Response schemas
β”‚   β”‚   β”œβ”€β”€ requests/
β”‚   β”‚   β”‚   β”œβ”€β”€ auth_requests.py
β”‚   β”‚   β”‚   β”œβ”€β”€ user_requests.py
β”‚   β”‚   β”‚   β”œβ”€β”€ portfolio_requests.py
β”‚   β”‚   β”‚   β”œβ”€β”€ chat_requests.py
β”‚   β”‚   β”‚   └── admin_requests.py
β”‚   β”‚   └── responses/
β”‚   β”‚       β”œβ”€β”€ auth_responses.py
β”‚   β”‚       β”œβ”€β”€ user_responses.py
β”‚   β”‚       β”œβ”€β”€ portfolio_responses.py
β”‚   β”‚       β”œβ”€β”€ chat_responses.py
β”‚   β”‚       └── admin_responses.py
β”‚   β”œβ”€β”€ api/                          # API routes
β”‚   β”‚   └── routes/
β”‚   β”‚       β”œβ”€β”€ auth_routes.py        # Authentication (11 endpoints)
β”‚   β”‚       β”œβ”€β”€ user_routes.py        # User management (7 endpoints)
β”‚   β”‚       β”œβ”€β”€ portfolio_routes.py   # Portfolio (5 endpoints)
β”‚   β”‚       β”œβ”€β”€ chat_routes.py        # Chat (5 endpoints)
β”‚   β”‚       β”œβ”€β”€ admin_routes.py       # Admin (22 endpoints)
β”‚   β”‚       └── websocket_routes.py   # WebSocket (1 endpoint)
β”‚   β”œβ”€β”€ services/                     # Business logic
β”‚   β”‚   β”œβ”€β”€ auth_service.py
β”‚   β”‚   β”œβ”€β”€ user_service.py
β”‚   β”‚   β”œβ”€β”€ portfolio_service.py
β”‚   β”‚   β”œβ”€β”€ chat_service.py
β”‚   β”‚   β”œβ”€β”€ rate_limit_service.py
β”‚   β”‚   β”œβ”€β”€ email_service.py
β”‚   β”‚   └── admin_service.py
β”‚   β”œβ”€β”€ mcp/                          # MCP Integration
β”‚   β”‚   β”œβ”€β”€ client.py                 # MCP client manager
β”‚   β”‚   β”œβ”€β”€ config.py                 # MCP configuration
β”‚   β”‚   β”œβ”€β”€ tool_handler.py           # Tool execution
β”‚   β”‚   └── llm_integration.py        # Claude integration
β”‚   β”œβ”€β”€ websocket/                    # WebSocket handling
β”‚   β”‚   β”œβ”€β”€ connection_manager.py     # Connection pool
β”‚   β”‚   β”œβ”€β”€ message_handler.py        # Message processing
β”‚   β”‚   β”œβ”€β”€ response_streamer.py      # Streaming responses
β”‚   β”‚   └── protocols.py              # WebSocket protocols
β”‚   β”œβ”€β”€ background/                   # Background jobs
β”‚   β”‚   β”œβ”€β”€ scheduler.py              # APScheduler config
β”‚   β”‚   β”œβ”€β”€ jobs/                     # Job definitions
β”‚   β”‚   └── tasks/                    # Task implementations
β”‚   β”œβ”€β”€ db/                           # Database
β”‚   β”‚   β”œβ”€β”€ migrations/               # SQL migrations
β”‚   β”‚   β”‚   └── v1_initial_schema.sql # Complete schema: tables, indexes, triggers, defaults
β”‚   β”‚   └── repositories/             # Data access layer
β”‚   β”‚       β”œβ”€β”€ user_repository.py
β”‚   β”‚       β”œβ”€β”€ chat_repository.py
β”‚   β”‚       β”œβ”€β”€ portfolio_repository.py
β”‚   β”‚       β”œβ”€β”€ otp_repository.py
β”‚   β”‚       β”œβ”€β”€ token_repository.py
β”‚   β”‚       β”œβ”€β”€ rate_limit_repository.py
β”‚   β”‚       β”œβ”€β”€ email_repository.py
β”‚   β”‚       β”œβ”€β”€ admin_repository.py
β”‚   β”‚       └── system_repository.py
β”‚   β”œβ”€β”€ utils/                        # Utilities
β”‚   β”‚   β”œβ”€β”€ validators.py
β”‚   β”‚   β”œβ”€β”€ formatters.py
β”‚   β”‚   β”œβ”€β”€ otp_generator.py
β”‚   β”‚   β”œβ”€β”€ email_templates.py
β”‚   β”‚   β”œβ”€β”€ helpers.py
β”‚   β”‚   └── logger.py
β”‚   └── exceptions/                   # Exception handling
β”‚       β”œβ”€β”€ custom_exceptions.py
β”‚       └── handlers.py
β”œβ”€β”€ mcp_servers/                      # 5 MCP Servers
β”‚   β”œβ”€β”€ fin_data.py                   # Financial Data Server (7 tools)
β”‚   β”œβ”€β”€ market_tech.py                # Market & Technical Server (9 tools)
β”‚   β”œβ”€β”€ gov_compliance.py             # Governance & Compliance (8 tools)
β”‚   β”œβ”€β”€ news_sent.py                  # News & Sentiment Server (10 tools)
β”‚   └── visualization.py              # Visualization Server (11 tools)
β”œβ”€β”€ scripts/                          # Setup scripts
β”‚   β”œβ”€β”€ init_db.py                    # Database initialization
β”‚   β”œβ”€β”€ seed_admin.py                 # Admin user creation
β”‚   β”œβ”€β”€ seed_rate_limits.py           # Rate limit setup
β”‚   └── run_migrations.py             # Migration runner
β”œβ”€β”€ .env                              # Environment variables
β”œβ”€β”€ .env.example                      # Environment template
β”œβ”€β”€ requirements.txt                  # Python dependencies
β”œβ”€β”€ pyproject.toml                    # Project configuration
β”œβ”€β”€ Dockerfile                        # Docker image
β”œβ”€β”€ docker-compose.yml                # Docker Compose
└── README.md                         # This file

Installation

Prerequisites

  • Python 3.11 or higher
  • PostgreSQL 14 or higher
  • pip or uv (package manager)
  • (Optional) Docker & Docker Compose

1. Clone Repository

git clone https://github.com/yourusername/kubera-backend.git
cd kubera-backend

2. Create Virtual Environment

# Using venv
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# OR using uv (recommended)
uv venv
source .venv/bin/activate  # On Windows: .venv\Scripts\activate

3. Install Dependencies

# Using pip
pip install --upgrade pip
pip install -r requirements.txt

# OR using uv
uv pip install -r requirements.txt

Configuration

1. Environment Variables

Copy .env.example to .env:

cp .env.example .env

Edit .env and configure the following:

APP_NAME=KUBERA
APP_VERSION=1.0.0
APP_ENV=development
DEBUG=True
ALLOWED_ORIGINS=http://localhost:3000,http://localhost:8000

SUPABASE_URL=https://your-project-id.supabase.co
SUPABASE_ANON_KEY=your-supabase-anon-key
POSTGRES_HOST=aws-0-ap-south-1.pooler.supabase.com
POSTGRES_PORT=6543
POSTGRES_USER=postgres.your-project-id
POSTGRES_PASSWORD=your-database-password
POSTGRES_DB=postgres
DATABASE_URL=postgresql://postgres.your-project-id:your-password@aws-0-ap-south-1.pooler.supabase.com:6543/postgres
POSTGRES_MIN_POOL_SIZE=2
POSTGRES_MAX_POOL_SIZE=10

SECRET_KEY=your-secret-key-generate-with-secrets-token-hex-32
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30
REFRESH_TOKEN_EXPIRE_DAYS=7

OPENROUTER_API_KEY=sk-or-v1-your-openrouter-api-key
OPENROUTER_MODEL=openai/gpt-4o-mini
OPENROUTER_SITE_URL=http://localhost:8000
OPENROUTER_APP_NAME=KUBERA

SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=your-email@gmail.com
SMTP_PASSWORD=your-gmail-app-password
SMTP_FROM_EMAIL=your-email@gmail.com
SMTP_FROM_NAME=KUBERA

OTP_EXPIRE_MINUTES=10
OTP_MAX_ATTEMPTS=3

RATE_LIMIT_BURST=10
RATE_LIMIT_PER_CHAT=50
RATE_LIMIT_PER_HOUR=150
RATE_LIMIT_PER_DAY=1000

PYTHON_EXECUTABLE=python

FINNHUB_API_KEY=your-finnhub-api-key
NEWSAPI_KEY=your-newsapi-key
ALPHA_VANTAGE_API_KEY=your-alphavantage-api-key
MARKETAUX_API_KEY=your-marketaux-api-key
INDIAN_API_KEY=your-indian-api-key

PORTFOLIO_UPDATE_FREQUENCY=10
PORTFOLIO_REPORT_FREQUENCY=disabled
PORTFOLIO_REPORT_SEND_TIME=09:00
PORTFOLIO_REPORT_DAY_WEEKLY=1
PORTFOLIO_REPORT_DAY_MONTHLY=1

TIMEZONE=Asia/Kolkata
LOG_LEVEL=INFO
LOG_FILE=logs/kubera.log

2. Generate Secret Key

# Using OpenSSL
openssl rand -hex 32

# OR using Python
python -c "import secrets; print(secrets.token_hex(32))"

Database Setup

Method 1: Automated Script (Recommended)

# Initialize database, run migrations, seed data
python scripts/init_db.py

Method 2: Manual Setup

# Step 1: Create database
createdb kubera_db

# Step 2: Run migrations
python scripts/run_migrations.py migrate

# Step 3: Create admin user
python scripts/seed_admin.py

# Step 4: Configure rate limits
python scripts/seed_rate_limits.py

Verify Setup

# Check migration status
python scripts/run_migrations.py status

# List admin users
python scripts/seed_admin.py list

Running the Application

Development Mode

# With auto-reload
uvicorn main:app --reload --host 0.0.0.0 --port 8000

# OR simply
python main.py

Production Mode

# Multi-worker
uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4

Access Points

Endpoint URL
🌐 API Root http://localhost:8000
πŸ“– Swagger Docs http://localhost:8000/docs
πŸ“š ReDoc http://localhost:8000/redoc
❀️ Health Check http://localhost:8000/health
πŸ”Œ WebSocket ws://localhost:8000/ws/chat

API Documentation

Authentication Endpoints (11)

POST /auth/register/step1              # Step 1: Send OTP to email
POST /auth/register/step2              # Step 2: Verify OTP
POST /auth/register/step3              # Step 3: Complete registration
POST /auth/login                       # Login with username and password
POST /auth/refresh                     # Refresh access token
POST /auth/logout                      # Logout user
GET  /auth/check-username/{username}   # Check username availability
POST /auth/password-reset/send-otp     # Send OTP for password reset
POST /auth/password-reset/confirm      # Confirm password reset with OTP
POST /auth/forgot-password/send-otp    # Send forgot password OTP
POST /auth/forgot-password/confirm     # Reset password with OTP

User Endpoints (7)

GET    /user/profile               # Get user profile
PUT    /user/profile               # Update user profile
PUT    /user/username              # Update username
PUT    /user/password              # Update password
GET    /user/email-preferences     # Get email preferences
PUT    /user/email-preferences     # Update email preferences
GET    /user/stats                 # Get user statistics

Portfolio Endpoints (5)

GET    /portfolio/                 # Get user portfolio
POST   /portfolio/                 # Add portfolio entry
PUT    /portfolio/{portfolio_id}   # Update portfolio entry
DELETE /portfolio/{portfolio_id}   # Delete portfolio entry
POST   /portfolio/update-prices    # Update portfolio prices

Chat Endpoints (5)

GET    /chats/                     # Get all chats
POST   /chats/                     # Create new chat
GET    /chats/{chat_id}            # Get chat with messages
DELETE /chats/{chat_id}            # Delete chat
PUT    /chats/{chat_id}/rename     # Rename chat

Admin Endpoints (22)

POST   /admin/login/send-otp                   # Admin login - Send OTP
POST   /admin/login/verify-otp                 # Admin login - Verify OTP
GET    /admin/dashboard                        # Get dashboard statistics
GET    /admin/dashboard/prompt-activity        # Get prompt activity time-series
GET    /admin/users                            # Get all users
GET    /admin/users/{user_id}                  # Get user details
PUT    /admin/users/{user_id}/deactivate       # Deactivate user
PUT    /admin/users/{user_id}/reactivate       # Reactivate user
GET    /admin/rate-limits/config               # Get rate limit configuration
PUT    /admin/rate-limits/global               # Update global rate limits
PUT    /admin/rate-limits/user/{user_id}       # Set user-specific rate limits
POST   /admin/rate-limits/whitelist            # Add user to whitelist
DELETE /admin/rate-limits/whitelist/{user_id}  # Remove user from whitelist
POST   /admin/rate-limits/reset/{user_id}      # Reset user rate limit counters
GET    /admin/rate-limits/violations           # Get rate limit violations
GET    /admin/portfolio-reports/settings       # Get portfolio report settings
PUT    /admin/portfolio-reports/settings       # Update portfolio report settings
POST   /admin/system/control                   # System control (start/stop)
GET    /admin/activity-logs                    # Get admin activity logs

# Super Admin only (role: super_admin)
GET    /admin/admins                           # List all admins
PUT    /admin/admins/{admin_id}/deactivate     # Deactivate an admin
PUT    /admin/admins/{admin_id}/reactivate     # Reactivate an admin

Root Endpoints (4)

GET    /                           # API Root
GET    /health                     # Health Check
GET    /mcp/tools                  # List MCP Tools
GET    /scheduler/status           # Scheduler Status

WebSocket (1)

WS /ws/chat?token={jwt_token}      # Real-time chat

MCP Servers

KUBERA uses 5 specialized MCP servers with 45 tools total:

Server 1: Financial Data (fin_data.py) - 7 Tools

Tool Description
fetch_company_fundamentals Core fundamental metrics
fetch_historical_financials Historical financial data
fetch_balance_sheet_data Balance sheet components
fetch_cash_flow_data Cash flow statement
fetch_dividend_history Dividend data & sustainability
fetch_eps_analysis EPS trends & analysis
validate_stock_symbol Symbol validation

Server 2: Market & Technical (market_tech.py) - 9 Tools

Tool Description
fetch_current_price_data Real-time price data
fetch_historical_price_data OHLCV historical data
fetch_technical_indicators SMA, RSI, MACD, BBands
fetch_volume_analysis Volume trends
fetch_volatility_metrics Beta, drawdown, Sharpe
fetch_comparative_performance Performance comparison
fetch_institutional_holding_data FII/DII holdings
fetch_liquidity_metrics Trading liquidity
validate_technical_data Data quality check

Server 3: Governance & Compliance (gov_compliance.py) - 8 Tools

Tool Description
fetch_promoter_holding_data Promoter & pledging info
fetch_board_composition Board structure
fetch_audit_quality Auditor information
fetch_regulatory_compliance Regulatory status
fetch_shareholding_pattern Complete shareholding
fetch_related_party_transactions Related party deals
fetch_governance_score Governance quality score
fetch_insider_transactions Insider trading patterns

Server 4: News & Sentiment (news_sent.py) - 10 Tools

Tool Description
fetch_news_articles Recent news articles
fetch_overall_news_sentiment Aggregate sentiment
fetch_analyst_ratings Analyst recommendations
fetch_social_sentiment Social media sentiment
fetch_company_announcements Official announcements
fetch_sector_sentiment Sector-wide sentiment
fetch_competitor_sentiment Competitor comparison
fetch_news_impact_analysis Price impact analysis
fetch_management_commentary Management guidance
calculate_sentiment_score Text sentiment scoring

Server 5: Visualization (visualization.py) - 11 Tools

Tool Description
generate_price_volume_chart Price & volume chart
generate_candlestick_chart Candlestick chart
generate_technical_indicators_chart Technical chart
generate_fundamental_comparison_chart Comparison chart
generate_financial_trend_chart Trend chart
generate_performance_vs_benchmark_chart Benchmark comparison
generate_valuation_heatmap Valuation heatmap
generate_portfolio_composition_chart Portfolio pie/treemap
generate_dividend_timeline_chart Dividend timeline
generate_risk_return_scatter Risk-return scatter
validate_chart_data Chart data validation

WebSocket Protocol

Connect

const ws = new WebSocket("ws://localhost:8000/ws/chat?token=YOUR_JWT_TOKEN");

Client β†’ Server Messages

// Send message
{
    "type": "message",
    "chat_id": "uuid",
    "message": "Analyze INFY stock"
}

// Ping (keep-alive)
{
    "type": "ping"
}

Server β†’ Client Messages

// Text chunk (streaming)
{
    "type": "text_chunk",
    "content": "Infosys is...",
    "chunk_id": 0
}

// Tool execution start
{
    "type": "tool_call_start",
    "tool_name": "fetch_company_fundamentals",
    "tool_id": "call_123"
}

// Tool execution complete
{
    "type": "tool_call_complete",
    "tool_id": "call_123",
    "result": { ... }
}

// Message complete
{
    "type": "message_complete",
    "message_id": "uuid",
    "metadata": {
        "tokens_used": 1500,
        "tools_used": ["fetch_company_fundamentals", "fetch_current_price_data"],
        "processing_time_ms": 2500,
        "chart_url": "https://...",    // Supabase storage URL (if chart generated)
        "chart_html": "<html>..."      // Direct HTML for rendering (if chart generated)
    }
}

// Error
{
    "type": "error",
    "message": "Rate limit exceeded",
    "code": "RATE_LIMITED"
}

Background Jobs

Configured Jobs

Job Frequency Description
Portfolio Price Update Every 30 minutes Updates stock prices via yfinance
Portfolio Reports Configurable Sends email reports (daily/weekly/monthly)
Cleanup OTPs Every hour Removes expired OTPs
Cleanup Tokens Every 6 hours Removes revoked/expired tokens

Check Scheduler Status

curl http://localhost:8000/scheduler/status

Rate Limiting

4-Level Fail-Fast System (DB-driven & live-configurable)

All limits are stored in the database and enforced per-prompt via RateLimitService. Changes made in the Admin Panel take effect on the next prompt β€” no server restart required.

Level Default Window Action
πŸš€ Burst 10 prompts 1 minute Block immediately
πŸ’¬ Per-Chat 50 prompts Per chat session Block prompt
⏰ Hourly 150 prompts 1 hour Block for remainder
πŸ“… Daily 1000 prompts 24 hours Block for remainder

Admin Controls

  • βœ… Update limits globally (live, no restart)
  • βœ… Set per-user overrides (takes priority over global)
  • βœ… Whitelist users (completely bypass all limits)
  • βœ… Reset individual user counters
  • βœ… View violation logs with user info and timestamp

Email Notifications

15+ Email Types

Category Templates
πŸ”‘ OTP Emails Registration, Password Reset, Admin Login
πŸ‘€ Account Emails Welcome, Password Changed, Account Deactivated
⚑ Rate Limit Emails Burst/Hourly/Daily Limit Exceeded
πŸ“Š Portfolio Emails Daily/Weekly/Monthly Reports
πŸ”” System Emails Maintenance, Security Alerts

Docker Deployment

Quick Start

# Build and run
docker-compose up -d

# View logs
docker-compose logs -f backend

# Stop
docker-compose down

Services

Service Port Description
backend 8000 FastAPI application
postgres 5432 PostgreSQL database
redis 6379 Redis cache (optional)
pgadmin 5050 Database management

Production Deployment

# Build production image
docker build -t kubera-backend:latest .

# Run with environment file
docker run -d \
  --name kubera-backend \
  --env-file .env \
  -p 8000:8000 \
  kubera-backend:latest

Development

Code Style

# Format code
black app/ mcp_servers/ scripts/

# Sort imports
isort app/ mcp_servers/ scripts/

# Lint
flake8 app/ mcp_servers/ scripts/

# Type checking
mypy app/

Database Migrations

# Create migration
python scripts/run_migrations.py create "description"

# Apply migrations
python scripts/run_migrations.py migrate

# Check status
python scripts/run_migrations.py status

Troubleshooting

Common Issues

MCP Client Not Initializing

# Check if all required API keys are set
echo $OPENROUTER_API_KEY

# Verify MCP server files exist
ls mcp_servers/

Database Connection Failed

# Check PostgreSQL is running
pg_isready -h localhost -p 5432

# Verify database exists
psql -l | grep kubera_db

WebSocket Connection Issues

# Check if server is running
curl http://localhost:8000/health

# Verify JWT token is valid

Email Not Sending

# Verify SMTP settings
# For Gmail, ensure "Less secure app access" or use App Passwords

Contributing

  1. Fork the repository
  2. Create feature branch (git checkout -b feature/amazing-feature)
  3. Commit changes (git commit -m 'Add amazing feature')
  4. Push to branch (git push origin feature/amazing-feature)
  5. Open Pull Request

Commit Convention

feat: Add new feature
fix: Bug fix
docs: Documentation update
style: Code style changes
refactor: Code refactoring
test: Add/update tests
chore: Maintenance tasks

License

This project is licensed under the MIT License - see the LICENSE file for details.


Support


πŸ™ Acknowledgments

  • OpenRouter for multi-model LLM access
  • FastAPI team for the amazing framework
  • FastMCP for MCP protocol implementation
  • yfinance for stock data

πŸ“Š Project Statistics

Metric Count
πŸ“ Total Files 150+
πŸ“ Lines of Code 15,000+
🌐 REST Endpoints 53
πŸ”Œ WebSocket Endpoints 1
πŸ—„οΈ Database Tables 15
πŸ“‡ Database Indexes 60+
πŸ”— Foreign Keys 10
βœ… Constraints 25+
⚑ Triggers 9
πŸ€– MCP Servers 5
πŸ”§ MCP Tools 45
⏰ Background Jobs 4
πŸ“§ Email Templates 15+
πŸ‘€ Admin Roles 2 (admin, super_admin)
πŸ“¦ Python Packages 50+
🐳 Docker Services 4

πŸš€ Quick Start

# 1. Setup
cp .env.example .env
# Edit .env with your values

# 2. Install
pip install -r requirements.txt

# 3. Initialize Database
python scripts/init_db.py

# 4. Create Admin
python scripts/seed_admin.py

# 5. Run Application
python main.py

# OR with Docker
docker-compose up -d

Version: 1.0.0 | Last Updated: May 2026

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors