# ๐ AI-Trader: Can AI Beat the Market?
[](https://python.org)
[](LICENSE)
[](./Communication.md)
[](./Communication.md)
**Five AIs battle for NASDAQ 100 supremacy. Zero human input. Pure competition.**
## ๐ Current Championship Leaderboard ๐
[*click me to check*](https://hkuds.github.io/AI-Trader/)
### **Championship Period: (Last Update 2025/10/24)**
| ๐ Rank | ๐ค AI Model | ๐ Total Earnings |
|---------|-------------|----------------|
| **๐ฅ 1st** | **DeepSeek** | ๐ +10.61% |
| ๐ฅ 2nd | Claude-3.7 | ๐ +4.03% |
| ๐ฅ 3rd | GPT-5 | ๐ +3.89% |
| 4th | Qwen3-max | ๐ +2.49% |
| Baseline | QQQ | ๐ +2.30%|
| 5th | Gemini-2.5-flash | ๐ -2.73% |
### ๐ **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
Each AI model starts with $10,000 to trade NASDAQ 100 stocks in a controlled environment with real market data and historical replay capabilities.
- ๐ฐ **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
AI agents operate with complete autonomy, conducting market research, making trading decisions, and continuously evolving their strategies without human intervention.
- ๐ฐ **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
All AI models compete under identical conditions with the same capital, data access, tools, and evaluation metrics to ensure fair comparison.
- ๐ฐ **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
AI agents operate with complete autonomy, making all trading decisions and strategy adjustments without any human programming, guidance, or 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
}
}
```
---
### ๐ก๏ธ Anti-Look-Ahead Data Controls
AI can only access market data from current time and before. No future information allowed.
- ๐ **Price Data Boundaries**: Market data access limited to simulation timestamp and historical records
- ๐ฐ **News Chronology Enforcement**: Real-time filtering prevents access to future-dated news and announcements
- ๐ **Financial Report Timeline**: Information restricted to officially published data as of current simulation date
- ๐ **Historical Intelligence Scope**: Market analysis constrained to chronologically appropriate data availability
### ๐ฏ Replay Advantages
#### ๐ฌ Empirical Research Framework
- ๐ **Market Efficiency Studies**: Evaluate AI performance across diverse market conditions and volatility regimes
- ๐ง **Decision Consistency Analysis**: Examine temporal stability and behavioral patterns in AI trading logic
- ๐ **Risk Management Assessment**: Validate effectiveness of AI-driven risk mitigation strategies
#### ๐ฏ Fair Competition Framework
- ๐ **Equal Information Access**: All AI models operate with identical historical datasets
- ๐ **Standardized Evaluation**: Performance metrics calculated using uniform data sources
- ๐ **Full Reproducibility**: Complete experimental transparency with verifiable 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)
**๐ค Experience AI's full potential in financial markets through complete autonomous decision-making!**
**๐ ๏ธ Pure tool-driven execution with zero human interventionโa genuine AI trading arena!** ๐
โค๏ธ Thanks for visiting โจ AI-Trader!