IndexError: array index out of range when dealing with RSI indicator
-
Hello all,
I keep receiving an error and looking at the trace, it seems to all stem from when I decide to use the RSI indicator.
# === Create a Strategy === class AmazingCrossover(bt.Strategy): def log(self, txt, dt=None): '''Logging function for this strategy''' dt = dt or self.datas[0].datetime.date(0) print('%s, %s' % (dt.isoformat(), txt)) def __init__(self): # # Create indicators # fast_ema = bt.ind.ExponentialMovingAverage(period = 5) # slow_ema = bt.ind.ExponentialMovingAverage(period = 10) # rsi = bt.ind.RSI(period = 10) # To keep track of pending orders and buy price/commission self.order = None self.buyprice = None self.buycomm = None def notify_order(self, order): if order.status in [order.Submitted, order.Accepted]: # Buy/Sell order submitted/accepted to/by broker - Nothing to do return # Check if an order has been completed # Attention: broker could reject order if not enough cash if order.status in [order.Completed]: if order.isbuy(): self.log( 'BUY EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' % (order.executed.price, order.executed.value, order.executed.comm)) self.buyprice = order.executed.price self.buycomm = order.executed.comm else: # Sell self.log('SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' % (order.executed.price, order.executed.value, order.executed.comm)) self.bar_executed = len(self) elif order.status in [order.Canceled, order.Margin, order.Rejected]: self.log('Order Canceled/Margin/Rejected') self.order = None def notify_trade(self, trade): if not trade.isclosed: return self.log('OPERATION PROFIT, GROSS %.2f, NET %.2f' % (trade.pnl, trade.pnlcomm)) def next(self): fast_ema = bt.ind.ExponentialMovingAverage(period = 5) slow_ema = bt.ind.ExponentialMovingAverage(period = 10) rsi = bt.ind.RSI(period = 10) # Check if an order is pending ... if yes, we cannot send a 2nd one if self.order: return # Check if we are in the market if not self.position: # Buy Condition if fast_ema > slow_ema: if rsi > 50: self.log('BUY CREATE, %.2f' % self.dataclose[0]) # Keep track of the created order to avoid a 2nd order self.order = self.buy() else: # Already in the market ... we might sell if fast_ema < slow_ema: if rsi < 50: # SELL, SELL, SELL!!! (with all possible default parameters) self.log('SELL CREATE, %.2f' % self.dataclose[0]) # Keep track of the created order to avoid a 2nd order self.order = self.sell() if __name__ == '__main__': # Create a Cerebro identity cerebro = bt.Cerebro() # Add the Strategy cerebro.addstrategy(AmazingCrossover) # Create a data feed data = bt.feeds.GenericCSVData( dataname='USDT_BTC.csv', fromdate=datetime.datetime(2018, 1, 1), todate=datetime.datetime(2018, 12, 31), nullvalue=0.0, datetime=0, high=2, low=3, open=4, close=1, volume=6, openinterest=-1 ) # Add the data to Cerebro cerebro.adddata(data) # Set our desired cash start cerebro.broker.setcash(10000.0) # Set the commission cerebro.broker.setcommission(commission = 0.002) # Get starting value print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue()) # Run over everything cerebro.run() # Get final value print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
Here is the error trace.
Traceback (most recent call last): File "/Users/developer/PycharmProject/AmazingCrossover/AmazingCrossover.py", line 141, in <module> cerebro.run() File "/Users/developer/PycharmProject/AmazingCrossover/venv/lib/python3.7/site-packages/backtrader/cerebro.py", line 1127, in run runstrat = self.runstrategies(iterstrat) File "/Users/developer/PycharmProject/AmazingCrossover/venv/lib/python3.7/site-packages/backtrader/cerebro.py", line 1293, in runstrategies self._runonce(runstrats) File "/Users/developer/PycharmProject/AmazingCrossover/venv/lib/python3.7/site-packages/backtrader/cerebro.py", line 1695, in _runonce strat._oncepost(dt0) File "/Users/developer/PycharmProject/AmazingCrossover/venv/lib/python3.7/site-packages/backtrader/strategy.py", line 311, in _oncepost self.nextstart() # only called for the 1st value File "/Users/developer/PycharmProject/AmazingCrossover/venv/lib/python3.7/site-packages/backtrader/lineiterator.py", line 347, in nextstart self.next() File "/Users/developer/PycharmProject/AmazingCrossover/AmazingCrossover.py", line 81, in next rsi = bt.ind.RSI(period = 10) File "/Users/developer/PycharmProject/AmazingCrossover/venv/lib/python3.7/site-packages/backtrader/indicator.py", line 53, in __call__ return super(MetaIndicator, cls).__call__(*args, **kwargs) File "/Users/developer/PycharmProject/AmazingCrossover/venv/lib/python3.7/site-packages/backtrader/metabase.py", line 88, in __call__ _obj, args, kwargs = cls.doinit(_obj, *args, **kwargs) File "/Users/developer/PycharmProject/AmazingCrossover/venv/lib/python3.7/site-packages/backtrader/metabase.py", line 78, in doinit _obj.__init__(*args, **kwargs) File "/Users/developer/PycharmProject/AmazingCrossover/venv/lib/python3.7/site-packages/backtrader/indicators/rsi.py", line 179, in __init__ upday = UpDay(self.data, period=self.p.lookback) File "/Users/developer/PycharmProject/AmazingCrossover/venv/lib/python3.7/site-packages/backtrader/indicator.py", line 53, in __call__ return super(MetaIndicator, cls).__call__(*args, **kwargs) File "/Users/developer/PycharmProject/AmazingCrossover/venv/lib/python3.7/site-packages/backtrader/metabase.py", line 88, in __call__ _obj, args, kwargs = cls.doinit(_obj, *args, **kwargs) File "/Users/developer/PycharmProject/AmazingCrossover/venv/lib/python3.7/site-packages/backtrader/metabase.py", line 78, in doinit _obj.__init__(*args, **kwargs) File "/Users/developer/PycharmProject/AmazingCrossover/venv/lib/python3.7/site-packages/backtrader/indicators/rsi.py", line 46, in __init__ self.lines.upday = Max(self.data - self.data(-self.p.period), 0.0) File "/Users/developer/PycharmProject/AmazingCrossover/venv/lib/python3.7/site-packages/backtrader/lineroot.py", line 227, in __sub__ return self._operation(other, operator.__sub__) File "/Users/developer/PycharmProject/AmazingCrossover/venv/lib/python3.7/site-packages/backtrader/lineroot.py", line 88, in _operation return self._operation_stage2(other, operation, r=r) File "/Users/developer/PycharmProject/AmazingCrossover/venv/lib/python3.7/site-packages/backtrader/lineroot.py", line 209, in _operation_stage2 other = other[0] File "/Users/developer/PycharmProject/AmazingCrossover/venv/lib/python3.7/site-packages/backtrader/linebuffer.py", line 163, in __getitem__ return self.array[self.idx + ago] IndexError: array index out of range
What am I missing here? I think I am missing something with the arguments of RSI but after looking at the docs I am not sure.
Any help would be appreciated. Thanks.
-
@ihustling said in IndexError: array index out of range when dealing with RSI indicator:
def next(self): fast_ema = bt.ind.ExponentialMovingAverage(period = 5) slow_ema = bt.ind.ExponentialMovingAverage(period = 10) rsi = bt.ind.RSI(period = 10)
You tell us where you have seen that in the docs ...
I can only suggest you go to the Docs - Quickstart Guide
Reading some of the other sections may also help.
-
@backtrader If you were wondering where I got the EMA indicators from, you mention SMA throughout the Quickstart guide and on your Github home page, so I figured switching to EMA was available. As for the RSI, it is present in your Indicator Reference, found here.
Regardless, I have remedied the issue by just using my own RSI function. Thanks for the help.
-
@ihustling said in IndexError: array index out of range when dealing with RSI indicator:
If you were wondering where I got the EMA indicators from, you mention SMA throughout the Quickstart guide and on your Github home page
Respectfully but truly sincere: you haven't read the docs.
Sorry, you seem to be in a rush and the trees are not letting you see the forest.
@backtrader said in IndexError: array index out of range when dealing with RSI indicator:
def next(self): fast_ema = bt.ind.ExponentialMovingAverage(period = 5) slow_ema = bt.ind.ExponentialMovingAverage(period = 10) rsi = bt.ind.RSI(period = 10)
You WILL NEVER see those indicators (nor any other) defined inside the
next
method.From the Quickstart Guide:
- Permalink to the section: https://www.backtrader.com/docu/quickstart/quickstart.html#adding-an-indicator
def __init__(self): # Keep a reference to the "close" line in the data[0] dataseries self.dataclose = self.datas[0].close # To keep track of pending orders and buy price/commission self.order = None self.buyprice = None self.buycomm = None # Add a MovingAverageSimple indicator self.sma = bt.indicators.SimpleMovingAverage(self.datas[0], period=self.params.maperiod)
I know it's tempting to go very quickly and be winning the first millions during your first days of algotrading, but I do truly believe you should read the docs. Be it backtrader, be it any other platform.
Even if you look at the GitHub page the code looks like this
class SmaCross(bt.SignalStrategy): def __init__(self): sma1, sma2 = bt.ind.SMA(period=10), bt.ind.SMA(period=30)