Convert daily pandas stock data to monthly data using first trade day of the month

前端 未结 3 765
一生所求
一生所求 2020-12-30 16:41

I have a set of calculated OHLCVA daily securities data in a pandas dataframe like this:

>>> type(data_dy)


        
3条回答
  •  情深已故
    2020-12-30 17:13

    Instead of M you can pass MS as the resample rule:

    df =pd.DataFrame( range(72), index = pd.date_range('1/1/2011', periods=72, freq='D'))
    
    #df.resample('MS', how = 'mean')    # pandas <0.18
    df.resample('MS').mean()  # pandas >= 0.18
    

    Updated to use the first business day of the month respecting US Federal Holidays:

    df =pd.DataFrame( range(200), index = pd.date_range('12/1/2012', periods=200, freq='D'))
    
    from pandas.tseries.offsets import CustomBusinessMonthBegin
    from pandas.tseries.holiday import USFederalHolidayCalendar
    bmth_us = CustomBusinessMonthBegin(calendar=USFederalHolidayCalendar())
    
    df.resample(bmth_us).mean()
    

    if you want custom starts of the month using the min month found in the data try this. (It isn't pretty, but it should work).

    month_index =df.index.to_period('M')
    
    min_day_in_month_index = pd.to_datetime(df.set_index(new_index, append=True).reset_index(level=0).groupby(level=0)['level_0'].min())
    
    custom_month_starts =CustomBusinessMonthBegin(calendar = min_day_in_month_index)
    

    Pass custom_start_months to the fist parameter of resample

提交回复
热议问题