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

How to get data out of

  • 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

  • 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,
    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 = [,3,i) for i in range(1,6)]
        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]
            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:
    if __name__ == '__main__':
        # Create a cerebro entity
        cerebro = bt.Cerebro()
        Stock1Data = MakeArbitraryData() #GetStockData(Symbol[0],fromDate,toDate)
        Stock2Data = MakeArbitraryData() #GetStockData(Symbol[1],fromDate,toDate)#
        data1 = bt.feeds.PandasData(dataname=Stock1Data,
                                   # datetime='Date',
        data2 = bt.feeds.PandasData(dataname=Stock2Data,
                                   # datetime='Date',
        # Add the Data Feed to Cerebro
        # Set our desired cash start
        # Print out the starting conditions
        print('Starting Portfolio Value: %.2f' %
        # Run over everything
        # Print out the final result
        print('Final Portfolio Value: %.2f' %
    #    cerebro.plot()

Log in to reply