如何在Matplotlib中移除Python可变频率数据的周末间隔?
移除可变频率时间序列图表中的周末间隙
我查找过相关解决方案,但均无法完全满足需求。假设我们有如下pandas可变频率时间序列数据:
import pandas as pd testDf = pd.DataFrame( {'ImpliedVolatility': { pd.Timestamp('2022-11-30 16:20:00+0100'): 19.1269013106775, pd.Timestamp('2022-11-30 16:30:00+0100'): 19.0800712368193, pd.Timestamp('2022-12-01 15:20:00+0100'): 19.5300982613676, pd.Timestamp('2022-12-02 09:00:00+0100'): 18.8579952967423, pd.Timestamp('2022-12-02 09:20:00+0100'): 18.6791915364582, pd.Timestamp('2022-12-02 15:10:00+0100'): 18.5538057657658, pd.Timestamp('2022-12-02 15:20:00+0100'): 18.6965706501837, pd.Timestamp('2022-12-02 15:50:00+0100'): 17.5678872272944, pd.Timestamp('2022-12-05 09:00:00+0100'): 18.2304285690717}})
用常规方式可以轻松绘制出图表:
import matplotlib.pyplot as plt fig1, ax1 = plt.subplots() fig1.autofmt_xdate() ax1.plot(testDf.ImpliedVolatility, 'o-') plt.show()

但我希望移除图表中的周末间隙,具体来说是移除周五午夜至周日午夜的间隔。
网上的解决方案存在诸多问题,最常见的是会将刻度频率重置为固定间隔,示例代码如下:
import numpy as np import matplotlib.ticker as ticker fig, axes = plt.subplots(ncols=1) # 自定义格式化器 N = len(testDf) ind = np.arange(N) # 均匀分布的绘图索引 def format_date(x, pos=None): thisind = np.clip(int(x + 0.5), 0, N - 1) return testDf.index[thisind].strftime('%Y-%m-%d %Hh') ax = axes ax.plot(ind, testDf.ImpliedVolatility, 'o-') ax.xaxis.set_major_formatter(ticker.FuncFormatter(format_date)) fig.autofmt_xdate() plt.show()

这种方案并不适用于可变频率数据。
注:理想情况是移除所有非交易时间,但不同交易所规则不同,本文关注EUREX期权交易所的数据。
我尝试过包括StackOverflow在内的多种在线方案,它们普遍存在重置X轴刻度频率为固定间隔的问题。
内容的提问来源于stack exchange,提问作者johnukfr
相关产品推荐
相关产品推荐

