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

retrieve backtraders information as a dataframe

  • Hi,

    I'm pretty new to backtrader. I've read through the manual but haven't found the answer yet to a question I have. Is there a way to retrieve everything you feed into backtrader as a dataframe.

    for example, we feed OHLC data into backtrader, we create 2 moving averages, we add a long and short signal when crossing over etc.

    Is there a way to then also get all this information in a dataframe? eg the columns would look something like:

    Date, Open, High, Low, Close, MA1, MA2, Signal


  • Using analyzers. The return of running cerebro is a strategy object.

    strat =

    'strat' in this case is a strategy object and will contain any analyzers you have built and added to the cerebro engine. The analyzer will be the data in the form of a dictionary. In your case because you desire your custom indicators along with your OHLCV, you could build a custom analyzer. Here is an example you can use for the class definition:

    class OHLCMMS(bt.analyzers.Analyzer):
        """This analyzer reports the OHLCV +lines of each of datas.
          - timeframe (default: ``None``)
            If ``None`` then the timeframe of the 1st data of the system will be
          - compression (default: ``None``)
            Only used for sub-day timeframes to for example work on an hourly
            timeframe by specifying "TimeFrame.Minutes" and 60 as compression
            If ``None`` then the compression of the 1st data of the system will be
          - get_analysis
            Returns a dictionary with returns as values and the datetime points for
            each return as keys
        def start(self):
            tf = min(d._timeframe for d in self.datas)
            self._usedate = tf >= bt.TimeFrame.Days
            self.rets = {}
        def next(self):
            self.rets[] = [
        def get_analysis(self):
            return self.rets

    To add this to cerebro:

    cerebro.addanalyzer(OHLCMMS, _name="OHLCMMS")

    After you run the backtest you can extract your information from 'strat' as follows:


    Which you can then turn into a dataframe as:

    df = pd.DataFrame.from_dict(
            columns=["open", "high", "low", "close", "MA1", "MA2", "signal"],

  • @run-out thanks a lot, really appreciated! hadn't read that far yet so should have just read the full guide first.

Log in to reply