如何在金融图表中跳过空日期(周末)

27 投票
8 回答
39318 浏览
提问于 2025-04-15 13:35
ax.plot_date((dates, dates), (highs, lows), '-')

我现在正在使用这个命令来绘制金融的最高点和最低点,使用的是Matplotlib。效果很好,但我想知道怎么去掉因为没有市场数据而在x轴上留下的空白,比如周末和节假日。

我有日期、最高点、最低点、收盘价和开盘价的列表。我找不到任何关于创建一个x轴显示日期但不强制使用固定比例的图表的例子。

8 个回答

7

这是一个最新的回答(2018年),使用的是Matplotlib 2.1.2和Python 2.7.12。

这个函数equidate_ax可以帮你处理简单的日期x轴,确保数据点之间的间距是均匀的。它是通过ticker.FuncFormatter实现的,参考了这个例子

from __future__ import division
from matplotlib import pyplot as plt
from matplotlib.ticker import FuncFormatter
import numpy as np
import datetime


def equidate_ax(fig, ax, dates, fmt="%Y-%m-%d", label="Date"):
    """
    Sets all relevant parameters for an equidistant date-x-axis.
    Tick Locators are not affected (set automatically)

    Args:
        fig: pyplot.figure instance
        ax: pyplot.axis instance (target axis)
        dates: iterable of datetime.date or datetime.datetime instances
        fmt: Display format of dates
        label: x-axis label
    Returns:
        None

    """    
    N = len(dates)
    def format_date(index, pos):
        index = np.clip(int(index + 0.5), 0, N - 1)
        return dates[index].strftime(fmt)
    ax.xaxis.set_major_formatter(FuncFormatter(format_date))
    ax.set_xlabel(label)
    fig.autofmt_xdate()


#
# Some test data (with python dates)
#
dates = [datetime.datetime(year, month, day) for year, month, day in [
    (2018,2,1), (2018,2,2), (2018,2,5), (2018,2,6), (2018,2,7), (2018,2,28)
]]
y = np.arange(6)


# Create plots. Left plot is default with a gap
fig, [ax1, ax2] = plt.subplots(1, 2)
ax1.plot(dates, y, 'o-')
ax1.set_title("Default")
ax1.set_xlabel("Date")


# Right plot will show equidistant series
# x-axis must be the indices of your dates-list
x = np.arange(len(dates))
ax2.plot(x, y, 'o-')
ax2.set_title("Equidistant Placement")
equidate_ax(fig, ax2, dates)

默认绘图方法和均匀x轴的比较

8

其中一个scikits.timeseries宣传的功能是“可以创建时间序列图,并且轴标签的间距很智能”。

你可以在这里看到一些示例图。在第一个示例中(如下图所示),使用了“商业”频率的数据,这样就会自动排除假期和周末等时间段。它还会隐藏缺失的数据点,这在图中表现为间隙,而不是用线性插值来填补这些空缺。

alt text

6

我觉得你需要“人工合成”你想要的图表形式。可以通过使用 xticks 来设置刻度标签,让它们显示你想要的日期字符串(当然,虽然你表示的日期不是均匀分布的,但刻度还是要放在均匀间隔的位置),然后再用普通的 plot 来绘制图表。

撰写回答