eviews 和 Python 中的移动平均线
Moving average in eviews and Python
我想问一下在时间序列趋势分析中做移动平均模型的时候
当我们在 eviews 中做移动平均时,我们会做类似下面的代码
moving average = @movavc(data, n)
但是在 python 中,我们将执行如下操作:
data["mov_avc"] = data.rolling(window=n).mean()
在 eviews 中做简单移动平均时,我们首先会丢失但也会丢失最后几个观察结果,在 python 中,我们只会丢失第一个观察结果。
怎么会这样?
如果我答对了你的问题,你想了解为什么在 python 中执行 window 大小 n 的移动平均线不丢最后几分
查看 pandas.rolling() docs 您会看到以下注释:
By default, the result is set to the right edge of the window. This
can be changed to the center of the window by setting center=True.
这意味着默认情况下,滚动 window 不以计算平均值的值为中心。
让我们通过一个例子来看看它是如何工作的。
我们有一个简单的 DataFrame:
In [2]: ones_matrix = np.ones((5,1))
...: ones_matrix[:,0] = np.array([i+1 for i in range(ones_matrix.shape[0])])
...: index = [chr(ord('A')+i) for i in range(ones_matrix.shape[0])]
...: df = pd.DataFrame(data = ones_matrix,columns=['Value'],index=index)
...: df
Out[2]:
Value
A 1.0
B 2.0
C 3.0
D 4.0
E 5.0
现在让我们滚动 window 大小 3。 (请注意,我明确地写了参数 center=False 但这是调用 df.rolling() 的默认值)
In [3]: rolled_df = df.rolling(window=3,center=False).mean()
...: rolled_df
Out[3]:
Value
A NaN
B NaN
C 2.0
D 3.0
E 4.0
前两行是 NaN,而最后的点保留在那里。例如,如果您注意到 index C 的行,滚动后的值为 2。但是之前是3。这意味着该索引的新值是对具有索引 {A,B,C} 的值分别为 {1,2,3} 的行进行平均的结果。
因此您可以看到 window 在计算该位置的平均值时并未以索引 C 为中心,而是以索引 B 为中心。
您可以通过设置 centered=True 来更改它,从而输出预期的行为:
In [4]: centred_rolled_df = df.rolling(window=3,center=True).mean()
...: centred_rolled_df
Out[4]:
Value
A NaN
B 2.0
C 3.0
D 4.0
E NaN
我想问一下在时间序列趋势分析中做移动平均模型的时候 当我们在 eviews 中做移动平均时,我们会做类似下面的代码
moving average = @movavc(data, n)
但是在 python 中,我们将执行如下操作:
data["mov_avc"] = data.rolling(window=n).mean()
在 eviews 中做简单移动平均时,我们首先会丢失但也会丢失最后几个观察结果,在 python 中,我们只会丢失第一个观察结果。
怎么会这样?
如果我答对了你的问题,你想了解为什么在 python 中执行 window 大小 n 的移动平均线不丢最后几分
查看 pandas.rolling() docs 您会看到以下注释:
By default, the result is set to the right edge of the window. This can be changed to the center of the window by setting center=True.
这意味着默认情况下,滚动 window 不以计算平均值的值为中心。
让我们通过一个例子来看看它是如何工作的。
我们有一个简单的 DataFrame:
In [2]: ones_matrix = np.ones((5,1))
...: ones_matrix[:,0] = np.array([i+1 for i in range(ones_matrix.shape[0])])
...: index = [chr(ord('A')+i) for i in range(ones_matrix.shape[0])]
...: df = pd.DataFrame(data = ones_matrix,columns=['Value'],index=index)
...: df
Out[2]:
Value
A 1.0
B 2.0
C 3.0
D 4.0
E 5.0
现在让我们滚动 window 大小 3。 (请注意,我明确地写了参数 center=False 但这是调用 df.rolling() 的默认值)
In [3]: rolled_df = df.rolling(window=3,center=False).mean()
...: rolled_df
Out[3]:
Value
A NaN
B NaN
C 2.0
D 3.0
E 4.0
前两行是 NaN,而最后的点保留在那里。例如,如果您注意到 index C 的行,滚动后的值为 2。但是之前是3。这意味着该索引的新值是对具有索引 {A,B,C} 的值分别为 {1,2,3} 的行进行平均的结果。
因此您可以看到 window 在计算该位置的平均值时并未以索引 C 为中心,而是以索引 B 为中心。
您可以通过设置 centered=True 来更改它,从而输出预期的行为:
In [4]: centred_rolled_df = df.rolling(window=3,center=True).mean()
...: centred_rolled_df
Out[4]:
Value
A NaN
B 2.0
C 3.0
D 4.0
E NaN