平稳序列的拟合和预测建模步骤
假如某个观察值序列通过序列预处理可以判定为平稳非白噪声序列,就可以利用ARMA模型对该序列建模。建模的基本步骤如图所示
案例分析
本文章使用Python对S&P500股票市场指数的交易做平稳序列的拟合和预测
参考网址:https://www.statsmodels.org/stable/examples/index.html#time-series-analysis
- 导入数据库
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from statsmodels.tsa.stattools import acf, pacf
from statsmodels.tsa.stattools import adfuller
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
from statsmodels.stats.diagnostic import acorr_ljungbox
%matplotlib inline
import warnings#忽略警告
warnings.filterwarnings("ignore")
- 正确显示中文
import matplotlib as mpl
mpl.rcParams['font.sans-serif'] = 'SimHei'
mpl.rcParams['axes.unicode_minus'] = False
- 导入数据
df = pd.read_csv(r"S&P500.csv",index_col=['Date'])
df.head()
df.index = pd.to_datetime(df.index).to_period('D') # 将字符串索引转换成时间索引
ts = df['Price'] # 生成pd.Series对象
ts.plot()
稳定性检验
P=adfuller(ts, autolag='AIC')
print(P)
#输出结果
(-0.6136546122261047, 0.8678666975160572, 9, 494, {'1%': -3.4436568932270095, '5%': -2.8674084917497074, '10%': -2.5698956806372832}, 5060.71624603719)
#p值为0.8678666975160572>0.05,说明该序列不平稳
纯随机性检验
acorr_ljungbox(ts, lags = [5, 20])
#输出结果
(array([2385.60087981, 8237.52689955]), array([0., 0.]))
#p值为0<0.05,说明该序列为非白噪声
计算收益率
#取对数,再进行差分
r=np.log(ts).diff()
r=r.re