######################################################
############### Econometria Aplicada #################
######################## ARMA ######################## 
######## Pedro Valls  - FGV-EESP ######
######################################################

# Pacotes -----------------------------------------------------------------
load_package<-function(x){
  x<-as.character(match.call()[[2]])
  if (!require(x,character.only=TRUE)){
    install.packages(pkgs=x,repos="http://cran.r-project.org")
    require(x,character.only=TRUE)
  }
}

load_package('tseries')
## Loading required package: tseries
###

# Fix the random seed
set.seed(02011921)
u<-rnorm(1000)
yarma1<-u[1]
# Generate ARMA(1,1) with f=0.5 and a=0.3
for(i in 2:1000){
  yarma1[i]<-0.8*yarma1[i-1]+u[i]-0.3*u[i-1]
}
plot(yarma1, col='blue', type='l')

# Scatter plot between the series and its lags, idea of temporal dependence
par(mfrow=c(3,1))

plot(embed(yarma1,2)[,c(2,1)], col='blue') # Y and Y(-1)
plot(embed(yarma1,3)[,c(3,1)], col='blue') # Y and Y(-2)
plot(embed(yarma1,20)[,c(20,1)], col='blue') # Y and Y(-20)

# Test normality
# Testando normalidade usando qq plot
par(mfrow=c(1,1))
hist(yarma1, breaks = 50, freq=F,
     xlab='', ylab='', main='')
dist<-function(n){
  dnorm(n, mean(yarma1), sd(yarma1))
}
curve(dist, add=T, col='red')
d<-density(yarma1)
lines(d, col='blue')
legend('topleft', legend=c('yarma1','Normal','Kernel'),
       col=c(1,2,4), pch=15)

# Testando normalidade usando qq plot
par(mfrow=c(1,1))
qqnorm(yarma1); qqline(yarma1, col=2) 

# teste de normalidade de Jarque Bera 


jarque.bera.test(yarma1)
## 
##  Jarque Bera Test
## 
## data:  yarma1
## X-squared = 0.10249, df = 2, p-value = 0.95
# Test for constant mean and variance
mean_yarma1<-mean(yarma1[1:100])
stdev_yarma1<-sd(yarma1[1:100])
par(mfrow=c(1,1))
plot(yarma1, col='blue', type='l')
abline(h=mean_yarma1+1.96*stdev_yarma1, col='red', lty=2)
abline(h=mean_yarma1-1.96*stdev_yarma1, col='red', lty=2)

# ACF for yarma1
par(mfrow=c(2,1))
acf(yarma1, lag.max=12)
pacf(yarma1, lag.max=12)