Home > OS >  Add columns to a rolling-apply function
Add columns to a rolling-apply function

Time:06-03

I have daily_data data like this:

                 Close
Date
2022-06-01  148.710007
2022-05-31  148.839996
2022-05-27  149.639999
2022-05-26  143.779999
2022-05-25  140.520004
2022-05-24  140.360001
2022-05-23  143.110001
2022-05-20  137.589996
2022-05-19  137.350006
2022-05-18  140.820007
...

I then do a rolling percent change calculation, sampleStr = '180 D':

dfSeries = daily_data['Close'].rolling(resampleStr).apply(lambda x : (x[0] - x[-1])/x[0])

If I print this I get this:

Date
2022-06-01    0.000000
2022-05-31   -0.000874
2022-05-27   -0.006254
2022-05-26    0.033152
2022-05-25    0.055074
2022-05-24    0.056150
2022-05-23    0.037657
2022-05-20    0.074776
2022-05-19    0.076390
2022-05-18    0.053056
2022-05-17   -0.003564
2022-05-16    0.021317
2022-05-13    0.010759
2022-05-12    0.041356
2022-05-11    0.014861
2022-05-10   -0.039002

However, I would like to add columns to this for a sanity check, I would like to add the Date of x[0] (actually this is already there I think), the Date of x[-1], the Close of x[0], and the Close of x[-1], to dfSeries.

How do I do this?

CodePudding user response:

Seems like you just need to use pd.concat with shifted columns

For example, if your window is 3, you can do

pd.concat([df['Close'].rolling(3).apply(lambda x : (x[0] - x[-1])/x[0]).reset_index(), 
           df.reset_index()['Date'].shift(-3).rename('Date in T-3'), 
           df.reset_index()['Close'].shift(-3).rename('Close in T-3')], 
           axis=1
           )

which means you are concatenating three objects. The first one, is the result you provided in the original post; the second one, the shifted Date column; and the last one, the shifted Close column.

  • Related