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/

    How can I get observers records for custom plotting?

    General Code/Help
    2
    5
    143
    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.
    • asdasda
      asdasda last edited by

      The built-in plotting style not good for me, I want to draw with plotly. But how can I export the trade record, cash/value record, etc..?

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

        @asdasda I use plotly. You can export your analyzers (not observers) at the end of your backtest. When you call:

        cerebro.run()
        

        cerebro returns a list of strategy objects at the end of the backtest. Usually you run one backtest a time so there's only one strategy object in the list, but some people run multiple strategies at once.

        In the strategy object are all the analyzers, amongst other things.

        The analyzers are contained in a list so that if you go:

        strat = cerebro.run()
        # analyzers are found in a list here. 
        strat[0].analyzers  # you find all the analyzers here.
        

        There's a handy method to get the results of your analyzer.

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

        Analyzers have different outputs so it's really up to you to move this data to a csv/excel/db file.

        Here is an example of an analyzer being converted for a database and for going to an excel sheet.

        Here's an example of an analyzer and the code I use after to convert it to db and excel.

        # ANALYZER: 
        class CashMarket(bt.analyzers.Analyzer):
            """
            Analyzer returning cash and market values
            """
        
            def __init__(self):
                self.current_date = None
        
            def start(self):
                super(CashMarket, self).start()
        
            def create_analysis(self):
                self.rets = {}
                self.vals = 0.0
        
            def notify_cashvalue(self, cash, value):
                date = self.data.datetime.date()
                if date != self.current_date:
                    self.vals = (cash, value)
                    self.rets[self.strategy.datetime.datetime()] = self.vals
                    self.current_date = date
                else:
                    pass
        
            def get_analysis(self):
                return self.rets
        # CONVERTING RESULTS
        
        def cashmarket(
            scene, analyzer, test_number, workbook=None, sheet_format=None, agg_dict=None
        ):
            """
            Portfolio cash and total values.
        
            :param workbook: Excel workbook to be saved to disk.
            :param analyzer: Backtest analyzer.
            :param sheet_format: Dictionary holding formatting information such as col width, font etc.
            :param agg_dict: Collects the dictionary outputs from backtrader for using in platting.
            :return workbook: Excel workbook to be saved to disk.
            """
            # Get the stats auto ordered nested dictionary
            value = analyzer.get_analysis()
        
            columns = [
                "Date",
                "Cash",
                "Value",
            ]
        
            if scene["save_db"]:
                df = pd.DataFrame(value)
                df = df.T
                df = df.reset_index()
                df.columns = columns
                df = add_key_to_df(df, test_number)
                agg_dict["value"] = df
        
            if scene["save_excel"]:
        
                worksheet = workbook.add_worksheet("value")
        
                worksheet.write_row(0, 0, columns)
        
                worksheet.set_row(0, None, sheet_format["header_format"])
        
                worksheet.set_column("A:C", sheet_format["wide"], sheet_format["float_2d"])
        
                for i, (k, v) in enumerate(value.items()):
                    date = k.strftime("%y-%m-%d %H:%M")
                    worksheet.write_row(i + 1, 0, [date])
                    worksheet.write_row(i + 1, 1, v)
        
            return workbook, agg_dict

        RunBacktest.com

        asdasda 2 Replies Last reply Reply Quote 0
        • asdasda
          asdasda @run-out last edited by

          @run-out It looks good, thank you.

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

            @run-out But why my analyzers are empty? I had run strategies = cerebro.run().

            18ea4f17-b3d0-408c-aabe-b4fabc4a7cd8-image.png

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

              @asdasda Read up on how to create and add analyzers to backtrader. You should find you answer there.

              RunBacktest.com

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