pythonbacktrader

Backtrader not plotting


I am trying to get a plot to show with some test code in VSC.

I have version 3.2.2 of Matplotlib installed, as that is stated in Backtrader's documentation to be the compatible version. I am running Python 3.10.13 in a custom environment.

Here are my matplotlib installations. Matplotlib_inline is still showing in the conda-forge channel, even though I reinstalled it via pip. I am trying to keep packages installed in the same fashion, but some of my packages were installed with pip versus conda. I have all of the imported packages from my actual code below installed. I don't know if this is a dependency/comptaibility issue, but I suspect that.

# Name                    Version                   Build  Channel
matplotlib                3.2.2                    pypi_0    pypi
matplotlib-inline         0.1.7              pyhd8ed1ab_0    conda-forge

I don't think there are any issues with my code -- no errors appear. The output under my last cell after trying to plot is [[<Figure size 640x480 with 4 Axes>]].

My code:

%matplotlib inline

import matplotlib
import matplotlib_inline
import matplotlib.pyplot as plt  # For plotting with matplotlib
import backtrader as bt
import backtrader.plot as btplt
import datetime
import yfinance as yf

import backtrader.plot as btplt

df = yf.download('AAPL', start='2010-01-01', end='2024-01-01')

feed = bt.feeds.PandasData(dataname=df)

cerebro = bt.Cerebro()

cerebro.adddata(feed)

cerebro.run()

matplotlib.pyplot.switch_backend('module://ipykernel.pylab.backend_inline')
cerebro.plot()

No plot shows in the final cell, just [[<Figure size 640x480 with 4 Axes>]]

I tried uninstalling and reinstall all associated packages. I even tried an older version of matplotlib. I was hoping this would fix the no-plot issue. Still, no plot shows.


Solution

  • Try this approach to display the plot in both VSC and Colab. Save the plot as an image and display it using IPython.display.Image:

    from IPython.display import Image
    
    # Set the path to save the image
    img_path = "backtrader_plot.png"
    
    # Generate the plot and save it
    fig = cerebro.plot(style="candlestick")[0][0]
    fig.savefig(img_path)
    
    # Display the saved image
    Image(filename=img_path)
    

    backtrader_plot