我有一个数据框:
CAT ^GSPC
Date
2012-01-06 80.435059 1277.810059
2012-01-09 81.560600 1280.699951
2012-01-10 83.962914 1292.079956
....
2017-09-16 144.56653 2230.567646
我希望找到每个时期最近63天的股票/和S& P指数的斜率。我试过了:
x = 0
temp_dct = {}
for date in df.index:
x += 1
max(x, (len(df.index)-64))
temp_dct[str(date)] = np.polyfit(df['^GSPC'][0+x:63+x].values,
df['CAT'][0+x:63+x].values,
1)[0]
然而,我觉得这是非常" unpythonic" ,但是我在将滚动/移位功能集成到这里时遇到了麻烦。
我的预期输出是有一个名为" Beta"具有所有可用日期的S& P(x值)和股票(y值)的斜率
答案 0 :(得分:0)
# this will operate on series
def polyf(seri):
return np.polyfit(seri.index.values, seri.values, 1)[0]
# you can store the original index in a column in case you need to reset back to it after fitting
df.index = df['^GSPC']
df['slope'] = df['CAT'].rolling(63, min_periods=2).apply(polyf, raw=False)
运行此命令后,将有一个新列存储拟合结果。