Matplotlib Candlestick graph looks weird

2019-09-16 04:21发布

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:
This is the graph

1条回答
成全新的幸福
2楼-- · 2019-09-16 04:39

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

enter image description here

查看更多
登录 后发表回答