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 to get data out of cerebro.run()



  • Hi,
    Lets just say that I need to get the current date of run and the corresponding close value on to a pandas dataframe and then access it after cerebro has run. How do I do this. Thus at each execution of next() in my strategy, I need to update this pandas dataframe and then once all runs are over, I need it to make it available outside cerebro.run().



  • Adding a code sample to explain what I need. In the below code sample, I just print out close values of two stocks in my strategy in each iteration of next(). What do I need to do if I want to push it to a say a pandas dataframe (with the index as dates).

    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 pandas as pd
    import numpy as np
    import datetime
    import matplotlib
    
    # Import the backtrader platform
    import backtrader as bt
    import backtrader.feeds as btfeeds
    
    def MakeArbitraryData(): # make random 'open,high,close,low' data
        A = np.random.randint(0,10,size=(5,4)) #create 5 X 4 matrix of random integers
        Apd = pd.DataFrame(data=A,columns=['Open','High','Close','Low'])
        DateRange = [datetime.date(2018,3,i) for i in range(1,6)]
        Apd['Date']=pd.Series(DateRange,dtype='datetime64[ns]')
        Apd = Apd.set_index('Date')
        return Apd
        
    
    #add a strategy to just print close value
    class TestStrategy(bt.Strategy):
        
        def log(self, txt, dt=None):
            """logging function for this strategy
                this is essentially the print function for the strategy"""
            dt = dt or self.datas[0].datetime.date(0)
            print('%s, %s' % (dt.isoformat(),txt))
                
        def __init__(self):
            self.Stock1close = self.datas[0].close
            self.Stock2close = self.datas[1].close
            # To keep track of pending orders
            self.order = None
                    
        def next(self):
            self.log('Stock 1 Close, %.2f' % self.Stock1close[0])
            self.log('Stock 2 Close, %.2f' % self.Stock2close[0])
            
            
            if self.order:
                return
            
            
    
    if __name__ == '__main__':
        # Create a cerebro entity
        cerebro = bt.Cerebro()
        cerebro.addstrategy(TestStrategy)    
        Stock1Data = MakeArbitraryData() #GetStockData(Symbol[0],fromDate,toDate)
        Stock2Data = MakeArbitraryData() #GetStockData(Symbol[1],fromDate,toDate)#
        data1 = bt.feeds.PandasData(dataname=Stock1Data,
                                   # datetime='Date',
                                   nocase=True,
                                   )
        data2 = bt.feeds.PandasData(dataname=Stock2Data,
                                   # datetime='Date',
                                   nocase=True,
                                   )
        # Add the Data Feed to Cerebro
        cerebro.adddata(data1)
        cerebro.adddata(data2)
    
        # Set our desired cash start
        cerebro.broker.setcash(1000.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())
    
    #    cerebro.plot()

Log in to reply
 

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