Navigation

    Backtrader Community

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

    output results to json file

    General Code/Help
    2
    4
    198
    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.
    • B
      bkak last edited by

      Is it possible to somehow output all results from backtrader into a json file or similar such that i can visualize it in my own program?

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

        @bkak Yes. The analyzer results are included in the strategy object that is returned at the end of the backest. You can take those results and manipulate them as you see fit.

        Here's an example of obtaining the results of the cash_market analyzer.

        results = cerebro.run() 
        print(results[0].analyzers.getbyname("cash_market").get_analysis())
        

        Here's the whole code converting the dictionary to json.

        import backtrader as bt
        import json
        
        class CashMarket(bt.analyzers.Analyzer):
            """
            Analyzer returning cash and market values
            """
        
            def create_analysis(self):
                self.rets = {}
                self.vals = 0.0
        
            def notify_cashvalue(self, cash, value):
                self.vals = (self.strategy.datetime.datetime().strftime("%Y-%m-%d"), cash,
                             value)
                self.rets[len(self)] = self.vals
        
            def get_analysis(self):
                return self.rets
        
        class Strategy(bt.Strategy):
        
            def __init__(self):
                self.rsi = bt.ind.RSI(period=14)
        
            def next(self):
                if not self.position:
                    if self.rsi <= 35:
                        self.buy()
                elif self.rsi >= 65:
                    self.close()
        
        
        if __name__ == "__main__":
        
            cerebro = bt.Cerebro()
        
            data = bt.feeds.GenericCSVData(
                dataname="data/2006-day-001.txt",
                dtformat=("%Y-%m-%d"),
                timeframe=bt.TimeFrame.Days,
                compression=1,
            )
            cerebro.adddata(data)
        
            cerebro.addstrategy(Strategy)
        
            cerebro.addanalyzer(CashMarket, _name = "cash_market")
        
            # Execute
            results = cerebro.run()
        
            # Dictionary
            dictionary = results[0].analyzers.getbyname("cash_market").get_analysis()
            json_object = json.dumps(dictionary, indent=4)
            print(json_object)
        
        

        RunBacktest.com

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

          @run-out said in output results to json file:

          import backtrader as bt
          import json

          class CashMarket(bt.analyzers.Analyzer):
          """
          Analyzer returning cash and market values
          """

          def create_analysis(self):
              self.rets = {}
              self.vals = 0.0
          
          def notify_cashvalue(self, cash, value):
              self.vals = (self.strategy.datetime.datetime().strftime("%Y-%m-%d"), cash,
                           value)
              self.rets[len(self)] = self.vals
          
          def get_analysis(self):
              return self.rets
          

          class Strategy(bt.Strategy):

          def __init__(self):
              self.rsi = bt.ind.RSI(period=14)
          
          def next(self):
              if not self.position:
                  if self.rsi <= 35:
                      self.buy()
              elif self.rsi >= 65:
                  self.close()
          

          if name == "main":

          cerebro = bt.Cerebro()
          
          data = bt.feeds.GenericCSVData(
              dataname="data/2006-day-001.txt",
              dtformat=("%Y-%m-%d"),
              timeframe=bt.TimeFrame.Days,
              compression=1,
          )
          cerebro.adddata(data)
          
          cerebro.addstrategy(Strategy)
          
          cerebro.addanalyzer(CashMarket, _name = "cash_market")
          
          # Execute
          results = cerebro.run()
          
          # Dictionary
          dictionary = results[0].analyzers.getbyname("cash_market").get_analysis()
          json_object = json.dumps(dictionary, indent=4)
          print(json_object)
          

          Thank you for this very detailed example. However when i tried to run the code, the results list is empty. Do you have any idea why?

          B 1 Reply Last reply Reply Quote 0
          • B
            bkak @bkak last edited by

            @bkak ah sorry, my mistake :) It seems to work great!

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