【问题标题】:How I display the graph that return by backtrader in streamlit?如何在 streamlit 中显示 backtrader 返回的图表?
【发布时间】:2022-01-12 03:16:36
【问题描述】:

我尝试使用 python 中的回溯库对股票数据进行回测。我使用这个简单的策略

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)

然后我运行它并尝试绘制它并以流光显示

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

但我无法在流光下看到图表。有谁知道如何在 streamlit 中显示 backtrader 的图表?提前致谢。

【问题讨论】:

    标签: python stock streamlit backtrader


    【解决方案1】:

    我对反向交易者不太熟悉,所以我从他们的documentation 中举了一个关于如何创建情节的例子。图中用到的数据可以从他们的github repository下载。

    解决方案包含以下步骤:

    1. 确保我们使用不向用户显示绘图的 matplotlib 后端,因为我们想在 Streamlit 应用程序中显示它,并且 backtrader 的 plot() 函数显示绘图。这可以使用:

       matplotlib.use('Agg')
      
    2. 从 backtrader 的 plot() 函数中获取 matplotlib 图形。这可以使用:

       figure = cerebro.plot()[0][0]
      
    3. 以流光显示绘图。这可以使用:

       st.pyplot(figure)
      

    大家一起:

    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)
    

    输出:

    【讨论】:

      猜你喜欢
      • 2023-03-16
      • 2021-11-09
      • 2022-10-15
      • 2023-02-19
      • 2020-06-10
      • 2021-11-28
      • 1970-01-01
      • 2016-05-07
      • 2018-04-17
      相关资源
      最近更新 更多