Backtest your Trading Systems with Python — Plotting
This story is part of the Backtrader series. You can find the other stories here: Improve your Trading with Python. Also, there is a GitHub repo associated with this series, you can find it here if you want to follow the code in a clearer way: Backtrader Series.
When it comes to backtesting, plotting is a very important feature. Indeed, it’s important to have a visual representation of what’s happening with your strategy.
Today, I’ll explain how you can customize the charts Backtrader can generate for you.
How to Plot
I’ve already talked about it, but a quick reminder for you if you’ve forgotten.
To plot, you need first to backtest a strategy through cerebro.run() . And then you just have to call cerebro.plot() with the same Cerebro object.
cerebro.run() cerebro.plot()
It will then display a beautiful chart!

Observers
Observers are Backtrader objects used especially for plotting. When you call cerebro.plot() , by default, there are 3 Observers: BuySell, Trade, and CashValue.
You can see them in the picture above, at the top of the picture.
If you want to disable them, you have to pass in stdstats=False when you call cerebro.run()
cerebro.run(stdstats=False)
cerebro.plot()
As you can see, there are not here anymore. There’s still something at the bottom of the chart, but I’ll talk about this later.
You can add Observers to a Cerebro using cerebro.addobserver(observer) .
By default, Backtrader provides some Cerebros, such as the 3 mentioned above, but also others like TimeReturn , LogReturns , Benchmark , etc… (full reference here).
Let’s add the TimeReturn observer to our chart:
cerebro.addobserver(bt.observers.TimeReturn) crebro.run() cerebro.plot()

Here it is, at the top of the chart.
It’s also possible to develop custom observers, but I’ll talk about it after explaining plotlines .
Plotinfo/Plotlines
When developing Observers and Indicators, you can use attributes to specify what to plot, and how it should be plotted.
Let’s take an example to explain. We’ll develop an indicator representing the price, but with a delay. In the chart, it should look like this:

As you can see, it’s just the price, but with a delay.
Here is the code for the indicator:











