######################################################
############### 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 r=-0.5
yma8<-u[1]
for(i in 2:1000){
yma8[i]<-u[i]-0.8*u[i-1]
}
plot(yma8, type='l', col='blue')

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

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

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

# teste normalidade usando Jarque Bera
jarque.bera.test(yma8)
##
## Jarque Bera Test
##
## data: yma8
## X-squared = 1.401, df = 2, p-value = 0.4963
# Test for constant mean and variance
mean_yma8<-mean(yma8[1:100])
stdev_yma8<-sd(yma8[1:100])
plot(yma8, type='l', col='blue')
abline(h=mean_yma8+1.96*stdev_yma8, col='red', lty=2)
abline(h=mean_yma8-1.96*stdev_yma8, col='red', lty=2)

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