当前位置:网站首页>机器学习之时间序列
机器学习之时间序列
2022-07-21 16:49:00 【强仔fight】
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()
边栏推荐
- 资料分享|基于SHT11的简易温湿度检测仿真
- SQL Server Setting UUID
- SSM project complete source code [easy to understand]
- Notes on formal languages and compilers & tutorial Chapter 2 context free languages
- web3再牛 也沒能逃出這幾個老巨頭的手掌心
- 西门子博图安装期间反复重启的问题处理
- R language uses oneway The test function performs one-way ANOVA. If there is the same variance between groups, set the var.equal parameter to true to obtain a more relaxed test
- Comment changer la police de la console en console?
- Airflow详细搭建过程(亲测 + 总结)
- leetcode-09(下一个排列+快乐数+全排列)
猜你喜欢
如何设置抓包手机端
Fastjson 代码执行 CVE-2022-25845
活动报名:如何零基础快速上手开源的 Tapdata Live Data Platform?
Unified payment callback interface of Alipay (applicable to H5, PC and APP)
wallys/new product/DR7915/MT7915+MT7975/WiFi6 MiniPCIe Module 2T2R
Web3 couldn't escape the palm of these old giants
控制台字体怎么改为console?
Next. JS and Remix
vector介绍及底层原理
接口文档进化图鉴,有些古早接口文档工具,你可能都没用过
随机推荐
小程序选项卡
R语言ggplot2可视化:可视化散点图并为散点图中的数据点添加公式标签、使用ggrepel包的geom_text_repel函数避免数据点公式标签互相重叠(添加公式标签)
Read the paper with me - multi model text recognition network
状态管理之 Zustand
MySql中on与where的区别个人总结——分清楚条件应该写在哪里
WebSockets 和 Server-Sent Events
解密“海莲花”组织(域控检测防御)
Overview of nftfi track layout
R语言检验相关性系数的显著性:使用cor.test函数计算相关性系数的值和置信区间及其统计显著性(如果变量来自非正态分布总体使用Spearman方法)
性能测试----测试计划编写
为什么都说考完二建就要去准备一建,这几点你一定不知道!
微信小程序 wx.request的简单封装
R language uses the ggarrange function of ggpubr package to combine multiple images, and uses the ggexport function to save the visual image in TIFF format (width parameter specifies width, height par
Kubernetes static storage and dynamic storage
移动端测试用例的编写
SQL Server Setting UUID
两个元素的矩阵乘除法「建议收藏」
Next.js 与 Remix
极客星球丨字节跳动一站式数据治理解决方案及平台架构
vector介绍及底层原理