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

Save out indicator values into a dataframe

  • Hi all,

    I am new to this powerful tool and trying to get myself familiar with its use. I developed a self-defined indicator in cerebro and I would like to have it saved into a new dataframe. Also I would like to ask how to adjust the height of the indicator subplot for it ? Is there a way to achieve that? Thanks!


  • Hi Will,
    I am not sure exactly what you want but if you are looking to play around with plotting, you can see some of the options here:

    Note that Backtrader uses matplotlib for plotting so you should find the plotting quite flexible.

    Can you elaborate a bit more on what you mean when you say that you would like to save it to a new dataframe?

  • Thanks for the answer!

    As for the indicator, I mean I develop a self-defined indicator in the cerebro engine. It can be plotted properly in the final graph. But I would like to look deeper into the indicator values during the backtest process.

    As for now, I can only inspect them from plot and not sure on whether they are precisely calculated. Besides, the subplot for the indicator is quite narrow to see them clearly. The first idea came to me is to output the indicator values during the test period along with price data into a dataframe to inspect them. Is there a way to do it?

    Hope I can find help here! Thanks!

  • Will, I would like to know if you got further on this subject.
    I would also be interested in outputting indicators into a DataFrame.

  • administrators

    Indicators can be written out automatically (to the destination of your choice) with a Writer. See

    And to automatically add a writer to cerebro which writes to standard output. See

    • Docs - Cerebro

      Use cerebro = Cerebro(writer=True) or

    Indicators are by default not added to the output of writers, you need to enable it. For example

    def __init__(self):
        mysma = bt.indicators.SMA(period=15)
        mysma.csv = True

    As for writing the values to a DataFrame, you may pass a DataFrame as a named argument to the indicator and add the values, but taking into account that appending values to a DataFrame is a very expensive operation, you may prefer to do it at once during Strategy.stop

    def stop(self):
        myvalues = self.mysma.sma.get(size=len(self.mysma))

    which you can easily put into a DataFrame

  • @backtrader Wow, thank you very much!

Log in to reply