Monthly Archives: October 2023

Backtrader Testing vs Live Timeframe Considerations

I’ve been doing some backtesting using backtrader and then comparing that data with real trading on IBKR using the API.

I’ve attempted to make a profitable trading system using SPY or QQQ or other ETFs. I’ve found that the most profitable timeframe has been using 60 minute data.

One avenue that I’be been testing is using only certain times of the trading day for certain strategies. I’ve discovered that there is some nuance that is worth commenting on. One thing I discovered using 60 minute data was that using live trading, the “next” method isn’t called until a full hour has elapsed, after which the markets might actually be already closed. To fix this problem, I modified my code to use a smaller interval, say 2 minutes, to check for certain exit conditions while still using hourly data for any entrances.

When testing this in backtrader using historical data, I encountered some difficulty because of how the bars are labeled for time. The historical data has a timestamp at the beginning of the bar. For example, a timestamp of 10:00 on an hourly bar contains the data from 10:00 until 10:59:59.

This is different from the way that live data is handled by backtrader. In backtrader, the bar for 11:00:00 contains data from 10:00:00 until 11:00:00.

This difference caused problems for my testing logic until I added the interval (2 minutes for 2 minute data) to all of the timestamps in the dataframe prior to adding them to the backtrader engine.