Matplotlib Candlestick graph looks weird

◇◆丶佛笑我妖孽 提交于 2019-12-12 04:09:36

问题


I was trying to plot a candlestick graph using stock data extracted from quandl. However, the graph looks eerie, only a few bars showed up. I have no idea what is going on. Any help is greatly appreciated.

Here is the code:

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:


There are two major issue here.

  • The dates should be numeric values corresponding to the dates in question.

    date_val=matplotlib.dates.date2num(df.index.to_pydatetime()) 
    
  • The second argument of candlestick_ohlc needs to be a sequence of sequences, i.e. each datum needs to be in it individually as (time, open, high, low, close, ...).

A possible solution:

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()

Or, more 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()



来源:https://stackoverflow.com/questions/46379780/matplotlib-candlestick-graph-looks-weird

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!