【发布时间】:2019-06-24 00:44:09
【问题描述】:
我正在尝试使用 pyfinance 包进行简单的线性回归,并使用 PandasRollingOLS 进行滚动回归测试(使用 min_window 选项滚动)。
它可以工作,但我想在函数中有一个 min_window。
我希望在 rollingOLS 函数中有 min_window,因为如果我们有一个 90 的窗口,它不会对前 90 个值执行 OLS。我想执行一个 OLS 扩展直到 90 个观察开始时至少有 12 个观察(min_window),然后滚动 90(窗口)
我试图理解包的代码,但我无法在代码中包含 min_window。
我想要这种功能(这是 PandasRollingOLS 类的 init):
def __init__(self, y, x=None, window=None, **min_window=None**, has_const=False, use_const=True):
我想我应该更新下面发布的 utils.rolling_windows 上的代码,有人可以帮我吗?
def rolling_windows(a, window):
"""Creates rolling-window 'blocks' of length `window` from `a`.
Note that the orientation of rows/columns follows that of pandas.
Example
-------
import numpy as np
onedim = np.arange(20)
twodim = onedim.reshape((5,4))
print(twodim)
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]
[16 17 18 19]]
print(rwindows(onedim, 3)[:5])
[[0 1 2]
[1 2 3]
[2 3 4]
[3 4 5]
[4 5 6]]
print(rwindows(twodim, 3)[:5])
[[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]
[[ 8 9 10 11]
[12 13 14 15]
[16 17 18 19]]]
"""
if window > a.shape[0]:
raise ValueError('Specified `window` length of {0} exceeds length of'
' `a`, {1}.'.format(window, a.shape[0]))
if isinstance(a, (Series, DataFrame)):
a = a.values
if a.ndim == 1:
a = a.reshape(-1, 1)
shape = (a.shape[0] - window + 1, window) + a.shape[1:]
strides = (a.strides[0],) + a.strides
windows = np.squeeze(np.lib.stride_tricks.as_strided(a, shape=shape,
strides=strides))
# In cases where window == len(a), we actually want to "unsqueeze" to 2d.
# I.e., we still want a "windowed" structure with 1 window.
if windows.ndim == 1:
windows = np.atleast_2d(windows)
return windows
谢谢大家!
亚历山德罗
【问题讨论】:
标签: python regression linear-regression