1. White noise
n=1000
x = ts( rnorm(n))
lags = 20
acf_true = c(1,rep(0,lags))
plot(x, main = "Simulated data, white noise")

acf(x, type="cov", lag.max = lags, main="ACF, white noise")
points( seq(0,lags), acf_true, col=2 )
legend( "topright", legend=c("Sample","True"), lty=c(1,0), col=c(1,2), pch=c(NA,1))

2. Moving average
n = 1000
w = ts( rnorm(n+2) )
x = 2 + filter( w, sides=2, filter=c(.5,.8,.2))
x = ts( x[2:n+1])
lags = 20
acf_true = c(0.93, 0.56, 0.10, rep(0,lags-2))
plot(x, main="Simulated data, moving average")

acf(x, type="cov", lag.max = lags, main="ACF, moving average")
points(seq(0,lags), acf_true, col=2)
legend( "topright", legend=c("Sample","True"), lty=c(1,0), col=c(1,2), pch=c(NA,1))

3. Autoregressive
n = 10000
w = ts( rnorm(n+1) )
phi = 0.95
alpha = 1
# To get stationary data, we need to initialize the process by drawing from the limiting distribution
x0 = rnorm(1,alpha/(1-phi),sqrt(1/(1-phi^2)))
x = filter( w+alpha, sides=1, method="recurs", filter=c(phi), init=x0)
x = ts(x[2:(n+1)])
lags = 20
acf_true = 1/(1-phi^2) * phi ^ seq(0,lags)
plot(x, main="Simulated data, autoregressive")

acf(x, type="cov", lag.max = lags, main="ACF, autoregressive")
points(seq(0,lags), acf_true, col=2)
legend( "topright", legend=c("Sample","True"), lty=c(1,0), col=c(1,2), pch=c(NA,1))

4. Signal plus noise
n = 1000
w = ts(rnorm(n))
s = ts( 2*cos(2*pi*(seq(1,n)+15)/20) )
x = w + s
lags = 100
acf_true = c(1,rep(0,lags))
plot(x, main="Simulated data, signal plus noise")

# Not stationary!
acf(x, type="cov", lag.max = lags, main="ACF, signal plus noise")
points(seq(0,lags), acf_true, col=2)
legend( "topright", legend=c("Sample","True"), lty=c(1,0), col=c(1,2), pch=c(NA,1))
