在熊猫df python中滚动计算坡度

问题描述 投票:8回答:1

我有一个数据框:

            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]

但是,我觉得这是非常“不可思议的”,但是在将滚动/移位功能集成到其中时遇到了麻烦。

我的预期输出是在所有可用日期中都有一个名为“ Beta”的列,该列具有标准普尔(x值)和股票(y值)的斜率

python dataframe yahoo-finance
1个回答
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)
运行此命令后,将在新列中存储拟合结果。
© www.soinside.com 2019 - 2024. All rights reserved.