2017-09-23 235 views
0

我試圖用quandl提取的股票數據繪製燭臺圖。但是,這張圖看起來很可怕,只有幾個小節出現。我不知道發生了什麼事。任何幫助是極大的讚賞。Matplotlib燭臺圖看起來很奇怪

下面是代碼:

start=dt.datetime(2000,1,1) 
end=dt.datetime(2017,9,20) 
df=quandl.get('WIKI/TWTR',start_date=start,end_date=end) 
date_val=[x for x in range(len(df.index))] 
open_val=np.array(df['Adj. Open'],dtype=np.float64) 
high_val=np.array(df['Adj. High'],dtype=np.float64) 
low_val=np.array(df['Adj. Low'],dtype=np.float64) 
close_val=np.array(df['Adj. Close'],dtype=np.float64) 
ohlc_data=[date_val,open_val,high_val,low_val,close_val] 
ax1=plt.subplot(111) 
candlestick_ohlc(ax1,ohlc_data,width=0.9,colorup='g',colordown='r',alpha=0.8) 
plt.show() 

這是圖表:
This is the graph

回答

1

這裏有兩個主要問題。

  • 日期應該是與相關日期對應的數值。

    date_val=matplotlib.dates.date2num(df.index.to_pydatetime()) 
    
  • candlestick_ohlc的第二個參數需要是序列的序列,即每個數據需要在它單獨地(time, open, high, low, close, ...)

一個可能的解決方案:

import matplotlib.pyplot as plt 
import matplotlib.dates 
from matplotlib.finance import candlestick_ohlc 
import datetime as dt 
import quandl 

start=dt.datetime(2000,1,1) 
end=dt.datetime(2017,9,20) 
df=quandl.get('WIKI/TWTR',start_date=start,end_date=end) 

#convert dates to datetime, then to float 
date_val=matplotlib.dates.date2num(df.index.to_pydatetime()) 

open_val=df['Adj. Open'].values 
high_val=df['Adj. High'].values 
low_val=df['Adj. Low'].values 
close_val=df['Adj. Close'].values 
# ohlc_data needs to be a sequence of sequences 
ohlc_data=zip(*[date_val,open_val,high_val,low_val,close_val]) 

ax1=plt.subplot(111) 
candlestick_ohlc(ax1,ohlc_data,colorup='g',colordown='r',alpha=0.8) 

# Format x axis for dates 
ax1.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%Y-%m-%d')) 
ax1.figure.autofmt_xdate() 
plt.show() 

或者,更consise:

import matplotlib.pyplot as plt 
import matplotlib.dates 
from matplotlib.finance import candlestick_ohlc 
import datetime as dt 
import quandl 

start=dt.datetime(2000,1,1) 
end=dt.datetime(2017,9,20) 
df=quandl.get('WIKI/TWTR',start_date=start,end_date=end) 

#convert dates to datetime, then to float 
df["Date"]=matplotlib.dates.date2num(df.index.to_pydatetime()) 
ohlc_data= df[["Date",'Adj. Open','Adj. High','Adj. Low','Adj. Close']].values 

ax1=plt.subplot(111) 
candlestick_ohlc(ax1,ohlc_data,colorup='g',colordown='r',alpha=0.8) 

# Format x axis for dates 
ax1.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%Y-%m-%d')) 
ax1.figure.autofmt_xdate() 
plt.show() 

enter image description here

+0

這是非常有用的。非常感謝! –