V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
yellowtail
V2EX  ›  问与答

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

  •  
  •   yellowtail · 2020-09-20 16:05:05 +08:00 · 972 次点击
    这是一个创建于 1307 天前的主题,其中的信息可能已经有所发展或是发生改变。

    方法一使用 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() 感觉太丑了...希望能给点优化意见

    2 条回复    2020-09-20 19:47:19 +08:00
    yellowtail
        1
    yellowtail  
    OP
       2020-09-20 16:08:33 +08:00
    https://imgchr.com/i/wTGMOf resample 方法 60 分钟以上的错误
    volvo007
        2
    volvo007  
       2020-09-20 19:47:19 +08:00   ❤️ 1
    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
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1226 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 23:55 · PVG 07:55 · LAX 16:55 · JFK 19:55
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.