# 4.2 移动平均模型（Moving Average）

移动平均模型（MA）依赖的基础是每个时刻点的值是历史数据点错误项的函数，其中这些错误项是互相独立的。

MA模型和AR模型的公式很类似，只是将公式中的历史数值替换成了历史数据的错误项e，由于错误项e是互相独立的，所以在MA模型中，t时刻的数值仅仅和最近的q个数值有关，而和更早的数据之间没有自相关性，在下面的实战中可以看到，如果对MA序列绘制ACF图，它的自相关关系是突然截断的。而AR序列的ACF图常常是缓慢下降的。

$$
y\_t = \mu + e\_t + \theta\_1 \* e\_{t -1} + \theta\_2 \* e\_{t -2} + ... + \theta\_q \* y\_{t - q}
$$

同样的，和AR模型类似，满足上述公式的时间序列可以用MA(q)来表示。

**python代码实战**&#x20;

```python
import matplotlib.pyplot as plt
import numpy as np
from statsmodels.tsa.arima_model import ARMA
from statsmodels.tsa.arima_process import ArmaProcess
from statsmodels.graphics.tsaplots import plot_acf
%matplotlib inline
```

模拟MA序列

```python
# ar,ma必须以array的形式输入，且第一位表示lag=0，通常这个值会设为1
ar = np.array([1])  # ar项只有一个间隔=0的值表示是一个纯MA序列
ma = np.array([1, -0.9]) # ma序列有两个值，第一个是常数项，第二个是前一个时刻的系数，这是一个MA(1)模型
MA_object = ArmaProcess(ar, ma)
simulated_data = MA_object.generate_sample(nsample=1000)
plt.plot(simulated_data)
```

![](https://3993849477-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-Mhv1ams1lvf_fMUn_is%2F-MiFXKeXOI4m3_TwlTd1%2F-MiFXYIEizpfMItYrSwf%2F4_6.png?alt=media\&token=1062bedb-f677-412f-ad50-e062798b3b68)

```python
# 画出acf图像后看到，如上文所说，对于一个MA(1)序列，从时间间隔大于等于2开始，相关系数断崖式下降
plot_acf(simulated_data, lags=20)
plt.show()
```

![](https://3993849477-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-Mhv1ams1lvf_fMUn_is%2F-MiFXKeXOI4m3_TwlTd1%2F-MiFXfFEuqJlawhCp52I%2F4_7.png?alt=media\&token=52ea77e4-6dd1-44c3-b949-3a98a9e8718e)

模型拟合与评估

```python
# order=(0,1)表示这是一个纯MA(1)模型
mod = ARMA(simulated_data_1, order=(0, 1))  
res = mod.fit()

# 观察模型拟合结果， 系数为-0.8937，和我们创建时间序列的系数-0.9很接近
print(res.summary())

# 打印拟合值
print(res.params)
```

```
[-6.05711676e-04 -8.93691112e-01]
```

模型预测

```python
res.plot_predict(start=990, end=1010)
plt.show()
```

![](https://3993849477-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-Mhv1ams1lvf_fMUn_is%2F-MiFXKeXOI4m3_TwlTd1%2F-MiFXk4ptLnmBp8XoB-s%2F4_8.png?alt=media\&token=9da02141-4a72-49d0-abec-3e7b840811c9)

可以看到MA模型仅仅对样本内的值有实际预测效果，对样本外的值会用统一用整体均值来预测


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://skywateryang.gitbook.io/timeseriesanalysis101/4.-ji-yu-tong-ji-xue-de-shi-jian-xu-lie-fen-xi-fang-fa/untitled-3.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
