Skip to content

Latest commit

 

History

History
228 lines (178 loc) · 6.96 KB

File metadata and controls

228 lines (178 loc) · 6.96 KB

CrewAI Stock Analysis System

A comprehensive AI-powered stock analysis system built with CrewAI and CopilotKit, featuring multiple specialized agents for financial research, analysis, and investment recommendations.

🚀 Features

  • Multi-Agent Architecture: Specialized AI agents for different aspects of stock analysis
  • Real-time Data Integration: SEC filings (10-K, 10-Q), financial websites, and market data
  • Comprehensive Analysis: Financial metrics, market sentiment, and investment recommendations
  • Web API: FastAPI-based RESTful API with CopilotKit integration
  • Interactive Interface: Built-in CopilotKit UI for seamless user interaction

🤖 Agents

1. Financial Analyst Agent

  • Role: Expert financial analyst specializing in stock market analysis
  • Capabilities:
    • P/E ratio, EPS growth, revenue trends analysis
    • Debt-to-equity ratio calculations
    • Industry peer comparisons
    • Market trend analysis
  • Tools: Calculator, SEC filings, website scraping, financial data extraction

2. Research Analyst Agent

  • Role: Market research specialist focusing on news and sentiment analysis
  • Capabilities:
    • Recent news article collection and summarization
    • Market sentiment analysis
    • Earnings announcements tracking
    • Press release monitoring
  • Tools: Website search, SEC filings, content scraping

3. Investment Advisor Agent

  • Role: Senior investment advisor providing strategic recommendations
  • Capabilities:
    • Comprehensive investment recommendations
    • Risk assessment
    • Portfolio strategy formulation
    • Insider trading activity analysis
  • Tools: Calculator, web research, financial modeling

🛠️ Tools & Integrations

Built-in Tools

  • Calculator Tool: Safe mathematical operations for financial calculations
  • SEC 10-K Tool: Semantic search through annual SEC filings
  • SEC 10-Q Tool: Quarterly SEC filing analysis
  • Website Search Tool: Real-time web data collection
  • Website Scraping Tool: Content extraction from financial websites

External APIs

  • SEC API: Official SEC filings data
  • OpenRouter: AI model access (DeepSeek R1)
  • Financial Data Sources: Real-time market data integration

📋 Project Structure

crew-ai/
├── stock_analysis/
│   ├── __init__.py
│   ├── main.py              # FastAPI application entry point
│   ├── crew.py              # CrewAI crew configuration
│   ├── config/
│   │   ├── agents.yaml      # Agent configurations
│   │   └── tasks.yaml       # Task definitions
│   └── tools/
│       ├── __init__.py
│       ├── calculator_tool.py    # Mathematical operations
│       └── sec_tool.py           # SEC filings integration
├── pyproject.toml           # Project dependencies
├── uv.lock                  # Dependency lock file
└── README.md               # This file

🚀 Quick Start

Prerequisites

  • Python 3.13+
  • UV package manager (recommended)
  • API keys for:
    • OpenRouter API
    • SEC API

Installation

  1. Clone the repository

    git clone https://github.com/Avyakta000/crew-ai.git
    cd crew-ai
  2. Install dependencies

    uv sync
  3. Environment Setup Create a .env file in the root directory:

    OPENROUTER_API_KEY=your_openrouter_api_key
    SEC_API_API_KEY=your_sec_api_key
    PORT=8000
  4. Run the application

    uv run python stock_analysis/main.py

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

🔧 Configuration

Agent Configuration (config/agents.yaml)

Defines the roles, goals, and backstories for each AI agent:

  • Financial Analyst: Market analysis expert
  • Research Analyst: News and sentiment specialist
  • Investment Advisor: Strategic recommendation provider

Task Configuration (config/tasks.yaml)

Specifies the tasks each agent performs:

  • Financial Analysis: Comprehensive stock health assessment
  • Research: News collection and market sentiment analysis
  • Filings Analysis: SEC document review and insights
  • Recommendation: Investment advice synthesis

🌐 API Endpoints

Core Endpoints

  • GET /health - Health check endpoint
  • POST /copilotkit - CopilotKit integration endpoint

Usage Example

# Health check
curl http://localhost:8000/health

# Run stock analysis (via CopilotKit)
curl -X POST http://localhost:8000/copilotkit \
  -H "Content-Type: application/json" \
  -d '{"company_stock": "AAPL"}'

🧪 Usage Examples

Basic Stock Analysis

from stock_analysis.crew import StockAnalysisCrew

# Initialize the crew
crew = StockAnalysisCrew()

# Run analysis for a specific stock
result = crew.crew().kickoff(inputs={"company_stock": "AAPL"})
print(result)

Custom Analysis

# The crew can be configured with different stocks
# Modify the SEC tools initialization in crew.py:
SEC10QTool("TSLA"),  # For Tesla
SEC10KTool("TSLA"),

🔑 Environment Variables

Variable Description Required
OPENROUTER_API_KEY OpenRouter API key for AI model access Yes
SEC_API_API_KEY SEC API key for filings data Yes
PORT Server port (default: 8000) No

📊 Analysis Workflow

  1. Research Phase: Collect recent news and market sentiment
  2. Financial Analysis: Analyze key metrics and ratios
  3. SEC Filings Review: Extract insights from official documents
  4. Synthesis: Combine all analyses into investment recommendations
  5. Output: Generate comprehensive investment report

🛡️ Security Features

  • Safe Calculator: Restricted mathematical operations only
  • Input Validation: Robust error handling for all inputs
  • API Rate Limiting: Built-in protection against abuse
  • Secure Headers: Proper HTTP headers for SEC API requests

🔧 Customization

Adding New Agents

  1. Define agent configuration in config/agents.yaml
  2. Create agent method in crew.py
  3. Add corresponding task in config/tasks.yaml
  4. Update crew composition in crew() method

Adding New Tools

  1. Create tool class in tools/ directory
  2. Import and configure in agent definitions
  3. Test integration with existing workflow

🐛 Troubleshooting

Common Issues

  1. API Key Errors

    • Verify environment variables are set correctly
    • Check API key validity and quotas
  2. SEC API Rate Limits

    • Implement request throttling
    • Consider caching for repeated requests
  3. Model Access Issues

    • Verify OpenRouter API key
    • Check model availability and pricing

Debug Mode

Enable verbose logging by setting verbose=True in agent configurations.

📈 Performance Considerations

  • Concurrent Processing: Sequential task execution for consistency
  • Memory Management: Efficient handling of large SEC documents
  • API Optimization: Smart caching and request batching
  • Error Recovery: Graceful handling of API failures