如何用 pandas 优雅拼装 k 线数据

2020-09-20 16:05:05 +08:00
 yellowtail

方法一使用 resample 按照网上案例写得,很简短,不过 apply 给字典参数的操作没有看懂。而且可能是因为中午休市的原因,超过六十分钟以上,取样会出问题,一天会出现五根一小时 k 线(一天四个交易时) 写法为 ohlc_dict ={ 'o':'first',
'h':'max',
'l':'min',
'c': 'last'
} dft = dft.resample(period, closed='right',label = 'right').apply(ohlc_dict).dropna()

方法二是用 cut dfx =pd.DataFrame()

df['tst'] = pd.cut(df.index,right=False,bins=range(len(df))[::120])

dfx['o']=df.groupby('tst')['o'].first()

dfx['c']=df.groupby('tst')['c'].last()

dfx['h']=df.groupby('tst')['h'].max()

dfx['l']=df.groupby('tst')['l'].min()

dfx['trade_date']=df.groupby('tst')['trade_date'].last() 感觉太丑了...希望能给点优化意见

1055 次点击
所在节点    问与答
2 条回复
yellowtail
2020-09-20 16:08:33 +08:00
https://imgchr.com/i/wTGMOf resample 方法 60 分钟以上的错误
volvo007
2020-09-20 19:47:19 +08:00
resample 函数接受字典参数,key 为列名并体现在返回的 df 里,value 为对应列需要执行的函数

dict of axis labels -> functions, function names or list of such.

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.resample.Resampler.apply.html#pandas.core.resample.Resampler.apply

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

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

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

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

© 2021 V2EX