Using functions from R library MSGARCH in Rcpp

Hi,

I am relatively new to R coding (programming in general) and Rcpp, so excuse me if I sound naive or uninformed.

I am working on Markov switching GARCH models in R using the MSGARCH package. I want to iterate the model over different specifications of variances and distributions. In fact, I have written an R code to that effect that I shall attach in the description. I wanted to implement something similar using Rcpp package but was unable to do so.

My question is that whether I can implement R functions from packages such as MSGARCH in a .cpp file and import that code using sourceCpp() inside my main R file. Also, is it possible to use R code chunks inside of nested for-loops written in C++? If not is there any other way to implement something like this in Rcpp?

The R code is as follows:

require(MSGARCH)

variances <- c("sGARCH", "gjrGARCH") # list containing model types
distributions <- c("norm", "std", "sstd") # list containing distributions
states <- c(1, 2) # list containing number of states


## pre-define an empty dataframe to append model names and BIC values to
Model <- BIC <- rep(0, times = 12) # empty vectors of length 12 for model and BIC
comparison.df <- data.frame(Model, BIC) # empty data frame of shape 2x12


# iterate model over different specifications

for (distribution in distributions) { # iterate over three distributions

  for (variance in variances) { # iterate over two models

    for (nstate in states) { # iterate over two states

      model.name <- paste("model",
        variance, distribution, nstate,
        sep = "."
      ) # variable name for model spec assignment
      
      model.fit.name <- paste(model.name,
        "fit",
        sep = "."
      ) # variable name for model fit assignment

      model.spec <- CreateSpec(
        variance.spec = list(model = rep(variance, times = nstate)), # model spec
        distribution.spec = list(distribution = rep(distribution, times = nstate))
      )
      
      model.fit <- FitML(spec = model.spec, data = residuals.series)
        
      assign(model.name, value = model.spec)
      assign(model.fit.name, value = model.fit)
     }
  }
}

System Information:

  • RStudio Edition: Desktop
  • RStudio Version: 1.2.5042
  • OS Version: macOS Catalina 10.15.4
  • R Version: 3.6.3

Thanks,
Adi

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.