Read data from Pandas



  • 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



  • Hi,

    is a simple:

    df = pd.read_pickle("data/"+_Symbol+""+cTF+".pkl")
    data = bt.feeds.PandasData(dataname=df,timeframe=1,openinterest=None)

  • administrators

    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)


Log in to reply
 

Looks like your connection to Backtrader Community was lost, please wait while we try to reconnect.