Content
# 🤖 Multi-Agent Intelligent Stock Analysis and Backtesting System
A complete stock investment solution based on **LangGraph** and **FastAPI**, integrating two core functionalities: **real-time analysis** and **historical backtesting**. Utilizing a multi-Agent parallel architecture, it provides professional-level fundamental, technical, and valuation analysis, and supports comprehensive historical validation of investment strategies.
## 🌟 System Features
### 📊 Dual-Core Mode
- **💡 Real-Time Analysis Mode**: Single deep analysis, generating a professional investment report in 3-5 minutes.
- **📈 Intelligent Backtesting Mode**: Historical strategy validation, automated investment decision backtesting, and performance evaluation.
### 🤖 Multi-Agent Parallel Analysis Engine
- **📈 Fundamental Analysis Agent**: In-depth analysis of financial status, profitability, and growth potential.
- **📉 Technical Analysis Agent**: Analysis of price trends, technical indicators, and support/resistance levels.
- **💰 Valuation Analysis Agent**: Valuation metrics, industry comparisons, and investment value assessments.
- **📝 Summary Analysis Agent**: Integrates professional analyses to generate comprehensive investment recommendations.
- **💡 Investment Decision Agent**: Generates standardized JSON investment decisions based on multi-dimensional analysis.
### 🚀 Core Advantages
- 🤖 **Intelligent Multi-Agent System**: Parallel analysis architecture based on LangGraph.
- 📊 **Comprehensive A-Share Data**: MCP protocol connection, 37 professional data analysis tools.
- 💹 **Three-Dimensional Analysis**: Fundamental + Technical + Valuation analysis executed in parallel.
- 🔄 **Real-Time Communication**: WebSocket real-time progress monitoring and log display.
- 📈 **Visual Backtesting**: High-definition charts with Chart.js, real-time progress tracking.
- 📄 **Professional Reports**: Investment analysis reports in Markdown format, supporting one-click export.
- 🎯 **Intelligent Parsing**: Automatically identifies stock codes and company names.
- ⚡ **Performance Optimization**: Connection pooling + intelligent caching, achieving over 85% speed improvement.
- 📱 **Modern Interface**: Responsive web design, perfectly supporting mobile devices.
## 🏗️ System Architecture
### 🔄 Complete Workflow
```
Real-Time Analysis Mode:
User Query → Intelligent Parsing → Parallel Agent Analysis → Summary Report → Visual Display
├── Fundamental Agent (Financial Data Analysis)
├── Technical Agent (Technical Indicator Analysis)
└── Valuation Agent (Valuation Comparison Analysis)
↓
Summary Agent → Comprehensive Investment Report
Intelligent Backtesting Mode:
Configuration Parameters → Time Series Generation → Loop Execution of Multi-Agent Analysis → JSON Decision Generation → Virtual Trading Execution → Performance Statistical Analysis
```
### 🛠️ Technical Architecture
```
Frontend Interface Layer (HTML5 + CSS3 + JavaScript + Chart.js)
↓ WebSocket Real-Time Communication
API Service Layer (FastAPI Real-Time Analysis + Flask Backtesting Service)
↓
Multi-Agent Workflow Engine (multi_agent_workflow.py)
├── MCP Connection Pool (30 seconds timeout + intelligent retry)
├── Gemini Model (60 seconds timeout + 2 retries)
└── Intelligent Caching System (Price Cache + Analysis Cache)
↓
Data Layer (37 MCP Professional Tools + Backtesting System)
```
### 💻 Tech Stack
- **Backend Framework**: FastAPI + Flask + LangGraph + LangChain + asyncio
- **Frontend Technology**: Native HTML/CSS/JavaScript + WebSocket + Chart.js
- **AI Model**: Google Gemini 2.0 Flash (optimized timeout + retry mechanism)
- **Data Source**: MCP Server (37 professional data tools for A-shares)
- **Backtesting Engine**: Multi-frequency decision support + virtual trading system + comprehensive performance statistics.
## 📦 Quick Start
### 1. Environment Preparation
```bash
# Clone the project
git clone --single-branch -b backtest https://github.com/kissjerryfan/mcp_agent.git
cd mcp_agent
```
```bash
# Install dependencies
pip install -r requirements.txt
```
### 2. Environment Configuration
Create a `.env` file:
```env
GOOGLE_API_KEY=your_google_api_key_here
GEMINI_MODEL=gemini-2.0-flash
```
### 3. Start the Service
#### 🚀 Real-Time Analysis Mode
```bash
python app.py
```
**Access Address**: http://localhost:8000/static/index.html
#### 📊 Backtesting Analysis Mode
```bash
python start_backtest_system.py
# or
python backtest_api.py
```
**Access Address**: http://localhost:5000
## 💡 Detailed User Guide
### 🔍 Real-Time Analysis Mode
#### Functional Features
- **⚡ Fast Analysis**: Complete multi-dimensional analysis in 3-5 minutes.
- **📊 Real-Time Monitoring**: WebSocket displays analysis progress and key steps in real-time.
- **📄 Professional Reports**: Generates complete investment analysis reports.
- **🎯 Intelligent Recognition**: Automatically parses company names and stock codes.
#### Access Address
- **🌐 Analysis Interface**: http://localhost:8000/static/index.html
- **📋 API Documentation**: http://localhost:8000/docs
- **🔌 WebSocket**: ws://localhost:8000/ws/multi
#### Query Format
**Standard Format**: `Please analyze the investment value of [Company Name]([Stock Code])`
**Example Queries**:
```
Please analyze the investment value of Kweichow Moutai(sh.600519)
Please analyze the investment value of BYD(sz.002594)
Please analyze the investment value of CATL(sz.300750)
Please analyze the investment value of Hikvision(sz.002415)
```
**Supported Stock Code Formats**:
- `sh.600519` (Shanghai Stock Exchange Main Board)
- `sz.000858` (Shenzhen Stock Exchange Main Board)
- `sz.300750` (ChiNext)
### 📈 Intelligent Backtesting Mode
#### ⚡ Performance Optimization Configuration Table
| Mode | Time Range | Decision Frequency | Number of Decision Points | Estimated Time | Applicable Scenarios | Recommendation |
| ------------ | ---------- | ------------------ | ------------------------ | -------------- | -------------------- | -------------- |
| ⚡ **Super Fast** | 3 months | Monthly Decision | 3 points | 2-3 minutes | Quick Experience Test | ⭐⭐⭐⭐⭐ |
| 🚀 **Fast** | 3 months | Weekly Decision | 12 points | 5-8 minutes | Daily Strategy Validation | ⭐⭐⭐⭐⭐ |
| 📊 **Standard** | 6 months | Weekly Decision | 24 points | 10-15 minutes | Detailed Strategy Analysis | ⭐⭐⭐⭐ |
| 📈 **Deep** | 12 months | Weekly Decision | 48 points | 20-30 minutes | Long-Term Strategy Research | ⭐⭐⭐ |
| ⚠️ **Detailed** | 3 months | Daily Decision | 90 points | 30-45 minutes | High-Frequency Strategy Research | ⭐⭐ |
#### 🎯 Backtesting Operation Process
**Step 1: Configure Backtesting Parameters**
1. **Select Stock**:
- Manually input company name and stock code.
- Or use quick selection buttons (Kweichow Moutai, BYD, CATL, etc.).
2. **Set Time Range**:
- 💡 **First-time users are advised**: 3 months time range.
- Choose the start and end dates for backtesting.
3. **Configure Strategy Parameters**:
- Set initial capital (≥10,000 yuan).
- 💡 **Recommended choice**: "Weekly Decision" for the best balance of speed and accuracy.
- ⚠️ **Avoid choosing**: "Daily Decision" as it will significantly increase time consumption.
**Step 2: Start Backtesting Analysis**
1. Click the "🚀 Start Backtest" button.
2. The system automatically displays the estimated total time.
3. A real-time progress bar shows the current analysis status and remaining time.
4. You can click "⏹️ Stop Backtest" at any time to interrupt the operation.
**Step 3: Analyze Result Display**
- **📊 Key Metrics Cards**: Total return, maximum drawdown, Sharpe ratio, trading win rate.
- **📈 Visual Charts**: Asset value trend chart, return distribution histogram.
- **📋 Detailed Trading Records**: Complete buy/sell records including price, quantity, and confidence level.
- **💾 One-Click Export**: Supports JSON format result download.
#### 💻 Programming Interface Usage
```python
from backtest_system import BacktestSystem
# Create an instance of the backtesting system
backtest = BacktestSystem(initial_capital=100000.0)
# Execute backtesting analysis
results = await backtest.run_backtest(
stock_code="sh.600519", # Stock code
company_name="Kweichow Moutai", # Company name
start_date="2024-01-01", # Start date
end_date="2024-06-30", # End date
frequency="weekly" # Decision frequency: daily/weekly/monthly
)
# Result analysis
print(f"Total Return: {results['total_return']:.2%}")
print(f"Maximum Drawdown: {results['max_drawdown']:.2%}")
print(f"Sharpe Ratio: {results['sharpe_ratio']:.2f}")
print(f"Trading Win Rate: {results['win_rate']:.1%}")
```
## 📊 Investment Decision Standard Format
The standardized JSON investment decision format generated by the system:
```json
{
"action": "BUY|SELL|HOLD", // Action type
"confidence": 0.85, // Confidence level (0.0-1.0)
"target_price": 1800.0, // Target price
"stop_loss": 1600.0, // Stop loss price
"position_size": 0.3, // Suggested position size (0.0-1.0)
"holding_period": "medium", // Holding period: short/medium/long
"risk_level": "medium", // Risk level: low/medium/high
"reasons": [ // Decision basis
"Strong fundamentals, continuous growth in ROE",
"Technical breakout of key resistance levels",
"Valuation is reasonable, PE below industry average"
]
}
```
## 📈 Analysis Report Example
The structure of the professional investment analysis report generated by the system:
```markdown
# Kweichow Moutai(sh.600519) Investment Analysis Report
## 📊 Executive Summary
Based on multi-Agent parallel analysis, Kweichow Moutai currently shows excellent investment value...
[AI-generated core investment insights and strategy recommendations]
## 📈 Key Points of Fundamental Analysis
**Financial Health**: Excellent | **Profitability**: Strong | **Growth Potential**: Stable
- ROE has exceeded 20% for five consecutive years, leading the industry in profitability.
- Revenue and net profit maintain a stable growth trend.
- Ample cash flow and healthy financial structure.
## 📉 Key Points of Technical Analysis
**Trend**: Upward | **Momentum**: Strong | **Support/Resistance**: 1650/1850
- Stock price successfully breaks through the 20-day moving average, strengthening the technical outlook.
- MACD indicator shows a golden cross signal, improving market sentiment.
- RSI indicator shows slight overbought conditions, requiring attention to pullback risks.
## 💰 Key Points of Valuation Analysis
**Valuation Level**: Reasonable | **PE**: 28.5 times | **PB**: 5.2 times
- Current PE is below the historical average of 30 times, making the valuation attractive.
- Valuation shows a clear advantage compared to leading companies in the same industry.
- PEG ratio indicates a good match between valuation and growth potential.
## ⚖️ Comprehensive Investment Rating
**Investment Recommendation**: Buy | **Target Price**: 1800-1900 yuan | **Risk Level**: Medium
## 🎯 Investment Highlights & ⚠️ Major Risks
[AI provides detailed analysis of investment highlights and risk warnings]
## 🚀 Operational Strategy Recommendations
[Specific entry timing, position management, stop-loss and take-profit strategies]
```
## 🛠️ Overview of MCP Data Tools (37 Professional Tools)
This system integrates 37 professional A-share data analysis tools, covering comprehensive investment analysis needs:
### 🏛️ Stock Market Data (4 Tools)
- **get_historical_k_data**: Historical K-line data (supports daily/weekly/monthly/minute levels).
- **get_stock_basic_info**: Basic stock information (industry classification, market capitalization, etc.).
- **get_dividend_data**: Historical dividend information (dividend rate, payout records).
- **get_adjust_factor_data**: Adjustment factor data (pre-adjustment, post-adjustment factors).
### 📊 Financial Statement Data (6 Tools)
- **get_profit_data**: Quarterly profitability data (ROE, ROA, net profit margin, etc.).
- **get_operation_data**: Quarterly operational capability data (various turnover ratios).
- **get_growth_data**: Quarterly growth capability data (revenue growth rate, profit growth rate).
- **get_balance_data**: Balance sheet data (asset structure, liability situation).
- **get_cash_flow_data**: Cash flow data (operating, investing, financing cash flows).
- **get_dupont_data**: DuPont analysis data (ROE decomposition analysis).
### 🔍 Market Overview Data (2 Tools)
- **get_trade_dates**: Trading calendar query (get trading days within a specified time range).
- **get_all_stock**: Comprehensive stock list and trading status.
### 📈 Index-Related Data (4 Tools)
- **get_stock_industry**: Industry classification data and sector information.
- **get_sz50_stocks**: List and weights of SSE 50 constituent stocks.
- **get_hs300_stocks**: List and weights of CSI 300 constituent stocks.
- **get_zz500_stocks**: List and weights of CSI 500 constituent stocks.
### 🌐 Macroeconomic Data (6 Tools)
- **get_deposit_rate_data**: Historical data of benchmark deposit rates.
- **get_loan_rate_data**: Historical data of benchmark loan rates.
- **get_required_reserve_ratio_data**: Records of changes in reserve requirement ratios.
- **get_money_supply_data_month**: Monthly money supply data (M0/M1/M2).
- **get_money_supply_data_year**: Annual summary of money supply data.
- **get_shibor_data**: Shanghai Interbank Offered Rate.
### ⏰ Date Tools & Analysis (2 Tools)
- **get_latest_trading_date**: Get the most recent trading date.
- **get_stock_analysis**: Comprehensive data-driven analysis report.
### 📉 Technical Indicator Analysis (4 Tools)
- **get_technical_indicators**: Comprehensive technical indicator calculations (MACD, RSI, KDJ, BOLL, WR, etc.).
- **get_moving_averages**: Multi-period moving averages (5/10/20/50/120/250 days).
- **calculate_bollinger_bands**: Bollinger Bands indicator calculation (upper, middle, lower bands).
- **calculate_macd**: Detailed MACD indicator calculation (DIF, DEA, MACD histogram).
- **calculate_rsi**: RSI relative strength indicator calculation.
### 💰 Valuation Analysis Tools (5 Tools)
- **get_valuation_metrics**: Valuation metrics and historical trends (PE, PB, PS, and historical percentiles).
- **calculate_peg_ratio**: PEG ratio calculation (price-to-earnings relative to earnings growth rate).
- **calculate_ddm_valuation**: DDM dividend discount model valuation.
- **calculate_dcf_valuation**: DCF cash flow discount valuation model.
- **get_comparable_analysis**: Valuation analysis of comparable companies in the same industry.
### 🔧 Other Tools (4 Tools)
- **get_market_analysis_timeframe**: Suggested time frame for market analysis.
- **format_trading_calendar**: Trading calendar formatting tool.
- **validate_stock_code**: Stock code format validation and standardization.
> 📋 **Detailed API Documentation**: For complete parameter descriptions and usage examples of each tool, please refer to [DOCUMENTS.md](DOCUMENTS.md).
## ⚡ Performance Optimization Results
### 🚀 Core Optimization Techniques (Achieving over 85% Speed Improvement)
- **🔄 MCP Connection Pool Technology** (50% improvement): Reusing connections to avoid repeated establishment, reducing network overhead.
- **💾 Intelligent Caching System** (30% improvement): Caching price data + analysis results to avoid repeated calculations.
- **⚡ Simplified Workflow** (15% improvement): Dedicated decision-making process optimized for backtesting.
- **⚙️ Default Parameter Optimization** (5% improvement): Pre-setting optimal time range and frequency configurations.
### 📊 Actual Performance Results
- **⚡ Super Fast Mode** (3 months/monthly decision): 3 decision points, 2-3 minutes (before optimization: 15-20 minutes).
- **🚀 Fast Mode** (3 months/weekly decision): 12 decision points, 5-8 minutes (before optimization: 45-60 minutes).
- **📊 Standard Mode** (6 months/weekly decision): 24 decision points, 10-15 minutes (before optimization: 90-120 minutes).
### 🔧 Layered Timeout Control Strategy
- **✅ Infrastructure Timeout** (retained): MCP connection 30 seconds, Gemini API 60 seconds, ensuring quick fault detection.
- **❌ Application Layer Timeout** (removed): No timeout limits on analysis workflows to avoid premature termination of complex tasks.
- **✅ Frontend Interaction Timeout** (retained): WebSocket reconnection every 3 seconds, chart loading waits for 10 seconds.
## 📁 Project Structure
```
mcp-agent/
├── 🚀 Core Service Layer
│ ├── app.py # Real-time analysis FastAPI server
│ ├── backtest_api.py # Backtesting system Flask server
│ ├── start_backtest_system.py # One-click startup script
│ └── multi_agent_websocket.py # WebSocket communication manager
│
├── 🤖 Multi-Agent Engine Layer
│ ├── multi_agent_workflow.py # Core workflow engine
│ ├── backtest_system.py # Intelligent backtesting system
│ └── agents/ # Agent module directory
│ ├── base_agent.py # Base Agent abstract class
│ ├── fundamental_agent.py # Fundamental analysis Agent
│ ├── technical_agent.py # Technical analysis Agent
│ ├── valuation_agent.py # Valuation analysis Agent
│ ├── summary_agent.py # Summary analysis Agent
│ └── investment_agent.py # Investment decision Agent
│
├── 🎨 Frontend Interface Layer
│ └── frontend/
│ ├── index.html # Real-time analysis main page
│ ├── backtest.html # Backtesting analysis page
│ ├── app.js # Real-time analysis JavaScript logic
│ ├── backtest_script.js # Backtesting functionality JavaScript logic
│ ├── style.css # Common style file
│ └── backtest_style.css # Backtesting specific styles
│
├── 📋 Configuration Document Layer
│ ├── requirements.txt # Python dependency list
│ ├── .env # Environment variable configuration file
│ ├── README.md # Main project documentation (this file)
│ └── DOCUMENTS.md # Detailed API documentation for MCP tools
│
└── 📊 Sample Data Layer
├── backtest_results_*.json # Sample backtesting result files
└── Investment_Analysis_Report_*.txt # Sample analysis report files
```
## 🔧 Advanced Configuration Options
### Complete Environment Variable Configuration
```env
# 🔑 Required Configuration
GOOGLE_API_KEY=your_google_api_key_here
# ⚙️ Optional Configuration
GEMINI_MODEL=gemini-2.0-flash # AI model version
MCP_SERVER_URL=http://localhost:3000/mcp/ # MCP server address
BACKTEST_CACHE_SIZE=1000 # Cache capacity limit
```
### MCP Server Connection Configuration
```python
# Connection configuration in multi_agent_workflow.py
"a_share_data_provider": {
"url": "http://localhost:3000/mcp/", # MCP server address
"transport": "streamable_http" # Transport protocol
}
```
### Key Parameters for Performance Tuning
```python
# Timeout control parameters
MCP_TIMEOUT = 30.0 # MCP connection timeout (seconds)
GEMINI_TIMEOUT = 60 # Gemini API call timeout (seconds)
MAX_RETRIES = 2 # Maximum retry count for connection failures
BASE_DELAY = 3 # Base delay time for retries (seconds)
# Caching optimization parameters
PRICE_CACHE_LIMIT = 1000 # Maximum entries for price data cache
ANALYSIS_CACHE_LIMIT = 500 # Maximum entries for analysis results cache
```
## 🚀 Quick Experience Demonstration
### One-Minute Experience with Backtesting Functionality
```bash
# Start the backtesting system (Web interface)
python start_backtest_system.py
# Or run command-line backtesting directly
python backtest_system.py --stock_code sh.600519 --mode super_fast --period 3M
```
### Test Real-Time Analysis Functionality
```bash
# Start real-time analysis service
python app.py
# Browser access test
# Address: http://localhost:8000/static/index.html
# Test query: Please analyze the investment value of Kweichow Moutai(sh.600519).
```
## 📞 Technical Support and Troubleshooting
### 🔧 Common Problem Solutions
1. **MCP Connection Failure**:
- Check network connection status.
- Verify MCP server running status.
- Confirm firewall settings.
2. **Gemini API Call Error**:
- Verify API key validity.
- Check API call quota limits.
- Confirm network connection is normal.
3. **Slow Backtesting Execution**:
- Use recommended fast mode configuration.
- Avoid selecting daily decision frequency.
- Check the status of the caching system.
4. **Frontend Interface Unreachable**:
- Confirm the corresponding server is running normally.
- Check if ports 8000/5000 are occupied.
- Verify firewall port opening status.
### ⚡ Performance Optimization Recommendations
- 🚀 **First-time Users**: Strongly recommend selecting "Super Fast Mode" (3 months/monthly) for a quick experience.
- 📊 **Daily Analysis**: Recommended to use "Fast Mode" (3 months/weekly) for a balance of analysis depth and execution speed.
- 🔧 **Avoid High-Frequency Decisions**: Unless conducting high-frequency strategy research, avoid daily decision frequency.
- 💾 **Regularly Clear Cache**: Periodically clear cache files to avoid excessive memory resource consumption.
### 👨💻 Developer Extension Guide
- 📝 **Add New Agents**: Inherit from the BaseAgent abstract class and implement the analyze method interface.
- 🔧 **Extend MCP Tools**: Refer to DOCUMENTS.md for complete API specifications.
- 📈 **Customize Investment Strategies**: Modify the decision generation logic in investment_agent.py.
- 🎨 **Personalize Interface Customization**: Edit HTML/CSS/JS source files in the frontend/ directory.
---
**📊 Data-Driven Intelligent Investment, Let AI Be Your Investment Analyst** | **Version 4.0** | **🤖 Multi-Agent + 📈 Backtesting = Complete Investment Solution**
## Contribution Guidelines
Feel free to submit Issues or Pull Requests to help improve the project. Please check existing Issues and documentation before contributing.
## License
This project is licensed under the MIT License - see the LICENSE file for details.
<div align="center">
<img src="https://capsule-render.vercel.app/api?type=waving&color=gradient&customColorList=12,15,20,24§ion=footer&height=100&animation=fadeIn" />
</div>
Connection Info
You Might Also Like
valuecell
Valuecell is a Python project for efficient data management.
hexstrike-ai
HexStrike AI is an AI-powered MCP cybersecurity automation platform with 150+ tools.
AP2
AP2 provides code samples and demos for the Agent Payments Protocol.
terminal-mcp
A terminal emulator exposed via MCP for AI assistants
mighty-security
Don't Simply Trust MCP Server Code, Validate and Scan
api2mcp4j
This is a revolutionary AI MCP plugin with excellent pluggable and...