Backtrader Community

    • 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/

    retrieve backtraders information as a dataframe

    General Discussion
    4
    4
    1246
    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.
    • Jens Halsberghe
      Jens Halsberghe last edited by

      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

      thanks

      1 Reply Last reply Reply Quote 1
      • run-out
        run-out last edited by

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

        strat = cerebro.run()
        

        '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.
            Params:
              - timeframe (default: ``None``)
                If ``None`` then the timeframe of the 1st data of the system will be
                used
              - 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
                used
            Methods:
              - 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[self.data.datetime.datetime()] = [
                    self.datas[0].open[0],
                    self.datas[0].high[0],
                    self.datas[0].low[0],
                    self.datas[0].close[0],
                    self.MA1[0],
                    self.MA2[0],
                    self.signal[0],
                ]
        
            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:

        strat[0].analyzers.getbyname("OHLCMMS").get_analysis()
        

        Which you can then turn into a dataframe as:

        df = pd.DataFrame.from_dict(
                strat[0].analyzers.getbyname("OHLCMMS").get_analysis(),
                orient="index",
                columns=["open", "high", "low", "close", "MA1", "MA2", "signal"],
            )
        

        RunBacktest.com

        Jens Halsberghe Bard Tim 2 Replies Last reply Reply Quote 2
        • Jens Halsberghe
          Jens Halsberghe @run-out last edited by

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

          1 Reply Last reply Reply Quote 1
          • Bard Tim
            Bard Tim @run-out last edited by

            @run-out that is smart,thanks

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