Here is a similar example in Python based on the sample MACDTrendAlgorithm. The original script produces two additional graphs to plot indicators with:
self.PlotIndicator("MACD", True, self.__macd, self.__macd.Signal)
self.PlotIndicator("SPY", self.__macd.Fast, self.__macd.Slow)
The QCAlgorithm's PlotIndicator method is great to plot an indicator quickly, but of course it won't allow you to do the overlay.
To create a plot which shows the SPY price with buy/sell signals at the top, along with the MACD indicator at the bottom, I added the following in the Initialize method:
overlayPlot = Chart("Overlay Plot")
overlayPlot.AddSeries(Series("SPY", SeriesType.Line, 0))
overlayPlot.AddSeries(Series("Buy", SeriesType.Scatter, 0))
overlayPlot.AddSeries(Series("Sell", SeriesType.Scatter, 0))
overlayPlot.AddSeries(Series("MACD", SeriesType.Line, 1))
overlayPlot.AddSeries(Series("MACD_Signal", SeriesType.Line, 1))
self.AddChart(overlayPlot)
The first line creates a new custom chart. Each AddSeries call specifies the name of a series (we use this to add points later), its type, and finally the index in the chart (index=0 series will be plotted in the top subplot and index=1 series in the bottom subplot). Finally, calling AddChart on the QCAlgorithm adds it to the backtesting output.
In the OnData method, I added:
if buy_signal_triggered:
self.Plot("Overlay Plot", "Buy", data["SPY"].Value)
elif sell_signal_triggered:
self.Plot("Overlay Plot", "Sell", data["SPY"].Value)
self.Plot("Overlay Plot", "SPY", data["SPY"].Value)
self.Plot("Overlay Plot", "MACD", self.__macd.Current.Value)
self.Plot("Overlay Plot", "MACD_Signal", self.__macd.Signal.Current.Value)
which adds a point to each series on every bar. buy_signal_triggered and sell_signal_triggered are just for having all the plotting in the same place.
Enjoy!
(Note the preview below will show the Overlay Plot compressed)