[Python] Backtrader Double Bollinger Band Error reg. Index out of Range

Discussão em 'Python' iniciado por Stack, Novembro 21, 2024.

  1. Stack

    Stack Membro Participativo

    I'm trying to code a double bollinger bands strategy with Backtrader and get following error.

    '''Starting Portfolio Value: 25000.00
    ---------------------------------------------------------------------------
    IndexError Traceback (most recent call last)
    <ipython-input-32-ddca45cee090> in <cell line: 2>()
    1 print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
    ----> 2 cerebro.run()
    3 print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())

    6 frames
    /usr/local/lib/python3.10/dist-packages/backtrader/linebuffer.py in __getitem__(self, ago)
    161
    162 def __getitem__(self, ago):
    --> 163 return self.array[self.idx + ago]
    164
    165 def get(self, ago=0, size=1):

    IndexError: array index out of range
    '''


    Here is the code I have. The issue I think is from the line 'Buy Condition 1', looking into the past 4 periods. Does it have something to do with setting up the data? How can I fix this? Thank you for your time in advance!!

    '''data = bt.feeds.YahooFinanceCSVData(
    dataname = 'BTC_22-24_4H.csv', openinterest = 6
    )

    cerebro = bt.Cerebro()
    cerebro.adddata(data)
    class DoubleBB(bt.Strategy):
    params = (
    ('bb_period', 20),
    ('dev1', 1),
    ('dev2', 2)
    )

    def __init__(self):
    # Bollinger band with deviation 1
    self.bb1 = bt.ind.BollingerBands(period=self.params.bb_period, devfactor=self.params.dev1)
    #Bollinger band with deviation 2
    self.bb2 = bt.ind.BollingerBands(period=self.params.bb_period, devfactor=self.params.dev2)

    # Buy Condition 1: In the last 4 periods, at least one low price was below the lower band of bb2
    self.low_below_bb2 = any(self.data.low[-i] <= self.bb2.bot[-i] for i in range(1, 4))
    # Buy Condition 2: Previous close price crosses over the lower band of bb1
    self.bb1_lower = bt.indicators.CrossOver(self.data.close, self.bb1.lines.bot, plotname='buy sig')
    # Buy Condition 3: Previous close price is between the lower band of bb1 and the middle line

    # Exit Condition 1: Close price crosses below the upper band of bb1
    self.bb1_upper = bt.indicators.CrossOver(self.data.close, self.bb1.lines.top, plotname='sell sig')

    def next(self):

    if not self.position:
    if (self.bb1_lower > 0) and low_below_bb2:
    self.buy()
    else:
    if self.bb1_upper < 0:
    self.close()
    '''

    Continue reading...

Compartilhe esta Página