本文介绍了使用 Matplotlib 的日内烛台图表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 Matplotlib 的财务图表时遇到了一些困难.似乎他们的烛台图表最适合处理每日数据,而我很难让它们处理盘中(每 5 分钟,晚上 9:30 到下午 4 点)数据.

我已经在 pastebin 中粘贴了示例数据.顶部是我从数据库中得到的内容,底部是格式化为有序浮点数的日期元组,以便在 Matplotlib 中使用.

如何从这些数据中制作出清晰易读的图表?我的最终目标是获得一个看起来像这样的图表:

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

数据点的增量可以从 5 分钟到 30 分钟不等.

我还制作了数据的 Pandas 数据框,但我不确定 Pandas 是否具有烛台功能.

解决方案

如果我没听错的话,你最关心的问题之一就是每日数据之间的差距.要摆脱它们,一种方法是人为地均匀分布"您的数据(当然,您会在日内丢失任何时间指示).

无论如何,这样做,您将能够获得一个看起来像您作为示例提出的图表的图表.

注释代码和结果图如下.

将 numpy 导入为 np导入 matplotlib.pyplot 作为 plt导入日期时间从 matplotlib.finance 导入烛台从 matplotlib.dates 导入 num2date# 文本文件中的数据,5 列:时间、开盘价、收盘价、最高价、最低价# 请注意,我使用的是您格式化为序数浮点数的时间data = np.loadtxt('finance-data.txt', delimiter=',')# 确定天数并创建这些天的列表ndays = np.unique(np.trunc(data[:,0]), return_index=True)x 天 = []对于 np.arange(len(ndays[0])) 中的 n:xdays.append(datetime.date.isoformat(num2date(data[ndays[1],0][n])))# 通过用等距值替换时间数组来创建新数据.# 这将允许在绘制数据时消除天之间的差距data2 = np.hstack([np.arange(data[:,0].size)[:, np.newaxis], data[:,1:]])# 绘制数据fig = plt.figure(figsize=(10, 5))ax = fig.add_axes([0.1, 0.2, 0.85, 0.7])# 轴的自定义ax.spines['right'].set_color('none')ax.spines['top'].set_color('none')ax.xaxis.set_ticks_position('底部')ax.yaxis.set_ticks_position('left')ax.tick_params(axis='both', direction='out', width=2, length=8,标签大小=12,垫=8)ax.spines['left'].set_linewidth(2)ax.spines['bottom'].set_linewidth(2)# 仅在开始新的一天时设置 x 轴的刻度ax.set_xticks(data2[ndays[1],0])ax.set_xticklabels(x 天,旋转 = 45,水平对齐 =右")ax.set_ylabel('报价($)', size=20)ax.set_ylim([177, 196])烛台(轴,数据2,宽度= 0.5,颜色='g',颜色向下='r')plt.show()

I've been having some difficulty with Matplotlib's finance charting. It seems like their candlestick charts work best with daily data, and I am having a hard time making them work with intraday (every 5 minutes, between 9:30 and 4 pm) data.

I have pasted sample data in pastebin. The top is what I get from the database, and the bottom is tupled with the date formatted into an ordinal float for use in Matplotlib.

Link to sample data

When I draw my charts there are huge gaps in it, the axes suck, and the zoom is equally horrible. http://imgur.com/y7O8A

How do I make a nice readable graph out of this data? My ultimate goal is to get a chart that looks remotely like this:

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

The data points can be in various increments from 5 minutes to 30 minutes.


I have also made a Pandas dataframe of the data, but I am not sure if pandas has candlestick functionality.

解决方案

If I understand well, one of your major concern is the gaps between the daily data.To get rid of them, one method is to artificially 'evenly space' your data (but of course you will loose any temporal indication intra-day).

Anyways, doing this way, you will be able to obtain a chart that looks like the one you have proposed as an example.

The commented code and the resulting graph are below.

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

这篇关于使用 Matplotlib 的日内烛台图表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 05:20