CrewAI Stock Analysis: Multi-Agent Investment Tool with AkShare & GPT

10月3日 Published inStock Market Tools

The CrewAI-powered stock analysis and investment tool is built upon a framework of coordinated agent teams, functioning essentially as a digital research department. Data collectors, analysts, and decision-makers collaborate through structured workflows to perform multi-dimensional analyses covering fundamental, technical, and industry-level metrics. The system is capable of batch processing multiple tickers simultaneously, monitoring real-time prices and indicators to trigger alerts as market conditions change. The end result is a detailed, automated report containing actionable investment recommendations, accessible via a web interface for streamlined task management. Technically, the system integrates CrewAI with AkShare, OpenAI, and Serper, utilizing a caching layer and robust error handling to ensure scalability and speed.

  • Intelligent Analysis: AI-driven evaluation across fundamentals, technical indicators, and industry context.
  • Batch Processing: Parallel execution for multiple stocks to minimize processing time.
  • Real-Time Monitoring: Continuous tracking of price action and key metrics with immediate movement alerts.
  • Decision Support: Consolidated analytical data translated into concrete investment suggestions.
  • Automated Reporting: System-generated reports and visualizations that eliminate the need for manual formatting.
  • Multi-Agent Setup: A specialized team of nine agents dividing the workload into collection, analysis, and decision phases.
  • Dual Architecture: Utilizes "Crews" for collaborative teamwork and "Flows" for rigorous process control.
  • Comprehensive Data Sources: Integration with AkShare, OpenAI, and Serper for data breadth and accuracy.
  • Caching: Efficient storage of analyzed data to reduce redundant API calls.
  • Error Handling: Built-in retry mechanisms and exception management for stability.
  • Modular Design: Allows for the addition of new features without disrupting the core architecture.

Core Components

Data Collection Crew

  • Market Researcher: Gathers news, industry updates, and company filings to provide necessary context.
  • Financial Data Expert: Retrieves financial statements and ratios, performing benchmarks against industry peers.
  • Technical Analyst: Fetches price history and computes technical indicators to identify market trends.
  • Data Validation Specialist: Ensures data quality, flags outliers, and cleanses the data feed.

Analysis Crew

  • Fundamental Analyst: Evaluates financial health, executes valuation models, and projects future growth.
  • Risk Assessor: Identifies and quantifies market exposure while suggesting specific controls.
  • Industry Expert: Analyzes competitive positioning, sector trends, and the impact of regulatory changes.

Decision Crew

  • Investment Strategist: Synthesizes findings into a formal rating, sets price targets, and estimates confidence levels.
  • Report Generator: Structures the final output and integrates charts to optimize readability.
  • Quality Monitor: Verifies the accuracy and consistency of all findings to ensure no analytical gaps exist.

AkShare Integration

  • Real-Time Data: Accesses live A-share pricing and volume data via AkShare.
  • Historical Data: Retrieves daily, weekly, and monthly bars for long-term trend analysis.
  • Financials: Direct access to financial statements and performance metrics with peer comparison capabilities.
  • Market Data: Monitors quotes, fund flows, and broader sentiment indicators.

Data Validation and Cleaning

  • Quality Scoring: Automatically assesses data completeness and filters out noise.
  • Anomaly Detection: Flags price spikes and data outliers for review.
  • Standardization: Ensures uniform formats and units across all data points.
  • Caching: Stores retrieved data to minimize duplicate requests and latency.

Fundamental Analysis

  • Ratio Analysis: Evaluation of PE, PB, ROE, and ROA.
  • Profitability: Analysis of revenue trends, net margins, and gross margins.
  • Valuation: Comprehensive modeling using DCF, comparables, and industry benchmarks.
  • Financial Health: Assessment of debt levels, cash flow, and solvency.

Technical Analysis

  • Trend Detection: Identification of moving averages, trendlines, and support/resistance levels.
  • Indicators: Calculation of RSI, MACD, KDJ, and Bollinger Bands.
  • Chart Patterns: Analysis of candlestick formations and volume-based clues.
  • Signals: Generation of buy and sell triggers derived from technical setups.

Industry Analysis

  • Positioning: Assessment of market share and the strength of the competitive moat.
  • Sector Trends: Monitoring of regulatory shifts, technological advancements, and growth outlooks.
  • Peer Comparison: Benchmarking strengths and weaknesses against primary rivals.
  • SWOT: A structured overview of internal and external strategic factors.

Risk Identification

  • Market Risk: Exposure to systemic factors and market volatility.
  • Financial Risk: Analysis of liquidity, leverage, and earnings stability.
  • Operational Risk: Assessment of management quality, strategy, and execution.
  • Industry Risk: Impact of policy changes, disruption, and competition.

Risk Quantification

  • Risk Score: A standardized 0–100 risk scale.
  • VaR Calculation: Estimation of potential loss at specific confidence levels.
  • Stress Testing: Simulation of performance under extreme market scenarios.
  • Sensitivity Analysis: Measuring the impact of shifts in key variables.

Investment Recommendation

  • Rating System: A six-tier scale: Strong Buy, Buy, Overweight, Hold, Underweight, and Sell.
  • Price Target: Valuation-based targets for specific time horizons.
  • Strategy Suggestions: Recommendations for long-term holding, swing trading, or value-based approaches.
  • Allocation Advice: Guidance on suggested portfolio weighting.

Smart Recommendations

  • Personalized: Recommendations tailored to the user's specific risk appetite.
  • Timing: Precision signals for market entry and exit.
  • Portfolio Optimization: A holistic view across multiple analyzed stocks.
  • Alternatives: Identifying similar tickers that may offer better value.

Automated Report Generation

  • Structured Format: Standardized sections covering the full analytical spectrum.
  • Visuals: Automatically generated charts and data visualizations.
  • Multi-Format Support: Exports available in Markdown, PDF, and HTML.
  • Custom Templates: Flexible layouts and content structures.

Executive Summary

  • Key Takeaways: Concise summaries of conclusions and investment ratings.
  • Highlighted Findings: Designated sections for critical data points.
  • Risk Warnings: Prominent flags for major concerns or red flags.
  • Action Items: Clearly defined next steps for the investor.

Real-Time Monitoring

  • Price Tracking: Continuous updates on live quotes.
  • Indicator Tracking: Monitoring for shifts in technical or fundamental metrics.
  • News Monitoring: Real-time tracking of headlines and regulatory filings.
  • Sentiment Tracking: Gauging the prevailing market mood.

Smart Alerts

  • Price Alerts: Triggered by the breach of pre-set price thresholds.
  • Indicator Alerts: Notifications for RSI crosses or unusual ratio movements.
  • News Alerts: Immediate updates on high-impact headlines.
  • Portfolio Alerts: Triggers based on aggregate portfolio risk or return levels.

Notification System

  • Email: Routine alert delivery to your inbox.
  • SMS: Text message alerts for urgent updates.
  • App Push: Direct mobile notifications.
  • Webhook: Support for custom integrations into external systems.

Installation and Configuration

Requirements

  • Python 3.8 or higher
  • Windows, macOS, or Linux
  • 4GB+ RAM recommended
  • Active internet connection for OpenAI API and data retrieval

Install Dependencies

git clone <repository-url>
cd crewai_stock_analysis_system
pip install -r requirements.txt
# Optional for A-share data integration
pip install akshare

Environment Setup

Create a .env file in the root directory:

OPENAI_API_KEY=your-openai-api-key-here
OPENAI_MODEL_NAME=gpt-4o
SERPER_API_KEY=your-serper-api-key-here
CACHE_TTL=3600
MAX_WORKERS=5
LOG_LEVEL=INFO

Verify Installation

python test_final_system.py
python main.py info

Command Line Usage

Single Stock Analysis

python main.py single --company "贵州茅台" --ticker "600519"
python main.py single --company "紫光股份" --ticker "000938" --no-cache

Batch Analysis

python main.py batch
python main.py batch --stocks-file stocks.txt --max-workers 5

Interactive Flows

python main.py interactive
python main.py batch-flow

Stocks File Format (stocks.txt)

# Company,Ticker
Apple Inc.,AAPL
Microsoft,MSFT
Alphabet,GOOGL
Amazon,AMZN
Tesla,TSLA

Web Interface

python src/web_app.py
# Access via http://localhost:5000

The web interface includes:

  • A real-time dashboard for price and indicator updates.
  • Task management for ongoing and historical analyses.
  • A report viewer with comprehensive download options.
  • System settings and alert configuration panels.

API Usage

Basic Single Analysis

from src.stock_analysis_system import StockAnalysisSystem

system = StockAnalysisSystem()
result = system.analyze_stock("贵州茅台", "600519")

if result['success']:
    print(f"Rating: {result['investment_rating']['rating']}")
    print(f"Score: {result['overall_score']:.1f}/100")

Batch Processing

stocks = [
    {'company': 'Microsoft', 'ticker': 'MSFT'},
    {'company': 'Alphabet', 'ticker': 'GOOGL'},
]
results = system.analyze_multiple_stocks(stocks, max_workers=3)

Real-Time Monitoring

from src.utils.monitor import StockMonitor

monitor = StockMonitor()
monitor.add_stock_to_monitor("Apple", "AAPL", interval=300)
monitor.add_alert_rule(
    "price_alert", "AAPL", "price", "above", 180.0,
    "Apple stock broke $180"
)
monitor.start_monitoring()

Advanced Features

Custom Analysis Flow

from src.flows.investment_flow import SmartInvestmentFlow

flow = SmartInvestmentFlow()
flow.set_analysis_depth("deep")
flow.set_risk_tolerance("medium")
flow.set_investment_horizon("long_term")
result = flow.kickoff()

Optimized Batch Processing

from src.utils.batch_analyzer import BatchStockAnalyzer

analyzer = BatchStockAnalyzer(max_workers=5)
def progress_callback(progress):
    print(f"{progress['percentage']:.1f}% complete")
analyzer.set_progress_callback(progress_callback)
result = analyzer.analyze_multiple_stocks(stocks, strategy="adaptive", timeout=300)

Core Tools List

Data Acquisition

  • AkShareTool: Real-time and historical A-share data.
  • MarketDataTool: Market quotes and institutional fund flow data.
  • NewsSearchTool: Aggregation of relevant headlines and filings.

Analysis

  • FundamentalAnalysisTool: Financial ratio calculations and valuations.
  • TechnicalAnalysisTool: Indicators and chart pattern identification.
  • RiskAssessmentTool: Identification and quantification of risk factors.
  • SentimentAnalysisTool: Analysis of news sentiment and market mood.

Decision

  • InvestmentAdvisorTool: Generation of ratings, targets, and strategies.
  • ReportGenerationTool: Creates formatted reports with integrated visuals.
  • QualityControlTool: Conducts accuracy and completeness checks.

Agent Configuration Examples

market_researcher:
  role: "Market Researcher"
  goal: "Collect news and industry updates for {company}"
  backstory: "Veteran market analyst with expertise in macroeconomic trends."
  tools: [akshare_tool, serper_dev_tool, sentiment_analysis_tool]

fundamental_analyst:
  role: "Fundamental Analyst"
  goal: "Assess financial health and intrinsic value"
  backstory: "Value investing specialist focusing on long-term balance sheet stability."
  tools: [fundamental_analysis_tool, financial_calculator_tool]

Advanced Configuration

Performance Tuning

system = StockAnalysisSystem()
system.cache_ttl = 7200   # Set cache time-to-live to 2 hours
system.max_cache_size = 1000

Concurrency Settings

analyzer = BatchStockAnalyzer(
    max_workers=10,
    timeout=600,
    retry_count=3,
    strategy="adaptive"
)

Custom Tool Development

from src.tools.base_tool import BaseTool

class CustomAnalysisTool(BaseTool):
    name: str = "Custom Analysis Tool"
    description: str = "Implements user-defined analysis logic"

    def _run(self, input_data: str) -> str:
        return self.custom_analysis(input_data)

    def custom_analysis(self, data):
        return "Custom analysis result"

Alert Rule Examples

# Price breakout alert
monitor.add_alert_rule("price_breakout", "AAPL", "price", "above", 180.0, "Breakout alert triggered")

# RSI oversold alert
monitor.add_alert_rule("rsi_oversold", "AAPL", "indicator", "below", 30, "RSI below 30")

# Rating score drop alert
monitor.add_alert_rule("score_drop", "AAPL", "score", "below", 60, "System rating downgrade")

Security and Compliance

  • API Key Management: Handled exclusively via environment variables. Regularly rotate keys, monitor usage, and set consumption limits.
  • Data Security: Implementation of encrypted local storage, restricted file permissions, data masking for sensitive fields, and access logging.
  • Compliance: Full adherence to data provider terms of service. Mandatory display of financial disclaimers and risk warnings in accordance with current regulations.

Performance Monitoring

  • System Metrics: Monitoring of CPU/memory usage, network latency, API success rates, and cache hit ratios.
  • Operational Metrics: Tracking of analysis success rates, average response times, error frequencies, and user feedback.
  • Optimization: Ongoing tuning of database queries, caching adjustments, and improvements to concurrency and memory management.

Troubleshooting

Common Errors

Missing API Key

  • Error: Missing OPENAI_API_KEY
  • Fix: Ensure the key is correctly added to your .env file.

Network Failure

  • Error: Request failed
  • Fix: Verify your internet connection, configure a proxy if necessary, or retry the request.

Data Fetch Failure

  • Error: Data unavailable
  • Fix: Verify the ticker symbol format and check the status of the data source provider.

Performance Issues

Slow Response Times

  • Reduce the number of concurrent workers.
  • Ensure caching is enabled.
  • Streamline complex queries and upgrade hardware if necessary.

Out of Memory

  • Reduce the batch size for analysis.
  • Clear the system cache.
  • Optimize data structures and consider adding swap space.

Data Quality Problems

Incomplete Data

  • Check the health of the primary data source.
  • Re-confirm ticker symbols.
  • Retry the fetch operation or configure fallback data sources.

Anomalous Data

  • Ensure validation modules are active.
  • Adjust outlier thresholds.
  • Perform manual corrections or enable quality-specific alerts.