title |
author |
date |
output |
市场预测2 |
zhangjian |
2020/3/16 |
html_document |
toc |
toc_depth |
highlight |
css |
includes |
true |
2 |
tango |
styles.css |
|
|
|
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
### 时间序列最简单的预测方法
#### 均值法
$$\hat{y}_{T+h | T}=\left(y_{1}+\cdots+y_{T}\right) / T$$
## 一个例子
```{r}
library(tidyverse)
library(forecast)
library(fpp2)
library(ggfortify)
library(ggthemes)
library(timetk)
library(DT)
# 设定数据
beer2 %
mutate(mm = ma(elecsales,order = 5))
ele %>% datatable(colnames = c("年份","原始数据","MA5"))
#ma5第一个数是2381.53,具体计算方式如下:
paste("这个数是这样得到的:",mean(pull(ele[1:5,'value'])),"下面会显示一个TRUE")
ele[3,3]==mean(pull(ele[1:5,'value']))
#ma5图
autoplot(elecsales,size=1.5,alpha=0.6 ,series="原始数据") +
autolayer(ma(elecsales,5), series="5-MA",size=1.5,alpha=0.6) +
xlab("年份") + ylab("亿瓦时") +
ggtitle("年度住宅售电量") +
scale_colour_manual(values=c("Data"="grey50","5-MA"="red"),
breaks=c("Data","5-MA"))+
theme(text = element_text(family = "STHeiti"))+
theme(plot.title = element_text(hjust = 0.5))+theme_clean()
#ma3图
autoplot(elecsales,size=1.5,alpha=0.6 ,series="原始数据") +
autolayer(ma(elecsales,3), series="3-MA",size=1.5,alpha=0.6) +
xlab("年份") + ylab("亿瓦时") +
ggtitle("年度住宅售电量") +
scale_colour_manual(values=c("Data"="grey50","3-MA"="red"),
breaks=c("Data","3-MA"))+
theme(text = element_text(family = "STHeiti"))+
theme(plot.title = element_text(hjust = 0.5))+theme_clean()
#ma3图
autoplot(elecsales,size=1.5,alpha=0.6 ,series="原始数据") +
autolayer(ma(elecsales,7), series="7-MA",size=1.5,alpha=0.6) +
xlab("年份") + ylab("亿瓦时") +
ggtitle("年度住宅售电量") +
scale_colour_manual(values=c("Data"="grey50","7-MA"="red"),
breaks=c("Data","7-MA"))+
theme(text = element_text(family = "STHeiti"))+
theme(plot.title = element_text(hjust = 0.5))+theme_clean()
```
## 移动平均的移动平均
```{r}
beer2 %
mutate(mm = ma(beer2,order = 4,centre = F)) %>%
mutate(mmm = ma(beer2,order = 4,centre = T))
beer2_df %>% datatable(colnames = c("年份","原始数据","MA4","2*4MA"))
# 450 = (451.25+448.75)/2
```
## 使用线性模型对时间序列进行预测
$$y_{t}=\beta_{0}+\beta_{1} t+\beta_{2} d_{2, t}+\beta_{3} d_{3, t}+\beta_{4} d_{4, t}+\varepsilon_{t}$$
```{r warning=FALSE}
beer2 %
as.data.frame() %>%
ggplot(aes(x=Data, y=Fitted, colour=as.factor(cycle(beer2)))) +
geom_point() +
ylab("拟合值") + xlab("真实值") +
ggtitle("啤酒的季度产出") +
scale_colour_brewer(palette="Dark2", name="季度") +
geom_abline(intercept=0, slope=1)+
theme(text = element_text(family = "STHeiti"))+
theme(plot.title = element_text(hjust = 0.5))
```
### 使用拟合好的模型进行预测
```{r warning=FALSE}
beer2