R/fit_bsts.R

Defines functions fit_bsts

Documented in fit_bsts

#' Fit a Bayesian Structural Time Series (BSTS) Model
#'
#' Fits a BSTS model for a time series y, given a vector or matrix of covariates z.
#'
#' @param y A numeric vector (time series response variable).
#' @param z A numeric vector or matrix (covariates).
#' @param lags Integer, number of lags for the autoregressive component.
#' @param MCMC.iter Integer, number of MCMC iterations.
#' @return A fitted BSTS model.
#' @importFrom bsts AddLocalLinearTrend AddDynamicRegression AddAr bsts
#' @export
#'
fit_bsts <- function(y, z, lags =0, MCMC.iter = 5000) {
  state_spec <- bsts::AddLocalLinearTrend(list(), y)
  state_spec <- bsts::AddDynamicRegression(state_spec, y ~ z)
  if(lags == 0){
    bsts_model <- bsts::bsts(y, state.specification = state_spec, niter = MCMC.iter)
  }
  else{
    state_spec <- bsts::AddAr(state_spec, y, lags = lags)
    bsts_model <- bsts::bsts(y, state.specification = state_spec, niter = MCMC.iter)
  }
  return(bsts_model)
}

Try the STCCGEV package in your browser

Any scripts or data that you put into this service are public.

STCCGEV documentation built on April 4, 2025, 1:50 a.m.