######################################################
############### Econometria Aplicada #################
######################## MA1 ######################### 
######## 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)
# Generate MA(1) with $\theta=0.5$
yma<-u[1]
for(i in 2:1000){
  yma[i]<-u[i]-0.5*u[i-1]
}
plot(yma, type='l', col='blue')

# Scatter plot between the series and it's lags, idea of temporal dependence
par(mfrow=c(3,1))
plot(embed(yma,2)[,c(2,1)], col='blue') # Y and Y(-1)
plot(embed(yma,3)[,c(3,1)], col='blue') # Y and Y(-2)
plot(embed(yma,20)[,c(20,1)], col='blue') # Y and Y(-20)

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

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

# teste normalidade usando Jarque Bera

jarque.bera.test(yma)
## 
##  Jarque Bera Test
## 
## data:  yma
## X-squared = 1.2014, df = 2, p-value = 0.5484
# Test for constant mean and variance
mean_yma<-mean(yma[1:100])
stdev_yma<-sd(yma[1:100])
plot(yma, type='l', col='blue')
abline(h=mean_yma+1.96*stdev_yma, col='red', lty=2)
abline(h=mean_yma-1.96*stdev_yma, col='red', lty=2)

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