Strategy code

The strategy code is simple and is located in dual_moving_average.py. A few highlights are shown below.

To use our historical data in backtrader, we download a CSV of AAPL prices and create our backtrader data feed from it:

import backtrader.feeds as btfeeds
from quantrocket.history import download_history_file

# Create data feed using QuantRocket data and add to backtrader
# (Put files in /tmp to have QuantRocket automatically clean them out after
# a few hours)
download_history_file(
    'usstock-free-1d',
    sids=['FIBBG000B9XRY4'],
    filepath_or_buffer='/tmp/backtrader-demo-1d.csv',
    fields=['Sid','Date','Open','Close','High','Low','Volume'])

data = btfeeds.GenericCSVData(
    dataname='/tmp/backtrader-demo-1d.csv',
    dtformat=('%Y-%m-%d'),
    datetime=1,
    open=2,
    close=3,
    high=4,
    low=5,
    volume=6
)
cerebro.adddata(data)

A backtest commonly ends by plotting a performance chart, but since our code will be running in a headless Docker container, we should save the plot to a file (which we'll tell QuantRocket to return to us when we run the backtest):

# Save the plot to PDF so the satellite service can return it
cerebro.plot(savefig=True, figfilename='/tmp/backtrader-plot.pdf')

Next Up

Part 4: Run backtest