[Python] Pandas Groupby Rolling Apply Custom Function (Pass Dataframe not Series)

Discussão em 'Python' iniciado por Stack, Janeiro 3, 2025.

  1. Stack

    Stack Membro Participativo

    I need to do a groupby then rolling and apply a custom function

    This is my custom function:

    def reg_DOL(group):
    g = group.copy()

    if pd.isna(group['lnebit'].iloc[0]) or pd.isna(group['lnsale'].iloc[0]):
    return np.NaN

    else:
    g['lnebit_t0'] = g['lnebit'].iloc[0]
    g['lnsale_t0'] = g['lnsale'].iloc[0]
    g['t'] = range(1, len(g) + 1)

    y, X = patsy.dmatrices('lnebit ~ lnebit_t0 + gebit:t -1', g, return_type='dataframe')
    model = sm.OLS(y, X, missing='drop')
    result = model.fit()
    g['resid_ebit'] = result.resid

    y, X = patsy.dmatrices('lnsale ~ lnsale_t0 + gsale:t -1', g, return_type='dataframe')
    model = sm.OLS(y, X, missing='drop')
    result = model.fit()
    g['resid_sale'] = result.resid

    y, X = patsy.dmatrices('resid_ebit ~ resid_sale', g, return_type='dataframe')
    model = sm.OLS(y, X, missing='drop')
    result = model.fit()
    dol = result.params['resid_sale']

    return dol


    And this is my groupby rolling

    comp.groupby('gvkey').rolling(window=20, min_periods=20).apply(lambda g: reg_DOL(g))


    So far I have been unsuccessful with this rolling. As I understand the root might be rolling only pass series not dataframe so that my rolling apply does not work here. If it is the issue, then how should I solve? If not then what is the problem?

    Thank you

    Continue reading...

Compartilhe esta Página