ai-trader logo

ai-trader

Community
whchien

Backtrader-powered backtesting framework for algorithmic trading, featuring 20+ strategies, multi-market support, CLI tools, and an integrated MCP server for professional traders.

Publisherwhchien
Repositoryai-trader
LanguagePython
Forks
100
Stars
698
Available tools
0
Transport typestdio
Categories
LicenseGPL-3.0
Links
  • Connect tools to AI workflows

    ai-trader exposes MCP capabilities that can be used by compatible AI clients and agents.

  • 0 available tools

    Browse the callable actions below, including names and descriptions when provided by the server.

  • Ready-to-copy setup

    Use the installation snippets to configure this server in your preferred MCP client.

  • Open source signals

    698 stars and 100 forks from the linked repository.

AI-Trader

Python Version License

中文版說明 (Chinese Subpage)

A professional, config-driven backtesting framework for algorithmic trading, built on Backtrader. Seamlessly test, optimize, and integrate trading strategies with Large Language Models (LLMs) across stocks, crypto, and forex markets.

Demo GIF

Key Features

  • Config-Driven Workflows: Define and manage backtests with version-controllable YAML files for reproducible results.
  • Seamless LLM Integration: Built-in MCP (Model Context Protocol) server allows AI assistants like Claude to run backtests, fetch data, and analyze strategies.
  • Multi-Market Support: Test strategies on US stocks, Taiwan stocks, cryptocurrencies, and forex.
  • Extensive Strategy Library: Comes with over 20 built-in strategies, from classic indicators to advanced adaptive models.
  • Powerful CLI: A rich command-line interface to run backtests, fetch market data, and list strategies.
  • Developer Friendly: Easily create and test custom strategies with simple helpers and a clear structure.

Quick Start

1. Installation

Option A: Install from PyPI (Recommended for using the CLI)

bash
pip install ai-trader

Use this if you want to:

  • Use the CLI commands: ai-trader run, ai-trader fetch, ai-trader quick
  • Run backtests on your own data files
  • Use as a library in your Python projects

Option B: Install from Source (Recommended for examples and config templates)

bash
git clone https://github.com/whchien/ai-trader.git
cd ai-trader

# Install dependencies (choose one method)
uv sync        # Recommended (fastest, modern tool)
# poetry install   # Or use Poetry
# pip install -e .  # Or traditional pip with editable install

Use this if you want to:

  • Run the config-based examples in config/backtest/
  • Use the example data files in data/
  • Run the example scripts in scripts/examples/
  • Contribute or customize strategies

2. Run a Backtest via CLI

If you cloned from source, run a predefined backtest using a configuration file:

bash
# Run a backtest from a config file (requires source installation)
ai-trader run config/backtest/classic/sma_example.yaml

Or, run a quick backtest on any data file (works with both pip and source installation):

bash
# Quick backtest on your own data file
ai-trader quick CrossSMAStrategy your_data.csv --cash 100000

3. Fetch Market Data

Download historical data for any supported market:

bash
# US Stock (default: saves to CSV)
ai-trader fetch TSM --market us_stock --start-date 2020-01-01

# Taiwan Stock (台灣股票)
ai-trader fetch 2330 --market tw_stock --start-date 2020-01-01

# Cryptocurrency
ai-trader fetch BTC-USD --market crypto --start-date 2020-01-01

# With SQLite persistent caching (NEW!)
ai-trader fetch AAPL --market us_stock --start-date 2024-01-01 --storage sqlite

# Save to both CSV and SQLite
ai-trader fetch AAPL --market us_stock --start-date 2024-01-01 --storage both

Persistent Data Storage with SQLite

By default, ai-trader fetch saves data to CSV. For faster repeated backtests, use SQLite:

bash
# First fetch: Downloads from API and caches in SQLite (~2-3 seconds)
ai-trader fetch AAPL --market us_stock --start-date 2024-01-01 --storage sqlite

# Repeated fetch: Loads from cache (~50ms, no API call)
ai-trader fetch AAPL --market us_stock --start-date 2024-01-01 --storage sqlite

# Check cached data
ai-trader data list
ai-trader data info

# Clean old data
ai-trader data clean --market us_stock --before 2020-01-01

Learn more about SQLite Storage →

Core Workflows

1. Configuration-Based Backtesting

The most robust way to run backtests is with a YAML config file.

my_backtest.yaml:

yaml
broker:
  cash: 1000000
  commission: 0.001425

data:
  file: "data/us_stock/TSM.csv"
  start_date: "2020-01-01"
  end_date: "2023-12-31"

strategy:
  class: "CrossSMAStrategy"
  params:
    fast: 10
    slow: 30

sizer:
  type: "percent"
  params:
    percents: 95

Run it:

bash
ai-trader run my_backtest.yaml

See config/backtest/ for more examples.

2. Python-Based Backtesting

For more granular control or integration into other Python scripts.

Simple approach:

python
from ai_trader import run_backtest
from ai_trader.backtesting.strategies.classic.sma import CrossSMAStrategy

# Run backtest with example data
results = run_backtest(
    strategy=CrossSMAStrategy,
    data_source=None,  # Uses built-in example data
    cash=1000000,
    strategy_params={"fast": 10, "slow": 30}
)

Step-by-step control: See scripts/examples/02_step_by_step.py for a detailed example.

3. LLM Integration (MCP Server)

Run ai-trader as a server to let AI assistants interact with your backtesting engine.

Start the Server (for testing):

bash
python -m ai_trader.mcp

Configure with Claude Desktop (Recommended):

  1. Locate your Claude Desktop configuration file:

    • macOS/Linux: ~/.config/Claude/claude_desktop_config.json
    • Windows: %APPDATA%\Claude\claude_desktop_config.json
  2. Add the ai-trader MCP server to the mcpServers section:

json
{
  "mcpServers": {
    "ai-trader": {
      "command": "python3",
      "args": ["-m", "ai_trader.mcp"],
      "cwd": "/path/to/ai-trader"
    }
  }
}

Configuration Notes:

  • Replace /path/to/ai-trader with your actual ai-trader project directory
  • If using a virtual environment, use the full path to the Python executable: /path/to/.venv/bin/python3
  • Restart Claude Desktop after updating the config file

Once configured, you can use Claude to interact with your backtesting engine with natural language commands like:

  • "Run a backtest of the CrossSMAStrategy on TSM data from 2020-2022."
  • "List all available trading strategies."
  • "Fetch Apple stock data from 2021 to 2024."

Creating Custom Strategies

Option 1: Using Claude Code Skills (Recommended)

The fastest way to create a new strategy is with the /add-strategy skill in Claude Code. The skill guides you through the process interactively:

bash
/add-strategy classic

This will prompt you for:

  • Strategy name (e.g., "MACDBBands")
  • Description
  • Parameters with defaults
  • Entry and exit conditions
  • Any custom indicators

The skill automatically handles:

  • File creation with proper naming conventions
  • Comprehensive docstrings
  • Automatic registration in __init__.py
  • Syntax validation

Learn more about Claude Code skills: https://code.claude.com/docs/en/skills

Option 2: Manual Creation

Create a new file in ai_trader/backtesting/strategies/classic/ and inherit from BaseStrategy.

python
# ai_trader/backtesting/strategies/classic/my_strategy.py
import backtrader as bt
from ai_trader.backtesting.strategies.base import BaseStrategy

class MyCustomStrategy(BaseStrategy):
    params = dict(period=20)

    def __init__(self):
        self.sma = bt.indicators.SMA(self.data.close, period=self.p.period)

    def next(self):
        if not self.position and self.data.close[0] > self.sma[0]:
            self.buy()
        elif self.position and self.data.close[0] < self.sma[0]:
            self.close()

The new strategy is automatically available to the CLI and run_backtest function.

Documentation & Resources

Contributing

Contributions are welcome! Feel free to report bugs, suggest features, or submit pull requests.

Show Your Support

If you find this project helpful, please give it a star !

License

This project is licensed under the GNU General Public License v3 (GPL-3.0). See the LICENSE file for details.

Installation

TypingMind
Prerequisites:

Node.js 18+

{
  "mcpServers": {
    "whchien-ai-trader": {
      "command": "",
      "args": []
    }
  }
}

Use ai-trader MCP with multiple AI models

TypingMind connects MCP tools at the workspace level, so once ai-trader is connected, you can use it with different AI models in TypingMind instead of setting it up separately for each model. This MCP runs locally through the TypingMind MCP connector on your device.

Setup guide to use the local connector

Use this when the MCP server needs access to local files, apps, or private resources on your computer.

1

Open the MCP settings

In TypingMind, go to Settings, Advanced Settings, then Model Context Protocol and choose Setup Connector.

  1. Open TypingMind in your browser.
  2. Click the Settings icon.
  3. Go to Advanced Settings.
  4. Open the Model Context Protocol section.
  5. Click Setup Connector and choose This Device.
TypingMind MCP connector setup screen with This Device selected
2

Run the connector command

Choose This Device, copy the command from TypingMind, and run it in Terminal. Keep the process running while you use MCP.

  1. Copy the setup command shown by TypingMind.
  2. Open Terminal on macOS or Windows Terminal on Windows.
  3. Paste and run the command.
  4. Approve the package install if Terminal asks you to proceed.
  5. Keep the Terminal window running while using MCP tools.
3

Add ai-trader as a server

When the connector status is Ready, click Edit Servers and paste the MCP server configuration.

  1. Wait until the connector status shows Ready.
  2. Click Edit Servers.
  3. Paste the ai-trader MCP server configuration.
  4. Save the server list.
  5. Refresh if you want to confirm the connector is still ready.
TypingMind MCP settings showing active server and Edit Servers button
{
  "mcpServers": {
    "whchien-ai-trader": {
      "command": "npx",
      "args": [
        "-y",
        "ai-trader"
      ]
    }
  }
}
4

Use it across models

Save the server list, open Plugins, enable the ai-trader MCP tools, then select any supported AI model in TypingMind and use the tools in chat or assign them to an AI agent.

  1. Open the Plugins page in TypingMind.
  2. Enable the ai-trader MCP tools.
  3. Start a chat and choose the AI model you want to use.
  4. Use the MCP tools in chat or assign them to an AI agent.
  5. Switch to another AI model whenever needed without reconnecting MCP.
TypingMind chat using enabled MCP tools with a selected AI model
Can you use ai-trader to help me with this task?
ai-trader
Sure. I read it.
Here is what I found using ai-trader.

Frequently asked questions

What is the ai-trader MCP server used for?

ai-trader is an MCP server that lets compatible AI clients connect to external tools and context. In TypingMind, you can add this MCP server once and make its tools available in your AI workspace.

Can I use ai-trader MCP with multiple AI models in TypingMind?

Yes. TypingMind connects MCP tools at the workspace level, so you can use ai-trader with different AI models such as Claude, ChatGPT, Gemini, or other models you have configured in TypingMind without setting up the MCP server separately for each model.

Why use ai-trader MCP with TypingMind?

TypingMind is one of the best frontends for LLM chat because it brings multiple AI models, prompts, plugins, AI agents, API keys, and MCP tools into one workspace. With ai-trader connected, you can use its MCP tools across your preferred models while keeping your chat workflow organized in TypingMind.

How do I connect ai-trader MCP to TypingMind?

ai-trader runs through the TypingMind local MCP connector. This is best when the MCP server needs access to local files, desktop apps, command-line tools, or private resources on your computer.

What tools does ai-trader MCP provide in TypingMind?

ai-trader exposes MCP capabilities that can be enabled from the TypingMind Plugins page and used in chat or assigned to AI agents.

Do I need to share my API keys with TypingMind to use ai-trader MCP?

No. TypingMind is local-first and lets you keep your model providers, API keys, prompts, and MCP configuration under your control. If ai-trader requires authentication, add the required headers, OAuth settings, or local configuration for that MCP server when you create the connection.

Related MCP Servers

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇