if (FALSE) {
# Specify an univariate GAS model with Student-t
# conditional distribution and time-varying scale.
library("GAS")
data("sp500ret")
GASSpec = UniGASSpec(Dist = "std", ScalingType = "Identity",
GASPar = list(location = FALSE, scale = TRUE,
shape = FALSE))
Fit = UniGASFit(GASSpec, sp500ret)
Fit
# Estimate the model with a different optimizer.
# Assume we want to use the Nelder and Mead optimization provided by
# the optim() function, we create
# the wrapper fn.NM.optim in this way
fn.NM.optim <- function(par0, data, GASSpec, FUN) {
optimizer = optim(par0, FUN, data = data, GASSpec = GASSpec, method = "Nelder-Mead",
control = list(trace = 0), hessian = TRUE)
out = list(pars = optimizer$par,
value = optimizer$value,
hessian = optimizer$hessian,
convergence = optimizer$convergence)
return(out)
}
Fit.NM.optim = UniGASFit(GASSpec, sp500ret, fn.optimizer = fn.NM.optim )
Fit.NM.optim
# Estimate time-varying Negative Binomial distribution for the Goals dataset.
# Let's use the gosolnp() optimizer for the time-varying model estimation and
# the solnp() optimizer for estimation of the static model for the choice of
# the starting values. The logical is(GASSpec, "list") is TRUE when the function
# is evaluated for the choice of starting values, and FALSE when the function
# is evaluated for the time-varying model.
# We can also make use of parallel computation calling a cluster object defined
# in the Global environment.
library("Rsolnp")
fn.gosolnp <- function(par0, data, GASSpec, FUN) {
if (is(GASSpec, "list")) {
optimiser = suppressWarnings(solnp(par0, FUN, data = data,
GASSpec = GASSpec,
control = list(trace = 0)))
} else {
cluster = get("cluster", envir = globalenv())
optimiser = suppressWarnings(gosolnp(
pars = NULL,
fun = FUN, data = data, cluster = cluster,
GASSpec = GASSpec,
n.sim = 100000,
n.restarts = 10,
LB = c(-5, -2, -2, -2),
UB = c(5, 8, 3.0, 5.0))
)
}
out = list(pars = optimiser$pars,
value = tail(optimiser$values, 1),
hessian = optimiser$hessian,
convergence = optimiser$convergence)
return(out)
}
data("Goals")
library("parallel")
cluster = makeCluster(2)
GASSpec = UniGASSpec(Dist = "negbin", ScalingType = "Inv",
GASPar = list(location = TRUE, scale = FALSE))
vY = na.omit(Goals[, 1])
Fit = UniGASFit(GASSpec, vY, fn.optimizer = fn.gosolnp)
Fit
stopCluster(cluster)
rm("cluster")
}
Run the code above in your browser using DataLab