Skip to content
Back to search

ai-trader

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

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/whchien--ai-trader/badge.svg)](/listings/whchien--ai-trader)

HTML

<a href="/listings/whchien--ai-trader"><img src="/api/listings/whchien--ai-trader/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

**1. Installation**

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

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)**

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:

# 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):

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

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

# 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 →**](agentic_ai_trader/trading-backtester/README.md#persistent-data-storage-with-sqlite)

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 266 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # AI-Trader
  2. [![Python Version](https://img.shields.io/badge/python-3.11%2B-blue)](https://www.python.org/downloads/)
  3. [![License](https://img.shields.io/badge/license-GPL--3.0-green)](LICENSE)
  4. [中文版說明 (Chinese Subpage)](README_zh.md)
  5. 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.
  6. ![Demo GIF](data/demo.gif)
  7. ## Key Features
  8. - **Config-Driven Workflows**: Define and manage backtests with version-controllable YAML files for reproducible results.
  9. - **Seamless LLM Integration**: Built-in MCP (Model Context Protocol) server allows AI assistants like Claude to run backtests, fetch data, and analyze strategies.
  10. - **Multi-Market Support**: Test strategies on US stocks, Taiwan stocks, cryptocurrencies, and forex.
  11. - **Extensive Strategy Library**: Comes with over 20 built-in strategies, from classic indicators to advanced adaptive models.
  12. - **Powerful CLI**: A rich command-line interface to run backtests, fetch market data, and list strategies.
  13. - **Developer Friendly**: Easily create and test custom strategies with simple helpers and a clear structure.
  14. ## Quick Start
  15. **1. Installation**
  16. **Option A: Install from PyPI (Recommended for using the CLI)**
  17. ```bash
  18. pip install ai-trader
  19. ```
  20. Use this if you want to:
  21. - Use the CLI commands: `ai-trader run`, `ai-trader fetch`, `ai-trader quick`
  22. - Run backtests on your own data files
  23. - Use as a library in your Python projects
  24. **Option B: Install from Source (Recommended for examples and config templates)**
  25. ```bash
  26. git clone https://github.com/whchien/ai-trader.git
  27. cd ai-trader
  28. # Install dependencies (choose one method)
  29. uv sync # Recommended (fastest, modern tool)
  30. # poetry install # Or use Poetry
  31. # pip install -e . # Or traditional pip with editable install
  32. ```
  33. Use this if you want to:
  34. - Run the config-based examples in `config/backtest/`
  35. - Use the example data files in `data/`
  36. - Run the example scripts in `scripts/examples/`
  37. - Contribute or customize strategies
  38. **2. Run a Backtest via CLI**
  39. **If you cloned from source**, run a predefined backtest using a configuration file:
  40. ```bash
  41. # Run a backtest from a config file (requires source installation)
  42. ai-trader run config/backtest/classic/sma_example.yaml
  43. ```
  44. Or, run a quick backtest on any data file (works with both pip and source installation):
  45. ```bash
  46. # Quick backtest on your own data file
  47. ai-trader quick CrossSMAStrategy your_data.csv --cash 100000
  48. ```
  49. **3. Fetch Market Data**
  50. Download historical data for any supported market:
  51. ```bash
  52. # US Stock (default: saves to CSV)
  53. ai-trader fetch TSM --market us_stock --start-date 2020-01-01
  54. # Taiwan Stock (台灣股票)
  55. ai-trader fetch 2330 --market tw_stock --start-date 2020-01-01
  56. # Cryptocurrency
  57. ai-trader fetch BTC-USD --market crypto --start-date 2020-01-01
  58. # With SQLite persistent caching (NEW!)
  59. ai-trader fetch AAPL --market us_stock --start-date 2024-01-01 --storage sqlite
  60. # Save to both CSV and SQLite
  61. ai-trader fetch AAPL --market us_stock --start-date 2024-01-01 --storage both
  62. ```
  63. **Persistent Data Storage with SQLite**
  64. By default, `ai-trader fetch` saves data to CSV. For faster repeated backtests, use SQLite:
  65. ```bash
  66. # First fetch: Downloads from API and caches in SQLite (~2-3 seconds)
  67. ai-trader fetch AAPL --market us_stock --start-date 2024-01-01 --storage sqlite
  68. # Repeated fetch: Loads from cache (~50ms, no API call)
  69. ai-trader fetch AAPL --market us_stock --start-date 2024-01-01 --storage sqlite
  70. # Check cached data
  71. ai-trader data list
  72. ai-trader data info
  73. # Clean old data
  74. ai-trader data clean --market us_stock --before 2020-01-01
  75. ```
  76. [**Learn more about SQLite Storage →**](agentic_ai_trader/trading-backtester/README.md#persistent-data-storage-with-sqlite)
  77. ## Core Workflows
  78. ### 1. Configuration-Based Backtesting
  79. The most robust way to run backtests is with a YAML config file.
  80. **`my_backtest.yaml`:**
  81. ```yaml
  82. broker:
  83. cash: 1000000
  84. commission: 0.001425
  85. data:
  86. file: "data/us_stock/TSM.csv"
  87. start_date: "2020-01-01"
  88. end_date: "2023-12-31"
  89. strategy:
  90. class: "CrossSMAStrategy"
  91. params:
  92. fast: 10
  93. slow: 30
  94. sizer:
  95. type: "percent"
  96. params:
  97. percents: 95
  98. ```
  99. **Run it:**
  100. ```bash
  101. ai-trader run my_backtest.yaml
  102. ```
  103. See `config/backtest/` for more examples.
  104. ### 2. Python-Based Backtesting
  105. For more granular control or integration into other Python scripts.
  106. **Simple approach:**
  107. ```python
  108. from ai_trader import run_backtest
  109. from ai_trader.backtesting.strategies.classic.sma import CrossSMAStrategy
  110. # Run backtest with example data
  111. results = run_backtest(
  112. strategy=CrossSMAStrategy,
  113. data_source=None, # Uses built-in example data
  114. cash=1000000,
  115. strategy_params={"fast": 10, "slow": 30}
  116. )
  117. ```
  118. **Step-by-step control:**
  119. See `scripts/examples/02_step_by_step.py` for a detailed example.
  120. ### 3. LLM Integration (MCP Server)
  121. Run `ai-trader` as a server to let AI assistants interact with your backtesting engine.
  122. **Start the Server (for testing):**
  123. ```bash
  124. python -m ai_trader.mcp
  125. ```
  126. **Configure with Claude Desktop (Recommended):**
  127. 1. Locate your Claude Desktop configuration file:
  128. - **macOS/Linux**: `~/.config/Claude/claude_desktop_config.json`
  129. - **Windows**: `%APPDATA%\Claude\claude_desktop_config.json`
  130. 2. Add the `ai-trader` MCP server to the `mcpServers` section:
  131. ```json
  132. {
  133. "mcpServers": {
  134. "ai-trader": {
  135. "command": "python3",
  136. "args": ["-m", "ai_trader.mcp"],
  137. "cwd": "/path/to/ai-trader"
  138. }
  139. }
  140. }
  141. ```
  142. **Configuration Notes:**
  143. - Replace `/path/to/ai-trader` with your actual ai-trader project directory
  144. - If using a virtual environment, use the full path to the Python executable: `/path/to/.venv/bin/python3`
  145. - Restart Claude Desktop after updating the config file
  146. Once configured, you can use Claude to interact with your backtesting engine with natural language commands like:
  147. - *"Run a backtest of the CrossSMAStrategy on TSM data from 2020-2022."*
  148. - *"List all available trading strategies."*
  149. - *"Fetch Apple stock data from 2021 to 2024."*
  150. ## Creating Custom Strategies
  151. ### Option 1: Using Claude Code Skills (Recommended)
  152. 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:
  153. ```bash
  154. /add-strategy classic
  155. ```
  156. This will prompt you for:
  157. - Strategy name (e.g., "MACDBBands")
  158. - Description
  159. - Parameters with defaults
  160. - Entry and exit conditions
  161. - Any custom indicators
  162. The skill automatically handles:
  163. - File creation with proper naming conventions
  164. - Comprehensive docstrings
  165. - Automatic registration in `__init__.py`
  166. - Syntax validation
  167. Learn more about Claude Code skills: https://code.claude.com/docs/en/skills
  168. ### Option 2: Manual Creation
  169. Create a new file in `ai_trader/backtesting/strategies/classic/` and inherit from `BaseStrategy`.
  170. ```python
  171. # ai_trader/backtesting/strategies/classic/my_strategy.py
  172. import backtrader as bt
  173. from ai_trader.backtesting.strategies.base import BaseStrategy
  174. class MyCustomStrategy(BaseStrategy):
  175. params = dict(period=20)
  176. def __init__(self):
  177. self.sma = bt.indicators.SMA(self.data.close, period=self.p.period)
  178. def next(self):
  179. if not self.position and self.data.close[0] > self.sma[0]:
  180. self.buy()
  181. elif self.position and self.data.close[0] < self.sma[0]:
  182. self.close()
  183. ```
  184. The new strategy is automatically available to the CLI and `run_backtest` function.
  185. ## Documentation & Resources
  186. - **[Strategy Examples](ai_trader/backtesting/strategies/README.md)**: Details on built-in strategies.
  187. - **[Example Scripts](scripts/examples/)**: 5 complete working examples for different use cases.
  188. - **[Config Templates](config/backtest/)**: YAML configuration templates.
  189. - **[Migration Guide](docs/MIGRATION_GUIDE.md)**: For upgrading from v0.1.x.
  190. ## Contributing
  191. Contributions are welcome! Feel free to report bugs, suggest features, or submit pull requests.
  192. ## Show Your Support
  193. If you find this project helpful, please give it a star !
  194. ## License
  195. This project is licensed under the GNU General Public License v3 (GPL-3.0). See the [LICENSE](LICENSE) file for details.

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.