在 Python 中绘制烛台

Plotting Candle Stick in Python

我正在尝试在 python 中绘制蜡烛图。这是我的代码

from pandas_datareader import data as pdr
import plotly.plotly as py
import plotly.graph_objs as go
import fix_yahoo_finance as yf

yf.pdr_override()
mcd = pdr.get_data_yahoo("MCD", start="2004-01-01", end="2005-07-31")
mcd_candle = go.Candlestick(x=mcd.index,open=mcd.Open,high=mcd.High,low=mcd.Low,close=mcd.Close)
data = [mcd_candle]
py.iplot(data, filename='Candle Stick')

这是我遇到的错误

PlotlyError: Because you didn't supply a 'file_id' in the call, we're assuming you're trying to snag a figure from a url. You supplied the url, '', we expected it to start with 'https://plot.ly'.

知道如何绘制蜡烛图吗?

问题一定是因为您没有提供 usernameapi key,您将从 https://plot.ly/settings/api link 中获得。如果要使用 plotly online 创建此图。首先创建一个帐户,然后获取 usernameapi key 并将其插入下面的代码中。

from pandas_datareader import data as pdr
import plotly.plotly as py
import plotly.graph_objs as go
import fix_yahoo_finance as yf
py.sign_in('<<username here>>', '<<api key here>>')
yf.pdr_override()
mcd = pdr.get_data_yahoo("MCD", start="2004-01-01", end="2005-07-31")
mcd_candle = go.Candlestick(x=mcd.index,open=mcd.Open,high=mcd.High,low=mcd.Low,close=mcd.Close)
data = [mcd_candle]
py.iplot(data, filename='Candle Stick')

还有一个使用plotly offline的选项,它不需要所有这些过程,请在下面找到实现代码。

from pandas_datareader import data as pdr
import plotly.offline as py_offline
import plotly.graph_objs as go
import fix_yahoo_finance as yf
py_offline.init_notebook_mode()

yf.pdr_override()
mcd = pdr.get_data_yahoo("MCD", start="2004-01-01", end="2005-07-31")
mcd_candle = go.Candlestick(x=mcd.index,open=mcd.Open,high=mcd.High,low=mcd.Low,close=mcd.Close)
data = [mcd_candle]
py_offline.iplot(data, filename='Candle Stick')
#for Spyder plotting use the below line instead
#py_offline.plot(data, filename='Candle Stick')

如果这些库尚不存在,请确保使用 pip 安装库 pandas_datareaderfix_yahoo_finance