Trying to get some idea on how to debug this. Just started to use backtesting.py + TA to conduct some backtesting. Seems to work for EMA indicator. RSI indicator did not work: Tried with self.rsi instead of self.rsi [-1] as well. But the same ValueError was raised.
Error seems to start from backtesting.py on line 139:
File ~\anaconda3\Lib\site-packages\backtesting\backtesting.py:139, in >Strategy.I(self, func, name, plot, overlay, color, scatter, *args, **kwargs)
ValueError: attempt to get argmax of an empty sequence.
Was expecting RSI Indicator to work like any other indicators.
import pandas as pd
import yfinance as yf
import ta
from backtesting import Backtest, Strategy, set_bokeh_output
from backtesting.lib import crossover
df = yf.download('AAPL', start='2022-12-01', end='2023-12-31')
class EMA_200(Strategy):
n1 = 200
n2 = 14
rsi_btm = 30
rsi_top = 70
def init(self):
close = self.data.Close
self.ema_200 = self.I(ta.trend.ema_indicator, pd.Series(close), self.n1)
self.rsi = self.I(ta.momentum.RSIIndicator, pd.Series(close), self.n2)
def next(self):
if self.data.index[-1] >= pd.to_datetime('2023-01-01'):
if not self.position: # no existing position
if (self.data.Close < self.ema_200) and (self.rsi[-1] <= self.rsi_btm):
self.buy()
elif self.data.Close > self.ema_200 and (self.rsi[-1] >= self.rsi_top):
self.sell()
elif self.position: # existing position
if (self.position.is_long) and (self.data.Close > self.ema_200) and (self.rsi[-1] >= self.rsi_top):
self.position.close()
elif (self.position.is_short) and (self.data.Close < self.ema_200) and (self.rsi[-1] >= self.rsi_btm):
self.position.close()
bt = Backtest(df, EMA_200, cash=1000000, commission=.002,
exclusive_orders=True)
stats = bt.run()
stats