赞
踩
arima
创建时间序列
timestamp
period
interval
date_range 可以指定开始时间与周期 H D M
rng = pd.date_range('2016/07/01', periods=10, freq='D') #起始时间 周期
time = pd.Series(np.random.randn(20), index=pd.date_range(dt.datetime(2013,1,1),periods=20))
time.truncate(before="2016/01/01")过滤
数据重采样
时间数据由一个频率转换到另一个频率
降采样 升采样
ts.resample(‘M’) .sum() .mean() 一个月的总和,均值 3D,
ffill空值取前面的值
bfill空值取后面的值
interpolate线性取值
滑动窗口
基于窗口做平均
data = pd.Series(np.random.randn(600), index=pd.date_range('7/1/2016',freq='D',periods=600))
data.rolling(window=10)
data.mean() 窗口的均值
plt.figure(figsize=(15,5))
df.plot(style='r--')
df.rolling(window=10).mean().plot(style='b')
平稳性要求序列的均值和方差不发生明显变化
严平稳 :不随时间改变而改变 ,
弱平稳:期望与相关系数(依赖性)不变 未来某时刻的值依赖于它的过去信息
差分法:时间序列在t与t-1时刻的差值
sentiment_short['diff_1'] = sentiment_short['UMCSENT'].diff(1)
sentiment_short['diff_2'] = sentiment_short['diff_1'].diff(1)
sentiment_short.plot(subplots=True, figsize(18.12))
自回归模型(AR)
描述当前值与历史值之间的关系,
自回归模型必须满足平稳性的要求 (平稳性,自相关性,自相关系数小于0.5不宜采用)
I 差分
p为自回归项,q为移动平均项数,d为时间序列成为平稳时所做的差分次数
移动平均模型(MA)
自回归模型中的误差项的累加
有效地消除预测中的随机波动
自相关系数ACF
有序的随机变量序列与自身相比较
自相关函数反映了同一序列在不同时序的取值之间的相关性
偏自相关系数
PACF 剔除了k-1个随机变量的干扰之后 x(t-k)对x(t)的影响
import statsmodels.api as sm
import statsmodels.formula.api as smf
import statsmodel.tsa.api as smt
import seaborn as sns
ARIMA建模流程:
1.将序列平稳(差分法确定d)
2.p和q阶数确定:ACF和PACF
3.ARIMA(p,d,q)
绘图模板:
def teplot(y, lags=None, title='', figsize=(14,8)): fig = plt.figure(figsize=figsize) layout =(2,2) ts_ax = plt.subplot2grid(layout,(0,0)) hist_ax = plt.subplot2grid(layout,(0,1)) acf_ax = plt.subplot2grid(layout,(1,0)) pacf_ax = plt.subplot2grid(layout,(1,1)) y.plot(ax=ts_ax) ts_ax.set_title(title) y.plot(ax=hist_ax, kind='hist', bins=25) hist_ax.set_title('Histogram') smt.graphics.plot_acf(y, lags=lags, ax=acf_ax) smt.graphics.plot_pacf(y, lags=lags, ax=pacf_ax) [ax.set_xlim(0) for ax in [acf_ax,pacf_ax]] sns.despine() plt.tight_layout() return ts_ax, acf_ax, pacf_ax arima200 = sm.tsa.SARIMAX(ts_train, order=(2,0,0)) model_results = arima200.fit() import itertools p_min=0 d_min=0 q_min=0 p_max=4 d_max=0 q_max=4 result_bic = pd.DataFrame(index=['AR{}'.format(i) for i in range(p_min,p_max+1)], columns=['MA{}'.format(i) for i in range(q_min,q_max+1)]) for p,d,q in itertools.product(range(p_min,P_max+1), range(d_min,d_max+1), range(q_min,q_max+1)): if p==0 and d==0 and q==0: results_bic.loc['AR{}'.format(p), 'MA{}'.format(q)]=np.nan continue try: model = sm.tsa.SARIMAX(ts_train, order(p,d,q),) result = model.fit() result_bic.loc['AR{}'.format(p), 'MA{}'.format(q)] = results.bic expect: continue results_bic = results_bic[results_bic.columns].astype(float)
AIC:迟迟信息准则
BIC:贝叶斯信息准则
k为模型参数个数,n为样本数量, L为似然函数
模型残差检验:
股票预测
import pandas_datareader import datetime from matplotlib.pylab import style from statsmodels.tsa.arima_model import ARIMA from statsmodels.graphics.tsaplots import plot_acf,plot_pacf stock = pd.read_csv(stockFile, index_col=0, parse_dates=[0]) stock_week = stock['Close'].resample('W-MON').mean() stock_train = stock_week['2000':'2015'] stock_train.plot(figsize=(12,8)) plt.legend(bbox_to_anchor=(1.25, 0.5)) plt.title("Stock Close") sns.despine() 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() model = ARIMA(stock_train, order=(1,1,1),freq='W-MON') result = model.fit() result.summary() pred = result.predict('20140609', '20160701', dynamic=True, typ='levels') plt.figure(figsize=(6,6)) plt.plot(pred) plt.plot(stock_train) model = ARIMA(a_train_diff2, order=(1,2,1),freq='D') result = model.fit() pred = result.predict('2016/11/22', '2016/11/30', dynamic=True) plt.figure(figsize=(15,5)) plt.plot(pred, c='b') plt.plot(time, c='r') plt.show()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。