A sophisticated multi-agent AI system that generates comprehensive equity research reports for NSE stocks using LangGraph orchestration with 7 specialized autonomous agents and 15+ integrated tools for collaborative reasoning.
This project is for only educational purpose. Do not use its output as stock recommendation.
This project uses yfinance python project which is intended for personal purpose only. Hence, do not use this project in production or commercial applications.
This system demonstrates advanced AI collaboration by using multiple specialized agents that work together to analyze stocks from different perspectives.
By default in agentic AI mode, the system uses AI-powered iterative agents that dynamically decide which tools to call and adapt their strategy based on findings:
- AI Research - Iterative LLM-based research that dynamically selects and executes tools
- AI Analysis - Comprehensive analysis agent performing all analysis types with iterative decision-making
- AI Report Generation - AI-driven report creation with professional formatting
Alternatively, you can use the mixed mode workflow (with --skip-ai flag) which follows a more traditional pipeline:
- Research Planning - Creates structured research plans with ordered tool calls
- Data Gathering - Company information, sector analysis, peer comparison
- Financial Analysis - Comprehensive financial statement analysis
- Management Analysis - Management effectiveness and governance assessment
- Technical Analysis - Technical indicators and trend analysis
- Valuation Analysis - Valuation metrics and target price calculation
- Report Synthesis - Final professional report generation
** Agentic AI Mode (Default Mode):**
User Input (Stock Symbol)
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโ
โ AIResearchAgent โ Iterative LLM-based research
โ (Default) โ Dynamically selects & executes tools
โโโโโโโโโโโโฌโโโโโโโโโโโ
โ
โโโโโโโผโโโโโโโโโโโโโโโ
โ AIAnalysisAgent โ Comprehensive analysis (all types)
โ (Default) โ Iterative decision-making
โโโโโโโฌโโโโโโโโโโโโโโโ
โ
โโโโโโโผโโโโโโโโโโโโโโโ
โ AIReportAgent โ AI-driven report generation
โ (Default) โ LLM creates content, tools generate PDF
โโโโโโโฌโโโโโโโโโโโโโโโ
โ
โโโโโโโผโโโโโโ
โ Final โ Markdown + PDF
โ Report โ
โโโโโโโโโโโโโ
Mixed Mode (Use --skip-ai flag):
User Input (Stock Symbol)
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโ
โ ResearchPlanner โ Creates structured research plan
โ Agent โ
โโโโโโโโโโโโฌโโโโโโโโโโโ
โ
โโโโโโโผโโโโโโ
โ Research โ Gathers company & sector data
โ Agent โ
โโโโโโโฌโโโโโโ
โ
โโโโโโโผโโโโโโฌโโโโโโโโโโโโโโ
โ โ โ โ
โโโโโโผโโ โโโผโโโ โโโผโโโ โโโโโโโโผโโ
โFinan-โ โMgmtโ โTechโ โValuat- โ 4 Analysis Agents
โcial โ โAnalโ โAnalโ โion โ (Run in Parallel)
โAnal โ โ โ โ โ โAnal โ
โโโโฌโโโโ โโโฌโโโ โโโฌโโโ โโโโโฌโโโโโ
โโโโโโโโโผโโโโโโโผโโโโโโโโโ
โ โ
โโโโโโโผโโโโโโโผโโโโโโ
โ Report Agent โ Synthesizes all results
โโโโโโโโโโโโโโโโโโโโ
โ
โโโโโโโผโโโโโโ
โ Final โ Markdown + PDF
โ Report โ
โโโโโโโโโโโโโ
The system employs 10 specialized agents organized into three phases. For comprehensive details on each agent's specialization, roles, responsibilities, and tool usage, see Agent Specialization Documentation.
Quick Overview:
Research Phase:
- ResearchPlannerAgent (Mixed Mode) - Creates structured research plans with ordered tool call sequences
- ResearchAgent (Mixed Mode) - Executes research plans to gather company information, sector overview, and peer data
- AIResearchAgent (Agentic AI Mode) - Iterative LLM-based research that dynamically selects and executes tools
Analysis Phase:
- FinancialAnalysisAgent (Mixed Mode) - Performs comprehensive financial statement analysis and ratio interpretation
- ManagementAnalysisAgent (Mixed Mode) - Analyzes management effectiveness and governance
- TechnicalAnalysisAgent (Mixed Mode) - Performs technical analysis with indicators and trends
- ValuationAnalysisAgent (Mixed Mode) - Performs valuation analysis and target price calculation
- AIAnalysisAgent (Agentic AI Mode) - Comprehensive analysis agent that performs all analysis types using iterative decision-making
Report Phase:
- ReportAgent (Mixed Mode) - Synthesizes all data into comprehensive reports
- AIReportAgent (Agentic AI Mode) - AI-driven report generation where content is created by LLM
Agent Selection:
- Default Mode (Agentic AI Mode): Uses AIResearchAgent โ AIAnalysisAgent โ AIReportAgent for fully iterative LLM-driven workflow
- Mixed Mode (
--skip-aior-s): Uses ResearchPlannerAgent โ ResearchAgent โ [4 Analysis Agents in Parallel] โ ReportAgent
See Agent Specialization Documentation for detailed information on each agent's specialization, responsibilities, tools, and when to use each mode.
Stock Data Tools:
- get_stock_metrics - Retrieves stock price data, financial metrics, market data (yfinance)
- get_company_info - Fetches company information, business details, fundamentals
- validate_symbol - Validates stock symbols against NSE
Web Search Tools:
- search_sector_news - Searches for sector-specific news and trends (DuckDuckGo)
- search_company_news - Searches for company-specific news
- search_market_trends - Searches for market trends and analysis
- generic_web_search - Generic web search capability
Analysis & Calculation Tools:
- TechnicalAnalysisFormatter - Formats and processes technical analysis data
- StockDataCalculator - Performs financial calculations and ratios
Report Generation Tools:
- PDFGeneratorTool - Generates professional PDF reports
- ReportFormatterTool - Formats reports in markdown/professional format
Text Processing Tools:
- SummarizerTool - AI-powered text summarization and insight extraction
summarize_text()- Summarizes documents with key pointsextract_insights()- Extracts structured insights from text
Additional Tools:
- PDFParserTool - Extracts text from PDF documents
- ReportFetcherTool - Downloads financial reports and transcripts
- MultiAgentOrchestrator - Manages workflow and agent coordination
- StateGraph - LangGraph StateGraph for workflow management
- Parallel Execution - Analysis agents run concurrently for efficiency
- Structured State - MultiAgentState (Pydantic model) for communication
- Error Handling - Graceful failure recovery with error propagation
- Conditional Logic - Smart routing based on results and errors
- State Management - Tracks progress across all 7 agents
- Python 3.10 or higher (Python 3.11+ recommended)
- OpenAI API key (Get one here)
- pip package manager (usually comes with Python)
- Optional: NVIDIA GPU with CUDA support for accelerated AI processing
Install the package in editable mode (allows you to edit code and have changes reflected immediately):
# Clone the repository
git clone <repository-url>
cd stock-report-generator
# Create and activate virtual environment (recommended)
python3 -m venv venv
source venv/bin/activate # On macOS/Linux
# venv\Scripts\activate # On Windows
# Install in editable mode
pip install -e .Install with GPU support:
pip install -e ".[gpu]"Install minimal dependencies:
pip install -e ".[minimal]"Set up environment variables:
# Copy the example environment file
cp env.example .env
# Edit .env with your API keys
nano .env # or vim .env on macOS/Linux, notepad .env on WindowsAdd your OpenAI API key to .env:
OPENAI_API_KEY=sk-your-actual-api-key-hereAfter installation, you can use the CLI command:
stock-report RELIANCE Or use Python directly:
cd src
python main.py RELIANCE- Clone the repository
git clone <repository-url>
cd stock-report-generator- Create a virtual environment (Recommended)
# Using venv (built-in with Python 3.10+)
python3 -m venv venv
# Activate virtual environment
# On macOS/Linux:
source venv/bin/activate
# On Windows:
venv\Scripts\activate- Install dependencies
# Upgrade pip first
pip install --upgrade pip
# Install all required packages
pip install -r requirements.txt- Set up environment variables
# Copy the example environment file
cp env.example .env
# Edit .env with your API keys
# On macOS/Linux:
nano .env
# or
vim .env
# On Windows:
notepad .envEdit the .env file and set your OpenAI API key:
OPENAI_API_KEY=sk-your-actual-api-key-here- Verify installation
# Test that Python can import the required modules
python3 -c "import langchain, langgraph, openai; print('Installation successful!')"For a lighter installation with only essential dependencies:
pip install -r requirements-minimal.txtFor GPU support (optional, requires NVIDIA GPU):
# Install base requirements first
pip install -r requirements.txt
# Install GPU-specific packages
pip install -r requirements-gpu.txt
# Verify GPU support
python -c "import torch; print(f'CUDA available: {torch.cuda.is_available()}')"# Build the Docker image
docker build -t stock-report-generator .
# Run with environment variables
docker run -e OPENAI_API_KEY=your_key_here stock-report-generator RELIANCE- Create necessary directories
mkdir -p reports temp data/inputs data/outputs- Verify configuration
python3 src/main.py --help- Run a test report
cd src
python3 main.py RELIANCE "Reliance Industries Limited" "Oil & Gas"Issue: ModuleNotFoundError: No module named 'langchain'
# Solution: Install dependencies
pip install -r requirements.txtIssue: pip: command not found
# Solution: Install pip or use python3 -m pip
python3 -m pip install -r requirements.txtIssue: Permission denied errors on macOS/Linux
# Solution: Use --user flag or activate virtual environment
pip install --user -r requirements.txt
# OR
source venv/bin/activate
pip install -r requirements.txtIssue: SSL/Certificate errors
# Solution: Update certificates or use trusted hosts
pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org -r requirements.txtIssue: Conflicting package versions
# Solution: Use a fresh virtual environment
python3 -m venv venv_fresh
source venv_fresh/bin/activate
pip install --upgrade pip
pip install -r requirements.txtIssue: OPENAI_API_KEY not found
# Solution: Set environment variable
export OPENAI_API_KEY=your_key_here
# OR add to .env file (see step 4 above)# Generate report for Reliance Industries
cd src
python main.py RELIANCE "Reliance Industries Limited" "Oil & Gas"
# Generate report for TCS (company name and sector auto-detected if not provided)
python main.py TCS
# Generate report for HDFC Bank
python main.py HDFCBANK "HDFC Bank Limited" "Banking"# Skip AI agents and use structured workflow (ResearchPlanner + ResearchAgent)
python main.py RELIANCE --skip-ai
# Short form
python main.py RELIANCE -s# Export graph diagram along with report
python main.py RELIANCE --export-graph graph.png
# Export graph only (without generating report)
python main.py --export-graph-only graph.pngpython main.py --help # Show all available optionsAvailable Flags:
--skip-aior-s: Skip AI agents and use ResearchPlannerAgent + ResearchAgent (structured workflow) instead of AIResearchAgent and AIAnalysisAgent (AI agents are enabled by default)--export-graph: Export the multi-agent workflow graph diagram--export-graph-only: Only export graph without generating report
If running from the project root directory:
# Method 1: Using module syntax
python -m src.main RELIANCE
# Method 2: Direct path
python src/main.py RELIANCEFor enhanced performance with AI models, you can enable GPU acceleration:
# Install GPU dependencies
pip install -r requirements-gpu.txt
# Verify GPU support
python -c "import torch; print(f'CUDA available: {torch.cuda.is_available()}')"# Build GPU-enabled image
docker build -f docker/Dockerfile.gpu -t stock-report-generator:gpu .
# Run with GPU support
docker run --gpus all -it stock-report-generator:gpu- NVIDIA GPU with CUDA Compute Capability 6.0+
- CUDA Toolkit 11.8 or 12.0
- 4GB+ GPU memory (8GB+ recommended)
๐ Detailed GPU setup guide: docs/GPU_SETUP.md
The system generates comprehensive reports in both Markdown and PDF formats with:
- Key highlights and metrics
- Investment thesis
- Management outlook
- Recommendation summary
- Basic information and trading data
- Financial metrics (P/E, P/B, EPS, etc.)
- Market cap and valuation ratios
- Sector trends and outlook
- Peer comparison
- Regulatory environment
- Growth opportunities
- Revenue and profit growth
- Valuation metrics
- Technical analysis
- Performance indicators
- Strategic initiatives
- Growth opportunities
- Risk factors
- Management outlook
- Investment thesis
- Target price and valuation
- Risk-reward profile
- Time horizon
- Sector-specific risks
- Company risks
- Market risks
- Regulatory risks
The system automatically generates professional PDF reports alongside markdown files. PDF reports feature:
- Clean, professional layout with proper typography
- Color-coded sections for easy navigation
- Consistent formatting and spacing
- Executive summary highlighting
- Financial metrics emphasis
- Automatic Generation: PDFs are created automatically with each report
- Professional Layout: A4 format with proper margins and headers
- Styled Sections: Different visual treatments for various report sections
- Bold Text Support: Proper formatting of bold text and emphasis
- List Formatting: Clean bullet points and numbered lists
- PDFGeneratorTool: Core PDF generation functionality
- Batch Conversion: Convert multiple markdown files to PDF
- Custom Styling: Professional financial report styling
# Required
OPENAI_API_KEY=your_openai_api_key
# Optional
DEFAULT_MODEL=gpt-4o-mini
OUTPUT_DIR=reports- Default Model: GPT-4o-mini (cost-effective)
- Max Tokens: 4000 per request
- Temperature: 0.1 (consistent outputs)
- Context Size: 10,000 entries
src/
โโโ agents/ # AI Agents (7 agents)
โ โโโ __init__.py
โ โโโ base_agent.py # Base agent class
โ โโโ research_planner_agent.py # Research planner agent
โ โโโ research_agent.py # Research agent
โ โโโ financial_analysis_agent.py # Financial analysis agent
โ โโโ management_analysis_agent.py # Management analysis agent
โ โโโ technical_analysis_agent.py # Technical analysis agent
โ โโโ valuation_analysis_agent.py # Valuation analysis agent
โ โโโ report_agent.py # Report synthesis agent
โโโ tools/ # Tool Implementations (15+ tools)
โ โโโ __init__.py
โ โโโ stock_data_tool.py # Stock data retrieval (yfinance, NSE)
โ โโโ web_search_tool.py # Web search (DuckDuckGo)
โ โโโ generic_web_search_tool.py # Generic web search
โ โโโ summarizer_tool.py # Text summarization
โ โโโ pdf_generator_tool.py # PDF generation
โ โโโ report_formatter_tool.py # Report formatting
โ โโโ technical_analysis_formatter.py # Technical analysis
โ โโโ stock_data_calculator.py # Financial calculations
โ โโโ pdf_parser_tool.py # PDF parsing
โ โโโ report_fetcher_tool.py # Report fetching
โโโ graph/ # LangGraph Orchestration
โ โโโ multi_agent_graph.py # MultiAgentOrchestrator
โโโ main.py # Entry point
โโโ config.py # Configuration
1. AI Research Phase (AIResearchAgent - Default)
- Iterative LLM-based research that dynamically selects and executes tools
- Analyzes stock symbol, company, and sector context
- Autonomously decides which tools to call based on current information
- Retrieves real-time stock data (yfinance, NSE)
- Searches for company and sector news
- Gathers peer comparison data
- Adapts research strategy based on findings
2. AI Analysis Phase (AIAnalysisAgent - Default)
- Comprehensive analysis agent that performs all analysis types
- Iterative decision-making process
- Performs financial, management, technical, and valuation analysis
- Dynamically adjusts analysis depth based on available data
- Synthesizes insights across all analysis dimensions
3. AI Report Generation (AIReportAgent - Default)
- AI-driven report generation where content is created by LLM
- PDF generation is handled by tools
- Professional markdown and PDF formatting
- Ensures all required sections are included
1. Research Planning Phase (ResearchPlannerAgent)
- Analyzes stock symbol, company, and sector context
- Reviews available tools
- Creates structured research plan with ordered tool calls
- Outputs executable plan for data gathering
2. Data Gathering Phase (ResearchAgent)
- Executes research plan from planner
- Retrieves real-time stock data (yfinance, NSE)
- Searches for company and sector news
- Gathers peer comparison data
- Collects comprehensive research data
3. Parallel Analysis Phase (4 Agents run concurrently)
- FinancialAnalysisAgent: Financial statement analysis, ratios, health assessment
- ManagementAnalysisAgent: Management effectiveness, governance analysis
- TechnicalAnalysisAgent: Technical indicators, trends, support/resistance
- ValuationAnalysisAgent: Valuation metrics, target price calculation
4. Report Synthesis Phase (ReportAgent)
- Receives all analysis results from 4 analysis agents
- Synthesizes comprehensive report
- Formats professional markdown document
- Generates PDF report with styling
- Ensures all required sections are included
- Graceful Degradation - System continues with partial data
- Fallback Analysis - AI-generated content when data unavailable
- Error Recovery - Automatic retry mechanisms
- Quality Validation - Consistency checking across agents
- Source Validation - Verifies data sources
- Consistency Checking - Identifies conflicting information
- Confidence Scoring - Rates analysis reliability
- Quality Metrics - Tracks report completeness
- Parallel Processing - Agents can run concurrently
- Caching - Reuses previously fetched data
- Rate Limiting - Respects API limits
- Memory Management - Efficient context storage
- Comprehensive Logging - Tracks all operations
- Performance Metrics - Measures execution time
- Error Tracking - Monitors failures
- Context Inspection - Debug workflow state
Default: AI Agents Enabled
import asyncio
from src.main import StockReportGenerator
# Initialize generator (AI agents enabled by default)
generator = StockReportGenerator()
# Generate report programmatically
async def main():
result = await generator.generate_report(
stock_symbol="RELIANCE",
company_name="Reliance Industries Limited", # Optional, auto-detected
sector="Oil & Gas" # Optional, auto-detected
)
print(f"Status: {result['workflow_status']}")
print(f"PDF Path: {result.get('pdf_path')}")
print(f"Errors: {result.get('errors', [])}")
# Run async function
asyncio.run(main())Use Structured Workflow (Skip AI Agents)
from src.main import StockReportGenerator
# Initialize with structured workflow (skip AI agents)
generator = StockReportGenerator(
use_ai_research=False, # Use ResearchPlanner + ResearchAgent
use_ai_analysis=False # Use separate analysis agents
)
# Synchronous wrapper
result = generator.generate_report_sync("RELIANCE")
print(f"Report generated: {result['workflow_status']}")pytest tests/# Format code
black src/
# Lint code
flake8 src/
# Type checking
mypy src/# Install development dependencies
pip install -r requirements.txt
# Set up pre-commit hooks
pre-commit installMain orchestrator class for the system. Initializes and manages the multi-agent workflow.
LangGraph-based orchestrator that manages workflow and agent coordination.
- Manages 7 agents with distinct roles
- Coordinates parallel execution of analysis agents
- Handles state management and error propagation
Generates a comprehensive stock report using all 7 agents.
- stock_symbol: NSE stock symbol (required)
- company_name: Full company name (optional, auto-detected)
- sector: Sector name (optional, auto-detected)
- Returns: Dictionary with workflow results, PDF path, errors, etc.
Synchronous wrapper for generate_report().
All agents inherit from BaseAgent and implement:
execute_task()- Main task executionexecute_task_partial()- Partial state update executionselect_tools()- Autonomous tool selection
We welcome contributions to the Stock Report Generator! Please follow these guidelines:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Make your changes
- Add tests for new functionality
- Ensure all tests pass
- Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
- Follow PEP 8 style guidelines
- Add type hints to all functions
- Include comprehensive docstrings
- Write unit tests for new features
- Update documentation as needed
- Keep functions under 100 lines
- Keep classes under 20 methods
- All functions must have type hints
- All classes and functions must have docstrings
- Functions should not exceed 100 lines
- Classes should not exceed 20 methods
- Scripts should not exceed 500 lines
- Run unit tests:
python -m pytest tests/unit/ - Run integration tests:
python -m pytest tests/integration/ - Ensure test coverage is maintained
This project is licensed under the MIT License - see the LICENSE file for details.
- GitHub: [@devendermishra]
- Issues: GitHub Issues
- Check the documentation
- Search existing issues
- Create a new issue for bugs or feature requests
- Join our discussions for questions
For issues and questions:
- Check the logs in
stock_report_generator.log - Review the error messages
- Verify API keys are correct
- Ensure all dependencies are installed
This system meets and exceeds multi-agent system requirements:
- โ 7 specialized agents with distinct roles (exceeds minimum of 3)
- โ 15+ integrated tools (exceeds minimum of 3)
- โ LangGraph orchestration framework with parallel execution
- โ
Clear communication via structured
MultiAgentState - โ Tools extend beyond basic LLM responses (API calls, file processing, calculations)
See REQUIREMENTS_CHECKLIST.md for detailed verification.
- Real-time Data Integration - Live market data feeds
- Additional Agents - News analysis, risk assessment, ESG analysis
- Advanced Analytics - Machine learning models for predictions
- Portfolio Analysis - Multi-stock comparison
- Custom Templates - Configurable report formats
- API Endpoints - REST API for integration
- Dashboard Interface - Web-based UI
- Visualization Tools - Charts, graphs, interactive reports
- DEVELOPER_HANDOFF.md - Developer onboarding and practical development guide
- REQUIREMENTS_CHECKLIST.md - Detailed requirements verification
- IMPLEMENTATION_SUMMARY.md - Comprehensive implementation details
- DOCUMENTATION.md - Comprehensive system documentation
- AGENT_SPECIALIZATION.md - Detailed agent information
Built with โค๏ธ using LangGraph, LangChain, and modern AI technologies.
Key Technologies:
- LangGraph for multi-agent orchestration
- LangChain for tool integration
- OpenAI GPT models for agent reasoning
- yfinance for stock data
- DuckDuckGo for web search
- ReportLab for PDF generation