[英]How I display the graph that return by backtrader in streamlit?
我嘗試使用 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)
然后我運行它並嘗試 plot 它並以流光顯示
cerebro=bt.Cerebro()
cerebro.addstrategy(CrossOver)
cerebro.adddata(data)
cerebro.run()
pl=cerebro.plot()
st.pyplot(pl)
但我無法在流光中看到圖表。 有誰知道如何在 streamlit 中顯示反向交易者的圖表? 提前致謝。
我對反向交易者不太熟悉,所以我從他們的文檔中舉了一個例子,說明如何創建 plot。 plot 中使用的數據可以從他們的github 存儲庫下載。
該解決方案包含以下步驟:
確保我們使用的 matplotlib 后端不會向用戶顯示繪圖,因為我們希望在 Streamlit 應用程序中顯示它,並且 backtrader 的 plot() function 顯示 Z32FA6E1B78A96D40289Z53E6A60 這可以使用:
matplotlib.use('Agg')
從 backtrader 的 plot() function 中獲取 matplotlib 圖。 這可以使用:
figure = cerebro.plot()[0][0]
以流光顯示 plot。 這可以使用:
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)
Output:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.