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

MultiData Strategy Does not Work



  • @backtrader said in MultiData Strategy Does not Work:

    %Y-%m-%d

    @ab_trader

    Backtrader,

    I have read the document sufficiently and I have programmed python in the past, thus aware of how to understand error messages for the most part. I am completely new to backtrader, and its frustrating that something so small is taking up so much time for me. I do not see it.

    You say that 2000-1-1 is not a suitable format for %Y-%m-%d. I have even tried other formats such as %Y/%m/%d and still getting the error:

    C:\Users\Sam\Anaconda64Best\python.exe "C:/Users/Sam/PycharmProjects/Test/.ipynb_checkpoints/Backtrader Sample SMA Strategy.py"
    Traceback (most recent call last):
    File "C:/Users/Sam/PycharmProjects/Test/.ipynb_checkpoints/Backtrader Sample SMA Strategy.py", line 53, in <module>
    fromdate=datetime.datetime(2000-1-1),
    TypeError: Required argument 'month' (pos 2) not found

    I am just frustrated because something so small as format never gets me caught up with python, but for this specific backtrading script it is. Makes me thing something could be off with my column numberings where i define datetime, time, open, etc.

    Anyhow full code below. Please help me here as I would like to really get into the main parts of understanding this language as opposed to continue to read this datetime documentation and not get anywhere (which is what has happened to me). Again, my full code is below that is causing this error:

    from __future__ import (absolute_import, division, print_function,
                            unicode_literals)
    
    import datetime  # For datetime objects
    import os.path  # To manage paths
    import sys  # To find out the script name (in argv[0])
    
    # Import the backtrader platform
    import backtrader as bt
    import backtrader.feeds as btfeeds
    
    
    # Create a Stratey
    class TestStrategy(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):                              # upon __init__ being called the strategy already has a list of datas that are present in the platform. This is a standard Python list and datas can be accessed in the order they were inserted.
            # Keep a reference to the "close" line in the data[0] dataseries
            self.dataclose = self.datas[0].close        # self.dataclose = self.datas[0].close keeps a reference to the close line. (close price)
                                                        # the first data in the list self.datas[0] is the default data for trading operations and to keep all strategy elements synchronized (its the system clock)
    
        def next(self):                                 # 'next' method will be called on each bar of the system clock (self.datas[0]). This is true until other things come into play like indicators, which need some bars to start producing an output.
            # Simply log the closing price of the series from the reference
            self.log('Close, %.2f' % self.dataclose[0])
    
            # if the price has been falling 3 sessions in a row..... buy buy buy!
            if self.dataclose[0] < self.dataclose[-1]:
                # current close less than previous close
    
                if self.dataclose[-1] < self.dataclose[-2]:
                    # previous close less than the previous close
    
                    # BUY, BUY, BUY!!! (with all possible default parameters)
                    self.log('BUY CREATE, %.2f' % self.dataclose[0])
                    self.buy()
    
    
    if __name__ == '__main__':
        # Create a cerebro entity
        cerebro = bt.Cerebro()
    
        # Add a strategy
        cerebro.addstrategy(TestStrategy)
    
        data = btfeeds.GenericCSVData(
            dataname='C:\\Users\\Sam\\PycharmProjects\\Test\\.ipynb_checkpoints\\orcl-1995-2014.txt',
    
            fromdate=datetime.datetime(2000-1-1),
            todate = datetime.datetime(2000-12-31),
    
            nullvalue=0.0, # missing values to be replaced with 0
    
            dtformat=('%Y-%m-%d'),
    
            datetime=0,
            open=1,
            high=2,
            low=3,
            close=4,
            adj_close=5,
            volume=6,
    
    
        )
    
    
    
    
    
        # Add the Data Feed to Cerebro
        cerebro.adddata(data)
    
        # Set our desired cash start
        cerebro.broker.setcash(100000.0)
    
        # Print out the starting conditions
        print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
    
        # Run over everything
        cerebro.run()
    
        # Print out the final result
        print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
    

    @ab_trader when I try your code syntax, for you I get the error:

    Starting Portfolio Value: 100000.00
    Traceback (most recent call last):
    File "C:/Users/Sam/PycharmProjects/Test/.ipynb_checkpoints/Backtrader Sample SMA Strategy.py", line 85, in <module>
    cerebro.run()
    File "C:\Users\Sam\Anaconda64Best\lib\site-packages\backtrader\cerebro.py", line 1142, in run
    runstrat = self.runstrategies(iterstrat)
    File "C:\Users\Sam\Anaconda64Best\lib\site-packages\backtrader\cerebro.py", line 1224, in runstrategies
    data.preload()
    File "C:\Users\Sam\Anaconda64Best\lib\site-packages\backtrader\feed.py", line 685, in preload
    while self.load():
    File "C:\Users\Sam\Anaconda64Best\lib\site-packages\backtrader\feed.py", line 476, in load
    _loadret = self._load()
    File "C:\Users\Sam\Anaconda64Best\lib\site-packages\backtrader\feed.py", line 707, in _load
    return self._loadline(linetokens)
    File "C:\Users\Sam\Anaconda64Best\lib\site-packages\backtrader\feeds\csvgeneric.py", line 114, in _loadline
    dt = datetime.strptime(dtfield, dtformat)
    File "C:\Users\Sam\Anaconda64Best\lib_strptime.py", line 565, in _strptime_datetime
    tt, fraction = _strptime(data_string, format)
    File "C:\Users\Sam\Anaconda64Best\lib_strptime.py", line 362, in _strptime
    (data_string, format))
    ValueError: time data '' does not match format '%Y-%m-%d'

    @ab_trader for your format, my full code is pasted below. I appreciate your help:

    from __future__ import (absolute_import, division, print_function,
                            unicode_literals)
    
    import datetime  # For datetime objects
    import os.path  # To manage paths
    import sys  # To find out the script name (in argv[0])
    
    # Import the backtrader platform
    import backtrader as bt
    import backtrader.feeds as btfeeds
    
    
    # Create a Stratey
    class TestStrategy(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):                              # upon __init__ being called the strategy already has a list of datas that are present in the platform. This is a standard Python list and datas can be accessed in the order they were inserted.
            # Keep a reference to the "close" line in the data[0] dataseries
            self.dataclose = self.datas[0].close        # self.dataclose = self.datas[0].close keeps a reference to the close line. (close price)
                                                        # the first data in the list self.datas[0] is the default data for trading operations and to keep all strategy elements synchronized (its the system clock)
    
        def next(self):                                 # 'next' method will be called on each bar of the system clock (self.datas[0]). This is true until other things come into play like indicators, which need some bars to start producing an output.
            # Simply log the closing price of the series from the reference
            self.log('Close, %.2f' % self.dataclose[0])
    
            # if the price has been falling 3 sessions in a row..... buy buy buy!
            if self.dataclose[0] < self.dataclose[-1]:
                # current close less than previous close
    
                if self.dataclose[-1] < self.dataclose[-2]:
                    # previous close less than the previous close
    
                    # BUY, BUY, BUY!!! (with all possible default parameters)
                    self.log('BUY CREATE, %.2f' % self.dataclose[0])
                    self.buy()
    
    
    if __name__ == '__main__':
        # Create a cerebro entity
        cerebro = bt.Cerebro()
    
        # Add a strategy
        cerebro.addstrategy(TestStrategy)
    
        data = btfeeds.GenericCSVData(
            dataname='C:\\Users\\Sam\\PycharmProjects\\Test\\.ipynb_checkpoints\\orcl-1995-2014.txt',
    
            fromdate=datetime.datetime.strptime("2000-1-1", "%Y-%m-%d"),
            todate=datetime.datetime.strptime("2000-12-31", "%Y-%m-%d"),
    
            nullvalue=0.0, # missing values to be replaced with 0
    
            dtformat=('%Y-%m-%d'),
    
            datetime=0,
            open=1,
            high=2,
            low=3,
            close=4,
            adj_close=5,
            volume=6,
    
    
        )
    


  • @backtrader

    Also, in your documentation it shows the format structure as:

    0_1507740057641_Capture.PNG

    My following code adjusted uses the same exact structure! And still get the error:

    Traceback (most recent call last):
    File "C:/Users/Sam/PycharmProjects/Test/.ipynb_checkpoints/Backtrader Sample SMA Strategy.py", line 85, in <module>
    cerebro.run()
    File "C:\Users\Sam\Anaconda64Best\lib\site-packages\backtrader\cerebro.py", line 1142, in run
    runstrat = self.runstrategies(iterstrat)
    File "C:\Users\Sam\Anaconda64Best\lib\site-packages\backtrader\cerebro.py", line 1224, in runstrategies
    data.preload()
    File "C:\Users\Sam\Anaconda64Best\lib\site-packages\backtrader\feed.py", line 685, in preload
    while self.load():
    File "C:\Users\Sam\Anaconda64Best\lib\site-packages\backtrader\feed.py", line 476, in load
    _loadret = self._load()
    File "C:\Users\Sam\Anaconda64Best\lib\site-packages\backtrader\feed.py", line 707, in _load
    return self._loadline(linetokens)
    File "C:\Users\Sam\Anaconda64Best\lib\site-packages\backtrader\feeds\csvgeneric.py", line 114, in _loadline
    dt = datetime.strptime(dtfield, dtformat)
    File "C:\Users\Sam\Anaconda64Best\lib_strptime.py", line 565, in _strptime_datetime
    tt, fraction = _strptime(data_string, format)
    File "C:\Users\Sam\Anaconda64Best\lib_strptime.py", line 362, in _strptime
    (data_string, format))
    ValueError: time data '' does not match format '%Y-%m-%d'

    What am i missing here? Makes no sense to me, and this is following the documentation structure. Code that follows it:

    from __future__ import (absolute_import, division, print_function,
                            unicode_literals)
    
    import datetime  # For datetime objects
    import os.path  # To manage paths
    import sys  # To find out the script name (in argv[0])
    
    # Import the backtrader platform
    import backtrader as bt
    import backtrader.feeds as btfeeds
    
    
    # Create a Stratey
    class TestStrategy(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):                              # upon __init__ being called the strategy already has a list of datas that are present in the platform. This is a standard Python list and datas can be accessed in the order they were inserted.
            # Keep a reference to the "close" line in the data[0] dataseries
            self.dataclose = self.datas[0].close        # self.dataclose = self.datas[0].close keeps a reference to the close line. (close price)
                                                        # the first data in the list self.datas[0] is the default data for trading operations and to keep all strategy elements synchronized (its the system clock)
    
        def next(self):                                 # 'next' method will be called on each bar of the system clock (self.datas[0]). This is true until other things come into play like indicators, which need some bars to start producing an output.
            # Simply log the closing price of the series from the reference
            self.log('Close, %.2f' % self.dataclose[0])
    
            # if the price has been falling 3 sessions in a row..... buy buy buy!
            if self.dataclose[0] < self.dataclose[-1]:
                # current close less than previous close
    
                if self.dataclose[-1] < self.dataclose[-2]:
                    # previous close less than the previous close
    
                    # BUY, BUY, BUY!!! (with all possible default parameters)
                    self.log('BUY CREATE, %.2f' % self.dataclose[0])
                    self.buy()
    
    
    if __name__ == '__main__':
        # Create a cerebro entity
        cerebro = bt.Cerebro()
    
        # Add a strategy
        cerebro.addstrategy(TestStrategy)
    
        data = btfeeds.GenericCSVData(
            dataname='C:\\Users\\Sam\\PycharmProjects\\Test\\.ipynb_checkpoints\\orcl-1995-2014.txt',
    
            fromdate=datetime.datetime(2000, 1, 1),
            todate = datetime.datetime(2000, 12, 31),
    
            nullvalue=0.0, # missing values to be replaced with 0
    
            dtformat=('%Y-%m-%d'),
    
            datetime=0,
            open=1,
            high=2,
            low=3,
            close=4,
            adj_close=5,
            volume=6,
    
    
        )
    
    
    
    
    
        # Add the Data Feed to Cerebro
        cerebro.adddata(data)
    
        # Set our desired cash start
        cerebro.broker.setcash(100000.0)
    
        # Print out the starting conditions
        print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
    
        # Run over everything
        cerebro.run()
    
        # Print out the final result
        print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
    


  • nevermind got it to work. Thanks guys for your patience and helping me out.


Log in to reply
 

});