首页 > 解决方案 > 当日期丢失时,散景消除数据时间轴中的间隙

问题描述

我试图用我拥有的 OHLC 数据绘制烛台。数据来自 5 分钟时间帧重采样到 4 小时时间帧,所以周末会有很大的差距。

# Load data
subdata = pd.read_csv(
  'data/M5/EURUSD.csv',
  header = None,
  skiprows = 0,
  sep = '\t',
  names = [
    'date',
    'open',
    'high',
    'low',
    'close',
    'volume'
  ],
)
subdata['date'] = pd.to_datetime(subdata['date'])
subdata.set_index(['date'], inplace = True)

# Resample
subdata = subdata.resample('4H').agg({
    'open': 'first',
    'high': 'max',
    'low': 'min',
    'close': 'last',
    'volume': 'sum'
}).dropna(axis=0)

在我重新采样数据然后使用 Bokeh 绘制数据之后,问题就出现了,那就是周末的差距。这里是我用来绘制数据的代码并使用这个概念来解决这个问题,但仍然无法正常工作。

fig1 = figure(x_axis_type='datetime', height=400, width=900)

# I try to add this code but still not work
fig1.xaxis.major_label_overrides = {
    i: date.strftime('%Y-%m-%d %H:%S') for i, date in enumerate(subdata.index)
}

wide = 12*60*60*200

inc = subdata['close'] > subdata['open']
dec = subdata['open'] > subdata['close']

fig1.segment(subdata.index, subdata['high'], subdata.index, subdata['low'], color='black')
fig1.vbar(subdata.index[inc], wide, subdata['open'][inc], subdata.close[inc], fill_color='#D5E1DD', line_color='black')
fig1.vbar(subdata.index[dec], wide, subdata['open'][dec], subdata['close'][dec], fill_color='#F2583E', line_color='black')

show(gridplot([[fig1]]))

这里的结果 周末有空档

我的代码有问题还是我的概念有问题?

标签: pythonpandasbokeh

解决方案


经过反复试验,我终于找到了问题的根源。将 xaxis 更改为enumerate(subdata.index)它意味着 xaxis 使用数字而不是日期时间。但是我仍然使用 datetime 来制作应该使用数字的图,这就是奇怪的事情。为什么散景仍然在 xaxis 数字上接收 xaxis 日期时间,这最终会产生间隙和错误的绘图?

为了解决这个问题,需要行中的索引号。就我而言,索引使用日期时间,因此需要为索引号创建一个新列,然后创建一个带有索引号的图。

# Here code to make number index
subdata['x'] = subdata.reset_index().index

fig1 = figure(x_axis_type='datetime', height=400, width=900)

fig1.xaxis.major_label_overrides = {
    i: date.strftime('%Y-%m-%d %H:%S') for i, date in enumerate(subdata.index)
}

wide = 0.5

inc = subdata['close'] > subdata['open']
dec = subdata['open'] > subdata['close']

fig1.segment(subdata['x'], subdata['high'], subdata['x'], subdata['low'], color='black')
fig1.vbar(subdata['x'][inc], wide, subdata['open'][inc], subdata['close'][inc], fill_color='#D5E1DD', line_color='black')
fig1.vbar(subdata['x'][dec], wide, subdata['open'][dec], subdata['close'][dec], fill_color='#F2583E', line_color='black')

show(gridplot([[fig1]]))

结果情节


推荐阅读