1.数据获取
import pandas as pd
import datetime
import pandas_datareader.data as web
import matplotlib.pyplot as plt
import seaborn as sns
from statsmodels.tsa.arima_model import ARIMA
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
#可以适用接口从雅虎获取股票数据
start=datetime.datetime(2000,1,1)
end=datetime.datetime(2015,12,31)
prices=web.DataReader('002578.SZ','yahoo',start,end)
prices.head()
#存入本地
prices.to_csv('data/yahoo.csv')
#从本地读取数据 本文用的是本地数据,未用接口数据
stock = pd.read_csv('data/yahoo.csv', index_col=0, parse_dates=[0])
stock.head(10)
2.训练数据
#下采样 日频数据太多
stock_week = stock['Close'].resample('W-MON').mean()
#训练数据
stock_train = stock_week['2000':'2015']
3.数据平稳性检测
#绘出数据折线图,查看数据是否平稳
stock_train.plot(figsize=(12,8))
plt.legend(bbox_to_anchor=(1.25, 0.5))
plt.title("Stock Close")
sns.despine()
4.一阶差分
stock_diff = stock_train.diff()
stock_diff = stock_diff.dropna()
plt.figure()
plt.plot(stock_diff)
plt.title('一阶差分')
plt.show()
acf = plot_acf(stock_diff, lags=20)
plt.title("ACF")
acf.show()
pacf = plot_pacf(stock_diff, lags=20)
plt.title("PACF")
pacf.show()
一阶差分后,ACF&PACF基本上都落在了0轴上,表明一阶差分就够用了。并且可确定pqd的的取值都为1。
5.模型训练
model = ARIMA(stock_train, order=(1, 1, 1),freq='W-MON')
model_pred = model.fit()
6.残差检测
from statsmodels.graphics.api import qqplot
#残差
resid=model_pred.resid.values
fig=plt.figure(figsize=(12,8))
fig=qqplot(resid,line='q',fit=True)
7.预测
pred = result.predict('20140609', '20160701',dynamic=True, typ='levels')
plt.figure(figsize=(6, 6))
plt.xticks(rotation=45)
plt.plot(pred)
plt.plot(stock_train)