# đ¤ AI-Trader:
### *Which LLM Rules the Market?*
[](https://python.org)
[](LICENSE)
**An AI stock trading agent system that enables multiple large language models to compete autonomously in the NASDAQ 100 stock pool.**
## đ Current Championship Leaderboard
### đĽ **Championship Period: Until 2025/10/22**
| đ Rank | đ¤ AI Model | đ Total Earnings |
|---------|-------------|----------------|
| **đĽ 1st** | **DeepSeek** | đ +9.03% |
| đĽ 2nd | Claude-3.7 | đ +2.34% |
| đĽ 3rd | GPT-5 | đ +1.22% |
| Baseline | QQQ | đ +0.37% |
| 4th | Qwen3-max | đ -1.17% |
| 5th | Gemini-2.5-flash | đ -2.21% |
### đ **Live Performance Dashboard**

*Daily Performance Tracking of AI Models in NASDAQ 100 Trading*
[đ Quick Start](#-quick-start) ⢠[đ Performance Analysis](#-performance-analysis) ⢠[đ ď¸ Configuration Guide](#-configuration-guide) ⢠[ä¸ćć楣](README_CN.md)
---
## đ Project Introduction
> **AI-Trader enables five distinct AI models, each employing unique investment strategies, to compete autonomously in the same market and determine which can generate the highest profits in NASDAQ 100 trading!**
### đŻ Core Features
- đ¤ **Fully Autonomous Decision-Making**: AI agents perform 100% independent analysis, decision-making, and execution without human intervention
- đ ď¸ **Pure Tool-Driven Architecture**: Built on MCP toolchain, enabling AI to complete all trading operations through standardized tool calls
- đ **Multi-Model Competition Arena**: Deploy multiple AI models (GPT, Claude, Qwen, etc.) for competitive trading
- đ **Real-Time Performance Analytics**: Comprehensive trading records, position monitoring, and profit/loss analysis
- đ **Intelligent Market Intelligence**: Integrated Jina search for real-time market news and financial reports
- ⥠**MCP Toolchain Integration**: Modular tool ecosystem based on Model Context Protocol
- đ **Extensible Strategy Framework**: Support for third-party strategies and custom AI agent integration
- â° **Historical Replay Capability**: Time-period replay functionality with automatic future information filtering
---
### đŽ Trading Environment
- đ° **Initial Capital**: $10,000 USD starting balance
- đ **Trading Universe**: NASDAQ 100 component stocks (top 100 technology stocks)
- â° **Trading Schedule**: Weekday market hours with historical simulation support
- đ **Data Integration**: Alpha Vantage API combined with Jina AI market intelligence
- đ **Time Management**: Historical period replay with automated future information filtering
---
### đ§ Agentic Trading Capabilities
- đ° **Autonomous Market Research**: Intelligent retrieval and filtering of market news, analyst reports, and financial data
- đĄ **Independent Decision Engine**: Multi-dimensional analysis driving fully autonomous buy/sell execution
- đ **Comprehensive Trade Logging**: Automated documentation of trading rationale, execution details, and portfolio changes
- đ **Adaptive Strategy Evolution**: Self-optimizing algorithms that adjust based on market performance feedback
---
### đ Competition Rules
Each AI model operates in complete isolation under identical conditions:
- đ° **Starting Capital**: $10,000 USD initial investment
- đ **Data Access**: Uniform market data and information feeds
- â° **Operating Hours**: Synchronized trading time windows
- đ **Performance Metrics**: Standardized evaluation criteria across all models
- đ ď¸ **Tool Access**: Identical MCP toolchain for all participants
đŻ **Objective**: Determine which AI model achieves superior investment returns through pure autonomous operation!
### đŤ Zero Human Intervention
- â **No Pre-Programming**: Zero preset trading strategies or algorithmic rules
- â **No Human Input**: Complete reliance on inherent AI reasoning capabilities
- â **No Manual Override**: Absolute prohibition of human intervention during trading
- â
**Tool-Only Execution**: All operations executed exclusively through standardized tool calls
- â
**Self-Adaptive Learning**: Independent strategy refinement based on market performance feedback
---
## â° Historical Replay Architecture
A core innovation of AI-Trader Bench is its **fully replayable** trading environment, ensuring scientific rigor and reproducibility in AI agent performance evaluation on historical market data.
### đ Temporal Control Framework
#### đ
Flexible Time Settings
```json
{
"date_range": {
"init_date": "2025-01-01", // Any start date
"end_date": "2025-01-31" // Any end date
}
}
```
---
#### đĄď¸ Future Information Isolation
- đ **Historical Price Data**: Restricted to current date and prior market data only
- đ° **Temporal News Filtering**: Automatic exclusion of future-dated news and market announcements
- đ **Published Financial Data**: Limited to officially released financial reports as of simulation date
- đ **Chronological Market Intelligence**: Information access constrained to historically available data points
### đŻ Replay Advantages
#### đŹ Scientific Research
- **đ Market Efficiency Research**: Test AI performance under different market conditions
- **đ§ Cognitive Bias Analysis**: Study temporal consistency of AI decisions
- **đ Risk Model Validation**: Verify effectiveness of risk management strategies
#### đŻ Competition Fairness
- **đ Fair Competition**: All AI models use the same historical information
- **đ Objective Evaluation**: Performance comparison based on same dataset
- **đ Transparency**: Completely reproducible experimental results
## đ Project Architecture
```
AI-Trader Bench/
âââ đ¤ Core System
â âââ main.py # đŻ Main program entry
â âââ agent/base_agent/ # đ§ AI agent core
â âââ configs/ # âď¸ Configuration files
â
âââ đ ď¸ MCP Toolchain
â âââ agent_tools/
â â âââ tool_trade.py # đ° Trade execution
â â âââ tool_get_price_local.py # đ Price queries
â â âââ tool_jina_search.py # đ Information search
â â âââ tool_math.py # đ§Ž Mathematical calculations
â âââ tools/ # đ§ Auxiliary tools
â
âââ đ Data System
â âââ data/
â â âââ daily_prices_*.json # đ Stock price data
â â âââ merged.jsonl # đ Unified data format
â â âââ agent_data/ # đ AI trading records
â âââ calculate_performance.py # đ Performance analysis
â
âââ đ¨ Frontend Interface
â âââ frontend/ # đ Web dashboard
â
âââ đ Configuration & Documentation
âââ configs/ # âď¸ System configuration
âââ prompts/ # đŹ AI prompts
âââ calc_perf.sh # đ Performance calculation script
```
### đ§ Core Components Details
#### đŻ Main Program (`main.py`)
- **Multi-Model Concurrency**: Run multiple AI models simultaneously for trading
- **Configuration Management**: Support for JSON configuration files and environment variables
- **Date Management**: Flexible trading calendar and date range settings
- **Error Handling**: Comprehensive exception handling and retry mechanisms
#### đ ď¸ MCP Toolchain
| Tool | Function | API |
|------|----------|-----|
| **Trading Tool** | Buy/sell stocks, position management | `buy()`, `sell()` |
| **Price Tool** | Real-time and historical price queries | `get_price_local()` |
| **Search Tool** | Market information search | `get_information()` |
| **Math Tool** | Financial calculations and analysis | Basic mathematical operations |
#### đ Data System
- **đ Price Data**: Complete OHLCV data for NASDAQ 100 component stocks
- **đ Trading Records**: Detailed trading history for each AI model
- **đ Performance Metrics**: Sharpe ratio, maximum drawdown, annualized returns, etc.
- **đ Data Synchronization**: Automated data acquisition and update mechanisms
## đ Quick Start
### đ Prerequisites
- **Python 3.8+**
- **API Keys**: OpenAI, Alpha Vantage, Jina AI
### ⥠One-Click Installation
```bash
# 1. Clone project
git clone https://github.com/HKUDS/AI-Trader.git
cd AI-Trader
# 2. Install dependencies
pip install -r requirements.txt
# 3. Configure environment variables
cp .env.example .env
# Edit .env file and fill in your API keys
```
### đ Environment Configuration
Create `.env` file and configure the following variables:
```bash
# đ¤ AI Model API Configuration
OPENAI_API_BASE=https://your-openai-proxy.com/v1
OPENAI_API_KEY=your_openai_key
# đ Data Source Configuration
ALPHAADVANTAGE_API_KEY=your_alpha_vantage_key
JINA_API_KEY=your_jina_api_key
# âď¸ System Configuration
RUNTIME_ENV_PATH=./runtime_env.json # Recommended to use absolute path
# đ Service Port Configuration
MATH_HTTP_PORT=8000
SEARCH_HTTP_PORT=8001
TRADE_HTTP_PORT=8002
GETPRICE_HTTP_PORT=8003
# đ§ AI Agent Configuration
AGENT_MAX_STEP=30 # Maximum reasoning steps
```
### đŚ Dependencies
```bash
# Install production dependencies
pip install -r requirements.txt
# Or manually install core dependencies
pip install langchain langchain-openai langchain-mcp-adapters fastmcp python-dotenv requests numpy pandas
```
## đŽ Running Guide
### đ Step 1: Data Preparation (`./fresh_data.sh`)
```bash
# đ Get NASDAQ 100 stock data
cd data
python get_daily_price.py
# đ Merge data into unified format
python merge_jsonl.py
```
### đ ď¸ Step 2: Start MCP Services
```bash
cd ./agent_tools
python start_mcp_services.py
```
### đ Step 3: Start AI Arena
```bash
# đŻ Run main program - let AIs start trading!
python main.py
# đŻ Or use custom configuration
python main.py configs/my_config.json
```
### â° Time Settings Example
#### đ
Create Custom Time Configuration
```json
{
"agent_type": "BaseAgent",
"date_range": {
"init_date": "2024-01-01", // Backtest start date
"end_date": "2024-03-31" // Backtest end date
},
"models": [
{
"name": "claude-3.7-sonnet",
"basemodel": "anthropic/claude-3.7-sonnet",
"signature": "claude-3.7-sonnet",
"enabled": true
}
]
}
```
### đ Start Web Interface
```bash
cd docs
python3 -m http.server 8000
# Visit http://localhost:8000
```
## đ Performance Analysis
### đ Competition Rules
| Rule Item | Setting | Description |
|-----------|---------|-------------|
| **đ° Initial Capital** | $10,000 | Starting capital for each AI model |
| **đ Trading Targets** | NASDAQ 100 | 100 top tech stocks |
| **â° Trading Hours** | Weekdays | Monday to Friday |
| **đ˛ Price Benchmark** | Opening Price | Trade using daily opening price |
| **đ Recording Method** | JSONL Format | Complete trading history records |
## âď¸ Configuration Guide
### đ Configuration File Structure
```json
{
"agent_type": "BaseAgent",
"date_range": {
"init_date": "2025-01-01",
"end_date": "2025-01-31"
},
"models": [
{
"name": "claude-3.7-sonnet",
"basemodel": "anthropic/claude-3.7-sonnet",
"signature": "claude-3.7-sonnet",
"enabled": true
}
],
"agent_config": {
"max_steps": 30,
"max_retries": 3,
"base_delay": 1.0,
"initial_cash": 10000.0
},
"log_config": {
"log_path": "./data/agent_data"
}
}
```
### đ§ Configuration Parameters
| Parameter | Description | Default Value |
|-----------|-------------|---------------|
| `agent_type` | AI agent type | "BaseAgent" |
| `max_steps` | Maximum reasoning steps | 30 |
| `max_retries` | Maximum retry attempts | 3 |
| `base_delay` | Operation delay (seconds) | 1.0 |
| `initial_cash` | Initial capital | $10,000 |
### đ Data Format
#### đ° Position Records (position.jsonl)
```json
{
"date": "2025-01-20",
"id": 1,
"this_action": {
"action": "buy",
"symbol": "AAPL",
"amount": 10
},
"positions": {
"AAPL": 10,
"MSFT": 0,
"CASH": 9737.6
}
}
```
#### đ Price Data (merged.jsonl)
```json
{
"Meta Data": {
"2. Symbol": "AAPL",
"3. Last Refreshed": "2025-01-20"
},
"Time Series (Daily)": {
"2025-01-20": {
"1. buy price": "255.8850",
"2. high": "264.3750",
"3. low": "255.6300",
"4. sell price": "262.2400",
"5. volume": "90483029"
}
}
}
```
### đ File Structure
```
data/agent_data/
âââ claude-3.7-sonnet/
â âââ position/
â â âââ position.jsonl # đ Position records
â âââ log/
â âââ 2025-01-20/
â âââ log.jsonl # đ Trading logs
âââ gpt-4o/
â âââ ...
âââ qwen3-max/
âââ ...
```
## đ Third-Party Strategy Integration
AI-Trader Bench adopts a modular design, supporting easy integration of third-party strategies and custom AI agents.
### đ ď¸ Integration Methods
#### 1. Custom AI Agent
```python
# Create new AI agent class
class CustomAgent(BaseAgent):
def __init__(self, model_name, **kwargs):
super().__init__(model_name, **kwargs)
# Add custom logic
```
#### 2. Register New Agent
```python
# Register in main.py
AGENT_REGISTRY = {
"BaseAgent": {
"module": "agent.base_agent.base_agent",
"class": "BaseAgent"
},
"CustomAgent": { # New addition
"module": "agent.custom.custom_agent",
"class": "CustomAgent"
},
}
```
#### 3. Configuration File Settings
```json
{
"agent_type": "CustomAgent",
"models": [
{
"name": "your-custom-model",
"basemodel": "your/model/path",
"signature": "custom-signature",
"enabled": true
}
]
}
```
### đ§ Extending Toolchain
#### Adding Custom Tools
```python
# Create new MCP tool
@mcp.tools()
class CustomTool:
def __init__(self):
self.name = "custom_tool"
def execute(self, params):
# Implement custom tool logic
return result
```
## đ Roadmap
### đ Future Plans
- [ ] **đ¨đł A-Share Support** - Extend to Chinese stock market
- [ ] **đ Post-Market Statistics** - Automatic profit analysis
- [ ] **đ Strategy Marketplace** - Add third-party strategy sharing platform
- [ ] **đ¨ Cool Frontend Interface** - Modern web dashboard
- [ ] **âż Cryptocurrency** - Support digital currency trading
- [ ] **đ More Strategies** - Technical analysis, quantitative strategies
- [ ] **â° Advanced Replay** - Support minute-level time precision and real-time replay
- [ ] **đ Smart Filtering** - More precise future information detection and filtering
## đ¤ Contributing Guide
We welcome contributions of all kinds! Especially AI trading strategies and agent implementations.
### đ§ AI Strategy Contributions
- **đŻ Trading Strategies**: Contribute your AI trading strategy implementations
- **đ¤ Custom Agents**: Implement new AI agent types
- **đ Analysis Tools**: Add new market analysis tools
- **đ Data Sources**: Integrate new data sources and APIs
### đ Issue Reporting
- Use GitHub Issues to report bugs
- Provide detailed reproduction steps
- Include system environment information
### đĄ Feature Suggestions
- Propose new feature ideas in Issues
- Describe use cases in detail
- Discuss implementation approaches
### đ§ Code Contributions
1. Fork the project
2. Create a feature branch
3. Implement your strategy or feature
4. Add test cases
5. Create a Pull Request
### đ Documentation Improvements
- Improve README documentation
- Add code comments
- Write usage tutorials
- Contribute strategy documentation
### đ Strategy Sharing
- **đ Technical Analysis Strategies**: AI strategies based on technical indicators
- **đ Quantitative Strategies**: Multi-factor models and quantitative analysis
- **đ Fundamental Strategies**: Analysis strategies based on financial data
- **đ Macro Strategies**: Strategies based on macroeconomic data
## đ Support & Community
- **đŹ Discussions**: [GitHub Discussions](https://github.com/HKUDS/AI-Trader/discussions)
- **đ Issues**: [GitHub Issues](https://github.com/HKUDS/AI-Trader/issues)
- **đ§ Contact**: your-email@example.com
## đ License
This project is licensed under the [MIT License](LICENSE).
## đ Acknowledgments
Thanks to the following open source projects and services:
- [LangChain](https://github.com/langchain-ai/langchain) - AI application development framework
- [MCP](https://github.com/modelcontextprotocol) - Model Context Protocol
- [Alpha Vantage](https://www.alphavantage.co/) - Financial data API
- [Jina AI](https://jina.ai/) - Information search service
---
**đ If this project helps you, please give us a Star!**
[](https://github.com/HKUDS/AI-Trader)
[](https://github.com/HKUDS/AI-Trader)
**đ¤ Let AI show its power in financial markets with complete autonomous decision-making!**
**đ ď¸ Pure tool-driven, zero human intervention, a true AI trading arena!** đ