使用Matplotlib绘制股票日内K线图

19

我在使用Matplotlib进行金融图表绘制时遇到了一些困难。似乎他们的蜡烛图最适合每日数据,而我很难让它们处理盘中数据(每5分钟,从上午9:30到下午4点之间的数据)。

我已经将样本数据粘贴在了pastebin中。顶部是我从数据库得到的数据,底部是加工过日期格式的数据,为Matplotlib使用的浮点序数提供了元组。

样本数据链接

当我绘制图表时,会出现巨大的空白,坐标轴糟糕,缩放也非常糟糕。 http://imgur.com/y7O8A

输入图片描述

如何制作一个漂亮易读的图形呢?我的最终目标是获得一个看起来像这样的图表:

输入图片描述

http://i.imgur.com/EnrTW.jpg

数据点可以是每5分钟到30分钟的各种增量。


我还制作了一个Pandas数据帧,但我不确定Pandas是否具有蜡烛图功能。


1
从您提供的数据来看,似乎您的数据已经每天从上午9:30到下午4:00之间每隔30分钟采集一次。数据间隙可能仅反映了未采集数据的日期中下午4:00到第二天上午9:30之间的时间差。顺便说一句,使用pandas库,您可以直接处理和分析原始数据并绘制它们。 - gcalmettes
Pandas似乎无法绘制ohlc /蜡烛图数据... - NoviceCoding
1
该 pastebin 链接已不再可用。 - alexandroid
相关(元数据):*如何解决一个相当具体的问题有很多重复?* - Peter Mortensen
1
请问您能否再次更新Pastebin数据? - DNB5brims
2个回答

49

如果我理解正确,你最担心的问题之一就是每日数据之间的间隔。 为了消除这些间隔,一种方法是人为地“平均分配”你的数据(但当然会失去任何日内时间指示)。

无论如何,以这种方式进行操作,你将能够获得类似于你提出的示例图表的图表。

以下是有注释的代码和结果图表。

import numpy as np
import matplotlib.pyplot as plt
import datetime

from matplotlib.finance import candlestick
from matplotlib.dates import num2date

# data in a text file, 5 columns: time, opening, close, high, low
# note that I'm using the time you formated into an ordinal float
data = np.loadtxt('finance-data.txt', delimiter=',')

# determine number of days and create a list of those days
ndays = np.unique(np.trunc(data[:,0]), return_index=True)
xdays =  []
for n in np.arange(len(ndays[0])):
    xdays.append(datetime.date.isoformat(num2date(data[ndays[1],0][n])))

# creation of new data by replacing the time array with equally spaced values.
# this will allow to remove the gap between the days, when plotting the data
data2 = np.hstack([np.arange(data[:,0].size)[:, np.newaxis], data[:,1:]])

# plot the data
fig = plt.figure(figsize=(10, 5))
ax = fig.add_axes([0.1, 0.2, 0.85, 0.7])
    # customization of the axis
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.tick_params(axis='both', direction='out', width=2, length=8,
               labelsize=12, pad=8)
ax.spines['left'].set_linewidth(2)
ax.spines['bottom'].set_linewidth(2)
    # set the ticks of the x axis only when starting a new day
ax.set_xticks(data2[ndays[1],0])
ax.set_xticklabels(xdays, rotation=45, horizontalalignment='right')

ax.set_ylabel('Quote ($)', size=20)
ax.set_ylim([177, 196])

candlestick(ax, data2, width=0.5, colorup='g', colordown='r')

plt.show()

graph


1
非常感谢您,先生。我上周没能参与编程,否则我早就给您颁发奖励了。再次感谢。 - NoviceCoding


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接