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

How does GenericCSVData work?



  • Hi everyone, while I'm studying Backtrader's DataFeed, I encountered a confused question about GenericCSVData. Please tell me what am I doing wrong? Thanks to everyone.

    from __future__ import (absolute_import, division, print_function,
                            unicode_literals)
    import datetime 
    import backtrader as bt
    
    
    class TestStrategy(bt.Strategy):
        params = (
            ('maperiod', 2),
        )
    
        def log(self, txt, dt=None):
            ''' Logging function fot this strategy'''
            dt = dt or self.datas[0].datetime.date(0)
            print('%s, %s' % (dt.isoformat(), txt))
            
        def __init__(self):
            self.dataclose = self.datas[0].close
            self.sma = bt.indicators.MovingAverageSimple(self.datas[0], period=self.params.maperiod)
            self.sma2 = bt.indicators.MovingAverageSimple(self.datas[0], period=self.params.maperiod * 2)
    
        def prenext(self):
            self.log("in prenex, len:%s" % len(self))
    
        def notify_order(self, order):
            self.log("In Order, order status: %s" % order.status)
    
        def notify_trade(self, trade):
            self.log("In trade, %s" % str(trade))
    
        def nextstart(self):
            self.log("nextstart called , len=%s" % len(self))
            super(TestStrategy, self).nextstart()
    
        def next(self):
            # Simply log the closing price of the series from the reference
            self.log('Close, %.2f' % self.dataclose[0])
    
    
    if __name__ == '__main__':
        cerebro = bt.Cerebro()
        data = bt.feeds.GenericCSVData(
            dataname='datas/orcl-1995-2014.txt',
            fromdate=datetime.datetime(1995, 1, 1),
            todate=datetime.datetime(1955, 12, 31),
            dtformat='%Y-%m-%d',
            datetime=0,
            time=-1,
            high=1,
            low=2,
            open=3,
            close=4,
            volume=5,
            openinterest=6,
            timeframe=bt.TimeFrame.Days
        )
        cerebro.adddata(data)
        cerebro.addstrategy(TestStrategy)
        print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
        cerebro.run()
        print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
    

    When i run the code, some errors happened as follow:

    File "D:\ProgramData\Anaconda3\envs\python36\lib\site-packages\backtrader\indicators\basicops.py", line 364, in once
        dst[i] = math.fsum(src[i - period + 1:i + 1]) / period
    IndexError: array assignment index out of range
    


  • Sorry, it's a stupid question. I found that i set a wrong todate in instantiating GenericCSVData. Because the todate is earlier thanfromdate.


Log in to reply
 

});