This directory contains example scripts demonstrating different ways to use ai-trader for backtesting.
Make the scripts executable:
chmod +x scripts/examples/*.pyRun an example:
python scripts/examples/01_simple_backtest.pyOr directly if executable:
./scripts/examples/01_simple_backtest.pyPurpose: Quickstart example using the run_backtest() convenience function.
What it demonstrates:
- Running a complete backtest with one function call
- Using the SMA (Simple Moving Average) strategy
- Passing strategy parameters
- Using example data
Recommended for: Beginners who want to get started quickly.
Purpose: Shows each step of the backtest process explicitly.
What it demonstrates:
- Creating a Cerebro instance
- Loading stock data
- Adding a strategy
- Configuring position sizer
- Adding analyzers
- Running backtest and printing results
Recommended for: Users who want full control over each step.
Purpose: Demonstrates portfolio/multi-stock backtesting.
What it demonstrates:
- Loading multiple stocks from a directory
- Using a rotation strategy
- Position sizing across multiple positions
- Portfolio-specific analyzers (SQN)
Recommended for: Users building portfolio strategies.
Purpose: Shows pure Backtrader usage without any helper functions.
What it demonstrates:
- Direct Backtrader API usage
- Creating custom strategies inline
- Full flexibility and control
- Manual result extraction
Recommended for: Advanced users who want maximum flexibility or are already familiar with Backtrader.
Purpose: Compare multiple strategies on the same data.
What it demonstrates:
- Running multiple strategies programmatically
- Extracting and comparing metrics
- Finding the best-performing strategy
- Creating comparison tables
Recommended for: Strategy research and optimization.
add_stock_data(cerebro, source=None)add_stock_data(cerebro, source="data/AAPL.csv")import pandas as pd
df = pd.read_csv("data/AAPL.csv", parse_dates=["Date"], index_col=["Date"])
add_stock_data(cerebro, source=df, name="AAPL")add_portfolio_data(cerebro, data_dir="./data/tw_stock/")cerebro.addstrategy(SMAStrategy)cerebro.addstrategy(SMAStrategy, fast_period=10, slow_period=30)run_backtest(
strategy=SMAStrategy,
strategy_params={"fast_period": 10, "slow_period": 30}
)add_sizer(cerebro, "percent", percents=95)add_sizer(cerebro, "fixed", stake=100)add_default_analyzers(cerebro) # sharpe, drawdown, returnsadd_analyzers(cerebro, ["sharpe", "drawdown", "returns", "trades", "sqn"])- Modify an example: Copy an example and modify it for your needs
- Create a custom strategy: See
04_pure_backtrader.pyfor inline strategy definition - Use config files: Try the CLI with config files in
config/backtest/ - Explore strategies: Check available strategies in
ai_trader/backtesting/strategies/
- Start with
01_simple_backtest.pyif you're new to backtesting - Use
02_step_by_step.pyas a template for custom backtests - Always compare your strategy against
BuyHoldStrategybenchmark - Include at least sharpe, drawdown, and returns analyzers
- Test on multiple time periods to validate robustness
- Consider transaction costs (commission parameter)
Most examples use load_example() which provides sample data. For real backtesting:
-
Download data using the CLI:
ai-trader fetch AAPL --market us --start-date 2020-01-01
-
Or use your own CSV files with columns:
Date, Open, High, Low, Close, Volume
- Check the main README.md for general documentation
- See config/backtest/README.md for YAML configuration docs
- Read strategy source code in ai_trader/backtesting/strategies/