2 回答

TA貢獻1820條經(jīng)驗 獲得超10個贊
IIUC,你可以set_index使用 PERIOD 和 BMfilter列,其中包含 PORT 的列(如果你有其他列你不想應(yīng)用該beta功能),然后rolling.apply像這樣使用:
print (df.set_index(['PERIOD','BM']).filter(like='PORT')
.rolling(3).apply(lambda x: beta(x, x.index.get_level_values(1)))
.reset_index())
PERIOD BM PORT1 PORT2
0 201504 -0.013 NaN NaN
1 201505 0.022 NaN NaN
2 201506 -0.039 0.714514 0.898613
3 201507 0.017 0.814734 1.055798
4 201508 -0.081 0.736486 0.907336
5 201509 -0.032 0.724490 0.887755
6 201510 0.090 0.598332 0.736964
7 201511 0.038 0.715848 0.789221
8 201512 -0.044 0.787248 0.778703
9 201601 -0.057 0.658877 0.794949
10 201602 -0.011 0.412270 0.789567
11 201603 0.026 0.354829 0.690573
12 201604 0.010 0.562924 0.558083
13 201605 0.031 1.716066 1.530471

TA貢獻1825條經(jīng)驗 獲得超6個贊
def getbetas(df, market, window = 45):
""" given an unstacked pandas dataframe (columns instruments, rows
dates), compute the rolling betas vs the market.
"""
nmarket = market/market.rolling(window).var()
thebetas = df.rolling(window).cov(other=nmarket)
return thebetas
添加回答
舉報