pythonstockstreamlitbacktrader

How I display the graph that return by backtrader in streamlit?


I try to do back testing on stock data using backtrading library in python. and I use this simple strategy

class CrossOver(bt.SignalStrategy):
    def __init__(self):
        sma=bt.ind.SMA(period=50)
        price=self.data
        crossover=bt.ind.CrossOver(price,sma)
        self.signal_add(bt.SIGNAL_LONG,crossover)

Then I run it and try to plot it and display in streamlit

cerebro=bt.Cerebro()
cerebro.addstrategy(CrossOver)
cerebro.adddata(data)
cerebro.run()
pl=cerebro.plot()
st.pyplot(pl)

But I am not able to see the graph in streamlit. does anyone know how to display backtrader's graph in streamlit? thanks in advance.


Solution

  • I'm not that familiar with backtrader so i took an example from their documentation on how to create a plot. The data used in the plot can be downloaded from their github repository.

    The solution contains the following steps:

    1. make sure we use a matplotlib backend that doesn't display the plots to the user because we want to display it in the Streamlit app and the plot() function of backtrader displays the plot. this can be done using:

       matplotlib.use('Agg')
      
    2. get the matplotlib figure from the plot() function of backtrader. this can be done using:

       figure = cerebro.plot()[0][0]
      
    3. display the plot in streamlit. this can be done using:

       st.pyplot(figure)
      

    All together:

    import streamlit as st
    import backtrader as bt
    import matplotlib
    
    # Use a backend that doesn't display the plot to the user
    # we want only to display inside the Streamlit page
    matplotlib.use('Agg')
    
    # --- Code from the backtrader plot example
    # data can be found in there github repo 
    class St(bt.Strategy):
        def __init__(self):
            self.sma = bt.indicators.SimpleMovingAverage(self.data)
    data = bt.feeds.BacktraderCSVData(dataname='2005-2006-day-001.txt')
    cerebro = bt.Cerebro()
    cerebro.adddata(data)
    cerebro.addstrategy(St)
    cerebro.run()
    figure = cerebro.plot()[0][0]
    
    # show the plot in Streamlit
    st.pyplot(figure)
    

    Output:

    enter image description here