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/

    Save cerebro plot to file

    General Code/Help
    5
    9
    3897
    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.
    • J
      jf last edited by

      Dear community,

      I am trying to save to cerebro output plot as a file with the following line of code:

      cerebro.plot(volume=False, savefig=True, figfilename='backtrader-plot.png')
      

      Unfortunately that doesn't work... Does anyone know how I can fix that?

      Your help would be highly appreciated!

      Thanks,
      J

      1 Reply Last reply Reply Quote 0
      • B
        Bingchen Liu last edited by

        I got the similar problem, I can't change plot size and save picture either. Thus I just rewrite the function in the cerebro.py file. This is my code, I hope this can give you some help.

        def plot(self, plotter=None, numfigs=1, iplot=True, start=None, end=None,
                 width=16, height=9, dpi=300, tight=True, use=None,path = None,
                 **kwargs):
            '''
            Plots the strategies inside cerebro
        
            If ``plotter`` is None a default ``Plot`` instance is created and
            ``kwargs`` are passed to it during instantiation.
        
            ``numfigs`` split the plot in the indicated number of charts reducing
            chart density if wished
        
            ``iplot``: if ``True`` and running in a ``notebook`` the charts will be
            displayed inline
        
            ``use``: set it to the name of the desired matplotlib backend. It will
            take precedence over ``iplot``
        
            ``start``: An index to the datetime line array of the strategy or a
            ``datetime.date``, ``datetime.datetime`` instance indicating the start
            of the plot
        
            ``end``: An index to the datetime line array of the strategy or a
            ``datetime.date``, ``datetime.datetime`` instance indicating the end
            of the plot
        
            ``width``: in inches of the saved figure
        
            ``height``: in inches of the saved figure
        
            ``dpi``: quality in dots per inches of the saved figure
        
            ``tight``: only save actual content and not the frame of the figure
            '''
            if self._exactbars > 0:
                return
        
            if not plotter:
                from . import plot
                if self.p.oldsync:
                    plotter = plot.Plot_OldSync(**kwargs)
                else:
                    plotter = plot.Plot(**kwargs)
        
            # pfillers = {self.datas[i]: self._plotfillers[i]
            # for i, x in enumerate(self._plotfillers)}
        
            # pfillers2 = {self.datas[i]: self._plotfillers2[i]
            # for i, x in enumerate(self._plotfillers2)}
            import matplotlib.pyplot as plt 
            figs = []
            for stratlist in self.runstrats:
                for si, strat in enumerate(stratlist):
                    rfig = plotter.plot(strat, figid=si * 100,
                                        numfigs=numfigs, iplot=iplot,
                                        start=start, end=end, use=use)
                    # pfillers=pfillers2)
        
                    figs.append(rfig)
                fig = plt.gcf() 
                plotter.show()
            fig.set_size_inches(width, height)
            fig.savefig(path,dpi = dpi) 
            return figs
        1 Reply Last reply Reply Quote 0
        • J
          jf last edited by

          Hi Bingchen,

          Thanks for providing your code, this excellent workaround is very helpful indeed!

          I was hoping for a more direct implementation where I could just specify the "savefig" within my code, and not messing with the original function. But it seems that this is not (yet) possible within backtrader...

          Cheers,
          JF

          1 Reply Last reply Reply Quote 0
          • B
            Bingchen Liu last edited by

            Hi JF,

            You are welcome. I'm glad that my code can give you some ideas. You can see from the code in the source file cerebro.py that although multiple input variables are given for plot function, some of them are not used in the plot function at all ==|||. Thus I guess that the plot function only give you some basic frames on these functions and you have to define by yourself if you want some specific ideas. For more about the plot, you can see doc for matplotlib.pyplot.

            Cheers,
            Bingchen

            1 Reply Last reply Reply Quote 0
            • J
              jf last edited by

              Ok great, thanks! On my search I also came across this website, where the author shows how he creates nice backtrader performance reports in PDF format. It is not exactly what I was looking for, but helped me a lot on the way. You can find the code / template files on github.

              Best,
              Jascha

              T 1 Reply Last reply Reply Quote 1
              • B
                Bingchen Liu last edited by

                I'm glad my reply can help and thank you for your sharing !

                Best,
                Bingchen

                1 Reply Last reply Reply Quote 0
                • T
                  tw00000 @jf last edited by

                  @jf said in Save cerebro plot to file:

                  Ok great, thanks! On my search I also came across this website, where the author shows how he creates nice backtrader performance reports in PDF format. It is not exactly what I was looking for, but helped me a lot on the way. You can find the code / template files on github.

                  Best,
                  Jascha

                  very cool! thanks!

                  1 Reply Last reply Reply Quote 0
                  • marticols
                    marticols last edited by

                    I don't know the reason savefig have been removed at https://github.com/backtrader/backtrader/commit/f6e7c6dfb4151c7d5d554e2bce5a2ced8daa85c5 commit.

                    For saving the figure i just do this:

                    figure = cerebro.plot(style ='candlebars')[0][0]
                    figure.savefig('example.png')

                    Shivanshu Bohara 1 Reply Last reply Reply Quote 4
                    • Shivanshu Bohara
                      Shivanshu Bohara @marticols last edited by

                      @marticols I'm getting this error while trying to save the plot by the method mentioned by you:
                      can't invoke "wm" command: application has been destroyed

                      Can you provide any help?

                      1 Reply Last reply Reply Quote 0
                      • 1 / 1
                      • First post
                        Last post
                      Copyright © 2016, 2017, 2018 NodeBB Forums | Contributors
                      $(document).ready(function () { app.coldLoad(); }); }