pandas 相关, k 线数据加工,用 resample 寻找价格最值相应时间遇到问题。

2022-06-08 17:38:28 +08:00
 bleutail
def func1(x):
        try:
                return x.index[x.argmax()]
        except:
                return -999
def func2(x):
        try:
                return x.index[x.argmin()]
        except:
                return -999
df_origin['high_time'] = (df['last'].resample(label='right', closed='right',rule=period).agg(lambda x:func1(x))) 
df_origin['low_time'] = (df['last'].resample(label='right', closed='right',rule=period).agg(lambda x:func2(x)))

原表是一个时间顺序的价格序列 如果不写 try except 的话 x.index[x.argmax()]会因为 resample 遇到非交易时间段会自动切割出空值,argmax 在空值会报错。感觉方法不好,想请教下正确思路。。

1382 次点击
所在节点    Python
2 条回复
milkpuff
2022-06-08 19:10:59 +08:00
用 groupby ,aggregate
group = data.groupby(data.index.values.astype(f'datetime64[{period}]').astype('datetime64[ns]'))
data = group.agg({
'open': 'first',
'high': 'max',
'low': 'min',
'close': 'last',
'volume': 'sum'
})
bleutail
2022-06-08 19:57:24 +08:00
@milkpuff 谢谢回复,不过需要的是该时段中最高价格的时刻

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/858228

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX