yellowtail
V2EX  ›  问与答

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

  •  
  •   yellowtail · Sep 20, 2020 · 1605 views
    This topic created in 2086 days ago, the information mentioned may be changed or developed.

    方法一使用 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 replies    2020-09-20 19:47:19 +08:00
    yellowtail
        1
    yellowtail  
    OP
       Sep 20, 2020
    https://imgchr.com/i/wTGMOf resample 方法 60 分钟以上的错误
    volvo007
        2
    volvo007  
       Sep 20, 2020   ❤️ 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
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3765 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 45ms · UTC 00:52 · PVG 08:52 · LAX 17:52 · JFK 20:52
    ♥ Do have faith in what you're doing.