Search code examples
rfunctionautocorrelation

Build a Function for Autocorrelation


I build the below AR(2) model :

# Generate noise
noise=rnorm(200, mean=0, sd=1) 

# Introduce a variable
ma_1=NULL
# Set the value of parameter theta1
theta1=0.7

# Loop for generating MA(1)
for(i in 2:200)
{
  ma_1[i] = 0.1 + noise[i] + theta1*noise[i-1]
}

plot(ma_1, main="MA(1) Model", type = "l", col= "blue")

Im trying to create a function to calculate the autocorrelation. I want to build a process so for for find that and then make a plot.

Any ideas ?


Solution

  • Taking the formula for the empirical autocorrelation on Enders' Applied econometric time series (4th edition, page 67):

    enter image description here

    where

    enter image description here

    Then we just need to write code for it):

    acf.new = function(y, smax, plot){
    
      values = numeric()
      for(i in 0:smax){
        values[i+1] = sum((y-mean(y))*(lag(y, i)-mean(y))) / sum((y-mean(y))^2)}
      
      if(plot){
        df = data.frame(Acf=values, Lag=0:smax)
    
        graph = ggplot(df, aes(x=Lag, y=Acf)) +
          geom_hline(aes(yintercept = 0)) +
          geom_segment(mapping=aes(xend=Lag, yend=0))
    
        plot(graph)}
    
      return(values)}
    

    The plot:

    enter image description here

    Endres also gives a formula for the variance of the the acf:

    enter image description here

    You can also use this to plot the confidence intervals like acf does. If you want, i can write code for it too.

    Checking the output (with set.seed(10)):

    > cbind(acf(ma_1, 23, plot=FALSE)$acf, acf.new(ma_1, 23))
    
                 [,1]        [,2]
     [1,]  1.00000000  1.00000000
     [2,]  0.54446735  0.54446735
     [3,]  0.10622437  0.10622437
     [4,]  0.05674789  0.05674789
     [5,]  0.07363862  0.07363862
     [6,]  0.06474101  0.06474101
     [7,]  0.03218385  0.03218385
     [8,] -0.00330324 -0.00330324
     [9,] -0.07926465 -0.07926465
    [10,] -0.10776187 -0.10776187
    [11,] -0.11907161 -0.11907161
    [12,] -0.09931743 -0.09931743
    [13,]  0.01019203  0.01019203
    [14,]  0.07401695  0.07401695
    [15,]  0.07139094  0.07139094
    [16,] -0.02332401 -0.02332401
    [17,] -0.14173214 -0.14173214
    [18,] -0.12507718 -0.12507718
    [19,] -0.04592383 -0.04592383
    [20,] -0.05617885 -0.05617885
    [21,] -0.12087564 -0.12087564
    [22,] -0.05018037 -0.05018037
    [23,] -0.01171499 -0.01171499
    [24,] -0.10177784 -0.10177784