Matplotlib error on plotting graph on streamlit cloud showing self.session.kernel error

I have used streamlit cloud to try and host my web app but the plotting always gives an error while it works on my local machine.

import streamlit as st
import backtrader as bt
import yfinance as yf
def backtestrsi():
    global strategy
    ticker=st.sidebar.text_input("Stock ticker", value="AAPL")
    start=st.sidebar.text_input("Start date", value="2018-01-31")
    end=st.sidebar.text_input("End date", value=today)
    cash=st.sidebar.text_input("Starting cash", value=10000)
    cash=int(cash)
    cerebro=bt.Cerebro()
    cerebro.broker.set_cash(cash)
    start_value=cash
    data = bt.feeds.PandasData(dataname=yf.download(ticker, start, end))
    start=start.split("-")
    end=end.split("-")
    for i in range(len(start)):
        start[i]=int(start[i])
    for j in range(len(end)):
        end[j]=int(end[j])
    year=end[0]-start[0]
    month=end[1]-start[1]
    day=end[2]-start[2]
    totalyear=year+(month/12)+(day/365)
    matplotlib.use('Agg')
    cerebro.adddata(data)

    cerebro.addstrategy(RSIStrategy)

    print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())

    cerebro.run()

    print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
    
    final_value=cerebro.broker.getvalue()
    returns=(final_value-start_value)*100/start_value
    annual_return=returns/totalyear
    returns=round(returns, 2)
    annual_return=round(annual_return,2)
    returns=str(returns)
    annual_return=str(annual_return)
    figure = cerebro.plot()[0][0]
    st.pyplot(figure)
    st.write('')
    st.subheader(f"{ticker}'s total returns are {returns}% with a {annual_return}% APY")
Error: File "/home/appuser/venv/lib/python3.8/site-packages/streamlit/scriptrunner/script_runner.py", line 475, in _run_script
    exec(code, module.__dict__)
File "/app/trial/trial.py", line 578, in <module>
    backtestrsi()
File "/app/trial/trial.py", line 133, in backtestrsi
    figure = cerebro.plot()[0][0]
File "/home/appuser/venv/lib/python3.8/site-packages/backtrader/cerebro.py", line 989, in plot
    rfig = plotter.plot(strat, figid=si * 100,
File "/home/appuser/venv/lib/python3.8/site-packages/backtrader/plot/plot.py", line 127, in plot
    matplotlib.use('nbagg')
File "/home/appuser/venv/lib/python3.8/site-packages/matplotlib/cbook/deprecation.py", line 296, in wrapper
    return func(*args, **kwargs)
File "/home/appuser/venv/lib/python3.8/site-packages/matplotlib/cbook/deprecation.py", line 358, in wrapper
    return func(*args, **kwargs)
File "/home/appuser/venv/lib/python3.8/site-packages/matplotlib/__init__.py", line 1281, in use
    plt.switch_backend(name)
File "/home/appuser/venv/lib/python3.8/site-packages/matplotlib/pyplot.py", line 195, in switch_backend
    close("all")
File "/home/appuser/venv/lib/python3.8/site-packages/matplotlib/pyplot.py", line 681, in close
    _pylab_helpers.Gcf.destroy_all()
File "/home/appuser/venv/lib/python3.8/site-packages/matplotlib/_pylab_helpers.py", line 72, in destroy_all
    manager.destroy()
File "/home/appuser/venv/lib/python3.8/site-packages/matplotlib/backends/backend_nbagg.py", line 126, in destroy
    self._send_event('close')
File "/home/appuser/venv/lib/python3.8/site-packages/matplotlib/backends/backend_webagg_core.py", line 490, in _send_event
    s.send_json(payload)
File "/home/appuser/venv/lib/python3.8/site-packages/matplotlib/backends/backend_nbagg.py", line 199, in send_json
    self.comm.send({'data': json.dumps(content)})
File "/home/appuser/venv/lib/python3.8/site-packages/ipykernel/comm/comm.py", line 137, in send
    self._publish_msg(
File "/home/appuser/venv/lib/python3.8/site-packages/ipykernel/comm/comm.py", line 71, in _publish_msg
    self.kernel.session.send(

Hi @Utkarsh_Gupta, welcome to the Streamlit community!

It appears that one of the packages you are using is trying to call out to IPython, which I’m not sure how it would work in the context of Streamlit Cloud. Unfortunately, I don’t have any experience with cerebro (I expect that’s the package giving you difficulty).

Best,
Randy

Thank you @randyzwitch for your reply sir, the error seems to showing in for a normal matplotlib plotting as well so it isn’t specific to cerebro. Furthermore, the same code runs perfectly on my local host server but gives me an error on streamlit cloud. Please assist