```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(kableExtra)
set.seed(123)
options(htmltools.dir.version = FALSE, servr.daemon = TRUE)
knitr::opts_chunk$set(fig.height=4, fig.align="center")
library(FishForecast)
#to install
#devtools::install_github("Fish-Forecast/FishForecast")
```


## Exponential Smoothing Models revisted

Let's imagine that our data look like so:
```{r}
dat <- sin((1:12)*pi/12)
plot(dat)
```

##

It is quite smooth (not like noise).  Let's fit a ETS with level and trend.  

What should the level be?  The one-step ahead ($h=1$) prediction model for an ETS is, where $l_t$ is the level to use in our prediction.  

$$\hat{y}_{t+1|1:t} = l_t + b_t$$
"level" is where to "start" our prediction and then we'll add our estimated trend $b_t$.

No error in the data and it is smooth, so $l_t$ should be $y_t$!

##

The estimated level for the ETS is in `fit$states`:

```{r echo=TRUE}
library(forecast)
fit <- ets(dat, model="AAN", damped=FALSE)
plot(dat, type="p",pch=2)
points(fit$states[2:13,1],pch=3)
legend("topright",c("data","l(t)"),pch=c(2,3))
```

##

The estimated trend to use depends on the $\beta$ (weighting). In this case, it is an average of past trends (`diff(dat)`) which make sense as the trend keeps changing.

```{r, echo=TRUE}
plot(diff(dat), type="p",pch=2)
points(fit$states[3:13,2],pch=3)
legend("topright",c("data","b(t)"),pch=c(2,3))
```

## ETS level and trend

```{r}
autoplot(fit)
````


## Let's look at longer data


```{r}
dat <- sin((1:100)*pi/12)
fit <- ets(dat, model="AAN", damped=FALSE)
autoplot(fit)
```

## In other cases, the best level is smoothed.

Let's imagine that our data look like so:
```{r echo=FALSE}
set.seed(123)
n <- 20
dat <- arima.sim(n,model=list(ar=c(0.5, -0.2)),sd=1)+rnorm(n,0,.2)
fit <- ets(dat, model="AAN", damped=FALSE)
plot(dat, type="p",pch=2)
lines(fit$states[2:(n+1),1],pch=3)
legend("topright",c("data","l(t)"),pch=c(2,NA), lty=c(0,1))
```

## Trend

$$\hat{y}_{t+1|1:t} = l_t + b_t$$

The best trend $b_t$ will take into account the estimated level and will be a smoothed value of the `diff(dat)`.

```{r echo=FALSE, fig.height=4}
plot(diff(dat), type="p",pch=2)
lines(fit$states[3:(n+1),2])
legend("topright",c("data","b(t)"),pch=c(2,NA),lty=c(0,1))
```

