Skip to content

Setting Up Your Trading Strategy Backtest

With your trading strategy ready for backtesting we will create a new script that will configure the DataSources, PaperExchange and handle the backtest completion event.

1. Create the Backtest Script

Create a new file named backtest.py with the following content:

python
import asyncio
from sma_sample_strategy import SMAStrategy
from superalgorithm.exchange import PaperExchange
from superalgorithm.data.providers.csv import CSVDataSource
from superalgorithm.backtesting.analytics import session_stats
from superalgorithm.utils.config import config

def backtest_complete_handler(strategy: SMAStrategy):
    print(session_stats(strategy.exchange.list_trades()))

async def main():
    # Initialize data source and strategy
    csv = CSVDataSource("BTC/USDT", "5m", csv_data_folder=config.get("CSV_DATA_FOLDER"))
    strategy = SMAStrategy([csv], PaperExchange())

    # Set up completion handler
    strategy.on("backtest_done", backtest_complete_handler)

    # Run the backtest
    await strategy.start()

if __name__ == "__main__":
    asyncio.run(main())

In the above code we are using the CSVDataSource to load OHLCV data from a file named BTC_USDT_5m.csv located in our <CSV_DATA_FOLDER> as explained below.

We also pass a default PaperExchange instance to our strategy, start the strategy and listen for the backtest_done event.

Finally, we use the session_stats method and pass all our trades from the backtest to compute the SessionStats results.

2. Configure Data

Download Historical Data

  1. Download the sample data file:

    wget superalgorithm.com/data/BTC_USDT_5m.csv.zip

    Or visit superalgorithm.com/data/BTC_USDT_5m.csv.zip in your browser and save the file.

  2. Create a data folder in your project directory:

    mkdir csv_data
  3. Unzip and move the downloaded CSV file to the data folder:

    mv BTC_USDT_5m.csv csv_data/

Create Configuration File

Create a config.yaml file in the root of your project directory with the following content:

yaml
CSV_DATA_FOLDER: csv_data

3. Run the Backtest

Execute the backtest script:

python backtest.py

Expected Output

After running the backtest, you'll see statistics about your strategy's performance, including:

  • Number of trades
  • Win rate
  • Profit/loss metrics
  • Other relevant performance indicators