Time Series autocorrelation

Asked

Viewed 502 times

5

Consider the stochastic process AR (1). Generate a sequence of 500 random variables and assume c = 3 and Phi = {0.5, 0.95, 1}. Make autocorrelations 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 shows NA result. Someone would have some hint?

  • I know it’s not the focus, but you can use the function filter to generate the AR processes (among others). I made a summary of this function in this link.

2 answers

4

Use the function acf of R, it graphs you and returns all the serial correlations to the order you want. If you want the partial autocorrelations the function pacf ta ai.

# 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)

inserir a descrição da imagem aqui

# 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

2

You are selecting only one element of 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.