消除绘制的Python Matplotlib烛台数据之间的差距

时间:2015-08-20 11:57:36

标签: python matplotlib

我希望能够在我的图表上绘制股票数据,而不会出现数据缺失的空白。

This answer有办法这样做:

# the dates in my example file-set are very sparse (and annoying) change the dates to be sequential
for i in range(len(r)-1):
    r['date'][i+1] = r['date'][i] + datetime.timedelta(days=1)

我不明白它是如何或为什么有效但试图在我的代码中实现它:

for i in range(len(date)-1):
    date[i+1] = date[i] + dt.timedelta(days=1)

Here's my chart

以下是我的图表的代码:

fig = plt.figure()
fig.set_size_inches(13.5, 8.5)
ax1 = plt.subplot2grid((6,1), (0,0), rowspan=4, colspan=1)
ax1.yaxis.tick_right()
ax1.xaxis.set_ticks_position('bottom')
plt.title('title')
# Add a seconds axis for the volume overlay
ax2 = plt.subplot2grid((6,1), (4,0), rowspan=4, colspan=1)
ax2.xaxis.set_ticks_position('bottom')

stock_price_url = 'https://www.quandl.com/api/v3/datasets/WIKI/AAPL/data.csv?start_date=2015-06-01&order=asc&end_date=2015-08-01&collapse=daily'
source_code = urllib.urlopen(stock_price_url).read().decode()
stock_data = []
split_source = source_code.split('\n')
for line in split_source:
    split_line = line.split(',')
    if 'Date' not in line:
        stock_data.append(line)


date, openp, highp, lowp, closep, volume = np.loadtxt(stock_data,
                                                      delimiter=',',
                                                      unpack=True,
                                                      converters={0:strpdate2num('%Y-%m-%d')},
                                                      usecols=(0,1,2,3,4,5))

x = 0
y = len(date)
ohlc = []

while x < y:
    append_me = date[x], openp[x], closep[x], highp[x], lowp[x], volume[x]
    ohlc.append(append_me)
    x+=1

candlestick(ax1, ohlc, width=0.4, colorup='g', colordown='r')

# create the second axis for the volume bar-plot
ax2.yaxis.tick_right()
ax2.yaxis.get_major_formatter().set_scientific(False)

# set the position of ax2 so that it is short (y2=0.32) but otherwise the same size as ax
ax2.set_position(mpl.transforms.Bbox([[0.125,0.1],[0.9,0.32]]))

# get data from candlesticks for a bar plot
dates = [x[0] for x in ohlc]
dates = np.asarray(dates)
volume = [x[5] for x in ohlc]
volume = np.asarray(volume)

# make bar plots and color differently depending on up/down for the day
pos = openp-closep<0
neg = openp-closep>0
ax2.bar(dates[pos],volume[pos],color='green',width=1,align='center')
ax2.bar(dates[neg],volume[neg],color='red',width=1,align='center')

#scale the x-axis tight
ax1.set_xlim(min(dates),max(dates))
ax2.set_xlim(min(dates),max(dates))

# the y-ticks for the bar were too dense, keep only every third one
yticks = ax2.get_yticks()
ax2.set_yticks(yticks[::3])

# format the x-ticks with a human-readable date. 
xt = ax1.get_xticks()
new_xticks = [dt.date.isoformat(num2date(d)) for d in xt]
ax1.set_xticklabels(new_xticks,rotation=45, horizontalalignment='right')
ax2.set_xticklabels(new_xticks,rotation=45, horizontalalignment='right')

plt.show()

任何帮助都会非常棒。

0 个答案:

没有答案