gpt4 book ai didi

python - 使用 Matplotlib 的日内烛台图表

转载 作者:IT老高 更新时间:2023-10-28 21:06:51 29 4
gpt4 key购买 nike

我在使用 Matplotlib 的财务图表时遇到了一些困难。似乎他们的烛台图最适合处理每日数据,但我很难让它们处理日内(每 5 分钟一次,在 9:30 到 4 点之间)数据。

我已将示例数据粘贴到 pastebin 中。顶部是我从数据库中得到的,底部是与格式化为序数 float 的日期元组,以便在 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 分钟不等。


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

最佳答案

如果我理解得很好,您主要关心的问题之一是每日数据之间的差距。要摆脱它们,一种方法是人为地“均匀分布”您的数据(但当然您会在一天内失去任何时间指示)。

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

注释代码和结果图如下。

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

关于python - 使用 Matplotlib 的日内烛台图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9673988/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com