复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58import numpy as np from matplotlib import pyplot as plt from statsmodels.graphics.tsaplots import plot_acf, plot_pacf from statsmodels.tsa.ar_model import AutoReg from statsmodels.stats.diagnostic import acorr_ljungbox as lb_test from statsmodels.tsa.stattools import adfuller # 1 构造随机游走模型 noise = np.random.normal(loc=0, scale=0.5, size=1000) x_list = np.ones(1000) alpha = 1.2 # <1 为随机游走模型,计算起来有意义,大于1前面对后面的影响逐步放大,计算无意义 for i in range(1, len(x_list)): x_list[i] = alpha * x_list[i - 1] + noise[i] fig = plt.figure(figsize=(10, 5)) # 1.1 图像显示,并且根据plot_pacf确定阶数为1 fig.add_subplot(3, 1, 1) plt.plot(range(len(x_list)), x_list) ax2 = fig.add_subplot(3, 1, 2) plot_acf(x_list, ax=ax2) ax3 = fig.add_subplot(3, 1, 3) plot_pacf(x_list, ax=ax3) plt.show() # 2 lb_test 检验,用来判断是否是白噪声,只有所有的值都>0.5, 就能判断为白噪声 print(lb_test(noise)) # 白噪声的值全>0.5,分析起来没意义 print(lb_test(x_list)) # 随机游走的值小于0.5,分析起来有意义 # 3 单位跟检验 dftest = adfuller(x_list,autolag='AIC') print(dftest) # 第一个t值,第二个是p值,当时间序列是平稳时,希望:t值小于1%的值,并且p值趋近于0,当alpha=0.5时满足; # 当alpha=1.1时,t=7e16,p=1,所以时间序列不平稳,也能使用ar模型 # 4 使用autoReg模型进行训练和预测 model = AutoReg(x_list, lags=1).fit() print(model.params) # 打印参数[-0.00227543 0.54392898],每次的值可能不一样 predict = model.predict(1, 999) # 预测 # 5 对误差进行分析 residual = x_list[1:] - predict # 计算真实-预测的误差 print(np.mean(residual)) # 查看噪声的均值=0 print(np.std(residual)) # 查看噪声的方差=0.507 # 对误差进行绘图,发现误差的自相关系数除了和他本身都是趋近于0,符合白噪声特点。 fig = plt.figure(figsize=(10, 5)) fig.add_subplot(3, 1, 1) plt.plot(range(len(residual)), residual) ax2 = fig.add_subplot(3, 1, 2) plot_acf(residual, ax=ax2) ax3 = fig.add_subplot(3, 1, 3) plot_pacf(residual, ax=ax3) plt.show()
最后
以上就是畅快网络最近收集整理的关于AR模型、单位根检验的全部内容,更多相关AR模型、单位根检验内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复