Navigation

    Backtrader Community

    • Register
    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/

    Log / Print OHLC and other line variables.

    General Code/Help
    2
    2
    197
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • P
      prateek last edited by

      I went through a lot of examples on this forum and designed a sample code, but I am stuck with an error. All I am trying to do is log/print the date-time, open, high, low, close, DIST_ESD_ALT1_365D, DIST_SPRD_ALT_1.1_365D, DIST_SPRD_ALT_1.2_365D, signal variables of "stk0" symbol.

      Similarly, just log/print the date-time, open, high, low, close, DIST_ESD_ALT1_365D, DIST_SPRD_ALT_1.1_365D, DIST_SPRD_ALT_1.2_365D, signal variables of "stk1" symbol.

      I have pickled the pandas dataframe "all_values". The pickled dataframe can be downloaded from :

      https://leonwtq-my.sharepoint.com/:f:/g/personal/bq468_a1e_me/EjjcFqNkcdZJpvV-YAStI-4B3YMgHeZiF2kiESm6Nw0mDw?e=rf9cev

      The code is as follows:

      from __future__ import (absolute_import, division, print_function,
                              unicode_literals)
      
      # Import the backtrader platform
      import backtrader as bt
      import pickle
      
      # Create a Stratey
      class TestStrategy(bt.Strategy):
      
          def log(self, txt, dt=None):
              ''' Logging function fot this strategy'''
      
      
          def __init__(self):
              # Keep a reference to the "close" line in the data[0] dataseries
      
              self.stk0_symbol = self.p.stk0_symbol
              self.stk1_symbol = self.p.stk1_symbol
      
              # Strategy params
              self.loss_limit = self.p.loss_limit
              self.consider_borrow_cost = self.p.consider_borrow_cost
              self.consider_commission = self.p.consider_commission
      
              # Parameters for printing
              self.print_bar = self.p.print_bar
              self.print_msg = self.p.print_msg
              self.print_transaction = self.p.print_transaction
      
      
      
          def next(self):
      
              # Log / Print the date-time, open, high, low, close,  'DIST_ESD_ALT1_365D', 'DIST_SPRD_ALT_1.1_365D', 'DIST_SPRD_ALT_1.2_365D', 'signal' of stk0
              # Log / Print the date-time, open, high, low, close,  'DIST_ESD_ALT1_365D', 'DIST_SPRD_ALT_1.1_365D', 'DIST_SPRD_ALT_1.2_365D', 'signal' of stk1
      
              pass
      
      
      
      class LineParam:
      
          def get_extra_df_columns(self, df, exclusion_list):
              lines = ()
              for column in df.columns:
                  if column not in exclusion_list:
                          lines = lines + (column,)
              return lines
      
          def _create_data_feeder(self, lines, params):
      
              return type('PandasDataFeed', (bt.feeds.PandasData,), {'lines': lines, 'params': params})
      
      if __name__ == '__main__':
      
          # Parameters for Overall Pair Backtest
      
          max_lookback = [220]  # Number of trading days
          lookback_value = [52]
          enter_threshold_size = [2]
          exit_threshold_size = [0.5]
          loss_limit = [-0.005]
          consider_borrow_cost = False
          consider_commission = True
          print_msg = True
          print_transaction = True
      
      
          # Create a cerebro entity
          cerebro = bt.Cerebro()
      
          parameters_stk0_dict = {}
          parameters_stk1_dict = {}
      
          infile = open("all_values", "rb")
          all_values = pickle.load(infile)
          symbols_list = ['NAVI.O', 'EFX']
      
          for i in range(len(symbols_list)):
              all_values = all_values.drop(['#RIC_' + symbols_list[i]], axis=1)
      
          all_values_column_names = list(all_values.columns.values)
      
          exclusion_list = ['Open_' + symbols_list[0], 'High_' + symbols_list[0], 'Low_' + symbols_list[0], 'Close_' + symbols_list[0],
                            'Open_' + symbols_list[1], 'High_' + symbols_list[1], 'Low_' + symbols_list[1], 'Close_' + symbols_list[1]]
      
          obj = LineParam()
          line_tuple=obj.get_extra_df_columns(all_values, exclusion_list)
      
      
          # Add stk0
          parameters_stk0_dict = {'datetime': 'Date-Time',
                                  'open': 'Open' + "_" + symbols_list[0],
                                  'high': 'High' + "_" + symbols_list[0],
                                  'low': 'Low' + "_" + symbols_list[0],
                                  'close': 'Close' + "_" + symbols_list[0]}
      
          for i in  range(len(line_tuple)):
              parameters_stk0_dict.update({line_tuple[i]: line_tuple[i]})
      
          parameters_stk0_tuple = tuple(parameters_stk0_dict.items())
      
      
          data_feeder  = obj._create_data_feeder(line_tuple, parameters_stk0_tuple)
      
          # Add the Data Feed to Cerebro
          cerebro.adddata(data_feeder(dataname=all_values, name="stk0"))
      
      
          # Add stk1
          parameters_stk1_dict = {'datetime': 'Date-Time',
                                  'open': 'Open' + "_" + symbols_list[1],
                                  'high': 'High' + "_" + symbols_list[1],
                                  'low': 'Low' + "_" + symbols_list[1],
                                  'close': 'Close' + "_" + symbols_list[1]}
      
      
          for i in  range(len(line_tuple)):
              parameters_stk1_dict.update({line_tuple[i]: line_tuple[i]})
      
          parameters_stk1_tuple = tuple(parameters_stk1_dict.items())
      
          data_feeder  = obj._create_data_feeder(line_tuple, parameters_stk1_tuple)
      
          # Add the Data Feed to Cerebro
          cerebro.adddata(data_feeder(dataname=all_values, name="stk1"))
      
      
          backtest_config_dict = \
              {'stk0_symbol': symbols_list[0],
               'stk1_symbol': symbols_list[1],
               'loss_limit': loss_limit,
               'consider_borrow_cost': consider_borrow_cost,
               'consider_commission': consider_commission,
               'print_msg': print_msg,
               'print_transaction': print_transaction}
      
      
          # Add a strategy
          cerebro.addstrategy(TestStrategy,
                              stk0_symbol=backtest_config_dict['stk0_symbol'],
                              stk1_symbol=backtest_config_dict['stk1_symbol'],
                              loss_limit=backtest_config_dict['loss_limit'],
                              consider_borrow_cost=backtest_config_dict['consider_borrow_cost'],
                              consider_commission=backtest_config_dict['consider_commission'],
                              print_msg=backtest_config_dict['print_msg'],
                              print_transaction=backtest_config_dict['print_transaction']
                              )
      
      
          # 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())
      

      Though I have not written the log/print code, but when I run this code, I get the following error :

      Traceback (most recent call last):
        File "C:\Program Files\JetBrains\PyCharm 2020.2\plugins\python\helpers\pydev\pydevd.py", line 1448, in _exec
          pydev_imports.execfile(file, globals, locals)  # execute the script
        File "C:\Program Files\JetBrains\PyCharm 2020.2\plugins\python\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
          exec(compile(contents+"\n", file, 'exec'), glob, loc)
        File "C:/Users/prate/Dropbox/01 Prateek Otto/Paper 3/Cerebro/Sample.py", line 159, in <module>
          cerebro.run()
        File "C:\Python37\lib\site-packages\backtrader\cerebro.py", line 1127, in run
          runstrat = self.runstrategies(iterstrat)
        File "C:\Python37\lib\site-packages\backtrader\cerebro.py", line 1212, in runstrategies
          data.preload()
        File "C:\Python37\lib\site-packages\backtrader\feed.py", line 438, in preload
          while self.load():
        File "C:\Python37\lib\site-packages\backtrader\feed.py", line 479, in load
          _loadret = self._load()
        File "C:\Python37\lib\site-packages\backtrader\feeds\pandafeed.py", line 255, in _load
          line[0] = self.p.dataname.iloc[self._idx, colindex]
        File "C:\Python37\lib\site-packages\backtrader\linebuffer.py", line 222, in __setitem__
          self.array[self.idx + ago] = value
      TypeError: must be real number, not Timestamp
      
      Process finished with exit code 1
      

      Can someone please help me. Thanks

      Kjiessar 1 Reply Last reply Reply Quote 0
      • Kjiessar
        Kjiessar @prateek last edited by

        @prateek

           self.array[self.idx + ago] = value
        TypeError: must be real number, not Timestamp
        

        self.idx or ago is an Timestamp and must be real number (int)
        try this

        if you create a dict with exact same names as parameters like

        backtest_config_dict = \
                {'stk0_symbol': symbols_list[0],
                 'stk1_symbol': symbols_list[1],
                 'loss_limit': loss_limit,
                 'consider_borrow_cost': consider_borrow_cost,
                 'consider_commission': consider_commission,
                 'print_msg': print_msg,
                 'print_transaction': print_transaction}
        
        
            # Add a strategy
            cerebro.addstrategy(TestStrategy,
                                stk0_symbol=backtest_config_dict['stk0_symbol'],
                                stk1_symbol=backtest_config_dict['stk1_symbol'],
                                loss_limit=backtest_config_dict['loss_limit'],
                                consider_borrow_cost=backtest_config_dict['consider_borrow_cost'],
                                consider_commission=backtest_config_dict['consider_commission'],
                                print_msg=backtest_config_dict['print_msg'],
                                print_transaction=backtest_config_dict['print_transaction']
                                )
        

        you can go like

        cerebro.addstrategy(TestStrategy, **backtest_config_dict )
        
        1 Reply Last reply Reply Quote 0
        • 1 / 1
        • First post
          Last post
        Copyright © 2016, 2017, 2018, 2019, 2020, 2021 NodeBB Forums | Contributors