简体   繁体   中英

Pandas: rolling window calculation requiring input from 2 columns

I am trying to calculate the CAPE ratio for individual stocks (link below but unlikely you'll need to know it to answer the question).

Link to CAPE definition

My dataframe has quarterly data for earnings per share ('EPS') and the CPI ('CPI Value'). I wish to calculate the 10 year (40 quarters) inflation-adjusted average PE.

So for each row of the new column the calculation requires:

  • a 40 period lookback
  • ratio of CPI at start of period over current CPI (starts at 1 at the start of each lookback window and gradually decreases to account for inflation)
  • this CPI ratio multiplied by the current EPS value
  • the average of all these multiplications for the window

eg- CAPE on day i:

CAPE[i] = Average of ((CPI[i-40] / CPI[i-40]) * EPS[i-40]), (CPI[i-40] / CPI[i-39]) * EPS[i-39], ... , (CPI[i-40] / CPI[i]) * EPS[i]))

Seems fairly clear that 'rolling' needs to be used, possibly with an 'agg' function.

I am struggling to do this since the calculation requires two columns from the dataframe instead of just one and I am not sure how to access them inside the rolling function.

Also don't think a 'helper' column is useful since the values change for each lookback window.

Toy example code below:

df = pd.DataFrame(index = range(100))

df['CPI Value'] = 1. + (df.index / 100.)

df['EPS'] = 10.

& here's my non-working attempt:

df['CAPE'] = df.rolling(40).agg(lambda x: ((x['CPI Value'][0] / x['CPI Value']) * x['EPS']).mean())

Couldn't get it to work with pandas even though it seems relatively trivial, kept getting tripped up with syntax or not passing through the correct parameters.

Numpy-extended's rolling_apply function seems to have worked though.

from numpy_ext import rolling_apply

def func(a,b): return np.mean((a.iloc[0] / a) * b)
df['inf_adj'] = rolling_apply(func, 40, df['CPI Value'], df['EPS'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM