For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/

Custom indicator shows NAN



  • Hi,
    I want to create custom indicator which x2 open price. However, it show "NAN" when I run the below code. Can you help me find out what am I doing wrong ? Thank you :)

    import backtrader as bt
    from datetime import datetime
    
    
    
    class firstStrategy(bt.Strategy):
        lines = ('doubleopen',)
        def __init__(self):
            self.l.doubleopen = self.data.open * 2
    
    
    
        def next(self):
            print('*' * 5, 'NEXT:', bt.num2date(self.data0.datetime[0]), self.data0._name, self.data0.open[0], self.doubleopen[0],
                   len(self.data0))
            print('h')
    
    # Variable for our starting cash
    startcash = 10000
    
    # Create an instance of cerebro
    cerebro = bt.Cerebro()
    
    # Add our strategy
    cerebro.addstrategy(firstStrategy)
    
    # Get Apple data from Yahoo Finance.
    data = bt.feeds.YahooFinanceData(
        dataname='AAPL',
        fromdate=datetime(2016, 1, 1),
        todate=datetime(2016, 3, 10),
        buffered=True
    )
    
    # Add the data to Cerebro
    cerebro.adddata(data)
    
    # Set our desired cash start
    cerebro.broker.setcash(startcash)
    
    # Run over everything
    cerebro.run()
    
    # Get final portfolio Value
    portvalue = cerebro.broker.getvalue()
    pnl = portvalue - startcash
    
    # Print out the final result
    print('Final Portfolio Value: ${}'.format(portvalue))
    print('P/L: ${}'.format(pnl))
    
    # Finally plot the end results
    #cerebro.plot(style='candlestick')


  • @nguyễn-tài-nguyên said in Custom indicator shows NAN:

    class firstStrategy(bt.Strategy):
    

    That's clearly NOT a custom indicator. Use bt.Indicator and embed the resulting indicator in a subclass of Strategy