| Title: | Bayesian Simultaneous Equation Models for Forecasting |
|---|---|
| Description: | Estimate and forecast Bayesian simultaneous equation models for macroeconomic time series. Provides tools to specify systems of behavioral equations and accounting identities, transform and manage time series, simulate from the posterior using a Metropolis-within-Gibbs sampler, and generate unconditional and conditional forecasts with user-defined priors and restrictions. Methods are described in Rathke A. and Sarferaz S. (forthcoming) "Bayesian Estimation of Simultaneous Equations Model". |
| Authors: | Samad Sarferaz [aut, cph] (ORCID: <https://orcid.org/0000-0001-9283-3293>), Merlin Scherer [aut, cre, cph] (ORCID: <https://orcid.org/0009-0005-7479-168X>), Laurent Florin [ctb], Andrew D. Martin [ctb, cph] (Adapted rwish/riwish code from MCMCpack), Kevin M. Quinn [ctb, cph] (Adapted rwish/riwish code from MCMCpack), Jong Hee Park [ctb, cph] (Adapted rwish/riwish code from MCMCpack), Bill Venables [ctb, cph] (Adapted multivariate_norm code from MASS::mvrnorm), Brian D. Ripley [ctb, cph] (Adapted multivariate_norm code from MASS::mvrnorm) |
| Maintainer: | Merlin Scherer <[email protected]> |
| License: | GPL (>= 3) |
| Version: | 0.4.1 |
| Built: | 2026-10-09 16:30:29 UTC |
| Source: | https://github.com/timothymerlin/koma |
Visualize autocorrelation functions (ACF) for coefficient draws from a
koma_estimate object. By default, beta, gamma, and sigma draws are shown
when available.
acf_plot(x, ...)acf_plot(x, ...)
x |
A |
... |
Additional arguments controlling the plot. See Details. |
Additional arguments supported in ...:
Optional character vector of endogenous variables to plot.
Optional character vector of parameter groups to plot (e.g., "beta", "gamma", "sigma"). Defaults to all available.
Optional integer thinning interval for the stored draws. Default is 1 (no thinning).
Optional integer cap on the number of draws used per ACF. When set, the most recent draws are kept.
Optional integer maximum lag for ACF computation. When
NULL, defaults to min(30, n_draws - 1) per series.
Optional numeric confidence level in (0, 1) used for
ACF significance bands. Default is 0.95.
Facet scale option passed to ggplot2::facet_wrap.
Default is "fixed".
Optional integer number of columns for facets.
Logical. If TRUE and plotly is available, return an
interactive plot via plotly::ggplotly. Default is FALSE.
ACF values are computed with stats::acf(..., plot = FALSE) for each
retained coefficient draw series.
Note: sigma plots use omega_tilde_jw and show only variances
(no covariances) from each covariance draw.
The red dashed horizontal lines show approximate significance bounds
for zero autocorrelation, where
and is the number of retained
draws for the corresponding coefficient series.
A ggplot object, or a plotly object when interactive = TRUE and
plotly is available.
if (requireNamespace("ggplot2", quietly = TRUE)) { data("simulated_sem") set.seed(11) fit <- estimate( ts_data = simulated_sem$ts_data, sys_eq = simulated_sem$sys_eq, dates = simulated_sem$dates, options = list(gibbs = list(ndraws = 10)) ) acf_plot(fit, params = "beta", max_lag = 12) }if (requireNamespace("ggplot2", quietly = TRUE)) { data("simulated_sem") set.seed(11) fit <- estimate( ts_data = simulated_sem$ts_data, sys_eq = simulated_sem$sys_eq, dates = simulated_sem$dates, options = list(gibbs = list(ndraws = 10)) ) acf_plot(fit, params = "beta", max_lag = 12) }
Convert an mets koma_ts object to a list
as_list(x, ...) ## S3 method for class 'mts' as_list(x, ...) ## S3 method for class 'list' as_list(x, ...)as_list(x, ...) ## S3 method for class 'mts' as_list(x, ...) ## S3 method for class 'list' as_list(x, ...)
x |
An object to be converted. |
... |
Additional arguments. |
A list with ets koma_ts objects.
x <- as_mets(list( y = as_ets(ts(1:8, start = c(2020, 1), frequency = 4)), z = as_ets(ts(11:18, start = c(2020, 1), frequency = 4)) )) as_list(x)x <- as_mets(list( y = as_ets(ts(1:8, start = c(2020, 1), frequency = 4)), z = as_ets(ts(11:18, start = c(2020, 1), frequency = 4)) )) as_list(x)
Convert a list object with ets koma_ts objects to a koma_ts multivariate time series (mets)
as_mets(x, ...) ## S3 method for class 'list' as_mets(x, ...)as_mets(x, ...) ## S3 method for class 'list' as_mets(x, ...)
x |
An object to be converted. |
... |
Additional arguments. |
A koma_ts multivariate time series object.
x <- list( y = as_ets(ts(1:8, start = c(2020, 1), frequency = 4)), z = as_ets(ts(11:18, start = c(2020, 1), frequency = 4)) ) as_mets(x)x <- list( y = as_ets(ts(1:8, start = c(2020, 1), frequency = 4)), z = as_ets(ts(11:18, start = c(2020, 1), frequency = 4)) ) as_mets(x)
Concatenate two time series
concat(x, y, ...) ## S3 method for class 'ts' concat(x, y, ...) ## S3 method for class 'list' concat(x, y, ...) ## S3 method for class 'mts' concat(x, y, ...)concat(x, y, ...) ## S3 method for class 'ts' concat(x, y, ...) ## S3 method for class 'list' concat(x, y, ...) ## S3 method for class 'mts' concat(x, y, ...)
x |
A |
y |
A |
... |
arguments passed to methods (unused for the default method). |
A koma_ts object containing x followed by y.
x <- as_ets(ts(c(100, 101, 102), start = c(2020, 1), frequency = 4)) y <- as_ets(ts(c(103, 104), start = c(2020, 4), frequency = 4)) concat(x, y)x <- as_ets(ts(c(100, 101, 102), start = c(2020, 1), frequency = 4)) y <- as_ets(ts(c(103, 104), start = c(2020, 4), frequency = 4)) concat(x, y)
Estimate a system of simultaneous equations model (SEM) using a Bayesian approach. This function incorporates Gibbs sampling and allows for both density and point forecasts.
estimate( ts_data, sys_eq, dates, ..., options = list(gibbs = list(), fill = list(method = "mean")), estimates = NULL ) ## S3 method for class 'list' estimate( ts_data, sys_eq, dates, ..., options = list(gibbs = list(), fill = list(method = "mean")), estimates = NULL )estimate( ts_data, sys_eq, dates, ..., options = list(gibbs = list(), fill = list(method = "mean")), estimates = NULL ) ## S3 method for class 'list' estimate( ts_data, sys_eq, dates, ..., options = list(gibbs = list(), fill = list(method = "mean")), estimates = NULL )
ts_data |
Time-series data set for the estimation. |
sys_eq |
A |
dates |
Key-value list for date ranges in various model operations. |
... |
Additional parameters. |
options |
Optional settings for estimation. Use
|
estimates |
Ignored. Re-estimating only some equations of a previously
estimated model is currently disabled; passing a |
After estimation, use summary for a
full table of posterior summaries (with optional credible intervals and
texreg output) and print for a concise
console-friendly overview of the estimated system.
An object of class koma_estimate.
An object of class koma_estimateis a list containing the following
elements:
The estimated parameters and other relevant information obtained from the model.
A koma_seq object containing details about the system of
equations used in the model.
The time-series data used for the estimation, with any NA
values removed and lagged variables created.
The Y matrix constructed from the balanced data, used in the estimation process.
The X matrix constructed from the balanced data, used in the estimation process.
The specifications used for the Gibbs sampling.
The date ranges used during estimation.
Character vector of series names that were
supplied as plain ts (not koma_ts) in ts_data. These are assumed to
already be in rates and tagged accordingly; see the "Plain ts input"
section below.
This function provides the option for parallel computing through
the future::plan() function.
For a detailed example on executing estimate in parallel, see the vignette:
vignette("parallel").
For more details, see the
future package documentation.
If any element of ts_data is a plain ts rather than a koma_ts
(see ets), it is assumed to already be in rates, the
form the model estimates on, and is converted to koma_ts with
series_type = "rate", method = "none": the values are used as-is, no
rate/level transformation is applied. A warning lists the affected
series, and the same list is stored in the returned object as
plain_ts_names (also surfaced when the koma_estimate is printed). If a
series actually needs to be converted from levels (e.g. via a percentage
or diff_log growth rate), convert it first with ets or
as_ets; see vignette("koma-extended-timeseries").
koma_ts objects may carry custom attributes beyond series_type/
method (e.g. a project-specific value_type). Since all series in
ts_data must share the same attribute names (see as_mets),
any such extra attributes found on sibling koma_ts series are set to
NA on the converted series.
ndraws: Integer specifying the number of Gibbs sampler draws. Default is
2000.
burnin_ratio: Numeric specifying the ratio for the burn-in period.
Default is 0.5.
nstore: Integer specifying the frequency of stored draws. Every
nstore-th draw after the burn-in is kept. Default is 1.
tau: Numeric tuning parameter for enforcing an acceptance rate.
Default is 1.1.
To create a koma_seq object see system_of_equations.
For a comprehensive example of using estimate, see
vignette("koma").
Related functions within the package that may be of interest:
forecast.
data("simulated_sem") set.seed(11) fit <- estimate( ts_data = simulated_sem$ts_data, sys_eq = simulated_sem$sys_eq, dates = simulated_sem$dates, options = list(gibbs = list(ndraws = 10)) ) print(fit)data("simulated_sem") set.seed(11) fit <- estimate( ts_data = simulated_sem$ts_data, sys_eq = simulated_sem$sys_eq, dates = simulated_sem$dates, options = list(gibbs = list(ndraws = 10)) ) print(fit)
Builds one or more texreg objects from a koma_estimate, so results
can be rendered with texreg::screenreg() or similar helpers.
extract.koma_estimate( model, variables = NULL, central_tendency = "mean", ci_low = 5, ci_up = 95, digits = 2, ... )extract.koma_estimate( model, variables = NULL, central_tendency = "mean", ci_low = 5, ci_up = 95, digits = 2, ... )
model |
A |
variables |
Optional character vector of endogenous variables to
include. Defaults to all variables in |
central_tendency |
Central tendency used when summarizing estimates (e.g., "mean", "median"). Defaults to "mean". |
ci_low |
Lower bound (percent) for credible intervals. Defaults to 5. |
ci_up |
Upper bound (percent) for credible intervals. Defaults to 95. |
digits |
Number of digits to round numeric values. Defaults to 2. |
... |
Unused. Included for |
A texreg object when one variable is requested, otherwise a named
list of texreg objects.
summary.koma_estimate for
summary output with optional texreg formatting.
if (requireNamespace("texreg", quietly = TRUE)) { data("simulated_sem") set.seed(11) fit <- estimate( ts_data = simulated_sem$ts_data, sys_eq = simulated_sem$sys_eq, dates = simulated_sem$dates, options = list(gibbs = list(ndraws = 10)) ) texreg::extract(fit, variables = "consumption") }if (requireNamespace("texreg", quietly = TRUE)) { data("simulated_sem") set.seed(11) fit <- estimate( ts_data = simulated_sem$ts_data, sys_eq = simulated_sem$sys_eq, dates = simulated_sem$dates, options = list(gibbs = list(ndraws = 10)) ) texreg::extract(fit, variables = "consumption") }
Filter a koma_ts object by attribute value
filter_by_attribute(x, attribute, value, var = NULL, ...) ## S3 method for class 'mts' filter_by_attribute(x, attribute, value, var = NULL, ...) ## S3 method for class 'list' filter_by_attribute(x, attribute, value, var = NULL, ...)filter_by_attribute(x, attribute, value, var = NULL, ...) ## S3 method for class 'mts' filter_by_attribute(x, attribute, value, var = NULL, ...) ## S3 method for class 'list' filter_by_attribute(x, attribute, value, var = NULL, ...)
x |
A koma_ts object or a list of koma_ts objects. |
attribute |
The attribute name to filter by. |
value |
The attribute value to match. |
var |
An optional variable to filter by. |
... |
arguments passed to methods (unused for the default method). |
A koma_ts object or list with the matching series.
x <- as_ets( ts(1:8, start = c(2020, 1), frequency = 4), series_type = "level", method = "diff_log" ) filter_by_attribute( list(x = x), attribute = "series_type", value = "level" )x <- as_ets( ts(1:8, start = c(2020, 1), frequency = 4), series_type = "level", method = "diff_log" ) filter_by_attribute( list(x = x), attribute = "series_type", value = "level" )
This function produces forecasts for the SEM.
forecast( estimates, dates, ..., restrictions = NULL, options = list(approximate = FALSE, probs = NULL, fill = list(method = "mean"), conditional_innov_method = "projection") ) ## S3 method for class 'koma_estimate' forecast( estimates, dates, ..., restrictions = NULL, options = list(approximate = FALSE, probs = NULL, fill = list(method = "mean"), conditional_innov_method = "projection") )forecast( estimates, dates, ..., restrictions = NULL, options = list(approximate = FALSE, probs = NULL, fill = list(method = "mean"), conditional_innov_method = "projection") ) ## S3 method for class 'koma_estimate' forecast( estimates, dates, ..., restrictions = NULL, options = list(approximate = FALSE, probs = NULL, fill = list(method = "mean"), conditional_innov_method = "projection") )
estimates |
A |
dates |
Key-value list for date ranges in various model operations. |
... |
Additional parameters. |
restrictions |
List of model constraints. Default is empty. |
options |
Optional settings for forecasting. Use
|
The forecast function for SEM uses the estimates from the koma_estimate
object to produce point forecasts and, optionally, quantile forecasts.
When options$approximate is FALSE (default), point forecasts are
computed from the predictive draws (with quantiles controlled by
options$probs). When TRUE, point forecasts are computed from the mean
and median of the coefficient draws for faster, approximate results.
The returned koma_forecast object keeps forecasts as named lists of
koma_ts (for mean, median, and quantiles) alongside the input data
and matrices used to produce them.
Use the print method to print a
the forecast results, use the plot method,
to visualize the forecasts and prediction intervals.
An object of class koma_forecast.
An object of class koma_forecast is a list containing the following
elements:
Mean point forecasts as a list of time series of class
koma_ts.
Median point forecasts as a list of time series of class
koma_ts.
A list of quantiles, where each element is named
according to the quantile (e.g., "q_5", "q_50", "q_95"), and contains the
forecasts for that quantile. This element is NULL if quantiles = FALSE.
Time-series data set used in forecasting.
The Y matrix constructed from the balanced data up to the current quarter, used for forecasting.
The X matrix used for forecasting.
This function provides the option for parallel computing through
the future::plan() function.
For a detailed example on executing estimate in parallel, see the vignette:
vignette("parallel").
For more details, see the
future package documentation.
For a comprehensive example of using forecast, see
vignette("koma").
Related functions within the package that may be of interest:
estimate.
data("simulated_sem") dates <- list( current = c(2024, 4), estimation = simulated_sem$dates$estimation, forecast = list(start = c(2025, 1), end = c(2025, 4)) ) ts_data <- simulated_sem$ts_data # Endogenous series must stop at the last observed quarter before forecasting. ts_data[simulated_sem$sys_eq$endogenous_variables] <- lapply( simulated_sem$sys_eq$endogenous_variables, function(x) { stats::window(ts_data[[x]], end = dates$current) } ) set.seed(11) fit <- estimate( ts_data = ts_data, sys_eq = simulated_sem$sys_eq, dates = dates, options = list(gibbs = list(ndraws = 10)) ) fc <- forecast(fit, dates = dates) print(fc)data("simulated_sem") dates <- list( current = c(2024, 4), estimation = simulated_sem$dates$estimation, forecast = list(start = c(2025, 1), end = c(2025, 4)) ) ts_data <- simulated_sem$ts_data # Endogenous series must stop at the last observed quarter before forecasting. ts_data[simulated_sem$sys_eq$endogenous_variables] <- lapply( simulated_sem$sys_eq$endogenous_variables, function(x) { stats::window(ts_data[[x]], end = dates$current) } ) set.seed(11) fit <- estimate( ts_data = ts_data, sys_eq = simulated_sem$sys_eq, dates = dates, options = list(gibbs = list(ndraws = 10)) ) fc <- forecast(fit, dates = dates) print(fc)
This function formats an object of class koma_seq for better readability.
It formats the equations to ensure proper spacing around operators and aligns
the equations for a cleaner display. Priors are read from x$priors and
shown in front of the term they belong to, with the error-term prior last.
Equation specific settings are read from x$equation_settings and appended
in square brackets.
## S3 method for class 'koma_seq' format(x, ...)## S3 method for class 'koma_seq' format(x, ...)
x |
An object of class |
... |
Additional arguments passed to or from other methods. |
A character vector of the formatted equations.
Compute Y and X matrix (data)
Use reduced form of the model to compute Y
generate_sample_data( sample_size, sample_start, burnin, gamma_matrix, beta_matrix, sigma_matrix, endogenous_variables, exogenous_variables, predetermined_variables )generate_sample_data( sample_size, sample_start, burnin, gamma_matrix, beta_matrix, sigma_matrix, endogenous_variables, exogenous_variables, predetermined_variables )
sample_size |
The number of observations. |
sample_start |
A vector of format |
burnin |
The number of observations to discard to mitigate the dependency on starting values. |
gamma_matrix |
A matrix that defines the relationships between the variables. |
beta_matrix |
A matrix that defines the coefficients of the equation. |
sigma_matrix |
A matrix that defines the standard deviation of the error terms. |
endogenous_variables |
A vector of endogenous variables. |
exogenous_variables |
A vector of exogenous variables. |
predetermined_variables |
A vector of predetermined variables. |
It creates a sample of data where the relationship between the variables is determined by the defined parameters.
A list containing three elements:
y_matrix: The dependent variable matrix with newly generated data.
x_matrix: The matrix of exogenous and predetermined variables with newly generated data.
ts_data: A list containing time series in growth rates.
gamma_matrix <- matrix(1, nrow = 1) beta_matrix <- matrix(c(0.2, 0.5, 0.3), nrow = 3) sigma_matrix <- matrix(0.01, nrow = 1) sample <- generate_sample_data( sample_size = 12, sample_start = c(2000, 1), burnin = 4, gamma_matrix = gamma_matrix, beta_matrix = beta_matrix, sigma_matrix = sigma_matrix, endogenous_variables = "y", exogenous_variables = "x", predetermined_variables = "y.L(1)" ) names(sample)gamma_matrix <- matrix(1, nrow = 1) beta_matrix <- matrix(c(0.2, 0.5, 0.3), nrow = 3) sigma_matrix <- matrix(0.01, nrow = 1) sample <- generate_sample_data( sample_size = 12, sample_start = c(2000, 1), burnin = 4, gamma_matrix = gamma_matrix, beta_matrix = beta_matrix, sigma_matrix = sigma_matrix, endogenous_variables = "y", exogenous_variables = "x", predetermined_variables = "y.L(1)" ) names(sample)
Look up the registered policy for a koma_ts attribute
get_koma_attr_policy(attr)get_koma_attr_policy(attr)
attr |
Name of the attribute. |
The list of handlers (merge, lag, window, na_omit)
registered via set_koma_attr_policy() for attr, or NULL if no
policy has been registered – in which case merges fall back to
default_koma_attr_merge() and lag/window/na_omit leave the
attribute value unchanged.
set_koma_attr_policy( "anker", merge = function(left, right, attr, op = NULL, template = NULL) NA ) get_koma_attr_policy("anker") get_koma_attr_policy("some_other_attribute") # NULL: nothing registeredset_koma_attr_policy( "anker", merge = function(left, right, attr, op = NULL, template = NULL) NA ) get_koma_attr_policy("anker") get_koma_attr_policy("some_other_attribute") # NULL: nothing registered
Computes highest density intervals (HDIs) for a numeric sample. The HDI is defined as the shortest interval containing a target probability mass.
hdi(x, ...) ## Default S3 method: hdi(x, probs = c(0.5, 0.99), ...)hdi(x, ...) ## Default S3 method: hdi(x, probs = c(0.5, 0.99), ...)
x |
A numeric vector of draws. |
... |
Unused. |
probs |
Numeric vector of target mass levels. Values in |
A list with class "koma_hdi" containing:
Named list of matrices with columns lower and
upper, one matrix per probs level.
Sample median of the draws (used as a center reference).
Named numeric vector of NA values (not defined for
HDI).
Named numeric vector of achieved mass for each level.
Numeric vector of target masses in (0, 1].
x <- rnorm(1000) hdi(x, probs = c(0.5, 0.9)) data("simulated_sem") set.seed(11) fit <- estimate( ts_data = simulated_sem$ts_data, sys_eq = simulated_sem$sys_eq, dates = simulated_sem$dates, options = list(gibbs = list(ndraws = 10)) ) hdi_fit <- hdi(fit, probs = c(0.5, 0.9)) names(hdi_fit$intervals)x <- rnorm(1000) hdi(x, probs = c(0.5, 0.9)) data("simulated_sem") set.seed(11) fit <- estimate( ts_data = simulated_sem$ts_data, sys_eq = simulated_sem$sys_eq, dates = simulated_sem$dates, options = list(gibbs = list(ndraws = 10)) ) hdi_fit <- hdi(fit, probs = c(0.5, 0.9)) names(hdi_fit$intervals)
Computes highest density intervals (HDIs) for coefficient draws from a
koma_estimate object.
## S3 method for class 'koma_estimate' hdi(x, variables = NULL, probs = c(0.5, 0.99), include_sigma = FALSE, ...)## S3 method for class 'koma_estimate' hdi(x, variables = NULL, probs = c(0.5, 0.99), include_sigma = FALSE, ...)
x |
A |
variables |
Optional character vector of endogenous variables to
include. Defaults to all variables in |
probs |
Numeric vector of target mass levels. Values in |
include_sigma |
Logical. If TRUE, compute HDIs for the error variance parameter (omega). Default is FALSE. |
... |
Unused. |
A list with class c("koma_estimate_hdi", "koma_hdi")
containing HDI intervals per coefficient.
Computes highest density intervals (HDIs) for predictive draws in a
koma_forecast object.
## S3 method for class 'koma_forecast' hdi(x, variables = NULL, probs = c(0.5, 0.99), ...)## S3 method for class 'koma_forecast' hdi(x, variables = NULL, probs = c(0.5, 0.99), ...)
x |
A |
variables |
Optional character vector of endogenous variables to
include. Defaults to all variables in |
probs |
Numeric vector of target mass levels. Values in |
... |
Unused. |
A list with class c("koma_forecast_hdi", "koma_hdi") containing
HDI intervals per variable and horizon, along with per-horizon centers and
achieved masses.
Computes highest density regions (HDRs) for a numeric sample using a kernel density estimate. For multimodal densities, the HDR can consist of multiple disjoint intervals.
hdr(x, ...) ## Default S3 method: hdr( x, probs = c(0.5, 0.99), n_grid = 4096, integration = c("monte_carlo", "grid"), mc_use_observed = FALSE, mc_draws = NULL, mc_quantile_type = 7, bw = "nrd0", adjust = 1, kernel = "gaussian", ... )hdr(x, ...) ## Default S3 method: hdr( x, probs = c(0.5, 0.99), n_grid = 4096, integration = c("monte_carlo", "grid"), mc_use_observed = FALSE, mc_draws = NULL, mc_quantile_type = 7, bw = "nrd0", adjust = 1, kernel = "gaussian", ... )
x |
A numeric vector of draws. |
... |
Additional arguments forwarded to
|
probs |
Numeric vector of target mass levels. Values in |
n_grid |
Number of grid points for the KDE. Default is 4096. |
integration |
Integration approach for the HDR cutoff. Use |
mc_use_observed |
Logical. If TRUE, Monte Carlo integration uses the
observed draws. This can be a reasonable approximation for large |
mc_draws |
Optional integer number of draws for Monte Carlo sampling
when |
mc_quantile_type |
Quantile type passed to |
bw |
Bandwidth for |
adjust |
Bandwidth adjustment factor for
|
kernel |
Kernel for |
The Monte Carlo integration option follows the approach described by Hyndman (1996) for computing HDRs from an estimated density.
A list with class "koma_hdr" containing:
Named list of matrices with columns lower and
upper, one matrix per probs level.
Location of the KDE mode.
The density object returned by stats::density.
Named numeric vector of density cutoffs for each level.
Named numeric vector of achieved mass for each level.
For integration = "grid", this is the area under the KDE above the
cutoff (grid-based). For integration = "monte_carlo", this is the
Monte Carlo coverage, i.e. the fraction of sampled points with
density above the cutoff.
Numeric vector of target masses in (0, 1].
Hyndman, R. J. (1996). Computing and graphing highest density regions. The American Statistician, 50(2), 120–126. doi:10.2307/2684423
x <- c(rnorm(500, -2, 0.5), rnorm(500, 2, 0.5)) hdr(x, probs = c(0.5, 0.9)) data("simulated_sem") set.seed(11) fit <- estimate( ts_data = simulated_sem$ts_data, sys_eq = simulated_sem$sys_eq, dates = simulated_sem$dates, options = list(gibbs = list(ndraws = 10)) ) hdr_fit <- hdr(fit, probs = c(0.5, 0.9)) names(hdr_fit$intervals)x <- c(rnorm(500, -2, 0.5), rnorm(500, 2, 0.5)) hdr(x, probs = c(0.5, 0.9)) data("simulated_sem") set.seed(11) fit <- estimate( ts_data = simulated_sem$ts_data, sys_eq = simulated_sem$sys_eq, dates = simulated_sem$dates, options = list(gibbs = list(ndraws = 10)) ) hdr_fit <- hdr(fit, probs = c(0.5, 0.9)) names(hdr_fit$intervals)
Computes highest density regions (HDRs) for coefficient draws from a
koma_estimate object.
## S3 method for class 'koma_estimate' hdr( x, variables = NULL, probs = c(0.5, 0.99), n_grid = 4096, integration = c("monte_carlo", "grid"), mc_use_observed = FALSE, mc_draws = NULL, mc_quantile_type = 7, bw = "nrd0", adjust = 1, kernel = "gaussian", include_sigma = FALSE, ... )## S3 method for class 'koma_estimate' hdr( x, variables = NULL, probs = c(0.5, 0.99), n_grid = 4096, integration = c("monte_carlo", "grid"), mc_use_observed = FALSE, mc_draws = NULL, mc_quantile_type = 7, bw = "nrd0", adjust = 1, kernel = "gaussian", include_sigma = FALSE, ... )
x |
A |
variables |
Optional character vector of endogenous variables to
include. Defaults to all variables in |
probs |
Numeric vector of target mass levels. Values in |
n_grid |
Number of grid points for the KDE. Default is 4096. |
integration |
Integration approach for the HDR cutoff. Use |
mc_use_observed |
Logical. If TRUE, Monte Carlo integration uses the
observed draws. This can be a reasonable approximation for large |
mc_draws |
Optional integer number of draws for Monte Carlo sampling
when |
mc_quantile_type |
Quantile type passed to |
bw |
Bandwidth for |
adjust |
Bandwidth adjustment factor for
|
kernel |
Kernel for |
include_sigma |
Logical. If TRUE, compute HDRs for the error variance parameter (omega). Default is FALSE. |
... |
Additional arguments forwarded to |
A list with class c("koma_estimate_hdr", "koma_hdr")
containing HDR intervals per coefficient. The object also includes an
outliers list with draws outside the largest HDR level.
Computes highest density regions (HDRs) for predictive draws in a
koma_forecast object.
## S3 method for class 'koma_forecast' hdr( x, variables = NULL, probs = c(0.5, 0.99), n_grid = 4096, integration = c("monte_carlo", "grid"), mc_use_observed = FALSE, mc_draws = NULL, mc_quantile_type = 7, bw = "nrd0", adjust = 1, kernel = "gaussian", ... )## S3 method for class 'koma_forecast' hdr( x, variables = NULL, probs = c(0.5, 0.99), n_grid = 4096, integration = c("monte_carlo", "grid"), mc_use_observed = FALSE, mc_draws = NULL, mc_quantile_type = 7, bw = "nrd0", adjust = 1, kernel = "gaussian", ... )
x |
A |
variables |
Optional character vector of endogenous variables to
include. Defaults to all variables in |
probs |
Numeric vector of target mass levels. Values in |
n_grid |
Number of grid points for the KDE. Default is 4096. |
integration |
Integration approach for the HDR cutoff. Use |
mc_use_observed |
Logical. If TRUE, Monte Carlo integration uses the
observed draws. This can be a reasonable approximation for large |
mc_draws |
Optional integer number of draws for Monte Carlo sampling
when |
mc_quantile_type |
Quantile type passed to |
bw |
Bandwidth for |
adjust |
Bandwidth adjustment factor for
|
kernel |
Kernel for |
... |
Additional arguments forwarded to
|
A list with class c("koma_forecast_hdr", "koma_hdr") containing
HDR intervals per variable and horizon. The object also includes per-horizon
modes, cutoff levels, and achieved masses.
Initiate default theme used to plot forecasts.
init_koma_theme( index = list(start = NULL, end = NULL), title = list(font = NULL, text = NULL), font = NULL, trace_name = NULL, xaxis = list(tickfont = NULL, range = list(start = NULL, end = NULL)), digits = list(quarterly = 2, level = 2, annual = 2), yaxis = list(y = list(title = list(text = "QoQ, in %"), tick_center = 0), y2 = list(title = list(text = "Level"), tick_center = 100), tickfont = NULL, number_ticks = 5), legend = list(font = NULL), color = list(marker = list(in_sample = "rgba(111,111,111,0.6)", forecast = "rgba(33,92,175,1)"), bar_textfont = list(in_sample = "black", forecast = "white")) )init_koma_theme( index = list(start = NULL, end = NULL), title = list(font = NULL, text = NULL), font = NULL, trace_name = NULL, xaxis = list(tickfont = NULL, range = list(start = NULL, end = NULL)), digits = list(quarterly = 2, level = 2, annual = 2), yaxis = list(y = list(title = list(text = "QoQ, in %"), tick_center = 0), y2 = list(title = list(text = "Level"), tick_center = 100), tickfont = NULL, number_ticks = 5), legend = list(font = NULL), color = list(marker = list(in_sample = "rgba(111,111,111,0.6)", forecast = "rgba(33,92,175,1)"), bar_textfont = list(in_sample = "black", forecast = "white")) )
index |
Optional list with two elements: |
title |
A list to specify title options. Default is NULL.
|
font |
Sets the global font. Note that fonts used in traces and other layout components inherit from the global font. |
trace_name |
Optional list to specify the naming of traces.
If not provided, the names will be generated based on the
start date of the forecasts. For instance, if the forecast
starts at 2023-Q1, the default name for
|
xaxis |
A list with custom labels for the x-axis.
|
digits |
A list specifying the number of decimal places shown for plotted values.
|
yaxis |
A list with custom labels for the y-axes
|
legend |
A list to specify legend options.
|
color |
A list containing color options for different elements of the plot. When working with RGBA colors, the alpha value (the 'A' in RGBA) determines the transparency of the color, ranging from 0 (fully transparent) to 1 (fully opaque).
|
A named list containing the theme settings.
theme <- init_koma_theme() names(theme)theme <- init_koma_theme() names(theme)
This function checks if the given object inherits from the class koma_seq,
indicating that it represents a system of equations.
is_system_of_equations(x)is_system_of_equations(x)
x |
An object to be checked. |
Logical. Returns TRUE if the object inherits from the class
koma_seq, and FALSE otherwise.
sys <- system_of_equations("y ~ x", exogenous_variables = "x") is_system_of_equations(sys)sys <- system_of_equations("y ~ x", exogenous_variables = "x") is_system_of_equations(sys)
A list of U.S. macro series from FRED (14 quarterly series).
kleinklein
A list of 14 ts objects:
Real GDP (bil. 2017 USD, SAAR; FRED: GDPC1)
Real PCE (bil. 2017 USD, SAAR; FRED: PCECC96)
Real private investment (bil. 2017 USD, SAAR; FRED: GPDIC1)
Real government spending (bil. 2017 USD, SAAR; FRED: GCEC1)
Real net exports (bil. 2017 USD, SAAR; FRED: NETEXC)
Nominal GDP (bil. USD, SAAR; FRED: GDP)
Nominal PCE (bil. USD, SAAR; FRED: PCEC)
Nominal private investment (bil. USD, SAAR; FRED: GPDI)
Nominal government spending (bil. USD, SAAR; FRED: GCE)
Nominal profits after tax (bil. USD, SAAR; FRED: CP)
Nominal private wages & salaries (bil. USD; FRED: A132RC1Q027SBEA)
Nominal government wages & salaries (bil. USD; FRED: B202RC1Q027SBEA)
Nominal fed tax receipts (bil. USD; FRED: W007RC1Q027SBEA)
GDP implicit price deflator (2017=100, SAAR; FRED: GDPDEF)
Federal Reserve Economic Data (FRED), Federal Reserve Bank of St. Louis.
Tools for estimating and forecasting large-scale macroeconomic models, including extended time series utilities used throughout the package.
Maintainer: Merlin Scherer [email protected] (ORCID) [copyright holder]
Authors:
Merlin Scherer [email protected] (ORCID) [copyright holder]
Samad Sarferaz [email protected] (ORCID) [copyright holder]
Other contributors:
Laurent Florin [email protected] [contributor]
Andrew D. Martin (Adapted rwish/riwish code from MCMCpack) [contributor, copyright holder]
Kevin M. Quinn (Adapted rwish/riwish code from MCMCpack) [contributor, copyright holder]
Jong Hee Park (Adapted rwish/riwish code from MCMCpack) [contributor, copyright holder]
Bill Venables (Adapted multivariate_norm code from MASS::mvrnorm) [contributor, copyright holder]
Brian D. Ripley (Adapted multivariate_norm code from MASS::mvrnorm) [contributor, copyright holder]
Useful links:
Report bugs at https://github.com/TimothyMerlin/koma/issues
The function ets is used to create an extended time-series
(ets) object. Any additional attribute passed is saved as such in the ets.
as_ets and is_ets coerce an object to a time-
series and test whether an object is a time series of class koma_ts.
ets( data = NA, start = NULL, end = NULL, frequency = NULL, deltat = NULL, ts.eps = getOption("ts.eps"), ... ) as_ets(x = stats::ts(), ...) is_ets(x)ets( data = NA, start = NULL, end = NULL, frequency = NULL, deltat = NULL, ts.eps = getOption("ts.eps"), ... ) as_ets(x = stats::ts(), ...) is_ets(x)
data |
a vector or matrix of the observed time-series
values. A data frame will be coerced to a numeric matrix via
|
start |
the time of the first observation. Either a single number or a vector of two numbers (the second of which is an integer), which specify a natural time unit and a (1-based) number of samples into the time unit. See the examples for the use of the second form. |
end |
the time of the last observation, specified in the same way
as |
frequency |
the number of observations per unit of time. |
deltat |
the fraction of the sampling period between successive
observations; e.g., 1/12 for monthly data. Only one of
|
ts.eps |
time series comparison tolerance. Frequencies are
considered equal if their absolute difference is less than
|
... |
Additional attributes. |
x |
An object to be coerced / checked. |
Mixed arithmetic between koma_ts and plain ts objects currently
follows base R's group generic dispatch and may emit an
"Incompatible methods" warning even when the resulting values are valid.
Coercing both operands to koma_ts avoids that warning.
A koma_ts object.
A koma_ts object.
TRUE if the object is of class koma_ts, otherwise FALSE.
x <- ets(ts(1:8, start = c(2020, 1), frequency = 4), series_type = "level", method = "diff_log" ) x x <- ts(1:8, start = c(2020, 1), frequency = 4) as_ets(x, series_type = "level", method = "diff_log") x <- as_ets(ts(1:8, start = c(2020, 1), frequency = 4)) is_ets(x)x <- ets(ts(1:8, start = c(2020, 1), frequency = 4), series_type = "level", method = "diff_log" ) x x <- ts(1:8, start = c(2020, 1), frequency = 4) as_ets(x, series_type = "level", method = "diff_log") x <- as_ets(ts(1:8, start = c(2020, 1), frequency = 4)) is_ets(x)
Required attributes of the input time series are:
series_type - "rate" or "level"
method - "percentage", "diff_log", "none", or an expression
level(x, ...) ## S3 method for class 'ts' level(x, ...) ## S3 method for class 'mts' level(x, ...) ## S3 method for class 'list' level(x, ...)level(x, ...) ## S3 method for class 'ts' level(x, ...) ## S3 method for class 'mts' level(x, ...) ## S3 method for class 'list' level(x, ...)
x |
A time series object. Supported classes are |
... |
arguments passed to methods (unused for the default method). |
An ets object.
x <- ets(c(0.3, 0.1, 0.2, -0.1), series_type = "rate", method = "percentage") level(x)x <- ets(c(0.3, 0.1, 0.2, -0.1), series_type = "rate", method = "percentage") level(x)
Computes the Root Mean Square Error (RMSE) of a model for a given prediction horizon, incrementing the in-sample data by a quarter for each calculation until the specified horizon equals the end date in the forecast period.
model_evaluation( sys_eq, variables, horizon, ts_data, dates, ..., evaluate_on_levels = TRUE, options = list(gibbs = list(), summary = "mean", approximate = FALSE), restrictions = NULL )model_evaluation( sys_eq, variables, horizon, ts_data, dates, ..., evaluate_on_levels = TRUE, options = list(gibbs = list(), summary = "mean", approximate = FALSE), restrictions = NULL )
sys_eq |
A |
variables |
A character vector of name(s) of the stochastic endogenous variable for which the forecast error(s) should be calculated. If NULL it is calculated for all variables. |
horizon |
The forecast horizon in quarters up to which the RMSE should be calculated. |
ts_data |
time series data set, must include data until end date of forecasting period. |
dates |
Key-value list for date ranges in various model operations. |
... |
Additional parameters. |
evaluate_on_levels |
Boolean, if TRUE RMSE is calculated on levels if FALSE on growth rates. |
options |
Optional settings for model evaluation. Use
|
restrictions |
List of model constraints. Default is empty. |
The function initiates the RMSE calculation from dates$forecast$start and
continues until dates$forecast$start + horizon equals dates$forecast$end.
In each iteration, a quarter is added to both the in-sample data and to
dates$forecast$start.
DataFrame containing the RMSE of the selected Variables up to the desired horizon.
data("simulated_sem") dates <- list( estimation = list(start = c(1977, 1), end = c(2018, 4)), forecast = list(start = c(2023, 2), end = c(2023, 3)) ) rmse <- model_evaluation( sys_eq = simulated_sem$sys_eq, variables = c("consumption", "investment"), horizon = 1, ts_data = simulated_sem$ts_data, dates = dates, evaluate_on_levels = TRUE, options = list(gibbs = list(ndraws = 10), summary = "mean") ) head(rmse)data("simulated_sem") dates <- list( estimation = list(start = c(1977, 1), end = c(2018, 4)), forecast = list(start = c(2023, 2), end = c(2023, 3)) ) rmse <- model_evaluation( sys_eq = simulated_sem$sys_eq, variables = c("consumption", "investment"), horizon = 1, ts_data = simulated_sem$ts_data, dates = dates, evaluate_on_levels = TRUE, options = list(gibbs = list(ndraws = 10), summary = "mean") ) head(rmse)
This function calculates the gamma and beta matrices based on the given character gamma and beta matrices, along with identity weights. It checks the identification of all stochastic equations and verifies the order and rank conditions for model identification.
model_identification( character_gamma_matrix, character_beta_matrix, identity_weights, call = rlang::caller_env() )model_identification( character_gamma_matrix, character_beta_matrix, identity_weights, call = rlang::caller_env() )
character_gamma_matrix |
A character matrix representing the gamma structure of the model. |
character_beta_matrix |
A character matrix representing the beta structure of the model. |
identity_weights |
A list of identity weights to help construct constant vectors. |
call |
The environment from which the error is called. Defaults to
|
NULL. This function is used for side effects, stopping execution if model identification conditions are not met.
equations <- "consumption ~ gdp + consumption.L(1) + consumption.L(2), investment ~ gdp + investment.L(1) + real_interest_rate, current_account ~ current_account.L(1) + world_gdp, manufacturing ~ manufacturing.L(1) + world_gdp, service ~ service.L(1) + population + gdp, gdp == 0.5*manufacturing + 0.5*service" exogenous_variables <- c("real_interest_rate", "world_gdp", "population") sys_eq <- system_of_equations(equations, exogenous_variables) model_identification( sys_eq$character_gamma_matrix, sys_eq$character_beta_matrix, sys_eq$identities )equations <- "consumption ~ gdp + consumption.L(1) + consumption.L(2), investment ~ gdp + investment.L(1) + real_interest_rate, current_account ~ current_account.L(1) + world_gdp, manufacturing ~ manufacturing.L(1) + world_gdp, service ~ service.L(1) + population + gdp, gdp == 0.5*manufacturing + 0.5*service" exogenous_variables <- c("real_interest_rate", "world_gdp", "population") sys_eq <- system_of_equations(equations, exogenous_variables) model_identification( sys_eq$character_gamma_matrix, sys_eq$character_beta_matrix, sys_eq$identities )
Plot HDR intervals for coefficients from a koma_estimate_hdr object.
Outliers beyond the outer HDR are shown if available in the object.
The plot requires HDR levels matching box_levels to be present in the
object.
## S3 method for class 'koma_estimate_hdr' plot(x, y = NULL, ...)## S3 method for class 'koma_estimate_hdr' plot(x, y = NULL, ...)
x |
A |
y |
Ignored. Included for compatibility with the generic function. |
... |
Additional arguments controlling the plot. See Details. |
Additional arguments supported in ...:
Optional character vector of endogenous variables to plot.
Optional character vector of parameter groups to plot (e.g., "beta", "gamma", "sigma").
Optional numeric probabilities in (0, 1] (or )
defining the inner and outer HDRs. By default, uses the available
HDR levels closest to 50% and the maximum probability.
Logical. If TRUE and plotly is available, return an
interactive plot via plotly::ggplotly. Default is FALSE.
A ggplot object, or a plotly object when interactive = TRUE and
plotly is available.
Plot koma forecasts
## S3 method for class 'koma_forecast' plot(x, y = NULL, ...)## S3 method for class 'koma_forecast' plot(x, y = NULL, ...)
x |
A |
y |
Ignored. Included for compatibility with the generic function. |
... |
Additional parameters:
|
A Plotly figure object displaying the data.
if (requireNamespace("plotly", quietly = TRUE)) { data("simulated_sem") dates <- list( current = c(2024, 4), estimation = simulated_sem$dates$estimation, forecast = list(start = c(2025, 1), end = c(2025, 4)) ) ts_data <- simulated_sem$ts_data ts_data[simulated_sem$sys_eq$endogenous_variables] <- lapply( simulated_sem$sys_eq$endogenous_variables, function(x) { stats::window(ts_data[[x]], end = dates$current) } ) set.seed(11) fit <- estimate( ts_data = ts_data, sys_eq = simulated_sem$sys_eq, dates = dates, options = list(gibbs = list(ndraws = 10)) ) fc <- forecast(fit, dates = dates) plot(fc, variables = "consumption") }if (requireNamespace("plotly", quietly = TRUE)) { data("simulated_sem") dates <- list( current = c(2024, 4), estimation = simulated_sem$dates$estimation, forecast = list(start = c(2025, 1), end = c(2025, 4)) ) ts_data <- simulated_sem$ts_data ts_data[simulated_sem$sys_eq$endogenous_variables] <- lapply( simulated_sem$sys_eq$endogenous_variables, function(x) { stats::window(ts_data[[x]], end = dates$current) } ) set.seed(11) fit <- estimate( ts_data = ts_data, sys_eq = simulated_sem$sys_eq, dates = dates, options = list(gibbs = list(ndraws = 10)) ) fc <- forecast(fit, dates = dates) plot(fc, variables = "consumption") }
Provides a concise, console-friendly overview of the estimated system.
## S3 method for class 'koma_estimate' print( x, ..., variables = NULL, central_tendency = "mean", ci_low = 5, ci_up = 95, digits = 2 )## S3 method for class 'koma_estimate' print( x, ..., variables = NULL, central_tendency = "mean", ci_low = 5, ci_up = 95, digits = 2 )
x |
A |
... |
Additional arguments forwarded to formatting internals. |
variables |
Optional character vector of endogenous variables to print. Defaults to all variables. |
central_tendency |
Central tendency used when summarizing estimates (e.g., "mean", "median"). Defaults to "mean". |
ci_low |
Lower bound (percent) for credible intervals. Defaults to 5. |
ci_up |
Upper bound (percent) for credible intervals. Defaults to 95. |
digits |
Number of digits to print for numeric values. Defaults to 2. |
Invisibly returns x after printing.
summary.koma_estimate for
detailed posterior summaries.
This function prints the forecasts contained in a koma_forecast object as
a multivariate time series (mts). Users can specify which variables to print
and select either the mean forecast, the median forecast, or specific
quantiles of the forecast distribution.
## S3 method for class 'koma_forecast' print(x, ..., variables = NULL, central_tendency = NULL, digits = 4)## S3 method for class 'koma_forecast' print(x, ..., variables = NULL, central_tendency = NULL, digits = 4)
x |
A |
... |
Additional parameters. |
variables |
Optional. A character vector of variable names to print. Default is NULL, which prints all forecasted variables. |
central_tendency |
Optional. A string specifying the type of forecast to print. Can be "mean", "median", or a quantile name like "q_5", "q_50", "q_95". Default is "mean" if available, otherwise "median", or a specified quantile. |
digits |
Optional. Integer number of decimal digits to round the printed output. Default is 4. |
This function prints the forecasts contained in a koma_forecast object.
Users can choose to print either the mean forecast, the median forecast, or
specific quantiles of the forecast distribution.
If variables is specified, only the forecasts for those variables are
printed.
If central_tendency is not specified, the function defaults to printing the
mean forecast if available, otherwise the median forecast, or a specified
quantile.
Printing converts the selected forecast list to an mts for readability; the
underlying koma_forecast object remains a list of koma_ts.
Invisibly returns x, the original koma_forecast object (a list
of koma_ts objects, one per forecasted variable). Called primarily for
its side effect of printing the selected forecast as a multivariate time
series (mts) to the console.
Delegates to summary() for console output.
## S3 method for class 'koma_hdi' print(x, ...)## S3 method for class 'koma_hdi' print(x, ...)
x |
A |
... |
Additional arguments forwarded to |
Invisibly returns x.
Delegates to summary() for console output.
## S3 method for class 'koma_hdr' print(x, ...)## S3 method for class 'koma_hdr' print(x, ...)
x |
A |
... |
Additional arguments forwarded to |
Invisibly returns x.
This function prints an object of class koma_seq
to ensure the equations are displayed in a readable format.
## S3 method for class 'koma_seq' print(x, ...)## S3 method for class 'koma_seq' print(x, ...)
x |
An object of class |
... |
Additional arguments passed to or from other methods. |
No return value, called for side effects. Prints a formatted representation of the system of equations to the console, with a section header followed by each equation on its own line.
Required attributes of the input time series are:
series_type - "rate" or "level"
method - "percentage", "diff_log", "none", or an expression
rate(x, ...) ## S3 method for class 'ts' rate(x, ...) ## S3 method for class 'list' rate(x, ...) ## S3 method for class 'mts' rate(x, ...)rate(x, ...) ## S3 method for class 'ts' rate(x, ...) ## S3 method for class 'list' rate(x, ...) ## S3 method for class 'mts' rate(x, ...)
x |
A time series object. Supported classes are |
... |
arguments passed to methods (unused for the default method). |
An ets object.
x <- ets(1:10, series_type = "level", method = "diff_log") rate(x)x <- ets(1:10, series_type = "level", method = "diff_log") rate(x)
Calculates a rebased time series using a given date range as the base period. The base period average is set to 100, and all other values are scaled accordingly.
rebase(x, start, end, ...) ## S3 method for class 'ts' rebase(x, start, end, ...) ## S3 method for class 'list' rebase(x, start, end, ...) ## S3 method for class 'mts' rebase(x, start, end, ...)rebase(x, start, end, ...) ## S3 method for class 'ts' rebase(x, start, end, ...) ## S3 method for class 'list' rebase(x, start, end, ...) ## S3 method for class 'mts' rebase(x, start, end, ...)
x |
An ets object. |
start |
the time of the first observation. Either a single number or a vector of two numbers (the second of which is an integer), which specify a natural time unit and a (1-based) number of samples into the time unit. See the examples for the use of the second form. |
end |
the time of the last observation, specified in the same way
as |
... |
arguments passed to methods (unused for the default method). |
An ets object with the level computed.
x <- as_ets(ts(c(90, 95, 100, 105), start = c(2020, 1), frequency = 4)) rebase(x, start = c(2020, 2), end = c(2020, 3))x <- as_ets(ts(c(90, 95, 100, 105), start = c(2020, 1), frequency = 4)) rebase(x, start = c(2020, 2), end = c(2020, 3))
Undoes a previous set_koma_attr_policy() call, restoring the default
behavior (see default_koma_attr_merge()) for attr. Since policies are
registered globally for the session, this is the only way to undo one
short of restarting R.
reset_koma_attr_policy(attr = NULL)reset_koma_attr_policy(attr = NULL)
attr |
Name of the attribute to reset. If |
The removed policy/policies, invisibly (as returned by
get_koma_attr_policy()), or NULL if nothing was registered for
attr.
set_koma_attr_policy( "anker", merge = function(left, right, attr, op = NULL, template = NULL) NA ) reset_koma_attr_policy("anker") get_koma_attr_policy("anker") # NULL againset_koma_attr_policy( "anker", merge = function(left, right, attr, op = NULL, template = NULL) NA ) reset_koma_attr_policy("anker") get_koma_attr_policy("anker") # NULL again
Compute running means (cumulative averages) for coefficient draws from a
koma_estimate object. By default, beta, gamma, and sigma draws are
included when available.
running_mean(x, ...)running_mean(x, ...)
x |
A |
... |
Additional arguments controlling the output. See Details. |
Additional arguments supported in ...:
Optional character vector of endogenous variables to include.
Optional character vector of parameter groups to include (e.g., "beta", "gamma", "sigma"). Defaults to all available.
Optional integer thinning interval for the stored draws. Default is 1 (no thinning).
Optional integer cap on the number of draws returned. When set, the most recent draws are kept.
Optional integer number of initial retained draws to
flag as a grace window for convergence interpretation. If NULL, defaults
to max(50, ceiling(0.1 * n_retained)) per series.
Note: sigma values are based on omega_tilde_jw and use only
variances (no covariances) from each covariance draw.
A data.frame with columns draw, value, variable, param,
coef, draw_position, in_grace_window, and label.
data("simulated_sem") set.seed(11) fit <- estimate( ts_data = simulated_sem$ts_data, sys_eq = simulated_sem$sys_eq, dates = simulated_sem$dates, options = list(gibbs = list(ndraws = 10)) ) rm_df <- running_mean(fit, params = "beta", max_draws = 100) head(rm_df)data("simulated_sem") set.seed(11) fit <- estimate( ts_data = simulated_sem$ts_data, sys_eq = simulated_sem$sys_eq, dates = simulated_sem$dates, options = list(gibbs = list(ndraws = 10)) ) rm_df <- running_mean(fit, params = "beta", max_draws = 100) head(rm_df)
Visualize running means (cumulative averages) from running_mean() with a
light grey
band over the grace-window region.
running_mean_plot(x, ...)running_mean_plot(x, ...)
x |
A |
... |
Additional arguments controlling the plot. See Details in
|
Additional plot arguments in ...:
Facet scale option passed to ggplot2::facet_wrap.
Default is "free_y".
Optional integer number of columns for facets.
Logical. If TRUE and plotly is available, return an
interactive plot via plotly::ggplotly. Default is FALSE.
A ggplot object, or a plotly object when interactive = TRUE and
plotly is available.
if (requireNamespace("ggplot2", quietly = TRUE)) { data("simulated_sem") set.seed(11) fit <- estimate( ts_data = simulated_sem$ts_data, sys_eq = simulated_sem$sys_eq, dates = simulated_sem$dates, options = list(gibbs = list(ndraws = 10)) ) running_mean_plot(fit, params = "beta", max_draws = 100) }if (requireNamespace("ggplot2", quietly = TRUE)) { data("simulated_sem") set.seed(11) fit <- estimate( ts_data = simulated_sem$ts_data, sys_eq = simulated_sem$sys_eq, dates = simulated_sem$dates, options = list(gibbs = list(ndraws = 10)) ) running_mean_plot(fit, params = "beta", max_draws = 100) }
Custom koma_ts attributes (e.g. anker) are combined using
default_koma_attr_merge() unless a policy is registered here. The
default policy requires both operands' values to be identical and errors
otherwise – use this function to define how an attribute should behave
under arithmetic (merge), stats::lag(), stats::window(), and
stats::na.omit().
set_koma_attr_policy( attr, merge = NULL, lag = NULL, window = NULL, na_omit = NULL )set_koma_attr_policy( attr, merge = NULL, lag = NULL, window = NULL, na_omit = NULL )
attr |
Name of the attribute. |
merge |
Optional binary merge handler with signature
|
lag |
Optional lag handler with signature
|
window |
Optional window handler with signature
|
na_omit |
Optional |
Policies are registered globally, for the current R session: once set,
attr is handled the same way for every koma_ts operation, for every
pair of series, not just the ones that prompted the call. There is no
unset/reset function, so a policy stays in effect until it is
overwritten or the session ends. A permissive merge handler (e.g. one
that silently drops a mismatch) can mask a genuine bug in an unrelated
part of the codebase where that same mismatch should have raised an
error – register the narrowest handler that solves your actual case,
not a blanket "never error" one.
The registered policy, invisibly.
# By default, koma_ts arithmetic errors if an attribute's values differ # between operands (see `default_koma_attr_merge()`) -- e.g. subtracting # two "rate" series to build an identity like an inflation spread, where # each side carries its own (different) base-level anchor. A linear # combination of two series' rates has no single base level to invert # back to, so here dropping the anchor on mismatch is the right call. # # This changes how *all* koma_ts arithmetic handles "anker" for the rest # of the session (see Details) -- only register this once you've decided # that "anker" values are never meant to be compared for equality # elsewhere in your workflow. set_koma_attr_policy( "anker", merge = function(left, right, attr, op = NULL, template = NULL) NA )# By default, koma_ts arithmetic errors if an attribute's values differ # between operands (see `default_koma_attr_merge()`) -- e.g. subtracting # two "rate" series to build an identity like an inflation spread, where # each side carries its own (different) base-level anchor. A linear # combination of two series' rates has no single base level to invert # back to, so here dropping the anchor on mismatch is the right call. # # This changes how *all* koma_ts arithmetic handles "anker" for the rest # of the session (see Details) -- only register this once you've decided # that "anker" values are never meant to be compared for equality # elsewhere in your workflow. set_koma_attr_policy( "anker", merge = function(left, right, attr, op = NULL, template = NULL) NA )
A compact simulated example bundle for documentation and quick-start
workflows with estimate(), forecast(), and diagnostic plots.
simulated_semsimulated_sem
A list with three elements:
A named list of ets time-series objects.
A koma_seq object defining the simulated system of equations.
A named list of date ranges for estimation examples.
Simulated within the package from the SEM data generator in
data-raw/DATASET.R.
Quarterly time series of key macro variables for a small open economy (Switzerland)
small_open_economysmall_open_economy
A list of 12 ts objects (quarterly):
Private consumption \(C_t\).
Gross fixed capital formation \(I_t\).
Exports \(X_t\).
Imports \(M_t\).
Price level \(P_t\).
Short‐term domestic interest rate \(R_t\).
Equilibrium output \(GDP_t\).
Domestic demand \(D_t\).
World GDP (exogenous) \(WGDP_t\).
German short‐term rate (exog) .
Nominal exchange rate (exog) \(ER_t\).
Oil price (exogenous) \(OP_t\).
https://www.seco.admin.ch/, https://kof.ethz.ch/
This function provides a summary for koma_estimate objects. It can return either a texreg object or an ASCII table.
## S3 method for class 'koma_estimate' summary(object, ...)## S3 method for class 'koma_estimate' summary(object, ...)
object |
A koma_estimate object. |
... |
Additional parameters:
Additional arguments are forwarded to texreg output helpers (for example,
arguments accepted by |
Returns a list of summary statistics for each variable (invisibly)
when use_texreg is FALSE. When use_texreg is TRUE and texreg is
installed, returns a texreg extract object that prints via
screenreg() when printed.
Prints HDI intervals for coefficients in a table per equation.
## S3 method for class 'koma_estimate_hdi' summary(object, ..., variables = NULL, params = NULL, digits = 3)## S3 method for class 'koma_estimate_hdi' summary(object, ..., variables = NULL, params = NULL, digits = 3)
object |
A |
... |
Unused. |
variables |
Optional character vector to filter variables. |
params |
Optional character vector to filter parameters (e.g., "beta", "gamma", "sigma"). |
digits |
Number of digits to round numeric values. Default is 3. |
Invisibly returns object.
Prints HDR intervals for coefficients in a table per equation.
## S3 method for class 'koma_estimate_hdr' summary(object, ..., variables = NULL, params = NULL, digits = 3)## S3 method for class 'koma_estimate_hdr' summary(object, ..., variables = NULL, params = NULL, digits = 3)
object |
A |
... |
Unused. |
variables |
Optional character vector to filter variables. |
params |
Optional character vector to filter parameters (e.g., "beta", "gamma", "sigma"). |
digits |
Number of digits to round numeric values. Default is 3. |
Invisibly returns object.
Prints a summary table for forecast horizons, including available central tendencies (mean/median) and quantiles.
## S3 method for class 'koma_forecast' summary(object, ..., variables = NULL, horizon = NULL, digits = 3)## S3 method for class 'koma_forecast' summary(object, ..., variables = NULL, horizon = NULL, digits = 3)
object |
A |
... |
Unused. |
variables |
Optional character vector to filter variables. |
horizon |
Optional numeric or character vector selecting forecast horizon. |
digits |
Number of digits to round numeric values. Default is 3. |
Invisibly returns object.
Prints HDI intervals for forecast horizons.
## S3 method for class 'koma_forecast_hdi' summary(object, ..., variables = NULL, horizon = NULL, digits = 3)## S3 method for class 'koma_forecast_hdi' summary(object, ..., variables = NULL, horizon = NULL, digits = 3)
object |
A |
... |
Unused. |
variables |
Optional character vector to filter variables. |
horizon |
Optional numeric or character vector selecting forecast horizon. |
digits |
Number of digits to round numeric values. Default is 3. |
Invisibly returns object.
Prints HDR intervals for forecast horizons.
## S3 method for class 'koma_forecast_hdr' summary(object, ..., variables = NULL, horizon = NULL, digits = 3)## S3 method for class 'koma_forecast_hdr' summary(object, ..., variables = NULL, horizon = NULL, digits = 3)
object |
A |
... |
Unused. |
variables |
Optional character vector to filter variables. |
horizon |
Optional numeric or character vector selecting forecast horizon. |
digits |
Number of digits to round numeric values. Default is 3. |
Invisibly returns object.
Prints HDI intervals for a single numeric sample.
## S3 method for class 'koma_hdi' summary(object, ..., digits = 3)## S3 method for class 'koma_hdi' summary(object, ..., digits = 3)
object |
A |
... |
Unused. |
digits |
Number of digits to round numeric values. Default is 3. |
Invisibly returns object.
Prints HDR intervals for a single numeric sample.
## S3 method for class 'koma_hdr' summary(object, ..., digits = 3)## S3 method for class 'koma_hdr' summary(object, ..., digits = 3)
object |
A |
... |
Unused. |
digits |
Number of digits to round numeric values. Default is 3. |
Invisibly returns object.
Create and manipulate a system of equations.
system_of_equations(equations = vector(), exogenous_variables = vector(), ...)system_of_equations(equations = vector(), exogenous_variables = vector(), ...)
equations |
A character string or vector containing the system of equations. If a single string, equations should be separated by commas. |
exogenous_variables |
A character vector of exogenous variables. |
... |
Additional arguments for future extensions. |
This function constructs an object of class koma_seq representing a system
of equations, extracting and organizing key components like endogenous
variables, gamma matrix, beta matrix, and more. Equations should be separated
by commas if provided as a single string.
An object of class koma_seq with the following components:
equations: A character vector of the equations.
endogenous_variables: A character vector of endogenous variables.
stochastic_equations: A character vector of stochastic equations.
identities: A character vector of identity equations.
character_gamma_matrix: A gamma matrix in character form.
character_beta_matrix: A beta matrix in character form.
predetermined_variables: A character vector of lagged variables.
total_exogenous_variables: A character vector of combined constant,
predetermined, and exogenous variables.
priors: A list of priors per equation.
Stochastic equations use ~ (e.g. y ~ x1 + x2).
Identity equations use == (e.g. y == 0.5*x1 + 0.5*x2).
Lagged variables are denoted by X.L(x) for variable X and lag L(x)
(e.g. .L(1), .L(2)).
Dummy variables can be written as
dummies(prefix, spec), e.g. dummies(covid, 1:8) expands to
covid_1+covid_2+...+covid_8. spec follows the same syntax as lag
ranges (a single index, a lower:upper range, or a comma-separated mix).
Expansion happens before validation, so every expanded name must still be
declared in exogenous_variables, just like a hand-typed variable.
Intercept are included by default, you can also explicitly specify the
constant by adding constant to the equation (e.g. y ~ constant + x1).
To exclude the intercept, add +0 or -1 to the equation
(e.g. y ~ 0 + x1).
For more details on the equation syntax, see
vignette("equations").
get_endogenous_variables(), get_identities(),
construct_gamma_matrix(), extract_lagged_vars(),
construct_beta_matrix(), get_max_lag()
equations <- "consumption ~ gdp + consumption.L(1) + consumption.L(2), investment ~ gdp + investment.L(1) + real_interest_rate, current_account ~ current_account.L(1) + world_gdp, manufacturing ~ manufacturing.L(1) + world_gdp, service ~ service.L(1) + population + gdp, gdp == 0.4*manufacturing + 0.6*service" exogenous_variables <- c("real_interest_rate", "world_gdp", "population") system <- system_of_equations(equations, exogenous_variables) print(system)equations <- "consumption ~ gdp + consumption.L(1) + consumption.L(2), investment ~ gdp + investment.L(1) + real_interest_rate, current_account ~ current_account.L(1) + world_gdp, manufacturing ~ manufacturing.L(1) + world_gdp, service ~ service.L(1) + population + gdp, gdp == 0.4*manufacturing + 0.6*service" exogenous_variables <- c("real_interest_rate", "world_gdp", "population") system <- system_of_equations(equations, exogenous_variables) print(system)
Visualize MCMC trace plots for coefficient draws from a koma_estimate
object. By default, beta, gamma, and sigma draws are shown when available.
trace_plot(x, ...)trace_plot(x, ...)
x |
A |
... |
Additional arguments controlling the plot. See Details. |
Additional arguments supported in ...:
Optional character vector of endogenous variables to plot.
Optional character vector of parameter groups to plot (e.g., "beta", "gamma", "sigma"). Defaults to all available.
Optional integer thinning interval for the stored draws. Default is 1 (no thinning).
Optional integer cap on the number of draws per trace. When set, the most recent draws are kept.
Facet scale option passed to ggplot2::facet_wrap.
Default is "free_y".
Optional integer number of columns for facets.
Logical. If TRUE and plotly is available, return an
interactive plot via plotly::ggplotly. Default is FALSE.
Note: sigma plots use omega_tilde_jw and show only variances
(no covariances) from each covariance draw.
A ggplot object, or a plotly object when interactive = TRUE and
plotly is available.
if (requireNamespace("ggplot2", quietly = TRUE)) { data("simulated_sem") set.seed(11) fit <- estimate( ts_data = simulated_sem$ts_data, sys_eq = simulated_sem$sys_eq, dates = simulated_sem$dates, options = list(gibbs = list(ndraws = 10)) ) trace_plot(fit, params = "beta", max_draws = 100) }if (requireNamespace("ggplot2", quietly = TRUE)) { data("simulated_sem") set.seed(11) fit <- estimate( ts_data = simulated_sem$ts_data, sys_eq = simulated_sem$sys_eq, dates = simulated_sem$dates, options = list(gibbs = list(ndraws = 10)) ) trace_plot(fit, params = "beta", max_draws = 100) }