【问题标题】:calculating slope on a rolling basis in pandas df python在pandas df python中滚动计算斜率
【发布时间】:2017-09-16 16:30:30
【问题描述】:

我有一个数据框:

            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 天的股票/和标准普尔指数的斜率。我试过了:

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]

但是我觉得这很“不符合 Python 标准”,但是我在将滚动/移位功能集成到其中时遇到了麻烦。

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

【问题讨论】:

  • 鉴于 LR 解决方案的简单性,我们可以使用 as_strided 制作一些东西。但是,我认为性能上的提升无法弥补编写此类解决方案的负担。

标签: python dataframe yahoo-finance


【解决方案1】:
# 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)

运行后,会有一个新的列存储拟合结果。

【讨论】:

    猜你喜欢
    • 2020-02-18
    • 1970-01-01
    • 2021-06-22
    • 2017-05-02
    • 1970-01-01
    • 2021-02-26
    • 2017-11-13
    • 1970-01-01
    • 2012-02-23
    相关资源
    最近更新 更多