#install.packages("fpp2")
#install.packages("tidyverse")
#install.packages("AER")
library(fpp2)
library(tidyverse)
library(AER)

# Q1
data("USMacroG", package = "AER")
autoplot(USMacroG)
co <- USMacroG[,"consumption"]
cpi <- USMacroG[,"cpi"]
summary(cpi)
boxplot(cpi)
autoplot(co)
# The series has a clear trend upwards, this makes sense as the
# consumption of the US households is tied to its disposable income and
# usually do not face high currency volatily
# nor major/prolonged economic crisis
acf(co)
Box.test(co, lag = 1, type="Ljung")
# There is a strong autocorrelation higher autocorrelation with lower lags
# meaning the data is usually highly correlated with its past timeseries
hist(co, 100, col="black")
shapiro.test(co)
# As we can see that is not normal, we proceed to transform with BoxCox
bc_lambda = BoxCox.lambda(co)
BoxCox.lambda(co)
bc_co = (BoxCox(co, bc_lambda))
autoplot(BoxCox(co, lambda=BoxCox.lambda(co)))
hist(bc_co, 100, col="black")
shapiro.test(bc_co)
# We can see that with the transformation the p-value its higher by one order of
# magnitude and still rejects the null hypothesis at 0.01, but behaves more normal.
# Q2
dpi <- USMacroG[,"dpi"]
autoplot(dpi)
dpi_growth = dpi - stats::lag(dpi, k=1)
autoplot(dpi_growth)
acf(dpi_growth)
# There is a slight trend to decrease, which also makes economical intuitive sense
# as the US economy becomes more developed the growth rate of its DPI becomes lower
# Could be said that the DPI increases with decreasing rates (Second derivative < 0)
Box.test(dpi, lag = 1, type="Ljung")
# Box Ljung test shows that p-value is very small, 10 to the power of -16 therefore
# we cannot reject the null hypothesis in favor of the alternative
# Meaning that there is autocorrelation