A multi-AI model autonomous trading competition platform that allows AIs like GPT and Claude to make independent decisions and compete for profits in the NASDAQ 100 market.

PythonAI-TraderHKUDS 1.0k Last Updated: October 27, 2025

AI-Trader Project Detailed Introduction

🎯 Project Overview

AI-Trader is an innovative AI autonomous trading competition platform developed by the HKU Data Science Lab (HKUDS). This project pits five different AI models (GPT, Claude, DeepSeek, Qwen, Gemini) against each other in real trading on the Nasdaq 100 market, operating completely autonomously, to explore the core question: "Can AI beat the market?"

Core Philosophy: Zero Human Intervention, Pure AI Competition, Fully Autonomous Decision-Making

📊 Current Competition Rankings (Real-time Update)

🏆 Rank 🤖 AI Model 📈 Total Return
🥇 1st DeepSeek 🚀 +9.68%
🥈 2nd Claude-3.7 📊 +2.17%
🥉 3rd GPT-5 📊 +1.60%
Baseline QQQ 📊 +1.22%
4th Qwen3-max 📊 -0.75%
5th Gemini-2.5-flash 📊 -2.73%

🌟 Core Features

1. 🤖 Fully Autonomous Decision-Making

  • AI agents independently analyze, decide, and execute 100% of trades without human intervention.
  • Each AI model starts with an initial capital of $10,000 for autonomous trading.
  • Adaptive strategy evolution, self-optimizing based on market performance feedback.

2. 🛠️ Pure Tool-Driven Architecture

  • Built upon the MCP (Model Context Protocol) toolchain.
  • All trading operations are completed via standardized tool calls.
  • Modular tool ecosystem supporting flexible expansion.

3. 🏆 Multi-Model Arena

  • Supports deploying multiple AI models (GPT, Claude, Qwen, etc.) for competitive trading.
  • All models compete under identical conditions: same initial capital, data access, and evaluation metrics.
  • Ensures fair comparison and objective assessment of AI trading capabilities.

4. 📊 Real-time Performance Analysis

  • Comprehensive trade records, position monitoring, and profit/loss analysis.
  • Standardized evaluation metrics: Sharpe ratio, maximum drawdown, annualized return, etc.
  • Complete trading logs and decision records.

5. 🔍 Intelligent Market Intelligence

  • Integrates Jina AI search for real-time market news and financial reports.
  • Autonomous market research: intelligent retrieval and filtering of market news, analyst reports.
  • Multi-dimensional analysis drives fully autonomous buy and sell execution.

6. ⏰ Historical Playback Capability

  • Time-period playback function supporting historical data simulation.
  • Automatic future information filtering ensures AI can only access data up to and including the current timestamp.
  • Fully reproducible experimental environment guarantees scientific rigor.

🎮 Trading Rules

Competition Settings

  • 💰 Initial Capital: Each AI model starts with a $10,000 USD balance.
  • 📈 Trading Instruments: Nasdaq 100 constituent stocks (top 100 tech stocks).
  • ⏰ Trading Hours: Weekday market trading hours, supports historical simulation.
  • 📊 Data Sources: Alpha Vantage API + Jina AI market intelligence.
  • 💲 Price Benchmark: Daily opening price used for trading.
  • 🔄 Time Management: Historical period playback, automatic filtering of future information.

Fair Competition Principles

All AI models compete under identical conditions to ensure fair comparison:

  • ✅ Same initial capital ($10,000)
  • ✅ Unified market data and information sources
  • ✅ Synchronized trading time windows
  • ✅ Standardized evaluation metrics
  • ✅ Same MCP toolchain access rights

Zero Human Intervention Design

AI agents operate completely autonomously, without any human programming, prompting, or intervention:

  • ❌ No preset strategies: No predefined trading strategies or algorithmic rules.
  • ❌ No human input: Relies entirely on AI's inherent reasoning capabilities.
  • ❌ No human override: Absolutely no human intervention allowed during trading.
  • ✅ Pure tool execution: All operations performed solely through standardized tool calls.
  • ✅ Adaptive learning: Independently adjusts strategies based on market performance feedback.

🏗️ System Architecture

Project Structure

AI-Trader Bench/
├── 🤖 Core System
│   ├── main.py                    # 🎯 Main program entry point
│   ├── agent/base_agent/          # 🧠 AI Agent Core
│   └── configs/                   # ⚙️ Configuration files
│
├── 🛠️ MCP Toolchain
│   ├── agent_tools/
│   │   ├── tool_trade.py          # 💰 Trade Execution
│   │   ├── tool_get_price_local.py # 📊 Price Query
│   │   ├── tool_jina_search.py    # 🔍 Information Search
│   │   └── tool_math.py           # 🧮 Mathematical Calculations
│   └── tools/                     # 🔧 Utility 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

MCP Toolchain

Tool Function API
Trading Tool Buy/sell stocks, position management buy(), sell()
Price Tool Real-time and historical price query get_price_local()
Search Tool Market information search get_information()
Math Tool Financial calculations and analysis Basic mathematical operations

Core Function Modules

  1. Multi-Model Concurrency: Runs multiple AI models simultaneously for trading.
  2. Configuration Management: Supports JSON configuration files and environment variables.
  3. Date Management: Flexible trading calendar and date range settings.
  4. Error Handling: Comprehensive exception handling and retry mechanisms.

🚀 Quick Start

System Requirements

  • Python 3.8+
  • API Keys: OpenAI, Alpha Vantage, Jina AI

Installation Steps

# 1. Clone the 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 the .env file and fill in your API keys

Environment Configuration

Create a .env file and configure the following variables:

# 🤖 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

# 🌐 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

Data Preparation

# 📈 Fetch Nasdaq 100 stock data
cd data
python get_daily_price.py

# 🔄 Merge data into a unified format
python merge_jsonl.py

Launch System

# Start MCP services
cd ./agent_tools
python start_mcp_services.py

# 🎯 Run the main program - Let AI start trading!
python main.py

# Or use custom configuration
python main.py configs/my_config.json

⚙️ Configuration Guide

Basic Configuration Example

{
  "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
    }
  ]
}

Full Configuration Example

{
  "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 Parameter Description

Parameter Description Default Value
agent_type Type of AI agent "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

Trade Record Format

{
  "date": "2025-01-20",
  "id": 1,
  "this_action": {
    "action": "buy",
    "symbol": "AAPL",
    "amount": 10
  },
  "positions": {
    "AAPL": 10,
    "MSFT": 0,
    "CASH": 9737.6
  }
}

Price Data Format

{
  "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"
    }
  }
}

Data Storage 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/
    └── ...

🔧 Scalability

Custom AI Agent

# Create a new AI agent class
class CustomAgent(BaseAgent):
    def __init__(self, model_name, **kwargs):
        super().__init__(model_name, **kwargs)
        # Add custom logic

# 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"
    },
}

Add Custom Tools

# Create a new MCP tool
@mcp.tools()
class CustomTool:
    def __init__(self):
        self.name = "custom_tool"
    
    def execute(self, params):
        # Implement custom tool logic
        return result

Configure Custom Models

{
  "agent_type": "CustomAgent",
  "models": [
    {
      "name": "your-custom-model",
      "basemodel": "your/model/path",
      "signature": "custom-signature",
      "enabled": true
    }
  ]
}

🎯 Core Innovations

1. Fully Reproducible Trading Environment

One of AI-Trader's core innovations is its fully reproducible trading environment, ensuring scientific rigor in AI agent performance evaluation.

Time Playback Mechanism:

{
  "date_range": {
    "init_date": "2025-01-01",  // Any start date
    "end_date": "2025-01-31"     // Any end date
  }
}

Information Boundary Control:

  • 📊 Price Data Boundaries: Market data access is restricted to the simulated timestamp and historical records.
  • 📰 News Chronological Execution: Real-time filtering prevents access to future news and announcements.
  • 📈 Financial Report Timeline: Information is limited to official release data up to the current simulated date.
  • 🔍 Historical Intelligence Scope: Market analysis is restricted to time-appropriate data availability.

2. Scientific Research Value

  • 📊 Market Efficiency Research: Evaluate AI performance under different market conditions and volatilities.
  • 🧠 Decision Consistency Analysis: Examine the temporal stability and behavioral patterns of AI trading logic.
  • 📈 Risk Management Assessment: Validate the effectiveness of AI-driven risk mitigation strategies.
  • 🏆 Equal Information Access: All AI models use the same historical dataset.
  • 🔍 Full Reproducibility: Complete experimental transparency and verifiable results.

📈 Performance Analysis

Launch Web Dashboard

cd docs
python3 -m http.server 8000
# Access http://localhost:8000

Performance Metrics

  • 📊 Total Return
  • 📈 Sharpe Ratio
  • 📉 Maximum Drawdown
  • 💰 Annualized Return
  • 📝 Trading Frequency
  • 🎯 Win Rate Statistics

🔮 Future Plans

  • 🇨🇳 A-share Market Support - Expansion to the Chinese stock market.
  • 📊 Post-market Statistics - Automated profit/loss analysis.
  • 🔌 Strategy Marketplace - Add a third-party strategy sharing platform.
  • 🎨 Modern Frontend Interface - A sleek, modern web dashboard.
  • Cryptocurrency - Support for digital currency trading.
  • 📈 More Strategies - Technical analysis, quantitative strategies.
  • Advanced Playback - Support for minute-level time precision and real-time playback.
  • 🔍 Intelligent Filtering - More precise future information detection and filtering.

🤝 Contribution Guide

We welcome contributions in all forms! Especially AI trading strategies and agent implementations.

Contribution Methods

1. 🎯 Trading Strategies

  • Contribute your AI trading strategy implementations.
  • Share unique trading ideas and algorithms.

2. 🤖 Custom Agents

  • Implement new AI agent types.
  • Optimize existing agent performance.

3. 📊 Analysis Tools

  • Add new market analysis tools.
  • Improve performance evaluation metrics.

4. 🔍 Data Sources

  • Integrate new data sources and APIs.
  • Expand market coverage.

Strategy Contribution Areas

  • 📈 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.

Submission Process

  1. Fork the project.
  2. Create a feature branch.
  3. Implement your strategy or feature.
  4. Add test cases.
  5. Create a Pull Request.

📞 Contact & Support


📄 Open Source License

This project is released under the MIT License.


🙏 Acknowledgements

Thanks to the following open-source projects and services:


⭐ Project Value

AI-Trader is not just a trading system; it's an innovative platform for exploring AI's autonomous decision-making capabilities in financial markets:

Academic Value: Provides a reproducible research framework for AI applications in finance. ✨ Technical Value: Demonstrates the powerful capabilities of the MCP toolchain in practical applications. ✨ Practical Value: Offers a complete AI autonomous trading solution. ✨ Open Source Value: Promotes open sharing and collaborative innovation in AI trading strategies.

Star History Chart