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/

    Read data from Pandas

    General Discussion
    data
    2
    3
    6210
    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.
    • G
      grat last edited by backtrader

      Hi,
      I'm new in backtrader

      I have a data in pickle and read:

               _Symbol="EURUSD"
               cTF='1min' 
               dataframe = pd.read_pickle("data/"+_Symbol+""+cTF+".pkl")
               dataframe.head()
      

      output:

      	Date	open	high	low	close	volume	datetime
      0	2016-04-01 00:00:00	1.13784	1.13793	1.13767	1.13788	252.53	2016-04-01 00:00:00
      1	2016-04-01 00:01:00	1.13788	1.13802	1.13777	1.13800	262.13	2016-04-01 00:01:00
      2	2016-04-01 00:02:00	1.13801	1.13817	1.13801	1.13816	233.21	2016-04-01 00:02:00
      3	2016-04-01 00:03:00	1.13816	1.13821	1.13811	1.13818	215.07	2016-04-01 00:03:00
      4	2016-04-01 00:04:00	1.13817	1.13820	1.13810	1.13815	171.65	2016-04-01 00:04:00
      

      class PandasData(bt.feed.DataBase):
          '''
          The ``dataname`` parameter inherited from ``feed.DataBase`` is the pandas
          DataFrame
          '''
      
          params = (
              # Possible values for datetime (must always be present)
              #  None : datetime is the "index" in the Pandas Dataframe
              #  -1 : autodetect position or case-wise equal name
              #  >= 0 : numeric index to the colum in the pandas dataframe
              #  string : column name (as index) in the pandas dataframe
              ('datetime', -1),
      
              # Possible values below:
              #  None : column not present
              #  -1 : autodetect position or case-wise equal name
              #  >= 0 : numeric index to the colum in the pandas dataframe
              #  string : column name (as index) in the pandas dataframe
              ('open', -1),
              ('high', -1),
              ('low', -1),
              ('close', -1),
              ('volume', -1),
              ('openinterest', None),
          )
      

           def runstrat():
                # Create a cerebro entity
                cerebro = bt.Cerebro(stdstats=False)
      
                # Add a strategy
                cerebro.addstrategy(TestStrategy)
      
                dataframe = pd.read_pickle("data/"+_Symbol+""+cTF+".pkl")
                data = PandasData(dataname=dataframe)
      
                 # 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())
      

      # Create a Stratey
               class TestStrategy(bt.Strategy):
          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):
              # Keep a reference to the "close" line in the data[0] dataseries
              self.dataclose = self.datas[0].close
      
          def next(self):
              # Simply log the closing price of the series from the reference
              self.log('Close, %.2f' % self.dataclose[0])
      
              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()
      

             runstrat()
      

      I'm have output:

      * Starting Portfolio Value: 100000.00
      * Final Portfolio Value: 100000.00
      

      Where is my mistake? I also trying data with datatime index. The same output.

      Thanks Milan

      1 Reply Last reply Reply Quote 0
      • G
        grat last edited by

        Hi,

        is a simple:

        df = pd.read_pickle("data/"+_Symbol+""+cTF+".pkl")
        data = bt.feeds.PandasData(dataname=df,timeframe=1,openinterest=None)
        
        1 Reply Last reply Reply Quote 0
        • B
          backtrader administrators last edited by

          Glad it worked.

          timeframe=1 seems anyhow odd because that is the actual value for bt.TimeFrame.Ticks and the data seems to be made up of 1-minute bars.

          The platform will not complain (especially if no resampling is done), but you can see that later in a plot.

          The suggestion would be to use: timeframe=bt.TimeFrame.Minutes (symbolic names seem better)

          1 Reply Last reply Reply Quote 1
          • 1 / 1
          • First post
            Last post
          Copyright © 2016, 2017, 2018, 2019, 2020, 2021 NodeBB Forums | Contributors