python - 当日期丢失时,散景消除数据时间轴中的间隙
问题描述
我试图用我拥有的 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]]))
我的代码有问题还是我的概念有问题?
解决方案
经过反复试验,我终于找到了问题的根源。将 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]]))
推荐阅读
- javascript - 我的 Sequelize/Node 设置错误?我在做一些明显错误的事情吗?
- python - 从数字列表中生成随机数
- python - 在定义的区域上创建图像拼贴
- tomcat - Grails 4 App 在 AWS Elastic Beanstalk 上启动期间停止
- excel - 如何使用工作表中的字符串值作为变量名
- reactjs - 在 docker-compose 上使用 nginx 代理反应应用程序
- 2sxc - 2sxc 实体,其字段必须是唯一的
- python - 每次单击按钮时移动一个标签 PyQt5
- python - Streamlit 加载列数据需要太多时间
- google-analytics - 如何在 Google Analytics 中获取所选期间的总月数?我们可以动态显示自定义报告的当前月份吗?