Time Series II

#SOCY7113arma.r
library(TSA)

# Let's look at a time series
data(airmiles, package="datasets")
plot(airmiles)

# It appears that there is a trend. We can try to fit a model
# of the effect of time.
iv1<-1:length(airmiles) # This creates a vector that counts time
summary(lm(airmiles~iv1))

# Now, let's model a quadratic function for the trend.
iv2<-iv1^2 # This is "time squared."
summary(lm(airmiles~iv1+iv2))

# We'll look at autocorrelation.
acf(airmiles,main="ACF airmiles")
acf(airmiles,type="p",main="ACF airmiles")

# We'll look at moving average.
# In R, you can create your own functions
# to do needed calculations. For example,
# the following code computes a moving average
# with a period of 3.
# ma3 <- function(x) {
# y<-numeric(length(x)-2)
# for (i in 2:(length(x)-1)) {
# y[i] <- (x[i-1] + x[i] + x[i+1]) / 3
# }
# y
# }
# You can invoke this function by first using:
source("http://www.courseserve.info/files/SOCY7113ma3.r")

data(airmiles, package="TSA")
plot(airmiles)
am.ma3<-ma3(airmiles)
plot(am.ma3[2:length(airmiles)-1])
lines(airmiles,col="red")

# To make the series stationary, we can try the diff()
# function.
plot(diff(airmiles))
plot(diff(diff(airmiles),lag=12))
acf(airmiles,type="p")
plot(y=diff(airmiles), x=zlag(diff(airmiles)), type="p")
plot(y=diff(airmiles), x=zlag(diff(airmiles),2), type="p")