Saturday, June 22, 2019

R Code: KALMAN FILTER & ARIMA

install.packages("KFAS")
install.packages("fredr")
install.packages("forecast")

library(KFAS);library(fredr) ; library(tseries); library(forecast)


fredr_set_key("42ff06776bcf17f9a4ccfe615b72673b")

# Real GDP

RGDP<- fredr(
  series_id = "A191RO1Q156NBEA",
  observation_start = as.Date("2006-01-01")
  )

RGDP<- data.frame(RGDP$value)

# Differencing series
RGDP_diff <- diff(RGDP[,1],lag = 1, differences = 1)

# Stationarity Test after differencing
adf_RGDP_diff<- adf.test(RGDP_diff,k=0)

## KALMAN FILTER

## Defining all system matrices
# Zt and Tt corresponds to the system matrix of observation and State Equation
Zt <- matrix(c(1,0),1,2)
Tt <- matrix(c(1,0,1,1),2,2)
# Ht and Qt corresponding to the covariance matrix of observational and state equation disturbances
Ht<- matrix(NA)
Qt <- matrix(NA)
# a1 = expected values of the initial states.
a1 <- matrix(c(1,0),2,1)
# P1 = covariance matrix of the nondiffuse part of the initial state vector.
P1 <- matrix(0,2,2)
## P1inf defining the initial state distribution
# and contains the covariance matrix of the diffuse part of the initial state vector
P1inf <- diag(2)



#  SSModelonly builds the model and used as an input object for various functions like fitSSM
RGDP_diff_SSM <- SSModel(RGDP_diff ~ -1+  SSMcustom(Z = Zt, T = Tt,  Q = Qt, a1 = a1, P1 = P1,P1inf = P1inf),H = Ht)

# fitSSM to find the maximum likelihood estimates of unknown parameters
# inits = Intial values for optim.
# Method = Broyden-Fletcher-Goldfarb-Shanno (BFGS) algorithm for optim.
RGDP_diff_MLE <- fitSSM(RGDP_diff_SSM, inits = c(0, 0), method = "BFGS")

# KFS will provide us the filtering and state smoothing
RGDP_diff_FILT_SMOO <- KFS(RGDP_diff_MLE$model)

# a = One step ahead prediction of states
# att = Filtered estimates of states
# alpha = Smoothed estimates of states

RGDP_diff_Kalman <- RGDP_diff_FILT_SMOO$muhat

# ARIMA
ACF <-acf(RGDP_diff)
PACF <-pacf(RGDP_diff)
ARIMA_Fit = arima(RGDP_diff, order=c(1,0,3))

ARIMA_Fit_forecast <- forecast(ARIMA_Fit, h=1)

ARIMA_Fitted <- fitted(ARIMA_Fit)

Df<- data.frame(RGDP_diff,RGDP_diff_Kalman,ARIMA_Fitted)
cor(Df)

plot(RGDP_diff, type="l", col="black"); lines(RGDP_diff_Kalman, col="red");lines(ARIMA_Fitted,col="blue")
legend("bottom", c("RGDP","RGDP_Kalman Filter","RGDP_ARIMA"), fill=c("black","red","blue"))

No comments:

R3 chase - Pursuit

Change Point Detection Time Series

  Change Point Detection Methods Kernel Change Point Detection: Kernel change point detection method detects changes in the distribution of ...