Time series autocorrelation

5

Consider the stochastic process AR (1). Generate a sequence of random variables 500 and assuming c = 3 and phi = {0.5, 0.95, 1}. Make autocorrelation from 1st to 3rd order (CR). How to generate these correlations in R?

T=500
e=rnorm(T)
phi1=.5
phi2=.9
phi3=1
c=3
y1=matrix(0,T,1)
y1[1]=e[1]
for(i in 2:T){y1[i]=c+phi1*y1[i-1]+e[i]}
y2=matrix(0,T,1)
y2[1]=e[1]
for(i in 2:T){y2[i]=c+phi2*y2[i-1]+e[i]}
y3=matrix(0,T,1)
y3[1]=e[1]
for(i in 2:T){y3[i]=c+phi3*y3[i-1]+e[i]}
y1[i-1]=lag(y1[i],-1)
y2[i-1]=lag(y2[i],-1)
y3[i-1]=lag(y3[i],-1)
y88=cbind(y1[i],y2[i],y3[i])
y88
lm(y88[,1]~y88[,2])
cor(y1[i],y1[i-1]) 

When I do this the correction presents NA result. Would anyone have any tips?

    
asked by anonymous 31.03.2016 / 18:59

2 answers

4

Use the acf function of R, it graphs you and returns all the serial correlations to the order you want. If you want partial autocorrelation, the pacf function is also there.

# Criando um Grid 1x3 para colocar os gráficos
par(mfrow=c(1,3))

# Calculando as ACF e plotando os gráficos
lagMax <- 10 # Máxima ordem de defasagem das correlações
acfy1 <- acf(y1, main = "Phi 0.50", lag = ordemMax)
acfy2 <- acf(y2, main = "Phi 0.95", lag = ordemMax)
acfy3 <- acf(y3, main = "Phi 1.00", lag = ordemMax)

# Se você vê os valores das correlações para cada lag  especifico
acfy1          # todos
acfy1[1]       # primeira ordem
acfy1[c(1,3)]  # primeira e terceira ordem

# uma forma mais prática de visualizar tudo é um data frame
# com todas as ACF das suas séries
df <- data.frame(lag = 0:lagMax, y1 = acfy1$acf, y2 = acfy2$acf
                 , y3 = acfy3$acf)

Let's look at the data.frame that was created:

# input
> df

# output
   lag           y1        y2        y3
1    0  1.000000000 1.0000000 1.0000000
2    1  0.481858929 0.8703826 0.9938383
3    2  0.205811504 0.7514128 0.9876520
4    3  0.057031134 0.6475811 0.9815168
5    4  0.057797474 0.5667994 0.9754042
6    5  0.039005187 0.4872700 0.9692915
7    6  0.007567483 0.4150687 0.9631947
8    7  0.003729219 0.3534594 0.9571159
9    8 -0.011893324 0.2982870 0.9510480
10   9 -0.089122429 0.2497955 0.9449967
11  10 -0.093402150 0.2171471 0.9389668
    
01.04.2016 / 16:21
2

You are selecting only one element from the series. In correlation, for example, what you have to do is the following - select all but the last and then all but the first.

cor(y1[-length(y1)], y1[-1])
[1] 0.5064076

cor(y2[-length(y1)], y2[-1])
[1] 0.9655964

cor(y3[-length(y1)], y3[-1])
[1] 0.9999973
    
01.04.2016 / 02:27