set.seed(1234)
library("forecast")
## Loading required package: zoo
## 
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
## Loading required package: timeDate
## This is forecast 7.3

Create sine-wave time series (no trend)

sin_ts <- function() ts(sin(seq(0, 10*pi, length.out = 500)), frequency = 500/5)

y <- sin_ts()
plot(y)

Autocorrelation function (correlation with value at a given lag)

acf(y)

Partial autocorrelation (additional auto correlation by lag)

pacf(y)

Estimate an autroregressive model

ar <- ar(y, method="ols")
## Warning in ar.ols(x, aic = aic, order.max = order.max, na.action =
## na.action, : model order: 3 singularities in the computation of the
## projection matrix results are only valid up to model order 2
ar
## 
## Call:
## ar(x = y, method = "ols")
## 
## Coefficients:
##      1       2  
##  1.996  -1.000  
## 
## Intercept: 2.944e-17 (5.67e-16) 
## 
## Order selected 2  sigma^2 estimated as  1.601e-28

predict and plot the next 100 values

plot(forecast(ar, 1000))

ARIMA(p, d, q). ARIMA contains three models AR, I (integrated) and MA (moving average) and has three parameters: * AR’s order p, * I’s degree of differencing d, and * MA window width q.

ar <- arima(y, c(2,0,0))
## Warning in log(s2): NaNs produced

## Warning in log(s2): NaNs produced

## Warning in log(s2): NaNs produced

## Warning in log(s2): NaNs produced
ar
## 
## Call:
## arima(x = y, order = c(2, 0, 0))
## 
## Coefficients:
##         ar1  ar2  intercept
##       1.996   -1          0
## s.e.  0.000    0          0
## 
## sigma^2 estimated as 8.615e-15:  log likelihood = 7385.84,  aic = -14763.67
plot(forecast(ar, 1000))

Sine wave with noise

add_noise <- function(x, sd=.1) {
  x + rnorm(length(x), sd=sd)
}

y <- sin_ts()
y <- add_noise(y)
plot(y)