I am trying to backtest a simple trading strategy using python3 using the backtesting module. Here is a sample of the data I am using through an external CSV:
Date,Open,High,Low,Close,Volume 2023-08-28 06:15:00,25959.8,25959.8,25905.7,25917.6,5838086.0 2023-08-28 06:30:00,25915.3,25931.9,25897.1,25910.0,6266633.0 2023-08-28 06:45:00,25909.1,25930.4,25903.9,25919.3,6325446.0 2023-08-28 07:00:00,25914.9,25923.7,25905.5,25905.5,3825150.0
Note that I have almost 2000, 15-minute timeframe data in my csv.
I keep getting this error:
ValueError: operands could not be broadcast together with shapes (367,) (1990,)
Here is the code I am using:
import pandas as pd
from backtesting import Backtest, Strategy
import talib
import backtesting as bt
data = pd.read_csv('2_BTC-USD-ALL-with-Indicators.csv')
data['Date'] = pd.to_datetime(data['Date'])
data.set_index('Date', inplace=True)
data.sort_index(inplace=True)
# Calculating custom indicators
data['ema200'] = talib.EMA(data['Close'], timeperiod=200)
data['ema3'] = talib.EMA(data['Close'], timeperiod=3)
class TrendRiderStrategy(Strategy):
n_bb = 25
stop_loss = 15
profit_target = 25
def init(self):
bb_upper, bb_middle, bb_lower = talib.BBANDS(self.data['Close'], timeperiod=self.n_bb, nbdevup=2, nbdevdn=2)
self.bb_upper = bb_upper[-len(self.data):]
self.bb_middle = bb_middle[-len(self.data):]
self.bb_lower = bb_lower[-len(self.data):]
def next(self):
if not self.position:
if self.data['Close'] > self.data['ema200'] and self.data['ema3'] > self.bb_middle:
self.buy()
elif self.position:
if self.data['Close'] < self.data['ema200'] and self.data['ema3'] < self.bb_middle:
self.position.close()
bt = Backtest(data, TrendRiderStrategy, cash=1_000_000, commission=0.02)
stats = bt.run()
print(stats)
# bt.plot()
You'll need to essentially convert your self.data['Close'] to an indicator in order to make the comparison. This seems to be a quirk of backtesting.py
Here is an example from the article below on its usage:
https://algotrading101.com/learn/backtesting-py-guide/#backtesting.py-optimizations
Hope that helps.