Title: | Bayesian Time Series Modeling with Stan |
---|---|
Description: | Fit Bayesian time series models using 'Stan' for full Bayesian inference. A wide range of distributions and models are supported, allowing users to fit Seasonal ARIMA, ARIMAX, Dynamic Harmonic Regression, GARCH, t-student innovation GARCH models, asymmetric GARCH, Random Walks, stochastic volatility models for univariate time series. Prior specifications are flexible and explicitly encourage users to apply prior distributions that actually reflect their beliefs. Model fit can easily be assessed and compared with typical visualization methods, information criteria such as loglik, AIC, BIC WAIC, Bayes factor and leave-one-out cross-validation methods. References: Hyndman (2017) <doi:10.18637/jss.v027.i03>; Carpenter et al. (2017) <doi:10.18637/jss.v076.i01>. |
Authors: | Asael Alonzo Matamoros [aut, cre], Cristian Cruz Torres [aut], Andres Dala [ctb], Rob Hyndman [ctb], Mitchell O'Hara-Wild [ctb] |
Maintainer: | Asael Alonzo Matamoros <[email protected]> |
License: | GPL-2 |
Version: | 1.0.1 |
Built: | 2025-01-24 07:20:29 UTC |
Source: | CRAN |
Fit univariate time series models using 'Stan' for full Bayesian inference. A wide range of distributions and models are supported, allowing users to fit Seasonal ARIMA, ARIMAX, Dynamic Harmonic Regression, GARCH, t-student innovation GARCH models, asymmetric GARCH, Random Walks, and stochastic volatility models. Prior specifications are flexible and explicitly encourage users to apply prior distributions that actually reflect their beliefs. Model fit can easily be assessed and compared with typical visualization methods, information criteria such as loglik, AIC, BIC WAIC, Bayes factor and leave-one-out cross-validation methods.
Carpenter, B. and Gelman, A. and Hoffman, D. and Lee, D. and Goodrich, B. and
Betancourt, M. and Brubaker, and Guo, L. and Riddell. 2017. Stan: A probabilistic
programming language. Journal of Statistical Software 76(1).
doi: 10.18637/jss.v076.i01
.
Stan Development Team. (2018). Stan Modeling Language Users Guide and Reference Manual,
Version 2.18.0. url: https://mc-stan.org
.
Hyndman, R. & Khandakar, Y. (2008). Automatic time series forecasting: the
forecast package for R
. Journal of Statistical Software. 26(3),
1-22.doi: 10.18637/jss.v027.i03
.
Tsay, R (2010). Analysis of Financial Time Series. Wiley-Interscience. 978-0470414354, second edition.
Shumway, R.H. and Stoffer, D.S. (2010).Time Series Analysis and Its Applications: With R Examples. Springer Texts in Statistics. isbn: 9781441978646. First edition.
Convenience function for computing the pointwise Akaike Information Criteria method from a varstan object.
aic(x)
aic(x)
x |
A varstan object of the time series fitted model. |
A numeric array of size R, containing the posterior samples of the AICc for a varstan object, where R is the number of iterations. If multiple chains are fitted, then the array is of length M*R, where M is the number of chains
Asael Alonzo Matamoros
library(astsa) model = Sarima(birth,order = c(0,1,2),seasonal = c(1,1,1)) fit1 = varstan(model,iter = 500,chains = 1) aic1 = aic(fit1) mean(aic1)
library(astsa) model = Sarima(birth,order = c(0,1,2),seasonal = c(1,1,1)) fit1 = varstan(model,iter = 500,chains = 1) aic1 = aic(fit1) mean(aic1)
Convenience function for computing the pointwise corrected Akaike Information Criteria method from a varstan object.
AICc(x)
AICc(x)
x |
A varstan object of the time series fitted model. |
A numeric array of size R, containing the posterior samples of the AICc for a varstan object, where R is the number of iterations. If multiple chains are fitted, then the array is of length M*R, where m is the number of chains
Asael Alonzo Matamoros
library(astsa) model = Sarima(birth,order = c(0,1,2),seasonal = c(1,1,1)) fit1 = varstan(model,iter = 500,chains = 1) aic1 = AICc(fit1) mean(aic1)
library(astsa) model = Sarima(birth,order = c(0,1,2),seasonal = c(1,1,1)) fit1 = varstan(model,iter = 500,chains = 1) aic1 = AICc(fit1) mean(aic1)
Total annual air passengers (in millions) including domestic and international aircraft passengers of air carriers registered in Australia. 1970-2016.
air
air
the format is: Annual Time-Series (1:27) from 1990 to 2016:
fpp2
Hyndman, R. & Khandakar, Y. (2008). Automatic time series forecasting: the
forecast package for R
. Journal of Statistical Software. 26(3),
1-22.doi: 10.18637/jss.v027.i03
Convert a varstan
object to a stanfit
object of the
rstan package.
as.stan(object)
as.stan(object)
object |
a varstan object. |
a stanfit object.
Asael Alonzo Matamoros
# Fitting a GARCH(1,1) model dat = garch(ipc,order = c(1,1,0)) fit1 = varstan(dat,iter = 500,chains = 1) # Converting to a Stanfit object stanfit1 = as.stan(fit1)
# Fitting a GARCH(1,1) model dat = garch(ipc,order = c(1,1,0)) fit1 = varstan(dat,iter = 500,chains = 1) # Converting to a Stanfit object stanfit1 = as.stan(fit1)
Quarterly visitor nights (in millions) spent by international tourists to Australia. 1999-2015
aust
aust
the format is: Quarterly Time-Series (1:44) from 1999 to 2015:
fpp2
Hyndman, R. & Khandakar, Y. (2008). Automatic time series forecasting: the
forecast package for R
. Journal of Statistical Software. 26(3),
1-22.doi: 10.18637/jss.v027.i03
Returns the best seasonal ARIMA model using a bic
value, this
function theauto.arima
function of the forecast package
to select the seasonal ARIMA model and estimates the model using a
HMC sampler.
auto.sarima(ts,seasonal = TRUE,xreg = NULL,chains=4,iter=4000,warmup=floor(iter/2), adapt.delta = 0.9,tree.depth =10,stepwise = TRUE, series.name = NULL, prior_mu0 = NULL,prior_sigma0 = NULL,prior_ar = NULL, prior_ma = NULL, prior_sar = NULL,prior_sma = NULL, prior_breg = NULL,...)
auto.sarima(ts,seasonal = TRUE,xreg = NULL,chains=4,iter=4000,warmup=floor(iter/2), adapt.delta = 0.9,tree.depth =10,stepwise = TRUE, series.name = NULL, prior_mu0 = NULL,prior_sigma0 = NULL,prior_ar = NULL, prior_ma = NULL, prior_sar = NULL,prior_sma = NULL, prior_breg = NULL,...)
ts |
a numeric or ts object with the univariate time series. |
seasonal |
optionally, a logical value for seasonal ARIMA models.
By default |
xreg |
Optionally, a numerical matrix of external regressors, which must have the same number of rows as ts. It should not be a data frame. |
chains |
An integer of the number of Markov Chains chains to be run, by default 4 chains are run. |
iter |
An integer of total iterations per chain including the warm-up, by default the number of iterations are 2000. |
warmup |
A positive integer specifying number of warm-up (aka burn-in)
iterations. This also specifies the number of iterations used for step-size
adaptation, so warm-up samples should not be used for inference. The number
of warmup should not be larger than |
adapt.delta |
An optional real value between 0 and 1, the thin of the jumps in a HMC method. By default is 0.9. |
tree.depth |
An integer of the maximum depth of the trees evaluated during each iteration. By default is 10. |
stepwise |
If TRUE, will do stepwise selection (faster). Otherwise, it searches over all models. Non-stepwise selection can be very slow, especially for seasonal models. |
series.name |
an optional string vector with the series names. |
prior_mu0 |
The prior distribution for the location parameter in an ARIMA model. By default
the value is set |
prior_sigma0 |
The prior distribution for the scale parameter in an ARIMA model. By default
the value is set |
prior_ar |
The prior distribution for the auto-regressive parameters in an ARIMA model.
By default the value is set |
prior_ma |
The prior distribution for the moving average parameters in an ARIMA model.
By default the value is set |
prior_sar |
The prior distribution for the seasonal auto-regressive parameters in a
SARIMA model. By default the value is set |
prior_sma |
The prior distribution for the seasonal moving average parameters in a
SARIMA model. By default the value is set |
prior_breg |
The prior distribution for the regression coefficient parameters in a
ARIMAX model. By default the value is set |
... |
Further arguments passed to |
Automatic ARIMA model fitting implemented by Rob Hyndman, this function finds the best
Seasonal ARIMA model using bic
, and then proceeds to fit the model using
varstan
function and the default priors of a Sarima
model constructor.
This function provides an initial model fit for beginning the Bayesian analysis
of the univariate time series. For better fit and model selection try different
models and other model selection criteria such as loo
or bayes_factor
.
The default arguments are designed for rapid estimation of models for many time series.
If you are analyzing just one time series, and can afford to take some more time, it is
recommended that you set stepwise
=FALSE
and reduce the number of iterations
per chain (iter
).
For more information look at auto.arima()
function of forecast package.
A varstan object with the "best" fitted ARIMA model to the data
Asael Alonzo Matamoros
Hyndman, R. & Khandakar, Y. (2008). Automatic time series forecasting: the
forecast package for R
. Journal of Statistical Software. 26(3),
1-22.doi: 10.18637/jss.v027.i03
.
Box, G. E. P. and Jenkins, G.M. (1978). Time series analysis: Forecasting and
control. San Francisco: Holden-Day. Biometrika, 60(2), 297-303.
doi:10.1093/biomet/65.2.297
.
Kennedy, P. (1992). Forecasting with dynamic regression models: Alan Pankratz, 1991.
International Journal of Forecasting. 8(4), 647-648.
url: https://EconPapers.repec.org/RePEc:eee:intfor:v:8:y:1992:i:4:p:647-648
.
Sarima
varstan
.
# Automatic Sarima model for the birth data auto.sarima(birth,iter = 500,chains = 1) # Dynamic Harmonic regression auto.sarima(birth,xreg = fourier(birth,K= 6),iter = 500,chains = 1)
# Automatic Sarima model for the birth data auto.sarima(birth,iter = 500,chains = 1) # Dynamic Harmonic regression auto.sarima(birth,xreg = fourier(birth,K= 6),iter = 500,chains = 1)
autoplot
takes an object of type ts
or mts
and creates
a ggplot object suitable for usage with stat_forecast
.
## S3 method for class 'ts' autoplot( object, series = NULL, xlab = "Time", ylab = deparse(substitute(object)), main = NULL, facets = FALSE, colour = TRUE, ... ) ## S3 method for class 'ts' fortify(model, data, ...)
## S3 method for class 'ts' autoplot( object, series = NULL, xlab = "Time", ylab = deparse(substitute(object)), main = NULL, facets = FALSE, colour = TRUE, ... ) ## S3 method for class 'ts' fortify(model, data, ...)
object |
Object of class “ |
series |
Identifies the time series with a colour, which integrates well with the functionality of geom_forecast. |
xlab |
a string with the plot's x axis label. By default a NUll value. |
ylab |
a string with the plot's y axis label. By default a counts" value. |
main |
a string with the plot's title. |
facets |
If TRUE, multiple time series will be faceted (and unless specified, colour is set to FALSE). If FALSE, each series will be assigned a colour. |
colour |
If TRUE, the time series will be assigned a colour aesthetic |
... |
Other plotting parameters to affect the plot. |
model |
Object of class “ |
data |
Not used (required for fortify method) |
fortify.ts
takes a ts
object and converts it into a data frame
(for usage with ggplot2).
None. Function produces a ggplot2 graph.
Mitchell O'Hara-Wild.
library(ggplot2) autoplot(USAccDeaths) lungDeaths <- cbind(mdeaths, fdeaths) autoplot(lungDeaths) autoplot(lungDeaths, facets=TRUE)
library(ggplot2) autoplot(USAccDeaths) lungDeaths <- cbind(mdeaths, fdeaths) autoplot(lungDeaths) autoplot(lungDeaths, facets=TRUE)
Preliminary autoplot methods for varstan models only valid for univariate time series models. The function prints the fitted values time series, the trace and density plots for the sampled model parameters, or the residuals' posterior mean time series.
## S3 method for class 'varstan' autoplot(object, prob = 0.95, ...)
## S3 method for class 'varstan' autoplot(object, prob = 0.95, ...)
object |
An object of class |
prob |
A number |
... |
Further arguments passed to |
None. Function produces a ggplot2 graph.
library(astsa) sf1 = auto.sarima(ts = birth,iter = 500,chains = 1) # fitted model autoplot(sf1)
library(astsa) sf1 = auto.sarima(ts = birth,iter = 500,chains = 1) # fitted model autoplot(sf1)
Compute Bayes factors from marginal likelihoods.
## S3 method for class 'varstan' bayes_factor(x1, x2, log = FALSE, ...)
## S3 method for class 'varstan' bayes_factor(x1, x2, log = FALSE, ...)
x1 |
A |
x2 |
Another |
log |
A boolean parameter for report the Bayes_factor in log scale. The default value is FALSE. |
... |
Additional arguments passed to |
The computation of marginal likelihoods based on bridge sampling requires
a lot more posterior samples than usual. A good conservative rule of thump
is perhaps 10-fold more samples (read: the default of 4000 samples may not
be enough in many cases). If not enough posterior samples are provided, the
bridge sampling algorithm tends to be unstable leading to considerably different
results each time it is run. We thus recommend running bridge_sampler
multiple times to check the stability of the results.
For more details check the bridgesampling package.
The bayes factors of two models.
library(astsa) # Fitting a seasonal arima model mod1 = Sarima(birth,order = c(0,1,2),seasonal = c(1,1,1)) fit1 = varstan(mod1,iter = 500,chains = 1) # Fitting a Dynamic harmonic regression mod2 = Sarima(birth,order = c(0,1,2),xreg = fourier(birth,K=6)) fit2 = varstan(mod2,iter = 500,chains = 1) # compute the Bayes factor bayes_factor(fit1, fit2)
library(astsa) # Fitting a seasonal arima model mod1 = Sarima(birth,order = c(0,1,2),seasonal = c(1,1,1)) fit1 = varstan(mod1,iter = 500,chains = 1) # Fitting a Dynamic harmonic regression mod2 = Sarima(birth,order = c(0,1,2),xreg = fourier(birth,K=6)) fit2 = varstan(mod2,iter = 500,chains = 1) # compute the Bayes factor bayes_factor(fit1, fit2)
beta(shape1,shape2)
beta(shape1 = 2, shape2 = 2)
beta(shape1 = 2, shape2 = 2)
shape1 |
the first form parameter |
shape2 |
the second form parameter |
Define a beta prior distribution using the hyper parameters shape1 and shape2, by default a beta(2,2) distribution is return.
a numerical vector interpreted as a prior in Stan
Convenience function for computing the pointwise Bayesian Information Criteria method from a varstan object.
bic(x)
bic(x)
x |
A varstan object of the time series fitted model. |
A numeric array of size R, containing the posterior samples of the aic for a varstan object, where R is the number of iterations. If multiple chains are fitted, then the array is of length M*R, where M is the number of chains
Asael Alonzo Matamoros
library(astsa) model = Sarima(birth,order = c(0,1,2),seasonal = c(1,1,1)) fit1 = varstan(model,iter = 500,chains = 1) bic1 = bic(fit1) mean(bic1)
library(astsa) model = Sarima(birth,order = c(0,1,2),seasonal = c(1,1,1)) fit1 = varstan(model,iter = 500,chains = 1) bic1 = bic(fit1) mean(bic1)
Monthly live births (adjusted) in thousands for the United States, 1948-1979.
birth
birth
the format is: Time-Series (1:373) from 1948 to 1979:
astsa
http://www.stat.pitt.edu/stoffer/tsa4/ http://www.stat.pitt.edu/stoffer/tsda/
Computes log marginal likelihood via bridge sampling, which can be used in the computation of Bayes factors and posterior model probabilities.
## S3 method for class 'varstan' bridge_sampler(samples, ...)
## S3 method for class 'varstan' bridge_sampler(samples, ...)
samples |
A |
... |
Additional arguments passed to
|
The varstan
class is just a thin wrapper that
contains the stanfit
objects.
Computing the marginal likelihood via the bridgesampler package for stanfit objects.
The computation of marginal likelihoods based on bridge sampling requires
a lot more posterior samples than usual. A good conservative rule of thump
is perhaps 10-fold more samples (read: the default of 4000 samples may not
be enough in many cases). If not enough posterior samples are provided, the
bridge sampling algorithm tends to be unstable leading to considerably different
results each time it is run. We thus recommend running bridge_sampler
multiple times to check the stability of the results.
For more details check the bridgesampling package.
the model's marginals likelihood from the bridge_sampler
package.
library(astsa) # Fitting a seasonal ARIMA model mod1 = Sarima(birth,order = c(0,1,2),seasonal = c(1,1,1)) fit1 = varstan(mod1,iter = 500,chains = 1) fit1 bridge_sampler(fit1) # Fitting a Dynamic harmonic regression mod2 = Sarima(birth,order = c(0,1,2),xreg = fourier(birth,K=6)) fit2 = varstan(mod2,iter = 500,chains = 1) fit2 bridge_sampler(fit2)
library(astsa) # Fitting a seasonal ARIMA model mod1 = Sarima(birth,order = c(0,1,2),seasonal = c(1,1,1)) fit1 = varstan(mod1,iter = 500,chains = 1) fit1 bridge_sampler(fit1) # Fitting a Dynamic harmonic regression mod2 = Sarima(birth,order = c(0,1,2),xreg = fourier(birth,K=6)) fit2 = varstan(mod2,iter = 500,chains = 1) fit2 bridge_sampler(fit2)
cauchy(mu,sd)
cauchy(mu = 0, sd = 1)
cauchy(mu = 0, sd = 1)
mu |
the location parameter mu |
sd |
the standard deviation parameter sigma |
Define a Cauchy prior distribution using the hyper parameters mu and sigma, by default a standard Cauchy(0,1) distribution is return.
a numerical vector interpreted as a prior in Stan
varstan
object.Performs a visual check of residuals in time series models, this method is inspired in
the check.residuals
function provided by the forecast
package.
check_residuals(object, ...)
check_residuals(object, ...)
object |
a varstan object. |
... |
Other plotting parameters to affect the plot. |
None. Function produces a ggplot2 graph.
Asael Alonzo Matamoros.
library(astsa) sf1 = auto.sarima(ts = birth,iter = 500,chains = 1) # fitted model check_residuals(sf1)
library(astsa) sf1 = auto.sarima(ts = birth,iter = 500,chains = 1) # fitted model check_residuals(sf1)
chisq(df)
chisq(df = 7)
chisq(df = 7)
df |
the degree freedom parameter df |
Define a gamma prior distribution using the degree freedom df hyper parameter, by default an chisq(7) distribution is return.
a numerical vector interpreted as a prior in Stan
The vector dem2gbp contains daily observations of the Deutschmark vs British Pound foreign exchange rate log-returns. This data set has been promoted as an informal benchmark for GARCH time-series software validation. See McCullough and Renfro (1999), and Brooks, Burke, and Persand (2001) for details. The nominal returns are expressed in percent as in Bollerslev and Ghysels (1996). The sample period is from January 3, 1984, to December 31, 1991, for a total of 1974 observations.
demgbp
demgbp
the format is: Time-Series (1:350) from 1984 to 1985:
bayesGARCH
Engle, R. (1982). Autoregressive Conditional Heteroscedasticity with Estimates of
the Variance of United Kingdom Inflation. Econometrica, 50(4), 987-1007.
url: http://www.jstor.org/stable/1912773
.
Bollerslev, T. (1986). Generalized autoregressive conditional heteroskedasticity.
Journal of Econometrics. 31(3), 307-327.
doi: https://doi.org/10.1016/0304-4076(86)90063-1
.
Ardia, D. and Hoogerheide, L. (2010). Bayesian Estimation of the GARCH(1,1) Model
with Student-t Innovations. The R Journal. 2(7), 41-47.
doi: 10.32614/RJ-2010-014
.
exponential(rate)
exponential(rate = 1)
exponential(rate = 1)
rate |
the rate parameter lambda in exponential distribution |
Define a gamma prior distribution using the rate hyper parameter, by default an exponential(1) distribution is return.
a numerical vector interpreted as a prior in Stan
Extract chains of an stanfit object implemented in rstan package
extract_stan(object,pars,permuted = TRUE,inc_warmup = FALSE,include = TRUE, ...)
extract_stan(object,pars,permuted = TRUE,inc_warmup = FALSE,include = TRUE, ...)
object |
a varstan object |
pars |
n optional character vector providing the parameter names (or other quantity names) of interest. If not specified, all parameters and other quantities are used. The log-posterior with name lp__ is also included by default. |
permuted |
A logical scalar indicating whether the draws after the warmup period in each chain should be permuted and merged. If FALSE, the original order is kept. For each stanfit object, the permutation is fixed (i.e., extracting samples a second time will give the same sequence of iterations). |
inc_warmup |
A logical scalar indicating whether to include the warmup draws. This argument is only relevant if permuted is FALSE. |
include |
A logical scalar indicating whether the parameters named in pars should be included (TRUE) or excluded (FALSE). |
... |
Further arguments passed to |
a list with the posterior samples of the provided parameters.
Asael Alonzo Matamoros
library(astsa) # Fitting a GARCH(1,1) model dat = garch(ipc,order = c(1,1,0)) fit2 = varstan(dat,iter = 500,chains = 1) # Extracting the mean parameter mu0 = extract_stan(fit2,pars = "mu0")
library(astsa) # Fitting a GARCH(1,1) model dat = garch(ipc,order = c(1,1,0)) fit2 = varstan(dat,iter = 500,chains = 1) # Extracting the mean parameter mu0 = extract_stan(fit2,pars = "mu0")
The function returns the posterior estimate of the fitted values
of a varstan
model, similar to the fit_values functions of other
packages.
## S3 method for class 'varstan' fitted(object, robust = FALSE, ...)
## S3 method for class 'varstan' fitted(object, robust = FALSE, ...)
object |
A varstan object, |
robust |
A boolean value, if its |
... |
Further arguments passed to |
This function returns a time series of the predicted mean response values.
A time series (ts)
of predicted mean response values.
Asael Alonzo Matamoros
forecast
is a generic function for forecasting from time series or
varstan models. The function invokes particular methods which
depend on the class of the first argument.
## S3 method for class 'varstan' forecast( object, h = 10, probs = c(0.8, 0.9), xreg = NULL, robust = FALSE, draws = 1000, seed = NULL, ... )
## S3 method for class 'varstan' forecast( object, h = 10, probs = c(0.8, 0.9), xreg = NULL, robust = FALSE, draws = 1000, seed = NULL, ... )
object |
a time series or varstan model for which forecasts are required. |
h |
Number of periods for forecasting. |
probs |
A numerical vector |
xreg |
Optionally, a numerical matrix of external regressors, which must have the same number of rows as ts. It should not be a data frame. |
robust |
A boolean for obtain the robust estimation. The default |
draws |
An integer indicating the number of draws to return. The default number of draws is 1000. |
seed |
An optional |
... |
Further arguments passed to |
If model=NULL
,the function forecast.ts
makes forecasts
using ets
models (if the data are non-seasonal or the seasonal
period is 12 or less) or stlf
(if the seasonal period is 13 or
more).
If model
is not NULL
, forecast.ts
will apply the
model
to the object
time series, and then generate forecasts
accordingly.
An object of class "forecast
".
The function summary
is used to obtain and print a summary of the
results, while the function plot
produces a plot of the forecasts and
prediction intervals.
The generic accessors functions fitted.values
and residuals
extract various useful features of the value returned by
forecast$model
.
An object of class "forecast"
is a list usually containing at least
the following elements:
model |
A list containing information about the fitted model |
method |
The name of the forecasting method as a character string |
mean |
Point forecasts as a time series |
lower |
Lower limits for prediction intervals |
upper |
Upper limits for prediction intervals |
level |
The confidence values associated with the prediction intervals |
x |
The original time series
(either |
residuals |
Residuals from the fitted model. For models with additive errors, the residuals will be x minus the fitted values. |
fitted |
Fitted values (one-step forecasts) |
Asael Alonzo Matamoros.
The "forecast"
methods of the forecast package.
fit = auto.sarima(ts = birth,iter = 500,chains = 1) fc = forecast(fit,h = 12)
fit = auto.sarima(ts = birth,iter = 500,chains = 1) fc = forecast(fit,h = 12)
fourier
returns a matrix containing terms from a Fourier series, up
to order K
, suitable for use in Sarima
or
auto.sarima
.
fourier(x, K, h = NULL)
fourier(x, K, h = NULL)
x |
Seasonal time series: a |
K |
Maximum order(s) of Fourier terms |
h |
Number of periods ahead to forecast (optional) |
The period of the Fourier terms is determined from the time series
characteristics of x
. When h
is missing, the length of
x
also determines the number of rows for the matrix returned by
fourier
. Otherwise, the value of h
determines the number of
rows for the matrix returned by fourier
, typically used for
forecasting. The values within x
are not used.
Typical use would omit h
when generating Fourier terms fitting a model
and include h
when generating Fourier terms for forecasting.
When x
is a ts
object, the value of K
should be an
integer and specifies the number of sine and cosine terms to return. Thus,
the matrix returned has 2*K
columns.
When x
is a msts
object, then K
should be a vector of
integers specifying the number of sine and cosine terms for each of the
seasonal periods. Then the matrix returned will have 2*sum(K)
columns.
Numerical matrix.
Rob J Hyndman
library(astsa) # Dynaimc Harmonic regression sf1 = auto.sarima(birth,xreg = fourier(birth,K= 6),iter = 500,chains = 1)
library(astsa) # Dynaimc Harmonic regression sf1 = auto.sarima(birth,xreg = fourier(birth,K= 6),iter = 500,chains = 1)
gamma(shape,rate)
gamma(shape = 2, rate = 1)
gamma(shape = 2, rate = 1)
shape |
the form parameter alpha in gamma distribution |
rate |
the rate parameter beta in gamma distribution |
Define a gamma prior distribution using the hyper parameters shape and rate, by default an gamma(2,1) distribution is return.
a numerical vector interpreted as a prior in Stan
Constructor of the GARCH(s,k,h)
object for Bayesian estimation in Stan.
garch(ts,order = c(1,1,0),arma = c(0,0),xreg = NULL, genT = FALSE,asym = "none",series.name = NULL)
garch(ts,order = c(1,1,0),arma = c(0,0),xreg = NULL, genT = FALSE,asym = "none",series.name = NULL)
ts |
a numeric or ts object with the univariate time series. |
order |
A specification of the garch model: the three components (s, k, h) are the arch order, the garch order, and the mgarch order. |
arma |
A specification of the ARMA model,same as order parameter: the two components (p, q) are the AR order,and the MA order. |
xreg |
Optionally, a numerical matrix of external regressors, which must have the same number of rows as ts. It should not be a data frame. |
genT |
a boolean value to specify for a generalized t-student garch model. |
asym |
a string value for the asymmetric function for an asymmetric GARCH process. By default
the value |
series.name |
an optional string vector with the time series names. |
The function returns a list with the data for running stan()
function of
rstan package.
By default the garch()
function generates a GARCH(1,1) model, when
genT
option is TRUE
a t-student innovations GARCH model
(see Ardia (2010)) is generated, and for Asymmetric GARCH models use the
option asym
for specify the asymmetric function, see Fonseca,
et. al (2019) for more details.
The default priors used in a GARCH(s,k,h) model are:
ar ~ normal(0,0.5)
ma ~ normal(0,0.5)
mu0 ~ t-student(0,2.5,6)
sigma0 ~ t-student(0,1,7)
arch ~ normal(0,0.5)
garch ~ normal(0,0.5)
mgarch ~ normal(0,0.5)
dfv ~ gamma(2,0.1)
breg ~ t-student(0,2.5,6)
For changing the default prior use the function set_prior()
.
The function returns a list with the data for running stan()
function of
rstan package.
Asael Alonzo Matamoros.
Engle, R. (1982). Autoregressive Conditional Heteroscedasticity with Estimates of
the Variance of United Kingdom Inflation. Econometrica, 50(4), 987-1007.
url: http://www.jstor.org/stable/1912773
.
Bollerslev, T. (1986). Generalized autoregressive conditional heteroskedasticity.
Journal of Econometrics. 31(3), 307-327.
doi: https://doi.org/10.1016/0304-4076(86)90063-1
.
Fonseca, T. and Cequeira, V. and Migon, H. and Torres, C. (2019). The effects of
degrees of freedom estimation in the Asymmetric GARCH model with Student-t
Innovations. arXiv doi: arXiv: 1910.01398
.
Ardia, D. and Hoogerheide, L. (2010). Bayesian Estimation of the GARCH(1,1) Model
with Student-t Innovations. The R Journal. 2(7), 41-47.
doi: 10.32614/RJ-2010-014
.
# Declaring a garch(1,1) model for the ipc data. dat = garch(ipc,order = c(1,1,0)) dat # Declaring a t-student M-GARCH(2,3,1)-ARMA(1,1) process for the ipc data. dat = garch(ipc,order = c(2,3,1),arma = c(1,1),genT = TRUE) dat # Declaring a logistic Asymmetric GARCH(1,1) process. dat = garch(ipc,order = c(1,1,0),asym = "logit") dat
# Declaring a garch(1,1) model for the ipc data. dat = garch(ipc,order = c(1,1,0)) dat # Declaring a t-student M-GARCH(2,3,1)-ARMA(1,1) process for the ipc data. dat = garch(ipc,order = c(2,3,1),arma = c(1,1),genT = TRUE) dat # Declaring a logistic Asymmetric GARCH(1,1) process. dat = garch(ipc,order = c(1,1,0),asym = "logit") dat
Get the sampled parameters of a varstan object.
get_parameters(object)
get_parameters(object)
object |
a varstan object |
a vector with the sampled parameters
Asael Alonzo Matamoros
library(astsa) sf1 = auto.sarima(birth,iter = 500,chains = 1) get_parameters(sf1)
library(astsa) sf1 = auto.sarima(birth,iter = 500,chains = 1) get_parameters(sf1)
The functions gets the defined distribution of a defined model parameter
get_prior(model,par,lag = 0)
get_prior(model,par,lag = 0)
model |
a time series model class specified in varstan. |
par |
a string value with the desired parameter which a prior is defined could be: "mu0", "sigma0", "ar", "ma", "arch", "garch", "mgarch", "dfv", "df", "LKJ" or "breg". |
lag |
an optional integer value, indicates the desired lag of the parameter which the prior is defined if lag = 0, then the prior distribution will be applied for all lags |
None. Prints the prior distribution of a desired parameter.
Asael Alonzo Matamoros
library(astsa) # get all the ar parameters dat = Sarima(birth,order = c(2,1,2)) get_prior(model = dat,par = "ar") # change the mean constant parameter dat = set_prior(model = dat,par = "mu0",dist = student(0,2.5,7)) get_prior(dat,par = "mu0") # change and print only the second ma parameter dat = set_prior(model = dat,par = "ma",dist = beta(2,2),lag = 2) get_prior(dat,par = "ma")
library(astsa) # get all the ar parameters dat = Sarima(birth,order = c(2,1,2)) get_prior(model = dat,par = "ar") # change the mean constant parameter dat = set_prior(model = dat,par = "mu0",dist = student(0,2.5,7)) get_prior(dat,par = "mu0") # change and print only the second ma parameter dat = set_prior(model = dat,par = "ma",dist = beta(2,2),lag = 2) get_prior(dat,par = "ma")
acf
plotPlot of the auto-correlation function for a univariate time series.
ggacf(y, title = NULL)
ggacf(y, title = NULL)
y |
a numeric vector or an object of the |
title |
a string with the plot's title. |
None. Function produces a ggplot2 graph.
Asael Alonzo Matamoros
x = rnorm(100) ggacf(x)
x = rnorm(100) ggacf(x)
Plots a histogram and density estimates using ggplot.
gghist(y, title = NULL, xlab = NULL, ylab = "counts", bins, add.normal = TRUE)
gghist(y, title = NULL, xlab = NULL, ylab = "counts", bins, add.normal = TRUE)
y |
a numeric vector or an object of the |
title |
a string with the plot's title. |
xlab |
a string with the plot's x axis label. By default a NUll value |
ylab |
a string with the plot's y axis label. By default a "counts" value |
bins |
The number of bins to use for the histogram. Selected by default using the Friedman-Diaconis rule. |
add.normal |
A boolean value. Add a normal density function for comparison,
by default |
None. Function produces a ggplot2 graph.
Rob J Hyndman
x = rnorm(100) gghist(x,add.normal = TRUE)
x = rnorm(100) gghist(x,add.normal = TRUE)
qqplot
with normal qqline
Plot the quantile-quantile plot and quantile-quantile line using ggplot.
ggnorm(y, title = NULL, add.normal = TRUE)
ggnorm(y, title = NULL, add.normal = TRUE)
y |
a numeric vector or an object of the |
title |
a string with the plot's title. |
add.normal |
Add a normal density function for comparison. |
None. Function produces a ggplot2 graph.
Asael Alonzo Matamoros
x = rnorm(100) ggnorm(x)
x = rnorm(100) ggnorm(x)
pacf
plot.Plot of the partial autocorrelation function for a univariate time series.
ggpacf(y, title = NULL)
ggpacf(y, title = NULL)
y |
a numeric vector or an object of the |
title |
a string with the plot's title. |
None.
Mitchell O'Hara-Wild and Asael Alonzo Matamoros
x = rnorm(100) ggpacf(x)
x = rnorm(100) ggpacf(x)
Constructor of the ets("A","A","Z")
object for Bayesian estimation in Stan.
Holt(ts,damped = FALSE,xreg = NULL,genT = FALSE,series.name = NULL)
Holt(ts,damped = FALSE,xreg = NULL,genT = FALSE,series.name = NULL)
ts |
a numeric or ts object with the univariate time series. |
damped |
a boolean value to specify a damped trend local level model. By default
is |
xreg |
Optionally, a numerical matrix of external regressors, which must have the same number of rows as ts. It should not be a data frame. |
genT |
a boolean value to specify for a generalized t-student SSM model. |
series.name |
an optional string vector with the time series names. |
The function returns a list with the data for running stan()
function of
rstan package.
When genT
option is TRUE
a t-student innovations ssm model (see Ardia (2010)) is generated
see Fonseca, et. al (2019) for more details.
The default priors used in a ssm( ) model are:
level ~ normal(0,0.5)
trend ~ normal(0,0.5)
damped~ normal(0,0.5)
sigma0 ~ t-student(0,1,7)
level1 ~ normal(0,1)
trend1 ~ normal(0,1)
dfv ~ gamma(2,0.1)
breg ~ t-student(0,2.5,6)
For changing the default prior use the function set_prior()
.
The function returns a list with the data for running stan()
function of
rstan package.
Asael Alonzo Matamoros.
Fonseca, T. and Cequeira, V. and Migon, H. and Torres, C. (2019). The effects of
degrees of freedom estimation in the Asymmetric GARCH model with Student-t
Innovations. arXiv doi: arXiv: 1910.01398
.
Sarima
auto.arima
set_prior
garch
mod1 = Holt(ipc) # Declaring a Holt damped trend model for the ipc data. mod2 = Holt(ipc,damped = TRUE)
mod1 = Holt(ipc) # Declaring a Holt damped trend model for the ipc data. mod2 = Holt(ipc,damped = TRUE)
Constructor of the ets("A","A","A")
object for Bayesian estimation in Stan.
Hw(ts,damped = FALSE,xreg = NULL,period = 0,genT = FALSE,series.name = NULL)
Hw(ts,damped = FALSE,xreg = NULL,period = 0,genT = FALSE,series.name = NULL)
ts |
a numeric or ts object with the univariate time series. |
damped |
a boolean value to specify a damped trend local level model. By default
is |
xreg |
Optionally, a numerical matrix of external regressors, which must have the same number of rows as ts. It should not be a data frame. |
period |
an integer specifying the periodicity of the time series by default the value frequency(ts) is used. |
genT |
a boolean value to specify for a generalized t-student SSM model. |
series.name |
an optional string vector with the time series names. |
The function returns a list with the data for running stan()
function of
rstan package.
When genT
option is TRUE
a t-student innovations ssm model (see Ardia (2010)) is generated
see Fonseca, et. al (2019) for more details.
The default priors used in a ssm( ) model are:
level ~ normal(0,0.5)
Trend ~ normal(0,0.5)
damped~ normal(0,0.5)
Seasonal ~ normal(0,0.5)
sigma0 ~ t-student(0,1,7)
level1 ~ normal(0,1)
trend1 ~ normal(0,1)
seasonal1 ~ normal(0,1)
dfv ~ gamma(2,0.1)
breg ~ t-student(0,2.5,6)
For changing the default prior use the function set_prior()
.
The function returns a list with the data for running stan()
function of
rstan package.
Asael Alonzo Matamoros.
Fonseca, T. and Cequeira, V. and Migon, H. and Torres, C. (2019). The effects of
degrees of freedom estimation in the Asymmetric GARCH model with Student-t
Innovations. arXiv doi: arXiv: 1910.01398
.
Sarima
auto.arima
set_prior
garch
mod1 = Hw(ipc) # Declaring a Holt Winters damped trend model for the ipc data. mod2 = Hw(ipc,damped = TRUE) # Declaring an additive Holt-Winters model for the birth data mod3 = Hw(birth,damped = FALSE)
mod1 = Hw(ipc) # Declaring a Holt Winters damped trend model for the ipc data. mod2 = Hw(ipc,damped = TRUE) # Declaring an additive Holt-Winters model for the birth data mod3 = Hw(birth,damped = FALSE)
inverse.chisq(df)
inverse.chisq(df = 7)
inverse.chisq(df = 7)
df |
the degree freedom parameter df |
Define a inverse chi square prior distribution using the hyper parameter df, by default an inverse.chisq(df = 2) distribution is return.
If sigma has a chi square distribution then 1/sigma has n inverse chi square distribution.
a numerical vector interpreted as a prior in Stan
inverse.gamma(shape,rate)
inverse.gamma(shape = 2, rate = 1)
inverse.gamma(shape = 2, rate = 1)
shape |
the form parameter alpha in gamma distribution |
rate |
the rate parameter beta in gamma distribution |
Define a inverse.gamma prior distribution using the hyper parameters shape and rate, by default an inverse.gamma(2,1) distribution is return.
If sigma has a gamma distribution then 1/sigma has n inverse gamma distribution. The rate parameter is the inverse of an scale parameter.
a numerical vector interpreted as a prior in Stan
Monthly return coefficients for the inflation. An economic indicator of a country's economy.
ipc
ipc
A time series of monthly data from 1980 to 2018.
https://www.bch.hn/series_estadisticas.php
jeffey.df()
jeffrey()
jeffrey()
Define a non informative Jeffrey's prior distribution, by default an jeffrey.df( ) distribution is return.
This prior can only be used in garch models with t-student innovations, or Bekk models with generalized t-student distribution.
a numerical vector interpreted as a prior in Stan
laplace(mu,sd)
laplace(mu = 0, sd = 1)
laplace(mu = 0, sd = 1)
mu |
the location parameter mu |
sd |
the standard deviation parameter sigma |
Define a Laplace prior distribution using the hyper parameters mu and sigma, by default a standard Laplace distribution is return.
The laplace distribution is exactly the same as the double exponential distribution
a numerical vector interpreted as a prior in Stan
LKJ(df)
LKJ(df = 2)
LKJ(df = 2)
df |
the degree freedom parameter df |
Define a Lewandowski Kurowicka and Joe (LKJ) matrix correlation prior distribution using the degree freedom df hyper parameter,by default a LKJ(2) distribution is return.
a numerical vector interpreted as a prior in Stan
Lewandowski D, Kurowicka D, Joe H (2009). "Generating random correlation matrices based on vines and extended onion method." Journal of Multivariate Analysis, 100(9), 1989 2001. ISSN 0047-259X. doi:https://doi.org/10.1016/j.jmva.2009.04.008. URL: http://www.sciencedirect.com/science/article/pii/S0047259X09000876.
Constructor of the ets("A","N","N")
object for Bayesian estimation in Stan.
LocalLevel(ts,xreg = NULL,genT = FALSE,series.name = NULL)
LocalLevel(ts,xreg = NULL,genT = FALSE,series.name = NULL)
ts |
a numeric or ts object with the univariate time series. |
xreg |
Optionally, a numerical matrix of external regressors, which must have the same number of rows as ts. It should not be a data frame. |
genT |
a boolean value to specify for a generalized t-student SSM model. |
series.name |
an optional string vector with the time series names. |
The function returns a list with the data for running stan()
function of
rstan package.
By default the ssm()
function generates a local level model (or a ets("A","N","N") or
exponential smoothing model from the forecast package). If trend
is set TRUE
,
then a local trend ssm model is defined (a equivalent ets("A","A","N") or Holt model from the
forecast package). For damped trend models set damped
to TRUE
. If seasonal
is set to TRUE
a seasonal local level model is defined (a equivalent ets("A","N","A") model
from the forecast package). For a Holt-Winters method (ets("A","A","A")) set Trend
and
seasonal
to TRUE
.
When genT
option is TRUE
a t-student innovations ssm model (see Ardia (2010)) is generated
see Fonseca, et. al (2019) for more details.
The default priors used in a ssm( ) model are:
level ~ normal(0,0.5)
sigma0 ~ t-student(0,1,7)
level1 ~ normal(0,1)
dfv ~ gamma(2,0.1)
breg ~ t-student(0,2.5,6)
For changing the default prior use the function set_prior()
.
The function returns a list with the data for running stan()
function of
rstan package.
Asael Alonzo Matamoros.
Fonseca, T. and Cequeira, V. and Migon, H. and Torres, C. (2019). The effects of
degrees of freedom estimation in the Asymmetric GARCH model with Student-t
Innovations. arXiv doi: arXiv: 1910.01398
.
Sarima
auto.arima
set_prior
garch
mod1 = LocalLevel(ipc)
mod1 = LocalLevel(ipc)
Convenience function for extracting the pointwise log-likelihood matrix or array from a fitted Stan model.
## S3 method for class 'varstan' log_lik(object, permuted = TRUE, ...)
## S3 method for class 'varstan' log_lik(object, permuted = TRUE, ...)
object |
A varstan object of the time series fitted model. |
permuted |
A logical scalar indicating whether the draws after
the |
... |
additional values need in log_lik methods |
Usually, an S x N matrix containing the pointwise log-likelihood
samples, where S is the number of samples and N is the number
of observations in the data. If permuted
is FALSE
,
an S x N x R array is returned, where R is the number of fitted
chains.
Vehtari, A., Gelman, A., & Gabry J. (2016). Practical Bayesian model
evaluation using leave-one-out cross-validation and WAIC. In Statistics
and Computing, doi:10.1007/s11222-016-9696-4
.
Gelman, A., Hwang, J., & Vehtari, A. (2014). Understanding predictive information criteria for Bayesian models. Statistics and Computing. 24, 997-1016.
Watanabe, S. (2010). Asymptotic equivalence of Bayes cross validation and widely applicable information criterion in singular learning theory. The Journal of Machine Learning Research. 11, 3571-3594.
library(astsa) model = Sarima(birth,order = c(0,1,2),seasonal = c(1,1,1)) fit1 = varstan(model,iter = 500,chains = 1) log1 = log_lik(fit1) log1
library(astsa) model = Sarima(birth,order = c(0,1,2),seasonal = c(1,1,1)) fit1 = varstan(model,iter = 500,chains = 1) log1 = log_lik(fit1) log1
Convenience function for extracting the posterior sample of the accumulated log-likelihood array from a fitted varstan object.
loglik(object, permuted = TRUE)
loglik(object, permuted = TRUE)
object |
A varstan object of the time series fitted model. |
permuted |
A logical scalar indicating whether the draws after the warmup period in each chain should be permuted and merged. If FALSE, the original order is kept. For each stanfit object, the permutation is fixed (i.e., extracting samples a second time will give the same sequence of iterations). |
A real value with the accumulated log likelihood.
Vehtari, A., Gelman, A., & Gabry J. (2016). Practical Bayesian model
evaluation using leave-one-out cross-validation and WAIC. In Statistics
and Computing, doi:10.1007/s11222-016-9696-4
.
Gelman, A., Hwang, J., & Vehtari, A. (2014). Understanding predictive information criteria for Bayesian models. Statistics and Computing. 24, 997-1016.
Watanabe, S. (2010). Asymptotic equivalence of Bayes cross validation and widely applicable information criterion in singular learning theory. The Journal of Machine Learning Research. 11, 3571-3594.
library(astsa) model = Sarima(birth,order = c(0,1,2),seasonal = c(1,1,1)) fit1 = varstan(model,iter = 500,chains = 1) log1 = loglik(fit1) log1
library(astsa) model = Sarima(birth,order = c(0,1,2),seasonal = c(1,1,1)) fit1 = varstan(model,iter = 500,chains = 1) log1 = loglik(fit1) log1
The loo
method for varstan objects. Computes approximate
leave-one-out cross-validation using Pareto smoothed importance
sampling (PSIS-LOO CV).
## S3 method for class 'varstan' loo(x, ...)
## S3 method for class 'varstan' loo(x, ...)
x |
A varstan object |
... |
additional values need in loo methods |
an object from the loo class with the results of the Pareto-Smooth Importance Sampling, leave one out cross validation for model selection.
Vehtari, A., Gelman, A., & Gabry J. (2016). Practical Bayesian model
evaluation using leave-one-out cross-validation and WAIC. In Statistics
and Computing, doi:10.1007/s11222-016-9696-4
.
Gelman, A., Hwang, J., & Vehtari, A. (2014). Understanding predictive information criteria for Bayesian models. Statistics and Computing. 24, 997-1016.
Watanabe, S. (2010). Asymptotic equivalence of Bayes cross validation and widely applicable information criterion in singular learning theory. The Journal of Machine Learning Research. 11, 3571-3594.
The loo package vignettes for demonstrations.
psis()
for the underlying Pareto Smoothed Importance Sampling (PSIS)
procedure used in the LOO-CV approximation.
pareto-k-diagnostic for convenience functions for looking at diagnostics.
loo_compare()
for model comparison.
library(astsa) model = Sarima(birth,order = c(0,1,2),seasonal = c(1,1,1)) fit1 = varstan(model,iter = 500,chains = 1) loo1 = loo(fit1) loo1
library(astsa) model = Sarima(birth,order = c(0,1,2),seasonal = c(1,1,1)) fit1 = varstan(model,iter = 500,chains = 1) loo1 = loo(fit1) loo1
Convenient way to call MCMC plotting functions implemented in the bayesplot package.
## S3 method for class 'varstan' mcmc_plot( object, pars = NULL, combo = c("dens", "trace"), fixed = FALSE, exact_match = FALSE, ... ) mcmc_plot(object, ...)
## S3 method for class 'varstan' mcmc_plot( object, pars = NULL, combo = c("dens", "trace"), fixed = FALSE, exact_match = FALSE, ... ) mcmc_plot(object, ...)
object |
An |
pars |
Names of parameters to be plotted, as given by a character vector or regular expressions. By default, all parameters except for group-level and smooth effects are plotted. May be ignored for some plots. |
combo |
An array that contains the types of plot. By default
combo = c("dens","trace"). Supported types are (as names) |
fixed |
Indicates whether parameter names
should be matched exactly ( |
exact_match |
Deprecated alias of argument |
... |
Additional arguments passed to the plotting functions.
See |
A ggplot
object
that can be further customized using the ggplot2 package.
## Not run: sf1 = stan_ssm(ipc,iter = 500,chains = 1) # plot posterior intervals mcmc_plot(sf1) # only show population-level effects in the plots mcmc_plot(sf1, pars = "level") ## End(Not run)
## Not run: sf1 = stan_ssm(ipc,iter = 500,chains = 1) # plot posterior intervals mcmc_plot(sf1) # only show population-level effects in the plots mcmc_plot(sf1, pars = "level") ## End(Not run)
The function returns a string with the users defined model for the given time series data.
model(object,...)
model(object,...)
object |
a varstan object or one of the defined current defined models in varstan package. |
... |
additional values need in print methods |
if object
is a varstan object the function will print the information of the
defined model inside of the object. If object
is one of the model classes (like
Sarima
, garch
, SVM
or varma
), then it will print the model
information as well.
For full information of the model with the used priors use the function report or just print the object.
a string with the defined time series model.
Asael Alonzo Matamoros.
report
print
library(astsa) model1 = Sarima(birth,order = c(0,1,2),seasonal = c(1,1,1)) model(model1)
library(astsa) model1 = Sarima(birth,order = c(0,1,2),seasonal = c(1,1,1)) model(model1)
naive is the model constructor for a random walk model applied to y
.
This is equivalent to an ARIMA(0,1,0) model. naive()
is simply a wrapper
to maintain forecast package similitude. seasonal
returns the model constructor
for a seasonal random walk equivalent to an ARIMA(0,0,0)(0,1,0)m model where m is the
seasonal period.
naive(ts,seasonal = FALSE,m = 0)
naive(ts,seasonal = FALSE,m = 0)
ts |
a numeric or ts object with the univariate time series. |
seasonal |
a Boolean value for select a seasonal random walk instead. |
m |
an optional integer value for the seasonal period. |
The random walk with drift model is
where is a normal iid error.
The seasonal naive model is
where is a normal iid error.
The function returns a list with the data for running stan()
function of
rstan package.
Asael Alonzo Matamoros
Hyndman, R. & Khandakar, Y. (2008). Automatic time series forecasting: the
forecast package for R
. Journal of Statistical Software. 26(3),
1-22.doi: 10.18637/jss.v027.i03
.
Box, G. E. P. and Jenkins, G.M. (1978). Time series analysis: Forecasting and
control. San Francisco: Holden-Day. Biometrika, 60(2), 297-303.
doi:10.1093/biomet/65.2.297
.
Kennedy, P. (1992). Forecasting with dynamic regression models: Alan Pankratz, 1991.
International Journal of Forecasting. 8(4), 647-648.
url: https://EconPapers.repec.org/RePEc:eee:intfor:v:8:y:1992:i:4:p:647-648
.
library(astsa) # A seasonal Random-walk model. model = naive(birth,seasonal = TRUE) model
library(astsa) # A seasonal Random-walk model. model = naive(birth,seasonal = TRUE) model
normal(mu,sd)
normal(mu = 0, sd = 1)
normal(mu = 0, sd = 1)
mu |
the location parameter mu |
sd |
the standard deviation parameter sigma |
Define a normal prior distribution using the hyper parameters mu and sigma, by default a standard normal distribution is return.
a numerical vector interpreted as a prior in Stan
Annual oil production (millions of tonnes), Saudi Arabia, 1965-2013.
oildata
oildata
the format is: Annual Time-Series (1:18) from 1996 to 2013:
fpp2
Hyndman, R. & Khandakar, Y. (2008). Automatic time series forecasting: the
forecast package for R
. Journal of Statistical Software. 26(3),
1-22.doi: 10.18637/jss.v027.i03
Preliminary plot methods for varstan models only valid for univariate time series models. The function prints the fitted values time series, the trace and density plots for the sampled model parameters, or the residuals' posterior mean time series.
## S3 method for class 'varstan' plot(x, prob = 0.95, ...)
## S3 method for class 'varstan' plot(x, prob = 0.95, ...)
x |
An object of class |
prob |
A number |
... |
Further arguments passed to |
None. Function produces a ggplot2 graph.
library(astsa) sf1 = auto.sarima(ts = birth,iter = 500,chains = 1) # fitted model plot(sf1)
library(astsa) sf1 = auto.sarima(ts = birth,iter = 500,chains = 1) # fitted model plot(sf1)
Compute posterior samples of the expected value/mean of the posterior
predictive distribution. Can be performed for the data used to fit the model
(posterior predictive checks) or for new data. By definition, these
predictions have smaller variance than the posterior predictions performed by
the posterior_predict.varstan
method. This is because only the
uncertainty in the mean is incorporated in the samples computed by
posterior_epred
while any residual error is ignored. However, the
estimated means of both methods averaged across samples should be very
similar.
## S3 method for class 'varstan' posterior_epred( object, h = 0, xreg = NULL, robust = FALSE, draws = 1000, seed = NULL, ... )
## S3 method for class 'varstan' posterior_epred( object, h = 0, xreg = NULL, robust = FALSE, draws = 1000, seed = NULL, ... )
object |
a varstan object |
h |
An integer indicating the number of predictions. The default number of predictions is 12. |
xreg |
Optionally, a numerical matrix of external regressors, which must have the same number of rows as ts. It should not be a data frame. |
robust |
A boolean for obtain the robust estimation. The default |
draws |
An integer indicating the number of draws to return. The default number of draws is 1000 |
seed |
An optional |
... |
Further arguments passed to |
An array
of predicted mean response values. For categorical and
ordinal models, the output is an S x N x C array. Otherwise, the output is an
S x N
matrix, where S is the number of posterior samples, N is the number
of observations, and C is the number of categories. In multivariate models, an
additional dimension is added to the output which indexes along the different
response variables.
The posterior_interval
function computes Bayesian posterior uncertainty
intervals. These intervals are often referred to as credible
intervals, for more details see rstanarm
posterior_interval(mat, prob = 0.9, ...)
posterior_interval(mat, prob = 0.9, ...)
mat |
a matrix containing the posterior samples of a fitted parameter |
prob |
A number |
... |
Further arguments passed to |
A matrix with two columns and as many rows as model parameters (or
the subset of parameters specified by pars
and/or
regex_pars
). For a given value of prob
, , the columns
correspond to the lower and upper
100*p%
interval limits and have the
names and
%
, where . For example, if
prob=0.9
is specified (a 90%
interval), then the column names will be "5%"
and "95%"
,
respectively.
Asael Alonzo Matamoros
The posterior predictive distribution is the distribution of the outcome implied by the model after using the observed data to update our beliefs about the unknown parameters in the model. Simulating data from the posterior predictive distribution using the observed predictors is useful for checking the fit of the model. Drawing from the posterior predictive distribution at interesting values of the predictors also lets us visualize how a manipulation of a predictor affects (a function of) the outcome(s). With new observations of predictor variables we can use the posterior predictive distribution to generate predicted outcomes.
## S3 method for class 'varstan' posterior_predict( object, h = 0, xreg = NULL, robust = FALSE, draws = 1000, seed = NULL, ... )
## S3 method for class 'varstan' posterior_predict( object, h = 0, xreg = NULL, robust = FALSE, draws = 1000, seed = NULL, ... )
object |
a varstan object |
h |
An integer indicating the number of predictions. The default number of predictions is 12. |
xreg |
Optionally, a numerical matrix of external regressors, which must have the same number of rows as ts. It should not be a data frame. |
robust |
A boolean for obtain the robust estimation. The default |
draws |
An integer indicating the number of draws to return. The default number of draws is 1000 |
seed |
An optional |
... |
Further arguments passed to |
A draws
by h
data.frame of simulations from the
posterior predictive distribution. Each row of the data.frame
is a vector of predictions generated using a single draw of
the model parameters from the posterior distribution.
Asael Alonzo Matamoros
This is a convenience function for computing
The method for stanreg objects calls
posterior_predict
internally, where as the method accepts the data.frame returned by
posterior_predict
as input and can be used to avoid multiple calls to
posterior_predict
.
## S3 method for class 'varstan' predictive_error( object, newdata = NULL, xreg = NULL, draws = 1000, seed = NULL, ... )
## S3 method for class 'varstan' predictive_error( object, newdata = NULL, xreg = NULL, draws = 1000, seed = NULL, ... )
object |
Either a fitted model object returned by one of the rstanarm
modeling functions (a stanreg object) or, for the |
newdata |
An array with the newdata vector. |
xreg |
Optional, a numerical matrix of external regressors, which must have the same number of rows as ts. It should not be a data frame. |
draws , seed
|
Optional arguments passed to |
... |
Further arguments passed to |
A draws
by nrow(newdata)
data.frame.
If object
is a varstan object of a varma model then newdata has to be a matrix
with number of cols as the dimension of the time series and number of rows
as the number new elements.
If object
is a posterior_predict
data.frame, then the
length of newdata
has to be equal to the ncol
of object
.
If object
is a posterior_predict
data.frame, for a varma model,
then the dimension product of newdata
matrix has to be equal to
the ncol
of object
.
posterior_predict
function from rstanarm package, to draw
from the posterior predictive distribution without computing predictive
errors.
Print a garch model
## S3 method for class 'garch' print(x, ...)
## S3 method for class 'garch' print(x, ...)
x |
a garch model from the varstan package |
... |
additional values need in print methods |
None. prints the object
Print a Holt model
## S3 method for class 'Holt' print(x, ...)
## S3 method for class 'Holt' print(x, ...)
x |
a Holt model from the varstan package |
... |
additional values need in print methods |
None. prints the object.
Print a Holt-Winter model
## S3 method for class 'Hw' print(x, ...)
## S3 method for class 'Hw' print(x, ...)
x |
a Hw from the varstan package |
... |
additional values need in print methods |
None. prints the object.
Print a Local Level model
## S3 method for class 'LocalLevel' print(x, ...)
## S3 method for class 'LocalLevel' print(x, ...)
x |
a LocalLevel model from the varstan package |
... |
additional values need in print methods |
None. prints the object.
Print a naive model
## S3 method for class 'naive' print(x, ...)
## S3 method for class 'naive' print(x, ...)
x |
a naive model from the varstan package |
... |
additional values need in print methods |
None. prints the object
Print a Sarima model
## S3 method for class 'Sarima' print(x, ...)
## S3 method for class 'Sarima' print(x, ...)
x |
a Sarima model from the varstan package |
... |
additional values need in print methods |
None. prints the object
Print a state-space model
## S3 method for class 'ssm' print(x, ...)
## S3 method for class 'ssm' print(x, ...)
x |
a ssm model from the varstan package |
... |
additional values need in print methods |
None. prints the object.
Print a Stochastic Volatility model
## S3 method for class 'SVM' print(x, ...)
## S3 method for class 'SVM' print(x, ...)
x |
a SVM model from the varstan package |
... |
additional values need in print methods |
None. prints the object
Print a varstan object
## S3 method for class 'varstan' print(x, ...)
## S3 method for class 'varstan' print(x, ...)
x |
a varstan object |
... |
additional values need in print methods |
None. prints the object.
The function returns a report with the users defined model for the given time series data and all the current defined priors of the model.
## S3 method for class 'varstan' prior_summary(object, ...)
## S3 method for class 'varstan' prior_summary(object, ...)
object |
a varstan object or one of the defined current defined reports in varstan package |
... |
additional values need in print methods |
if object
is a varstan object the function will print the information of the
defined model inside of the object. If object
is one of the model classes (like Sarima or garch)
then it will print the report information as well.
none. prints a string with the defined time series model report
Asael Alonzo Matamoros
library(astsa) dat2 = garch(birth,order = c(1,1,0)) prior_summary(dat2)
library(astsa) dat2 = garch(birth,order = c(1,1,0)) prior_summary(dat2)
The function returns a report with the users defined model for the given time series data and all the current defined priors of the model.
report(object,...)
report(object,...)
object |
an object varstan object or one of the defined current defined reports in varstan package |
... |
additional values need in print methods |
if object
is a varstan object the function will print the information of the
defined model inside of the object. If object
is one of the model classes (like Sarima or garch)
then it will print the report information as well.
none. prints a string with the defined time series model report
Asael Alonzo Matamoros
library(astsa) dat2 = garch(birth,order = c(1,1,0)) report(dat2)
library(astsa) dat2 = garch(birth,order = c(1,1,0)) report(dat2)
The function returns the posterior estimate of the residuals of a varstan model, similar to the residual functions of other packages.
## S3 method for class 'varstan' residuals(object, robust = FALSE, ...)
## S3 method for class 'varstan' residuals(object, robust = FALSE, ...)
object |
A varstan object, |
robust |
A boolean value, if its |
... |
Further arguments passed to |
This function only extracts the point-wise estimate of the time series residuals
for extracting all the data use extract_stan()
or posterior_intervals function
An array with the posterior estimate of the residuals of the time series model,
Asael Alonzo Matamoros
Constructor of the SARIMA model for Bayesian estimation in Stan.
Sarima(ts,order = c(1,0,0),seasonal = c(0,0,0),xreg = NULL,period = 0,series.name = NULL)
Sarima(ts,order = c(1,0,0),seasonal = c(0,0,0),xreg = NULL,period = 0,series.name = NULL)
ts |
a numeric or ts object with the univariate time series. |
order |
A specification of the non-seasonal part of the ARIMA model: the three components (p, d, q) are the AR order, the number of differences, and the MA order. |
seasonal |
A specification of the seasonal part of the ARIMA model,same as order parameter: the three components (p, d, q) are the seasonal AR order, the degree of seasonal differences, and the seasonal MA order. |
xreg |
Optionally, a numerical matrix of external regressors, which must have the same number of rows as ts. It should not be a data frame. |
period |
an integer specifying the periodicity of the time series by default the value frequency(ts) is used. |
series.name |
an optional string vector with the series names. |
The function returns a list with the data for running stan()
function of
rstan package
If xreg
option is used, the model by default will cancel the
seasonal differences adjusted (D = 0). If a value d
> 0 is used, all
the regressor variables in xreg
will be difference as well.
The default priors used in Sarima are:
ar ~ normal(0,0.5)
ma ~ normal(0,0.5)
mu0 ~ t-student(0,2.5,6)
sigma0 ~ t-student(0,1,7)
sar ~ normal(0,0.5)
sma ~ normal(0,0.5)
breg ~ t-student(0,2.5,6)
For changing the default prior use the function set_prior
The function returns a list with the data for running stan()
function of
rstan package.
Asael Alonzo Matamoros
Box, G. E. P. and Jenkins, G.M. (1978). Time series analysis: Forecasting and
control. San Francisco: Holden-Day. Biometrika, 60(2), 297-303.
doi:10.1093/biomet/65.2.297
.
Kennedy, P. (1992). Forecasting with dynamic regression models: Alan Pankratz, 1991.
International Journal of Forecasting. 8(4), 647-648.
url: https://EconPapers.repec.org/RePEc:eee:intfor:v:8:y:1992:i:4:p:647-648
.
Hyndman, R. & Khandakar, Y. (2008). Automatic time series forecasting: the
forecast package for R
. Journal of Statistical Software. 26(3),
1-22.doi: 10.18637/jss.v027.i03
# Declare a multiplicative seasonal ARIMA model for the birth data. library(astsa) model = Sarima(birth,order = c(0,1,2),seasonal = c(1,1,1)) model #Declare an Dynamic Harmonic Regression model for the birth data. model = Sarima(birth,order = c(1,0,1),xreg = fourier(birth,K = 2)) model
# Declare a multiplicative seasonal ARIMA model for the birth data. library(astsa) model = Sarima(birth,order = c(0,1,2),seasonal = c(1,1,1)) model #Declare an Dynamic Harmonic Regression model for the birth data. model = Sarima(birth,order = c(1,0,1),xreg = fourier(birth,K = 2)) model
setting a prior distribution to an specify model parameter.
set_prior(model, par = "ar", dist = normal(), lag = 0)
set_prior(model, par = "ar", dist = normal(), lag = 0)
model |
a time series model class specified in varstan. |
par |
a string value with the desired parameter which a prior is defined could be: "mu0", "sigma0", "ar", "ma", "arch", "garch", "mgarch", "dfv", "df", "LKJ" or "breg". |
dist |
the distribution of the prior parameter. The only accepted is a prior_dist object. |
lag |
an optional integer value, indicates the desired lag of the parameter which the prior is defined if lag = 0, then the prior distribution will be applied for all lags. |
varstan provides its own functions to manipulate the parameter prior, this functions return
a prior_dist
class, the dist
argument only accepts this objects.
lag
parameter is an optional value to change the prior distribution of one parameter in particular,
this argument is only valid for: "ar","ma", "arch", "garch", "mgarch", or "breg" par arguments. lag has to
be a integer lower than the total amount of lagged parameters of the model. For example, to ONLY
change the prior of the second "arch" parameter in a garch(3,1) model, a lag = 2 values must be specified.
For varma and Bekk models the covariance matrix Sigma is factorized as follows:
Sigma = D' Omega D
Where Omega is the correlation matrix that accepts an LKJ prior distribution D is a diagonal matrix with the inverse std deviations
For changing the degree freedom in a LKJ distribution for omega use par = "LKJ" and dist = LKJ(df), where df are the desired degree freedom.
For changing the the priors in the diagonal D use par = "sigma0" and select one of the available prior distributions.
For ar, ma garch, arch parameters in varma and Bekk models only normal distributions priors with different
mu and sd are accepted. Even if get_prior
accepts its change, Stan will change it to a normal(0,1) prior.
a time series model class specified in varstan with the changed prior.
Asael Alonzo Matamoros
library(astsa) dat = Sarima(birth,order = c(1,1,2)) dat = set_prior(model = dat,par = "ar",dist = normal(0,2)) dat dat = set_prior(model = dat,par = "mu0",dist = student(mu=0,sd = 2.5,df = 7)) dat dat = set_prior(model = dat,par = "ma",dist= beta(shape1 = 2,shape2 = 2),lag = 2) dat
library(astsa) dat = Sarima(birth,order = c(1,1,2)) dat = set_prior(model = dat,par = "ar",dist = normal(0,2)) dat dat = set_prior(model = dat,par = "mu0",dist = student(mu=0,sd = 2.5,df = 7)) dat dat = set_prior(model = dat,par = "ma",dist= beta(shape1 = 2,shape2 = 2),lag = 2) dat
Constructor of the ets("Z","Z","Z")
object for Bayesian estimation in Stan.
ssm(ts,trend = FALSE,damped = FALSE,seasonal = FALSE,xreg = NULL, period = 0,genT = FALSE,series.name = NULL)
ssm(ts,trend = FALSE,damped = FALSE,seasonal = FALSE,xreg = NULL, period = 0,genT = FALSE,series.name = NULL)
ts |
a numeric or ts object with the univariate time series. |
trend |
a boolean value to specify a trend local level model. By default
is |
damped |
a boolean value to specify a damped trend local level model. By default
is |
seasonal |
a boolean value to specify a seasonal local level model. By default
is |
xreg |
Optionally, a numerical matrix of external regressors, which must have the same number of rows as ts. It should not be a data frame. |
period |
an integer specifying the periodicity of the time series by default the value frequency(ts) is used. |
genT |
a boolean value to specify for a generalized t-student SSM model. |
series.name |
an optional string vector with the time series names. |
The function returns a list with the data for running stan()
function of
rstan package.
By default the ssm()
function generates a local level model (or a ets("A","N","N") or
exponential smoothing model from the forecast package). If trend
is set TRUE
,
then a local trend ssm model is defined (a equivalent ets("A","A","N") or Holt model from the
forecast package). For damped trend models set damped
to TRUE
. If seasonal
is set to TRUE
a seasonal local level model is defined (a equivalent ets("A","N","A") model
from the forecast package). For a Holt-Winters method (ets("A","A","A")) set Trend
and
seasonal
to TRUE
.
When genT
option is TRUE
a t-student innovations ssm model (see Ardia (2010)) is generated
see Fonseca, et. al (2019) for more details.
The default priors used in a ssm( ) model are:
level ~ normal(0,0.5)
Trend ~ normal(0,0.5)
damped~ normal(0,0.5)
Seasonal ~ normal(0,0.5)
sigma0 ~ t-student(0,1,7)
level1 ~ normal(0,1)
trend1 ~ normal(0,1)
seasonal1 ~ normal(0,1)
dfv ~ gamma(2,0.1)
breg ~ t-student(0,2.5,6)
For changing the default prior use the function set_prior()
.
The function returns a list with the data for running stan()
function of
rstan package.
Asael Alonzo Matamoros.
Fonseca, T. and Cequeira, V. and Migon, H. and Torres, C. (2019). The effects of
degrees of freedom estimation in the Asymmetric GARCH model with Student-t
Innovations. arXiv doi: arXiv: 1910.01398
.
Sarima
auto.arima
set_prior
garch
mod1 = ssm(ipc) # Declaring a Holt model for the ipc data. mod2 = ssm(ipc,trend = TRUE,damped = TRUE) # Declaring an additive Holt-Winters model for the birth data mod3 = ssm(birth,trend = TRUE,damped = TRUE,seasonal = TRUE)
mod1 = ssm(ipc) # Declaring a Holt model for the ipc data. mod2 = ssm(ipc,trend = TRUE,damped = TRUE) # Declaring an additive Holt-Winters model for the birth data mod3 = ssm(birth,trend = TRUE,damped = TRUE,seasonal = TRUE)
Fitting a GARCH(s,k,h)
model in Stan.
stan_garch( ts, order = c(1, 1, 0), arma = c(0, 0), xreg = NULL, genT = FALSE, asym = "none", chains = 4, iter = 2000, warmup = floor(iter/2), adapt.delta = 0.9, tree.depth = 10, stepwise = TRUE, prior_mu0 = NULL, prior_sigma0 = NULL, prior_ar = NULL, prior_ma = NULL, prior_mgarch = NULL, prior_arch = NULL, prior_garch = NULL, prior_breg = NULL, prior_gamma = NULL, prior_df = NULL, series.name = NULL, ... )
stan_garch( ts, order = c(1, 1, 0), arma = c(0, 0), xreg = NULL, genT = FALSE, asym = "none", chains = 4, iter = 2000, warmup = floor(iter/2), adapt.delta = 0.9, tree.depth = 10, stepwise = TRUE, prior_mu0 = NULL, prior_sigma0 = NULL, prior_ar = NULL, prior_ma = NULL, prior_mgarch = NULL, prior_arch = NULL, prior_garch = NULL, prior_breg = NULL, prior_gamma = NULL, prior_df = NULL, series.name = NULL, ... )
ts |
a numeric or ts object with the univariate time series. |
order |
A specification of the garch model: the three components (s, k, h) are the arch order, the garch order, and the mgarch order. |
arma |
A specification of the ARMA model,same as order parameter: the two components (p, q) are the AR order,and the MA order. |
xreg |
Optionally, a numerical matrix of external regressors, which must have the same number of rows as ts. It should not be a data frame. |
genT |
a boolean value to specify for a generalized t-student garch model. |
asym |
a string value for the asymmetric function for an asymmetric GARCH process. By default
the value |
chains |
An integer of the number of Markov Chains chains to be run, by default 4 chains are run. |
iter |
An integer of total iterations per chain including the warm-up, by default the number of iterations are 2000. |
warmup |
A positive integer specifying number of warm-up (aka burn-in)
iterations. This also specifies the number of iterations used for step-size
adaptation, so warm-up samples should not be used for inference. The number
of warmup should not be larger than |
adapt.delta |
An optional real value between 0 and 1, the thin of the jumps in a HMC method. By default is 0.9. |
tree.depth |
An integer of the maximum depth of the trees evaluated during each iteration. By default is 10. |
stepwise |
If TRUE, will do stepwise selection (faster). Otherwise, it searches over all models. Non-stepwise selection can be very slow, especially for seasonal models. |
prior_mu0 |
The prior distribution for the location parameter in an ARMA model. By default
the value is set |
prior_sigma0 |
The prior distribution for the scale parameter in an ARMA model. By default
the value is set |
prior_ar |
The prior distribution for the auto-regressive parameters in an ARMA model.
By default the value is set |
prior_ma |
The prior distribution for the moving average parameters in an ARMA model.
By default the value is set |
prior_mgarch |
The prior distribution for the mean GARCH parameters in a
GARCH model. By default the value is set |
prior_arch |
The prior distribution for the arch parameters in a GARCH model.
By default the value is set |
prior_garch |
The prior distribution for the GARCH parameters in a GARCH model.
By default the value is set |
prior_breg |
The prior distribution for the regression coefficient parameters in a
ARIMAX model. By default the value is set |
prior_gamma |
The prior distribution for the asymmetric parameters in am Asymmetric
GARCH model. By default the value is set |
prior_df |
The prior distribution for the degree freedom parameters in a t-student innovations
GARCH model. By default the value is set |
series.name |
an optional string vector with the series names. |
... |
Further arguments passed to |
The function returns a varstan
object with the fitted model.
By default the garch()
function generates a GARCH(1,1) model, when
genT
option is TRUE
a t-student innovations GARCH model
(see Ardia (2010)) is generated, and for Asymmetric GARCH models use the
option asym
for specify the asymmetric function, see Fonseca,
et. al (2019) for more details.
The default priors used in a GARCH(s,k,h) model are:
ar ~ normal(0,0.5)
ma ~ normal(0,0.5)
mu0 ~ t-student(0,2.5,6)
sigma0 ~ t-student(0,1,7)
arch ~ normal(0,0.5)
garch ~ normal(0,0.5)
mgarch ~ normal(0,0.5)
dfv ~ gamma(2,0.1)
breg ~ t-student(0,2.5,6)
For changing the default prior use the function set_prior()
.
A varstan
object with the fitted GARCH model.
Asael Alonzo Matamoros.
Engle, R. (1982). Autoregressive Conditional Heteroscedasticity with Estimates of
the Variance of United Kingdom Inflation. Econometrica, 50(4), 987-1007.
url: http://www.jstor.org/stable/1912773
.
Bollerslev, T. (1986). Generalized autoregressive conditional heteroskedasticity.
Journal of Econometrics. 31(3), 307-327.
doi: https://doi.org/10.1016/0304-4076(86)90063-1
.
Fonseca, T. and Cequeira, V. and Migon, H. and Torres, C. (2019). The effects of
degrees of freedom estimation in the Asymmetric GARCH model with Student-t
Innovations. arXiv doi: arXiv: 1910.01398
.
Ardia, D. and Hoogerheide, L. (2010). Bayesian Estimation of the GARCH(1,1) Model
with Student-t Innovations. The R Journal. 2(7), 41-47.
doi: 10.32614/RJ-2010-014
.
# Declaring a garch(1,1) model for the ipc data. sf1 = stan_garch(ipc,order = c(1,1,0),iter = 500,chains = 1) # Declaring a t-student M-GARCH(2,3,1)-ARMA(1,1) process for the ipc data. sf2 = stan_garch(ipc,order = c(2,3,1),arma = c(1,1),genT = TRUE,iter = 500,chains = 1)
# Declaring a garch(1,1) model for the ipc data. sf1 = stan_garch(ipc,order = c(1,1,0),iter = 500,chains = 1) # Declaring a t-student M-GARCH(2,3,1)-ARMA(1,1) process for the ipc data. sf2 = stan_garch(ipc,order = c(2,3,1),arma = c(1,1),genT = TRUE,iter = 500,chains = 1)
Fitting an Holt state-space model in Stan.
stan_Holt( ts, damped = FALSE, xreg = NULL, genT = FALSE, chains = 4, iter = 2000, warmup = floor(iter/2), adapt.delta = 0.9, tree.depth = 10, stepwise = TRUE, prior_sigma0 = NULL, prior_level = NULL, prior_level1 = NULL, prior_trend = NULL, prior_trend1 = NULL, prior_damped = NULL, prior_breg = NULL, prior_df = NULL, series.name = NULL, ... )
stan_Holt( ts, damped = FALSE, xreg = NULL, genT = FALSE, chains = 4, iter = 2000, warmup = floor(iter/2), adapt.delta = 0.9, tree.depth = 10, stepwise = TRUE, prior_sigma0 = NULL, prior_level = NULL, prior_level1 = NULL, prior_trend = NULL, prior_trend1 = NULL, prior_damped = NULL, prior_breg = NULL, prior_df = NULL, series.name = NULL, ... )
ts |
a numeric or ts object with the univariate time series. |
damped |
a boolean value to specify a damped trend local level model. By default
is |
xreg |
Optionally, a numerical matrix of external regressors, which must have the same number of rows as ts. It should not be a data frame. |
genT |
a boolean value to specify for a generalized t-student SSM model. |
chains |
An integer of the number of Markov Chains chains to be run, by default 4 chains are run. |
iter |
An integer of total iterations per chain including the warm-up, by default the number of iterations are 2000. |
warmup |
A positive integer specifying number of warm-up (aka burn-in)
iterations. This also specifies the number of iterations used for step-size
adaptation, so warm-up samples should not be used for inference. The number
of warmup should not be larger than |
adapt.delta |
An optional real value between 0 and 1, the thin of the jumps in a HMC method. By default is 0.9. |
tree.depth |
An integer of the maximum depth of the trees evaluated during each iteration. By default is 10. |
stepwise |
If TRUE, will do stepwise selection (faster). Otherwise, it searches over all models. Non-stepwise selection can be very slow, especially for seasonal models. |
prior_sigma0 |
The prior distribution for the scale parameter in an SSM model. By default
the value is set |
prior_level |
The prior distribution for the level parameter in a SSM model.
By default the value is set |
prior_level1 |
The prior distribution for the initial level parameter in a SSM model.
By default the value is set |
prior_trend |
The prior distribution for the trend parameter in a SSM model.
By default the value is set |
prior_trend1 |
The prior distribution for the initial trend parameter in a SSM model.
By default the value is set |
prior_damped |
The prior distribution for the damped trend parameter in a SSM model.
By default the value is set |
prior_breg |
The prior distribution for the regression coefficient parameters in a
ARMAX model. By default the value is set |
prior_df |
The prior distribution for the degree freedom parameters in a t-student innovations
SSM model. By default the value is set |
series.name |
an optional string vector with the series names. |
... |
Further arguments passed to |
The function returns a varstan
object with the fitted model.
When genT
option is TRUE
a t-student innovations ssm model (see Ardia (2010)) is generated
see Fonseca, et. al (2019) for more details.
The default priors used in a ssm( ) model are:
level ~ normal(0,0.5)
Trend ~ normal(0,0.5)
damped~ normal(0,0.5)
sigma0 ~ t-student(0,1,7)
level1 ~ normal(0,1)
trend1 ~ normal(0,1)
dfv ~ gamma(2,0.1)
breg ~ t-student(0,2.5,6)
For changing the default prior use the function set_prior()
.
A varstan
object with the fitted SSM model.
Asael Alonzo Matamoros.
Fonseca, T. and Cequeira, V. and Migon, H. and Torres, C. (2019). The effects of
degrees of freedom estimation in the Asymmetric GARCH model with Student-t
Innovations. arXiv doi: arXiv: 1910.01398
.
Sarima
auto.arima
set_prior
garch
# Declaring a Holt model for the ipc data. sf1 = stan_Holt(ipc,iter = 500,chains = 1) # Declaring a Holt damped trend model for the ipc data. sf2 = stan_Holt(ipc,damped = TRUE,iter = 500,chains = 1)
# Declaring a Holt model for the ipc data. sf1 = stan_Holt(ipc,iter = 500,chains = 1) # Declaring a Holt damped trend model for the ipc data. sf2 = stan_Holt(ipc,damped = TRUE,iter = 500,chains = 1)
Fitting a Holt-Winters state-space model in Stan.
stan_Hw( ts, damped = FALSE, xreg = NULL, period = 0, genT = FALSE, chains = 4, iter = 2000, warmup = floor(iter/2), adapt.delta = 0.9, tree.depth = 10, stepwise = TRUE, prior_sigma0 = NULL, prior_level = NULL, prior_level1 = NULL, prior_trend = NULL, prior_trend1 = NULL, prior_damped = NULL, prior_seasonal = NULL, prior_seasonal1 = NULL, prior_breg = NULL, prior_df = NULL, series.name = NULL, ... )
stan_Hw( ts, damped = FALSE, xreg = NULL, period = 0, genT = FALSE, chains = 4, iter = 2000, warmup = floor(iter/2), adapt.delta = 0.9, tree.depth = 10, stepwise = TRUE, prior_sigma0 = NULL, prior_level = NULL, prior_level1 = NULL, prior_trend = NULL, prior_trend1 = NULL, prior_damped = NULL, prior_seasonal = NULL, prior_seasonal1 = NULL, prior_breg = NULL, prior_df = NULL, series.name = NULL, ... )
ts |
a numeric or ts object with the univariate time series. |
damped |
a boolean value to specify a damped trend local level model. By default
is |
xreg |
Optionally, a numerical matrix of external regressors, which must have the same number of rows as ts. It should not be a data frame. |
period |
an integer specifying the periodicity of the time series by default the value frequency(ts) is used. |
genT |
a boolean value to specify for a generalized t-student SSM model. |
chains |
An integer of the number of Markov Chains chains to be run, by default 4 chains are run. |
iter |
An integer of total iterations per chain including the warm-up, by default the number of iterations are 2000. |
warmup |
A positive integer specifying number of warm-up (aka burn-in)
iterations. This also specifies the number of iterations used for step-size
adaptation, so warm-up samples should not be used for inference. The number
of warmup should not be larger than |
adapt.delta |
An optional real value between 0 and 1, the thin of the jumps in a HMC method. By default is 0.9. |
tree.depth |
An integer of the maximum depth of the trees evaluated during each iteration. By default is 10. |
stepwise |
If TRUE, will do stepwise selection (faster). Otherwise, it searches over all models. Non-stepwise selection can be very slow, especially for seasonal models. |
prior_sigma0 |
The prior distribution for the scale parameter in an SSM model. By default
the value is set |
prior_level |
The prior distribution for the level parameter in a SSM model.
By default the value is set |
prior_level1 |
The prior distribution for the initial level parameter in a SSM model.
By default the value is set |
prior_trend |
The prior distribution for the trend parameter in a SSM model.
By default the value is set |
prior_trend1 |
The prior distribution for the initial trend parameter in a SSM model.
By default the value is set |
prior_damped |
The prior distribution for the damped trend parameter in a SSM model.
By default the value is set |
prior_seasonal |
The prior distribution for the seasonal parameter in a SSM model.
By default the value is set |
prior_seasonal1 |
The prior distribution for the initial seasonal parameters in a SSM model.
The prior is specified for the first m seasonal parameters, where m is the periodicity of the
defined time series. By default the value is set |
prior_breg |
The prior distribution for the regression coefficient parameters in a
ARMAX model. By default the value is set |
prior_df |
The prior distribution for the degree freedom parameters in a t-student innovations
SSM model. By default the value is set |
series.name |
an optional string vector with the series names. |
... |
Further arguments passed to |
The function returns a varstan
object with the fitted model.
When genT
option is TRUE
a t-student innovations ssm model (see Ardia (2010)) is generated
see Fonseca, et. al (2019) for more details.
The default priors used in a ssm( ) model are:
level ~ normal(0,0.5)
Trend ~ normal(0,0.5)
damped~ normal(0,0.5)
Seasonal ~ normal(0,0.5)
sigma0 ~ t-student(0,1,7)
level1 ~ normal(0,1)
trend1 ~ normal(0,1)
seasonal1 ~ normal(0,1)
dfv ~ gamma(2,0.1)
breg ~ t-student(0,2.5,6)
For changing the default prior use the function set_prior()
.
A varstan
object with the fitted SSM model.
Asael Alonzo Matamoros.
Fonseca, T. and Cequeira, V. and Migon, H. and Torres, C. (2019). The effects of
degrees of freedom estimation in the Asymmetric GARCH model with Student-t
Innovations. arXiv doi: arXiv: 1910.01398
.
Sarima
auto.arima
set_prior
garch
# Declaring a Holt-Winters model for the ipc data. sf1 = stan_Hw(ipc,iter = 500,chains = 1) # Declaring a Holt-Winters damped trend model for the ipc data. sf2 = stan_ssm(ipc,damped = TRUE,iter = 500,chains = 1)
# Declaring a Holt-Winters model for the ipc data. sf1 = stan_Hw(ipc,iter = 500,chains = 1) # Declaring a Holt-Winters damped trend model for the ipc data. sf2 = stan_ssm(ipc,damped = TRUE,iter = 500,chains = 1)
Fitting a Local level state-space model in Stan.
stan_LocalLevel( ts, xreg = NULL, genT = FALSE, chains = 4, iter = 2000, warmup = floor(iter/2), adapt.delta = 0.9, tree.depth = 10, stepwise = TRUE, prior_sigma0 = NULL, prior_level = NULL, prior_level1 = NULL, prior_breg = NULL, prior_df = NULL, series.name = NULL, ... )
stan_LocalLevel( ts, xreg = NULL, genT = FALSE, chains = 4, iter = 2000, warmup = floor(iter/2), adapt.delta = 0.9, tree.depth = 10, stepwise = TRUE, prior_sigma0 = NULL, prior_level = NULL, prior_level1 = NULL, prior_breg = NULL, prior_df = NULL, series.name = NULL, ... )
ts |
a numeric or ts object with the univariate time series. |
xreg |
Optionally, a numerical matrix of external regressors, which must have the same number of rows as ts. It should not be a data frame. |
genT |
a boolean value to specify for a generalized t-student SSM model. |
chains |
An integer of the number of Markov Chains chains to be run, by default 4 chains are run. |
iter |
An integer of total iterations per chain including the warm-up, by default the number of iterations are 2000. |
warmup |
A positive integer specifying number of warm-up (aka burn-in)
iterations. This also specifies the number of iterations used for step-size
adaptation, so warm-up samples should not be used for inference. The number
of warmup should not be larger than |
adapt.delta |
An optional real value between 0 and 1, the thin of the jumps in a HMC method. By default is 0.9. |
tree.depth |
An integer of the maximum depth of the trees evaluated during each iteration. By default is 10. |
stepwise |
If TRUE, will do stepwise selection (faster). Otherwise, it searches over all models. Non-stepwise selection can be very slow, especially for seasonal models. |
prior_sigma0 |
The prior distribution for the scale parameter in an SSM model. By default
the value is set |
prior_level |
The prior distribution for the level parameter in a SSM model.
By default the value is set |
prior_level1 |
The prior distribution for the initial level parameter in a SSM model.
By default the value is set |
prior_breg |
The prior distribution for the regression coefficient parameters in a
ARMAX model. By default the value is set |
prior_df |
The prior distribution for the degree freedom parameters in a t-student innovations
SSM model. By default the value is set |
series.name |
an optional string vector with the series names. |
... |
Further arguments passed to |
The function returns a varstan
object with the fitted model.
When genT
option is TRUE
a t-student innovations ssm model (see Ardia (2010)) is generated
see Fonseca, et. al (2019) for more details.
The default priors used in a Local_level( ) model are:
level ~ normal(0,0.5)
sigma0 ~ t-student(0,1,7)
level1 ~ normal(0,1)
dfv ~ gamma(2,0.1)
breg ~ t-student(0,2.5,6)
For changing the default prior use the function set_prior()
.
A varstan
object with the fitted Local Level model.
Asael Alonzo Matamoros.
Fonseca, T. and Cequeira, V. and Migon, H. and Torres, C. (2019). The effects of
degrees of freedom estimation in the Asymmetric GARCH model with Student-t
Innovations. arXiv doi: arXiv: 1910.01398
.
Sarima
auto.arima
set_prior
garch
# Declaring a local level model for the ipc data. sf1 = stan_LocalLevel(ipc,iter = 500,chains = 1)
# Declaring a local level model for the ipc data. sf1 = stan_LocalLevel(ipc,iter = 500,chains = 1)
naive is the model constructor for a random walk model applied to y
.
This is equivalent to an ARIMA(0,1,0) model. naive()
is simply a wrapper
to maintain forecast package similitude. seasonal
returns the model constructor
for a seasonal random walk equivalent to an ARIMA(0,0,0)(0,1,0)m model where m is the
seasonal period.
stan_naive( ts, seasonal = FALSE, m = 0, chains = 4, iter = 2000, warmup = floor(iter/2), adapt.delta = 0.9, tree.depth = 10, stepwise = TRUE, prior_mu0 = NULL, prior_sigma0 = NULL, series.name = NULL, ... )
stan_naive( ts, seasonal = FALSE, m = 0, chains = 4, iter = 2000, warmup = floor(iter/2), adapt.delta = 0.9, tree.depth = 10, stepwise = TRUE, prior_mu0 = NULL, prior_sigma0 = NULL, series.name = NULL, ... )
ts |
a numeric or ts object with the univariate time series. |
seasonal |
a Boolean value for select a seasonal random walk instead. |
m |
an optional integer value for the seasonal period. |
chains |
An integer of the number of Markov Chains chains to be run, by default 4 chains are run. |
iter |
An integer of total iterations per chain including the warm-up, by default the number of iterations are 2000. |
warmup |
A positive integer specifying number of warm-up (aka burn-in)
iterations. This also specifies the number of iterations used for step-size
adaptation, so warm-up samples should not be used for inference. The number
of warmup should not be larger than |
adapt.delta |
An optional real value between 0 and 1, the thin of the jumps in a HMC method. By default is 0.9. |
tree.depth |
An integer of the maximum depth of the trees evaluated during each iteration. By default is 10. |
stepwise |
If TRUE, will do stepwise selection (faster). Otherwise, it searches over all models. Non-stepwise selection can be very slow, especially for seasonal models. |
prior_mu0 |
The prior distribution for the location parameter in an ARIMA model. By default
the value is set |
prior_sigma0 |
The prior distribution for the scale parameter in an ARIMA model. By default
the value is set |
series.name |
an optional string vector with the series names. |
... |
Further arguments passed to |
The random walk with drift model is
where is a normal iid error.
The seasonal naive model is
where is a normal iid error.
A varstan
object with the fitted naive Random Walk model.
Asael Alonzo Matamoros
Hyndman, R. & Khandakar, Y. (2008). Automatic time series forecasting: the
forecast package for R
. Journal of Statistical Software. 26(3),
1-22.doi: 10.18637/jss.v027.i03
.
Box, G. E. P. and Jenkins, G.M. (1978). Time series analysis: Forecasting and
control. San Francisco: Holden-Day. Biometrika, 60(2), 297-303.
doi:10.1093/biomet/65.2.297
.
Kennedy, P. (1992). Forecasting with dynamic regression models: Alan Pankratz, 1991.
International Journal of Forecasting. 8(4), 647-648.
url: https://EconPapers.repec.org/RePEc:eee:intfor:v:8:y:1992:i:4:p:647-648
.
library(astsa) # A seasonal Random-walk model. sf1 = stan_naive(birth,seasonal = TRUE,iter = 500,chains = 1)
library(astsa) # A seasonal Random-walk model. sf1 = stan_naive(birth,seasonal = TRUE,iter = 500,chains = 1)
Fitting a SARIMA model in Stan.
stan_sarima( ts, order = c(1, 0, 0), seasonal = c(0, 0, 0), xreg = NULL, period = 0, chains = 4, iter = 2000, warmup = floor(iter/2), adapt.delta = 0.9, tree.depth = 10, stepwise = TRUE, prior_mu0 = NULL, prior_sigma0 = NULL, prior_ar = NULL, prior_ma = NULL, prior_sar = NULL, prior_sma = NULL, prior_breg = NULL, series.name = NULL, ... )
stan_sarima( ts, order = c(1, 0, 0), seasonal = c(0, 0, 0), xreg = NULL, period = 0, chains = 4, iter = 2000, warmup = floor(iter/2), adapt.delta = 0.9, tree.depth = 10, stepwise = TRUE, prior_mu0 = NULL, prior_sigma0 = NULL, prior_ar = NULL, prior_ma = NULL, prior_sar = NULL, prior_sma = NULL, prior_breg = NULL, series.name = NULL, ... )
ts |
a numeric or ts object with the univariate time series. |
order |
A specification of the non-seasonal part of the ARIMA model: the three components (p, d, q) are the AR order, the number of differences, and the MA order. |
seasonal |
A specification of the seasonal part of the ARIMA model,same as order parameter: the three components (p, d, q) are the seasonal AR order, the degree of seasonal differences, and the seasonal MA order. |
xreg |
Optionally, a numerical matrix of external regressors, which must have the same number of rows as ts. It should not be a data frame. |
period |
an integer specifying the periodicity of the time series by default the value frequency(ts) is used. |
chains |
An integer of the number of Markov Chains chains to be run, by default 4 chains are run. |
iter |
An integer of total iterations per chain including the warm-up, by default the number of iterations are 2000. |
warmup |
A positive integer specifying number of warm-up (aka burn-in)
iterations. This also specifies the number of iterations used for step-size
adaptation, so warm-up samples should not be used for inference. The number
of warmup should not be larger than |
adapt.delta |
An optional real value between 0 and 1, the thin of the jumps in a HMC method. By default is 0.9. |
tree.depth |
An integer of the maximum depth of the trees evaluated during each iteration. By default is 10. |
stepwise |
If TRUE, will do stepwise selection (faster). Otherwise, it searches over all models. Non-stepwise selection can be very slow, especially for seasonal models. |
prior_mu0 |
The prior distribution for the location parameter in an ARIMA model. By default
the value is set |
prior_sigma0 |
The prior distribution for the scale parameter in an ARIMA model. By default
the value is set |
prior_ar |
The prior distribution for the auto-regressive parameters in an ARIMA model.
By default the value is set |
prior_ma |
The prior distribution for the moving average parameters in an ARIMA model.
By default the value is set |
prior_sar |
The prior distribution for the seasonal auto-regressive parameters in a
SARIMA model. By default the value is set |
prior_sma |
The prior distribution for the seasonal moving average parameters in a
SARIMA model. By default the value is set |
prior_breg |
The prior distribution for the regression coefficient parameters in a
ARIMAX model. By default the value is set |
series.name |
an optional string vector with the series names. |
... |
Further arguments passed to |
The function returns a varstan
object with the fitted model.
If xreg
option is used, the model by default will cancel the
seasonal differences adjusted (D = 0). If a value d
> 0 is used, all
the regressor variables in xreg
will be difference as well.
The default priors used in Sarima are:
ar ~ normal(0,0.5)
ma ~ normal(0,0.5)
mu0 ~ t-student(0,2.5,6)
sigma0 ~ t-student(0,1,7)
sar ~ normal(0,0.5)
sma ~ normal(0,0.5)
breg ~ t-student(0,2.5,6)
A varstan
object with the fitted SARIMA model.
Asael Alonzo Matamoros
Box, G. E. P. and Jenkins, G.M. (1978). Time series analysis: Forecasting and
control. San Francisco: Holden-Day. Biometrika, 60(2), 297-303.
doi:10.1093/biomet/65.2.297
.
Kennedy, P. (1992). Forecasting with dynamic regression models: Alan Pankratz, 1991.
International Journal of Forecasting. 8(4), 647-648.
url: https://EconPapers.repec.org/RePEc:eee:intfor:v:8:y:1992:i:4:p:647-648
.
Hyndman, R. & Khandakar, Y. (2008). Automatic time series forecasting: the
forecast package for R
. Journal of Statistical Software. 26(3),
1-22.doi: 10.18637/jss.v027.i03
library(astsa) # Declare a multiplicative seasonal ARIMA model for the birth data. sf1 = stan_sarima(birth,order = c(0,1,2), seasonal = c(1,1,1),iter = 500,chains = 1) #Declare an Dynamic Harmonic Regression model for the birth data. sf2 = stan_sarima(birth,order = c(1,0,1), xreg = fourier(birth,K = 2),iter = 500,chains = 1)
library(astsa) # Declare a multiplicative seasonal ARIMA model for the birth data. sf1 = stan_sarima(birth,order = c(0,1,2), seasonal = c(1,1,1),iter = 500,chains = 1) #Declare an Dynamic Harmonic Regression model for the birth data. sf2 = stan_sarima(birth,order = c(1,0,1), xreg = fourier(birth,K = 2),iter = 500,chains = 1)
Fitting an Additive linear State space model in Stan.
stan_ssm( ts, trend = FALSE, damped = FALSE, seasonal = FALSE, xreg = NULL, period = 0, genT = FALSE, chains = 4, iter = 2000, warmup = floor(iter/2), adapt.delta = 0.9, tree.depth = 10, stepwise = TRUE, prior_sigma0 = NULL, prior_level = NULL, prior_level1 = NULL, prior_trend = NULL, prior_trend1 = NULL, prior_damped = NULL, prior_seasonal = NULL, prior_seasonal1 = NULL, prior_breg = NULL, prior_df = NULL, series.name = NULL, ... )
stan_ssm( ts, trend = FALSE, damped = FALSE, seasonal = FALSE, xreg = NULL, period = 0, genT = FALSE, chains = 4, iter = 2000, warmup = floor(iter/2), adapt.delta = 0.9, tree.depth = 10, stepwise = TRUE, prior_sigma0 = NULL, prior_level = NULL, prior_level1 = NULL, prior_trend = NULL, prior_trend1 = NULL, prior_damped = NULL, prior_seasonal = NULL, prior_seasonal1 = NULL, prior_breg = NULL, prior_df = NULL, series.name = NULL, ... )
ts |
a numeric or ts object with the univariate time series. |
trend |
a boolean value to specify a trend local level model. By default
is |
damped |
a boolean value to specify a damped trend local level model. By default
is |
seasonal |
a boolean value to specify a seasonal local level model. By default
is |
xreg |
Optionally, a numerical matrix of external regressors, which must have the same number of rows as ts. It should not be a data frame. |
period |
an integer specifying the periodicity of the time series by default the value frequency(ts) is used. |
genT |
a boolean value to specify for a generalized t-student SSM model. |
chains |
An integer of the number of Markov Chains chains to be run, by default 4 chains are run. |
iter |
An integer of total iterations per chain including the warm-up, by default the number of iterations are 2000. |
warmup |
A positive integer specifying number of warm-up (aka burn-in)
iterations. This also specifies the number of iterations used for step-size
adaptation, so warm-up samples should not be used for inference. The number
of warmup should not be larger than |
adapt.delta |
An optional real value between 0 and 1, the thin of the jumps in a HMC method. By default is 0.9. |
tree.depth |
An integer of the maximum depth of the trees evaluated during each iteration. By default is 10. |
stepwise |
If TRUE, will do stepwise selection (faster). Otherwise, it searches over all models. Non-stepwise selection can be very slow, especially for seasonal models. |
prior_sigma0 |
The prior distribution for the scale parameter in an SSM model. By default
the value is set |
prior_level |
The prior distribution for the level parameter in a SSM model.
By default the value is set |
prior_level1 |
The prior distribution for the initial level parameter in a SSM model.
By default the value is set |
prior_trend |
The prior distribution for the trend parameter in a SSM model.
By default the value is set |
prior_trend1 |
The prior distribution for the initial trend parameter in a SSM model.
By default the value is set |
prior_damped |
The prior distribution for the damped trend parameter in a SSM model.
By default the value is set |
prior_seasonal |
The prior distribution for the seasonal parameter in a SSM model.
By default the value is set |
prior_seasonal1 |
The prior distribution for the initial seasonal parameters in a SSM model.
The prior is specified for the first m seasonal parameters, where m is the periodicity of the
defined time series. By default the value is set |
prior_breg |
The prior distribution for the regression coefficient parameters in a
ARMAX model. By default the value is set |
prior_df |
The prior distribution for the degree freedom parameters in a t-student innovations
SSM model. By default the value is set |
series.name |
an optional string vector with the series names. |
... |
Further arguments passed to |
The function returns a varstan
object with the fitted model.
By default the ssm()
function generates a local level model (or a ets("A","N","N") or
exponential smoothing model from the forecast package). If trend
is set TRUE
,
then a local trend ssm model is defined (a equivalent ets("A","A","N") or Holt model from the
forecast package). For damped trend models set damped
to TRUE
. If seasonal
is set to TRUE
a seasonal local level model is defined (a equivalent ets("A","N","A") model
from the forecast package). For a Holt-Winters method (ets("A","A","A")) set Trend
and
seasonal
to TRUE
.
When genT
option is TRUE
a t-student innovations ssm model (see Ardia (2010)) is generated
see Fonseca, et. al (2019) for more details.
The default priors used in a ssm( ) model are:
level ~ normal(0,0.5)
Trend ~ normal(0,0.5)
damped~ normal(0,0.5)
Seasonal ~ normal(0,0.5)
sigma0 ~ t-student(0,1,7)
level1 ~ normal(0,1)
trend1 ~ normal(0,1)
seasonal1 ~ normal(0,1)
dfv ~ gamma(2,0.1)
breg ~ t-student(0,2.5,6)
For changing the default prior use the function set_prior()
.
A varstan
object with the fitted SSM model.
Asael Alonzo Matamoros.
Fonseca, T. and Cequeira, V. and Migon, H. and Torres, C. (2019). The effects of
degrees of freedom estimation in the Asymmetric GARCH model with Student-t
Innovations. arXiv doi: arXiv: 1910.01398
.
Sarima
auto.arima
set_prior
garch
# Declaring a local level model for the ipc data. sf1 = stan_ssm(ipc,iter = 500,chains = 1) # Declaring a Holt model for the ipc data. sf2 = stan_ssm(ipc,trend = TRUE,damped = TRUE,iter = 500,chains = 1)
# Declaring a local level model for the ipc data. sf1 = stan_ssm(ipc,iter = 500,chains = 1) # Declaring a Holt model for the ipc data. sf2 = stan_ssm(ipc,trend = TRUE,damped = TRUE,iter = 500,chains = 1)
Fitting a Stochastic Volatility model (SVM) in Stan.
stan_SVM( ts, arma = c(0, 0), xreg = NULL, chains = 4, iter = 2000, warmup = floor(iter/2), adapt.delta = 0.9, tree.depth = 10, stepwise = TRUE, prior_mu0 = NULL, prior_sigma0 = NULL, prior_ar = NULL, prior_ma = NULL, prior_alpha = NULL, prior_beta = NULL, prior_breg = NULL, series.name = NULL, ... )
stan_SVM( ts, arma = c(0, 0), xreg = NULL, chains = 4, iter = 2000, warmup = floor(iter/2), adapt.delta = 0.9, tree.depth = 10, stepwise = TRUE, prior_mu0 = NULL, prior_sigma0 = NULL, prior_ar = NULL, prior_ma = NULL, prior_alpha = NULL, prior_beta = NULL, prior_breg = NULL, series.name = NULL, ... )
ts |
a numeric or ts object with the univariate time series. |
arma |
Optionally, a specification of the ARMA model,same as order parameter: the two components (p, q) are the AR order,and the MA order. |
xreg |
Optionally, a numerical matrix of external regressors, which must have the same number of rows as ts. It should not be a data frame. |
chains |
An integer of the number of Markov Chains chains to be run, by default 4 chains are run. |
iter |
An integer of total iterations per chain including the warm-up, by default the number of iterations are 2000. |
warmup |
A positive integer specifying number of warm-up (aka burn-in)
iterations. This also specifies the number of iterations used for step-size
adaptation, so warm-up samples should not be used for inference. The number
of warmup should not be larger than |
adapt.delta |
An optional real value between 0 and 1, the thin of the jumps in a HMC method. By default is 0.9. |
tree.depth |
An integer of the maximum depth of the trees evaluated during each iteration. By default is 10. |
stepwise |
If TRUE, will do stepwise selection (faster). Otherwise, it searches over all models. Non-stepwise selection can be very slow, especially for seasonal models. |
prior_mu0 |
The prior distribution for the location parameter in an SVM model. By default
the value is set |
prior_sigma0 |
The prior distribution for the scale parameter in an SVM model. By default
the value is set |
prior_ar |
The prior distribution for the auto-regressive parameters in an ARMA model.
By default the value is set |
prior_ma |
The prior distribution for the moving average parameters in an ARMA model.
By default the value is set |
prior_alpha |
The prior distribution for the arch parameters in a GARCH model.
By default the value is set |
prior_beta |
The prior distribution for the GARCH parameters in a GARCH model.
By default the value is set |
prior_breg |
The prior distribution for the regression coefficient parameters in a
ARIMAX model. By default the value is set |
series.name |
an optional string vector with the series names. |
... |
Further arguments passed to |
The function returns a varstan
object with the fitted model.
A varstan
object with the fitted SVM model.
Asael Alonzo Matamoros
Sangjoon,K. and Shephard, N. and Chib.S (1998). Stochastic Volatility: Likelihood
Inference and Comparison with ARCH Models. Review of Economic Studies.
65(1), 361-93. url: https://www.jstor.org/stable/2566931
.
Tsay, R (2010). Analysis of Financial Time Series. Wiley-Interscience. 978-0470414354, second edition.
Shumway, R.H. and Stoffer, D.S. (2010).Time Series Analysis and Its Applications: With R Examples. Springer Texts in Statistics. isbn: 9781441978646. First edition.
# Declares a SVM model for the IPC data sf1 = stan_SVM(ipc,arma = c(1,1),iter = 500,chains = 1)
# Declares a SVM model for the IPC data sf1 = stan_SVM(ipc,arma = c(1,1),iter = 500,chains = 1)
student(mu,sd)
student(mu = 0, sd = 1, df = 5)
student(mu = 0, sd = 1, df = 5)
mu |
the location parameter mu |
sd |
the standard deviation parameter sigma |
df |
the degree freedom parameter df |
Define a t student prior distribution using the hyper parameters mu, sigma and df as degree freedom, by default a standard t-student(0,1,5) distribution with 5 degree freedom is return.
a numerical vector interpreted as a prior in Stan
Summaries of parameter estimates and MCMC convergence diagnostics (Monte Carlo error, effective sample size, Rhat).
## S3 method for class 'varstan' summary(object, robust = FALSE, prob = 0.9, ...)
## S3 method for class 'varstan' summary(object, robust = FALSE, prob = 0.9, ...)
object |
A varstan object. |
robust |
A boolean value, if its |
prob |
A number |
... |
Further arguments passed to |
A data.frame with the posterior mean, standard error, credible intervals, effective sample
size (ess),and Rhat for all the model parameters in a varstan model, if robust
is TRUE
then the posterior mean and standard error, are replaced by the posterior mean and MAD.
Asael Alonzo Matamoros.
Constructor of the Stochastic Volatility model (SVM) for Bayesian estimation in Stan.
SVM(ts,arma = c(0,0),xreg = NULL,series.name = NULL)
SVM(ts,arma = c(0,0),xreg = NULL,series.name = NULL)
ts |
a numeric or ts object with the univariate time series. |
arma |
Optionally, a specification of the ARMA model,same as order parameter: the two components (p, q) are the AR order,and the MA order. |
xreg |
Optionally, a numerical matrix of external regressors, which must have the same number of rows as ts. It should not be a data frame. |
series.name |
an optional string vector with the time series names. |
The function returns a list with the data for running stan()
function of
rstan package.
The function returns a list with the data for running stan()
function of
rstan package.
Asael Alonzo Matamoros
Sangjoon,K. and Shephard, N. and Chib.S (1998). Stochastic Volatility: Likelihood
Inference and Comparison with ARCH Models. Review of Economic Studies.
65(1), 361-93. url: https://www.jstor.org/stable/2566931
.
Tsay, R (2010). Analysis of Financial Time Series. Wiley-Interscience. 978-0470414354, second edition.
Shumway, R.H. and Stoffer, D.S. (2010).Time Series Analysis and Its Applications: With R Examples. Springer Texts in Statistics. isbn: 9781441978646. First edition.
# Declares a SVM model for the IPC data model = SVM(ipc,arma = c(1,1)) model
# Declares a SVM model for the IPC data model = SVM(ipc,arma = c(1,1)) model
uniform(shape1,shape2)
uniform(min = 0, max = 1)
uniform(min = 0, max = 1)
min |
the first form parameter |
max |
the second form parameter |
Define a beta prior distribution using the hyper parameters min and max, by default a uniform(0,1) distribution is return.
a numerical vector interpreted as a prior in Stan
Constructor of the varstan object for Bayesian estimation in Stan.
varstan(model,chains=4,iter=2000,warmup=floor(iter/2), adapt.delta = 0.90,tree.depth =10,...)
varstan(model,chains=4,iter=2000,warmup=floor(iter/2), adapt.delta = 0.90,tree.depth =10,...)
model |
One of the |
chains |
An integer of the number of Markov Chains chains to be run, by default 4 chains are run. |
iter |
An integer of total iterations per chain including the warm-up, by default the number of iterations are 2000. |
warmup |
A positive integer specifying number of warm-up (aka burn-in)
iterations. This also specifies the number of iterations used for stepsize
adaptation, so warmup samples should not be used for inference. The number
of warmup should not be larger than |
adapt.delta |
An optional real value between 0 and 1, the thin of the jumps in a HMC method. By default is 0.9. |
tree.depth |
An integer of the maximum depth of the trees evaluated during each iteration. By default is 10. |
... |
Further arguments passed to |
The function estimates one of the defined models in Stan using
the stan()
function for sampling.
This is the principal package's function and the link with Stan, this function fits the posterior distribution of every parameter for a defined model using a HMC method.
Every estimated model become a varstan
object, with different methods
for summary, diagnostic, forecast and plotting.
Defining priors
Default priors are chosen to be non or very weakly informative so that their influence on the results will. However, after getting more familiar with Bayesian statistics, I recommend you to start thinking about reasonable informative priors for your model parameters.
Those can be changed using the function set_prior()
before estimating the
model with the varstan()
function. For checking the defined priors use
get_prior()
and report()
functions.
Adjusting the sampling behavior of Stan
In addition to choosing the number of iterations, warmup samples, and
chains, users can control the behavior of the NUTS sampler, by using the
control
argument. The most important reason to use control
is to decrease (or eliminate at best) the number of divergent transitions
that cause a bias in the obtained posterior samples. Whenever you see the
warning "There were x divergent transitions after warmup." you should really
think about increasing adapt_delta
. Increasing adapt_delta
will
slow down the sampler but will decrease the number of divergent transitions
threatening the validity of your posterior samples.
Another problem arises when the depth of the tree being evaluated in each iteration
is exceeded. This is less common than having divergent transitions, but may also
bias the posterior samples. When it happens, Stan will throw out a warning
suggesting to increase max_treedepth
. For more details on the control
argument see stan
.
a varstan
object with the estimated time series model.
A varstan
object is a list that contains the following values:
Stanfit a Stanfit object returned by rstan
pacakge.
stan.parmaters The parameters used in Stan for the sample.
model The defined model for the time series.
series.name The time series' name.
ts The provided time series data.
Asael Alonzo Matamoros
Carpenter, B. and Gelman, A. and Hoffman, D. and Lee, D. and Goodrich, B. and
Betancourt, M. and Brubaker, and Guo, L. and Riddell. 2017. Stan: A probabilistic
programming language. Journal of Statistical Software 76(1).
doi: 10.18637/jss.v076.i01
.
Stan Development Team. (2018). Stan Modeling Language Users Guide and Reference Manual,
Version 2.18.0. url: http://mc-stan.org
.
Paul-Christian Buerkner (2017). brms: An R Package for Bayesian Multilevel
Models Using Stan. Journal of Statistical Software, 80(1), 1-28.
doi:10.18637/jss.v080.i01
Hyndman, R. & Khandakar, Y. (2008). Automatic time series forecasting: the
forecast package for R
. Journal of Statistical Software. 26(3),
1-22.doi: 10.18637/jss.v027.i03
.
library(astsa) # Fitting a seasonal ARIMA model mod1 = Sarima(birth,order = c(0,1,2),seasonal = c(1,1,1)) fit1 = varstan(mod1,iter = 500,chains = 1) fit1 # Fitting a GARCH(1,1) model dat = garch(ipc,order = c(1,1,0)) fit2 = varstan(dat,iter = 500,chains = 1) fit2
library(astsa) # Fitting a seasonal ARIMA model mod1 = Sarima(birth,order = c(0,1,2),seasonal = c(1,1,1)) fit1 = varstan(mod1,iter = 500,chains = 1) fit1 # Fitting a GARCH(1,1) model dat = garch(ipc,order = c(1,1,0)) fit2 = varstan(dat,iter = 500,chains = 1) fit2
Compute the widely applicable information criterion (WAIC)
based on the posterior likelihood using the loo package.
For more details see waic
.
## S3 method for class 'varstan' waic(x, ...)
## S3 method for class 'varstan' waic(x, ...)
x |
A varstan object |
... |
additional values need in waic methods |
See the loo_compare
function of the loo package
for more details on model comparisons.
An object of class loo
. With the estimates of the
Watanabe-Akaike Information criteria.
Vehtari, A., Gelman, A., & Gabry J. (2016). Practical Bayesian model
evaluation using leave-one-out cross-validation and WAIC. In Statistics
and Computing, doi:10.1007/s11222-016-9696-4
.
Gelman, A., Hwang, J., & Vehtari, A. (2014). Understanding predictive information criteria for Bayesian models. Statistics and Computing. 24, 997-1016.
Watanabe, S. (2010). Asymptotic equivalence of Bayes cross validation and widely applicable information criterion in singular learning theory. The Journal of Machine Learning Research. 11, 3571-3594.
library(astsa) model = Sarima(birth,order = c(0,1,2),seasonal = c(1,1,1)) fit1 = varstan(model,iter = 500,chains = 1) waic1 = waic(fit1) waic1
library(astsa) model = Sarima(birth,order = c(0,1,2),seasonal = c(1,1,1)) fit1 = varstan(model,iter = 500,chains = 1) waic1 = waic(fit1) waic1