2012-03-12 73 views
15

我一直在使用Matplotlib的财务图表时遇到一些困难。看起来他们的烛台图表在日常数据中效果最好,而且我很难让他们在盘中(每5分钟,9:30和4:  pm之间)数据下工作。使用Matplotlib的日内烛台图表

我已经将样本数据粘贴到了pastebin中。顶部是我从数据库中得到的东西,底部是格式化为序号浮点数的日期,用于Matplotlib。

Link to sample data

当我画我的图表,中间有巨大差距,轴吸,变焦也同样可怕。 http://imgur.com/y7O8A

Enter image description here

如何使一个不错的可读性图出这个数据的?我的最终目标是获得一个图表,看起来远程像这样:

Enter image description here

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

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


我也做了一个熊猫数据框的数据,但我不确定熊猫是否有烛台功能。

+1

从您提供的数据,它看起来像你的数据已经从9:30 AM每次30min收集每天下午4:00。这种差距可能仅仅反映了从没有获得数据的那几天到下午4:00到9:30之间的时间。顺便说一句,使用[pandas](http://pandas.pydata.org/)图书馆,您可以直接处理和分析您的原始数据并绘制它们。 – gcalmettes 2012-03-13 19:49:52

+0

熊猫似乎无法绘制ohlc /烛台数据... – NoviceCoding 2012-03-14 17:06:02

+1

pastebin链接不再可用 – alexandroid 2015-04-21 13:48:38

回答

41

如果我理解的很好,你主要关心的是日常数据之间的差距。 为了摆脱它们,一种方法是人为地“均匀地”放置您的数据(但当然,您将在一天内丢失任何时间指示)。

无论如何,通过这种方式,您将能够获得一张看起来像您所提议的图表作为示例的图表。

评论代码和结果图如下。

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 2012-03-21 03:46:11