Pandas滚动OLS被弃用

时间:2017-01-06 10:58:00

标签: python pandas

当我运行旧代码时,我收到以下警告:" pandas.stats.ols模块已弃用,将在以后的版本中删除。我们引用像statsmodels"这样的外部包。 我无法理解statsmodel中是否存在用户友好的滚动OLS模块。 pandas.stats.ols模块的优点在于,您可以轻松地声明是否需要拦截,窗口类型(滚动,扩展)和窗口长度。是否有一个完全相同的模块?

例如:

YY = DataFrame(np.log(np.linspace(1,10,10)),columns=['Y'])
XX = DataFrame(np.transpose([np.linspace(1,10,10),np.linspace(‌​2,10,10)]),columns=[‌​'XX1','XX2'])
from pandas.stats.ols import MovingOLS
MovingOLS( y=YY['Y'], x=XX, intercept=True, window_type='rolling', window=5).resid

我想了解如何使用statsmodel或任何其他模块获取最后一行(剩余的移动ols)的结果。

由于

1 个答案:

答案 0 :(得分:2)

我创建了一个ols模块,旨在模仿大熊猫'已弃用MovingOLS;它是here

它有三个核心类:

  • OLS:静态(单窗口)普通最小二乘回归。输出是NumPy数组
  • RollingOLS:滚动(多窗口)普通最小二乘回归。输出是更高维度的NumPy数组。
  • PandasRollingOLS:将RollingOLS的结果包含在pandas系列& DataFrames。旨在模仿已弃用的pandas模块的外观。

请注意,该模块是package(我目前正在上传到PyPi的过程中)的一部分,它需要一个包间导入。

上面的前两个类完全在NumPy中实现,主要使用矩阵代数。 RollingOLS也广泛利用广播。属性很大程度上模仿了statsmodels' OLS RegressionResultsWrapper

一个例子:

# Pull some data from fred.stlouisfed.org
from pandas_datareader.data import DataReader

syms = {'TWEXBMTH' : 'usd', 
        'T10Y2YM' : 'term_spread', 
        'PCOPPUSDM' : 'copper'
       }
data = (DataReader(syms.keys(), 'fred', start='2000-01-01')
        .pct_change()
        .dropna())
data = data.rename(columns=syms)
print(data.head())
                # usd  term_spread   copper
# DATE                                     
# 2000-02-01  0.01260     -1.40909 -0.01997
# 2000-03-01 -0.00012      2.00000 -0.03720
# 2000-04-01  0.00564      0.51852 -0.03328
# 2000-05-01  0.02204     -0.09756  0.06135
# 2000-06-01 -0.01012      0.02703 -0.01850

# Rolling regressions

from pyfinance.ols import OLS, RollingOLS, PandasRollingOLS

y = data.usd
x = data.drop('usd', axis=1)

window = 12  # months
model = PandasRollingOLS(y=y, x=x, window=window)

# Here `.resids` will be a stacked, MultiIndex'd DataFrame.  Each outer
#     index is a "period ending" and each inner index block are the
#     subperiods for that rolling window.
print(model.resids)
# end         subperiod 
# 2001-01-01  2000-02-01    0.00834
            # 2000-03-01   -0.00375
            # 2000-04-01    0.00194
            # 2000-05-01    0.01312
            # 2000-06-01   -0.01460
            # 2000-07-01   -0.00462
            # 2000-08-01   -0.00032
            # 2000-09-01    0.00299
            # 2000-10-01    0.01103
            # 2000-11-01    0.00556
            # 2000-12-01   -0.01544
            # 2001-01-01   -0.00425

# 2017-06-01  2016-07-01    0.01098
            # 2016-08-01   -0.00725
            # 2016-09-01    0.00447
            # 2016-10-01    0.00422
            # 2016-11-01   -0.00213
            # 2016-12-01    0.00558
            # 2017-01-01    0.00166
            # 2017-02-01   -0.01554
            # 2017-03-01   -0.00021
            # 2017-04-01    0.00057
            # 2017-05-01    0.00085
            # 2017-06-01   -0.00320
# Name: resids, dtype: float64