
This project demonstrates a Proof-of-Concept (POC) for an AI-driven stock purchasing system integrated with Zerodha. The system leverages a multi-agent workflow where individual agents analyze financial transactions, generate an investment portfolio based on user savings and risk profile, select the most suitable stocks, and execute trades with optional human approval. The project highlights how AI can augment personal finance management by automating portfolio allocation and stock selection while maintaining user oversight for final investment decisions.
Personal finance and investment decision-making present several challenges:
AIStockTrader_Zerodha solves these challenges through an intelligent, transparent, and human-controlled AI workflow:
๐ Transaction Analysis โ ๐ก Smart Allocation โ ๐ Stock Selection โ โ
Human Approval โ ๐น Automated Execution
Key Innovation: Multi-agent LangGraph workflow with human-in-the-loop approval, combining AI automation with user trust and control.
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Frontend (Web UI) โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ HTML5 + JavaScript โ โ
โ โ - Transaction Upload Interface โ โ
โ โ - Real-time Workflow Status Display โ โ
โ โ - Approval Decision Buttons โ โ
โ โ - Order Confirmation Notifications โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ HTTP/WebSocket
โโโโโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Backend (FastAPI Server) โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ API Routes & State Management โ โ
โ โ - POST /upload - Process transaction files โ โ
โ โ - GET /status - Retrieve workflow state โ โ
โ โ - POST /approve - Submit approval decision โ โ
โ โ - GET /results - Fetch execution results โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ AI Agent Orchestration (LangGraph) โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Multi-Agent Pipeline โ โ
โ โ โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโ โ โ
โ โ โ Transaction โโ โ Portfolio โโ โ Stock โ โ โ
โ โ โ Analyzer โ โ Allocator โ โ Picker โ โ โ
โ โ โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโ โ โ
โ โ โ โ โ โ โ
โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ โ
โ โ โ Shared State (Finance Data Model) โ โ โ
โ โ โ - Savings Amount, Portfolio Allocation โ โ โ
โ โ โ - Investment Recommendations, Approval Status โ โ โ
โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโ
โผ โผ โผ
โโโโโโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโ
โ LLM API โ โ Finance โ โ Zerodha โ
โ(Groq) โ โ Tools โ โ API โ
โโโโโโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโ
AIStockTrader_Zerodha/
โ
โโโ src/
โ โโโ api/
โ โ โโโ server.py # FastAPI backend, routes, WebSocket
โ โ
โ โโโ templates/
โ โ โโโ index.html # Main web UI
โ โ โโโ styles.css # UI styling
โ โ โโโ client.js # Frontend logic
โ โ
โ โโโ core/
โ โ โโโ entity/
โ โ โ โโโ finance_state.py # State model definition
โ โ โ
โ โ โโโ graph/
โ โ โ โโโ graph_creation.py # LangGraph workflow creation
โ โ โ
โ โ โโโ helpers/
โ โ โ โโโ load_prompt.py # Prompt template loader
โ โ โ โโโ pdf_processor.py # Transaction PDF parsing
โ โ โ
โ โ โโโ nodes/
โ โ โ โโโ transaction_analyzer.py # Transaction analysis node
โ โ โ โโโ portfolio_allocator.py # Asset allocation node
โ โ โ โโโ stock_picker.py # Stock selection node
โ โ โ โโโ approval_node.py # Human approval node
โ โ โ โโโ execution_node.py # Order execution node
โ โ โ
โ โ โโโ tools/
โ โ โ โโโ zerodha_tools.py # Zerodha API wrapper
โ โ โ โโโ financial_tools.py # Financial calculations
โ โ โ โโโ data_tools.py # Data retrieval tools
โ โ โ
โ โ โโโ prompts/
โ โ โ โโโ system_prompt_*.txt # System prompts for agents
โ โ โ โโโ user_prompt_*.txt # User prompts for agents
โ โ โ
โ โ โโโ utils/
โ โ โโโ logger.py # Logging configuration
โ โ โโโ error_handler.py # Error handling utilities
โ โ โโโ retry_handler.py # Retry mechanism with backoff
โ โ
โ โโโ data/
โ โ โโโ transactions_november.pdf # Sample transaction file
โ โ
โ โโโ config.py # Configuration & LLM initialization
โ
โโโ tests/
โ โโโ test_agents.py # Agent unit tests
โ โโโ test_api.py # API endpoint tests
โ โโโ test_error_handling.py # Error scenario tests
โ โโโ test_integration.py # End-to-end workflow tests
โ
โโโ logs/
โ โโโ app.log # Application logs
โ
โโโ Dockerfile # Container configuration
โโโ docker-compose.yaml # Multi-container orchestration
โโโ requirements.txt # Python dependencies
โโโ .env.example # Environment template
โโโ .gitignore # Git ignore rules
โโโ LICENSE # License information
โโโ README.md # This file
The entire workflow follows a state machine pattern with five distinct stages:
Purpose: Extract financial insights from user transactions
Process:
State Output:
{
"monthly_transactions": [...],
"total_income": 50000,
"total_expenses": 37500,
"monthly_savings": 12500,
"current_step": "analyze_portfolio"
}
AI Prompt Used: system_prompt_transaction_analyzer.txt
Error Handling: PDF parsing failures trigger graceful error messages with retry options
Purpose: Recommend optimal asset class allocation based on savings
Process:
State Output:
{
"portfolio_allocation": {
"equity": {"percentage": 60, "amount": 7500},
"debt": {"percentage": 30, "amount": 3750},
"gold": {"percentage": 10, "amount": 1250}
},
"allocation_reasoning": "...",
"current_step": "select_stocks"
}
AI Prompt Used: system_prompt_portfolio_allocator.txt
Purpose: Select specific stocks for equity allocation
Process:
State Output:
{
"investment_instruments": [
{
"tradingsymbol": "INFY",
"company_name": "Infosys",
"allocation_amount": 3750,
"price": 1850,
"quantity": 2,
"reasoning": "..."
},
{
"tradingsymbol": "TCS",
"company_name": "Tata Consultancy",
"allocation_amount": 3750,
"price": 3500,
"quantity": 1,
"reasoning": "..."
}
],
"current_step": "awaiting_approval"
}
Purpose: Enable user review and decision-making before execution
Process:
UI Interaction Flow:
[Show Analysis] โ [Display Allocation] โ [List Stocks]
โ
[Approve Button] [Reject Button]
Audit Trail: All approvals logged with timestamp and user context
Purpose: Execute approved trades through Zerodha API
Process:
Order Execution Details:
{
"order_id": "230810000000001",
"tradingsymbol": "INFY",
"quantity": 2,
"price": 1850,
"status": "COMPLETED",
"timestamp": "2025-11-28T14:30:00Z",
"execution_details": {...}
}
Error Scenarios Handled:
The UI prioritizes simplicity, transparency, and quick decision-making through:
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ ๐ค Upload Transaction Statement โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ โ Drag & Drop or Click to Upload โโ
โ โ Supported: PDF, CSV โโ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ [Start Analysis โ] โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Design Decisions:
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ ๐ Workflow Progress โ
โ โ
Transaction Analysis Complete โ
โ โ
Portfolio Allocation Complete โ
โ โ
Stock Selection Complete โ
โ โณ Awaiting Your Approval... โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Design Decisions:
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ ๐ฐ Financial Analysis โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ Monthly Income: โน50,000 โ
โ Monthly Expenses: โน37,500 โ
โ Monthly Savings: โน12,500 โ
โ โ
โ ๐ Recommended Allocation โ
โ - Equity (60%): โน7,500 โ
โ - Debt (30%): โน3,750 โ
โ - Gold (10%): โน1,250 โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Design Decisions:
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ ๐ Recommended Stocks โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ 1. INFY (Infosys) โ
โ - Allocation: โน3,750 โ
โ - Current Price: โน1,850 โ
โ - Quantity: 2 shares โ
โ - Reason: Growth leader in IT sector โ
โ โ
โ 2. TCS (Tata Consultancy) โ
โ - Allocation: โน3,750 โ
โ - Current Price: โน3,500 โ
โ - Quantity: 1 share โ
โ - Reason: Stable dividend yield โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Design Decisions:
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ โ
APPROVE THIS PLAN โ
โ Proceed with stock purchase โ
โ [APPROVE โ] [REJECT โ] โ
โ โ
โ โน๏ธ This action will execute trades โ
โ on your Zerodha account โ
โ Review all details above before โ
โ making a decision โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Design Decisions:
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ โ
ORDERS EXECUTED SUCCESSFULLY โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ Order #1: INFY - 2 shares @ โน1,850 โ
โ Status: โ
COMPLETED โ
โ Order ID: 230810000000001 โ
โ โ
โ Order #2: TCS - 1 share @ โน3,500 โ
โ Status: โ
COMPLETED โ
โ Order ID: 230810000000002 โ
โ โ
โ Total Investment: โน7,500 โ
โ [View Zerodha Portfolio โ] โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Design Decisions:
Happy Path:
Upload โ Analyze โ Review โ Approve โ Execute โ Success
Rejection Path:
Upload โ Analyze โ Review โ Reject โ [Ask for Modifications]
Error Path:
Upload โ Error โ Show Message โ [Retry] or [Cancel]
| Layer | Technology | Purpose | Rationale |
|---|---|---|---|
| Frontend | HTML5 + CSS3 | Web interface | Simple, no build step required |
| Frontend Logic | JavaScript (Vanilla) | Client-side interactions | Lightweight, no framework overhead |
| Backend Framework | FastAPI 0.115+ | REST API server | Fast, modern, auto-docs |
| Backend Runtime | Python 3.10+ | Application runtime | Rich ecosystem, AI/ML libraries |
| AI Orchestration | LangGraph | Multi-agent workflow | State machine, tool calling |
| LLM Provider | Groq (Llama 3.3) | Language model inference | Fast, cost-effective |
| LLM Framework | LangChain | Agent prompting, tools | Proven patterns, wide adoption |
| Finance API | Zerodha Kiteconnect | Stock trading | India's largest retail broker |
| Document Processing | PyPDF2 | Transaction PDF parsing | Lightweight, reliable |
| Data Manipulation | Pandas | Financial data handling | Standard in finance domain |
| Logging | Loguru | Application logging | Structured, colorized logs |
| Environment Config | python-dotenv | Secrets management | Standard practice |
| Server Deployment | Uvicorn | ASGI server | FastAPI standard |
| Containerization | Docker | Application packaging | Reproducible deployment |
| Orchestration | Docker Compose | Multi-service setup | Local development + testing |
Before starting, ensure you have:
git clone https://github.com/yourusername/AIStockTrader_Zerodha.git
cd AIStockTrader_Zerodha
# Windows
python -m venv .venv
.venv\Scripts\activate
# Linux/macOS
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
This installs:
fastapi>=0.115.0 - Web frameworkuvicorn[standard]>=0.30.0 - ASGI serverlangchain-groq - LLM integrationlanggraph - Agent orchestrationkiteconnect - Zerodha APIPyPDF2 - PDF parsingloguru - Loggingpython-dotenv - Configurationpandas - Data handlingjinja2 - Template renderingCreate a .env file in the project root:
cp .env.example .env
Edit .env with your credentials:
# LLM Configuration
GROQ_API_KEY=your_groq_api_key_here
GROQ_LLM_MODEL=llama-3.3-70b-versatile
# Zerodha Configuration
ZERODHA_API_KEY=your_zerodha_api_key
ZERODHA_SECRET_KEY=your_zerodha_secret_key
REQUEST_TOKEN_FROM_URL=https://kite.zerodha.com/connect/login?v=3&api_key=API_KEY
ZERODHA_ACCESS_TOKEN=your_zerodha_access_token
# Application Configuration
DEBUG=True
LOG_LEVEL=INFO
ENVIRONMENT=development
uvicorn src.api.server:app --reload --host 0.0.0.0 --port 8000
Output:
INFO: Uvicorn running on http://0.0.0.0:8000
INFO: Application startup complete
Open your browser and navigate to:
http://127.0.0.1:8000
To improve reliability and make debugging easier, the project now includes a centralized custom exception hierarchy located in:
src/utils/exceptions.py
Provides clear, meaningful error types instead of generic exceptions
Allows the retry system to differentiate between retryable and non-retryable failures
Makes debugging easier by showing high-level, human-readable messages
| Exception Name | Purpose |
|---|---|
| AppError | Base class for all app errors |
| PDFReadError | PDF extraction failures |
| ZerodhaAPIError | Problems calling Zerodha APIs / LTP fetch |
| ToolExecutionError | Generic tool-level failure |
| RetryableError | Forces retry mechanism |
Clear separation of failure types
Better error propagation in agents
Unified error handling across the system
A reusable @retry decorator has been added to automatically retry failing operations.
๐ File:
src/utils/retry.py
Retry unstable functions (e.g., network calls, API requests)
Exponential backoff (delay โ delay * backoff)
Optional jitter to prevent retry storms
Logs all retry attempts
Supports custom retryable exception types
@retry(max_attempts=5, delay=2, backoff=2, retry_on=(ZerodhaAPIError,)) def fetch_prices(): return kite.ltp(['NSE:INFY'])
Makes your agents fault tolerant
Prevents instant failures on temporary API issues
Ensures stable and smooth execution
A production-grade logging system has been added using Loguru.
๐ File:
src/utils/logger.py
Colorized, detailed console logs
Persistent file logging (logs/app.log)
Automatic log rotation (10MB max โ zipped rotate)
Backtrace + diagnose mode for debugging
Zero print() calls --- entire app uses logger
`from src.utils.logger import logger
logger.info("Starting stock suggestion tool...")
logger.success("Order placement complete")
logger.error("Failed to fetch Zerodha data")`
Helps track errors quickly
Works seamlessly inside FastAPI + agents
Enables auditability for production
A complete test suite is now added under:
tests/
PDF reader tool
Portfolio builder logic
Retry decorator behavior
Stock suggestion tool
Core utilities
pytest -v
Ensures agents and tools work as expected
Reduces regressions as features grow
Makes CI/CD-ready
The project now supports full containerization.
Dockerfile
docker-compose.yml
docker-compose up --build
./data โ /app/data
./logs โ /app/logs
Consistent environment
Easy to run anywhere
Cloud/server deployment-ready
๐ฐ Total Savings: โน12,500
๐ Portfolio: {'Equity': 60%, 'Debt': 30%, 'Gold': 10%}
๐ Suggested Stocks: [{'tradingsymbol': '364D100926-TB', 'price': 94.75}]
โณ Awaiting Approval: True
โ
Approved: True
๐น Executed Order: Stock purchase executed โ Failed to place order: AMO not allowed.
๐ Status: Executing stock purchase...
This project integrates with the Zerodha KiteConnect API for accessing live market data, fetching LTPs, and placing buy orders.
To use these features, you must configure your environment variables correctly.
Create a .env file in the project root:
# Zerodha API
KITE_API_KEY=your_api_key
KITE_API_SECRET=your_api_secret
KITE_REQUEST_TOKEN=your_request_token
# Optional
KITE_ACCESS_TOKEN=your_access_token
| Variable | Purpose | Required |
|---|---|---|
KITE_API_KEY | Identifies your app on Zerodha | โ |
KITE_API_SECRET | Secret used to generate session token | โ |
KITE_REQUEST_TOKEN | Temporary token obtained after login | โ |
KITE_ACCESS_TOKEN | Permanent session token (once generated) | Optional (auto-generated if not provided) |
Follow these steps carefully.
Log in using your regular Zerodha credentials.
Subscribe to the KiteConnect API (paid monthly).
Create a new app.
You will immediately get:
API Key
API Secret
Add these to .env.
Zerodha requires you to generate a new request token each day.
To generate it:
https://kite.trade/connect/login?api_key=YOUR_API_KEY
Zerodha User ID
Password
Pin
https://your-redirect-url.com/?status=success&request_token=abcd1234efgh5678
request_token.KITE_REQUEST_TOKEN=abcd1234efgh5678
access_token (Once per day)In your project code, session generation is done via:
data = kite.generate_session(request_token, api_secret=API_SECRET)
kite.set_access_token(data["access_token"])
You can print the value or log it for reference:
logger.info(f"Access Token: {data['access_token']}")
Add it to .env if you want persistent usage:
KITE_ACCESS_TOKEN=your_access_token
Used in:
src/core/tools/stock_suggest.py
Wrapped with retry logic:
@retry(max_attempts=6, delay=2)
def _safe_ltp_call(kite, symbols):
return kite.ltp(symbols)
Used in:
src/core/tools/stock_buy.py
Example:
order = kite.place_order(
tradingsymbol=symbol,
exchange="NSE",
quantity=quantity,
transaction_type="BUY",
order_type="MARKET",
product="CNC"
)
Includes:
structured logs
retry for network/API errors
custom ZerodhaAPIError for failures
Request token expires every few minutes, so you must generate it daily.
Access token expires at the end of each trading day.
Zerodha does NOT allow auto-login --- must authenticate manually.
You must subscribe to KiteConnect API (โน500/month).