| Title: | Bayesian Simultaneous Equation Models for Forecasting |
| Version: | 0.3.1 |
| 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". |
| URL: | https://timothymerlin.github.io/koma/, https://github.com/TimothyMerlin/koma |
| License: | GPL (≥ 3) |
| Suggests: | devtools (≥ 2.4.5), ggplot2 (≥ 3.5.0), usethis (≥ 3.1.0), pkgdown (≥ 2.0.7), knitr (≥ 1.43), rmarkdown (≥ 2.24), future (≥ 1.33.0), parallelly (≥ 1.36.0), withr (≥ 3.0.0), texreg (≥ 1.39.4), testthat (≥ 3.2.3), plotly (≥ 4.11.0), webshot2 (≥ 0.1.2) |
| Encoding: | UTF-8 |
| RoxygenNote: | 7.3.3 |
| Config/testthat/edition: | 3 |
| Imports: | cli (≥ 3.6.3), doFuture (≥ 1.0.0), foreach (≥ 1.5.2), glue (≥ 1.8.0), Matrix (≥ 1.5.4.1), methods, progressr (≥ 0.15.0), purrr (≥ 1.0.4), rlang (≥ 1.1.6), stats (≥ 4.0.2), tempdisagg (≥ 1.1), utils (≥ 4.4.1) |
| Depends: | R (≥ 4.1.0) |
| LazyData: | true |
| VignetteBuilder: | knitr |
| BugReports: | https://github.com/TimothyMerlin/koma/issues |
| NeedsCompilation: | no |
| Packaged: | 2026-07-20 11:58:06 UTC; tischere |
| Author: | Samad Sarferaz |
| Maintainer: | Merlin Scherer <scherer@kof.ethz.ch> |
| Repository: | CRAN |
| Date/Publication: | 2026-07-29 17:00:02 UTC |
koma: Large Scale Macroeconomic Model
Description
Tools for estimating and forecasting large-scale macroeconomic models, including extended time series utilities used throughout the package.
Author(s)
Maintainer: Merlin Scherer scherer@kof.ethz.ch (ORCID) [copyright holder]
Authors:
Samad Sarferaz sarferaz@kof.ethz.ch (ORCID) [copyright holder]
Laurent Florin florin@kof.ethz.ch
Other contributors:
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]
See Also
Useful links:
Report bugs at https://github.com/TimothyMerlin/koma/issues
Autocorrelation Function Plots for koma_estimate Objects
Description
Visualize autocorrelation functions (ACF) for coefficient draws from a
koma_estimate object. By default, beta, gamma, and sigma draws are shown
when available.
Usage
acf_plot(x, ...)
Arguments
x |
A |
... |
Additional arguments controlling the plot. See Details. |
Details
Additional arguments supported in ...:
- variables
Optional character vector of endogenous variables to plot.
- params
Optional character vector of parameter groups to plot (e.g., "beta", "gamma", "sigma"). Defaults to all available.
- thin
Optional integer thinning interval for the stored draws. Default is 1 (no thinning).
- max_draws
Optional integer cap on the number of draws used per ACF. When set, the most recent draws are kept.
- max_lag
Optional integer maximum lag for ACF computation. When NULL, defaults to
min(30, n_draws - 1)per series.- conf_level
Optional numeric confidence level in
(0, 1)used for ACF significance bands. Default is0.95.- scales
Facet scale option passed to
ggplot2::facet_wrap. Default is "fixed".- facet_ncol
Optional integer number of columns for facets.
- interactive
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
\pm z_{1-\alpha/2}/\sqrt{n} for zero autocorrelation, where
\alpha = 1 - \mathrm{conf\_level} and n is the number of retained
draws for the corresponding coefficient series.
Value
A ggplot object, or a plotly object when interactive = TRUE and
plotly is available.
Examples
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)
}
Add Parameter Draws to a Long Data Frame
Description
Internal helper that checks whether a parameter group is selected and, if so, delegates draw extraction to a caller-supplied builder function.
Usage
add_draws(
param_name,
draws,
coef_names,
params,
variable,
build_draw_df,
mat_transform = NULL
)
Arguments
param_name |
Character scalar naming the parameter group (e.g., "beta"). |
draws |
A list of MCMC draws for the parameter group. |
coef_names |
Character vector of coefficient names. |
params |
Character vector of selected parameter groups. |
variable |
Character scalar naming the endogenous variable. |
build_draw_df |
Function that converts draws into a long data.frame. |
mat_transform |
Optional function to transform the draw matrix before conversion. |
Value
A data.frame or NULL when the parameter group is not selected or no
draws are available.
Adjust Constant Vector Using Identity Weights
Description
Adjusts a given constant vector based on a list of identity weights. The identity weights are used to replace specific elements in the constant vector with corresponding numeric values.
Usage
adjust_constant_vector(constant_vector, identity_weights)
Arguments
constant_vector |
A numeric vector representing the constant terms to be adjusted. |
identity_weights |
A list where each element corresponds to a set of identity rules. |
Value
The adjusted constant vector in numeric form with modified values based on the identity weights.
Align a koma_ts attribute or metadata series to another time series
Description
Align a koma_ts attribute or metadata series to another time series
Usage
align_koma_attr(x, attr = NULL, template)
Arguments
x |
A |
attr |
Name of the attribute to align. Only used when |
template |
A time series whose |
Value
The aligned attribute value.
Convert an mets koma_ts object to a list
Description
Convert an mets koma_ts object to a list
Usage
as_list(x, ...)
## S3 method for class 'mts'
as_list(x, ...)
## S3 method for class 'list'
as_list(x, ...)
Arguments
x |
An object to be converted. |
... |
Additional arguments. |
Value
A list with ets koma_ts objects.
Examples
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)
Description
Convert a list object with ets koma_ts objects to a koma_ts multivariate time series (mets)
Usage
as_mets(x, ...)
## S3 method for class 'list'
as_mets(x, ...)
Arguments
x |
An object to be converted. |
... |
Additional arguments. |
Value
A koma_ts multivariate time series object.
Examples
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)
Attach Color Codes to Data Frame Based on Status
Description
This function maps the status_column values in the provided data frame to
color codes, based on a specified color mapping, and attaches these color
codes as a new column color_code in the data frame.
Usage
attach_color_code(df_long, marker_color, status_column)
Arguments
df_long |
A data frame containing a column specified by |
marker_color |
A named list or other key-value mapping structure where the names or keys correspond to statuses and the values correspond to color codes. |
status_column |
The name of the column in |
Value
A data frame identical to df_long, but with an additional column
color_code which contains the color codes mapped from the status_column
based on the marker_color mapping.
Vectorize Beta Matrix
Description
Converts the character representation of the beta matrix into a transformation matrix and constant vector, such that vector = transformation_matrix %*% parameters + constant_vector where vector = vec(character_beta_matrix)
Usage
beta_vectorization(character_beta_matrix)
Arguments
character_beta_matrix |
A character matrix representing the beta structure of the model. |
Value
A list with three elements:
- transformation_matrix
A numeric matrix used for parameter transformation.
- parameters
A character vector of parameter names.
- constant_vector
A numeric vector for constant terms.
Build Fan Chart Data from Forecast Quantiles
Description
Constructs a long data frame with lower/upper band values for fan charts. If requested quantiles are missing, they are computed from forecast draws.
Usage
build_fan_data(x, tsl, forecast_start, variables, fan_quantiles)
Arguments
x |
A |
tsl |
In-sample time series list used to anchor the forecast. |
forecast_start |
Forecast start date for windowing. |
variables |
Character vector of variables to include. |
fan_quantiles |
Numeric probabilities for the fan chart. |
Value
A data frame with band values for plotting or NULL when no bands
can be constructed.
Build Whisker Data for Growth Rates from Forecast Quantiles
Description
Constructs a data frame with lower/upper values for growth-rate whiskers. If requested quantiles are missing, they are computed from forecast draws.
Usage
build_whisker_data(x, tsl, forecast_start, variables, fan_quantiles)
Arguments
x |
A |
tsl |
In-sample time series list used to anchor the forecast. |
forecast_start |
Forecast start date for windowing. |
variables |
Character vector of variables to include. |
fan_quantiles |
Numeric probabilities for the whisker bounds. |
Value
A data frame with whisker bounds or NULL when no bounds can be
constructed.
Calculate Dynamic Weights for Identity Equations
Description
Computes the weights required for identity equations using time series data. The weights represent how components collectively sum up to or are related to an aggregate value over the specified time period.
Usage
calculate_eq_weights(ts_data, iden, start, end)
Arguments
ts_data |
A named list of |
start |
A numeric value representing the start date for the time series
data subset. This value should be in the numeric format used by the function
|
end |
A numeric value representing the end date for the time series data
subset, in the same numeric format as |
Value
A list of stats::ts objects containing the calculated weights for
the given aggregate value and its components. The top-level name of the
list is the aggregate value, and its sub-level names correspond to the
component names.
Calculate the Forecast Error
Description
This function calculates the the desired forecast errors for the desired variables given the true values and the forecasts
Usage
calculate_error(forecasts, realized, variables)
Arguments
forecasts |
A mets-object containing the forecasts. |
realized |
A mets-object containing the true values. |
variables |
A character vector of name(s) of the stochastic endogenous variable for which the forecast error(s) should be calculated. |
Value
List of errors
Concatenate two time series
Description
Concatenate two time series
Usage
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, ...)
Arguments
x |
A |
y |
A |
... |
arguments passed to methods (unused for the default method). |
Value
A koma_ts object containing x followed by y.
Examples
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)
Conditional Fill and Forecast for Time Series Data
Description
This function fills missing observations and extends the time series data up to and including the current quarter. The function conditionally forecasts based on the estimates and realized observations.
Usage
conditional_fill(ts_data, sys_eq, dates, estimates, fill_method)
Arguments
ts_data |
Time-series data set for the estimation. |
sys_eq |
A |
dates |
Key-value list for date ranges in various model operations. |
estimates |
Optional. A |
fill_method |
Character string indicating which central tendency measure ("mean" or "median") to use when filling ragged edges. |
Value
An extended time series list containing the filled and forecasted time series up to the current quarter.
Construct Balanced Data
Description
Construct Balanced Data
Usage
construct_balanced_data(
ts_data,
endogenous_variables,
total_exogenous_variables,
start,
end,
state = NULL
)
Arguments
ts_data |
Time series data. |
endogenous_variables |
Endogenous variables. |
total_exogenous_variables |
Exogenous and / or predetermined variables to include in x matrix. |
start |
Start date for truncation. |
end |
End date for truncation. |
state |
An environment used to share mutable state between function calls, particularly for issuing warnings only once during the forecasting process. |
Value
A list containing the truncated time series data, y_matrix, x_matrix the number of observations, the date of last observation and the frequency.
Construct \hat{\beta_j}
Description
\hat{\beta_j} = (x_b'x_b)^{-1} x_b' Z_j
with x_b being the predetermined variables and constant of equation
j and Z_j = y_j - Y_j * \gamma_j
Usage
construct_beta_hat_j_matrix(x_matrix, z_matrix_j, character_beta_matrix, jx)
Arguments
x_matrix |
A |
z_matrix_j |
A |
character_beta_matrix |
A matrix |
jx |
The index of equation |
Value
\hat{\beta_j} with dimensions k \times 1.
Construct Beta Matrix
Description
Constructs the B matrix based on the given system of equations and the exogenous variables.
Usage
construct_beta_matrix(equations, exogenous_variables)
Arguments
equations |
A character string containing the system of equations, where equations are separated by commas. |
exogenous_variables |
A character vector representing the exogenous variables. |
Value
Beta matrix.
Construct Companion Matrices for Dynamic SEM
Description
Construct Companion Matrices for Dynamic SEM
Usage
construct_companion_matrix(posterior, exogenous_variables)
Arguments
posterior |
A list containing gamma_matrix, beta_matrix, sigma_matrix and phi_matrix derived from the LIBA estimates. |
exogenous_variables |
A character vector of names of exogenous variables. |
Value
A list containing matrices in companion form: phi_matrix, beta_tilde_matrix, gamma_matrix, c_matrix, and values n and p.
Construct Gamma Matrix
Description
Constructs a Gamma matrix based on the given system of equations and endogenous variables.
This function constructs a Gamma matrix, which is a diagonal matrix representing the coefficients of endogenous variables in the system of equations. The Gamma matrix is used in various econometric models. It also returns the constructed weights and parameters.
Usage
construct_gamma_matrix(equations, endogenous_variables)
Arguments
equations |
A character string containing the system of equations, where equations are separated by commas. |
endogenous_variables |
A character vector representing the endogenous variables. |
Value
A Gamma matrix.
Construct a Dynamic SEM (Structural Equation Model) Phi Matrix
Description
This function constructs the list of lagged endogenous coefficient matrices
\Phi(1), \ldots, \Phi(L) from the system of equations and the beta
matrix. It identifies lagged endogenous regressors in each equation and maps
their coefficients into the corresponding \Phi(\ell) matrix in the
dynamic SEM:
Y\Gamma = \tilde{X}\tilde{B} + Y_{t-1}\Phi(1) + \cdots + Y_{t-p}\Phi(L) + U.
Usage
construct_phi(sys_eq, beta_matrix)
Arguments
sys_eq |
A list containing the system of equations. Must
include |
beta_matrix |
A numeric matrix of beta coefficients corresponding to the exogenous variables in the system of equations. |
Value
A named list of n \times n matrices, one per lag \ell,
where each matrix \Phi(\ell) contains the coefficients on the
\ell-lagged endogenous variables. The list names correspond to lag
orders (as character strings).
Construct reduced form coefficients \Pi_0
Description
Computes the estimated \Pi_0, which is a (k \times n_j) matrix
of reduced form coefficients, where n_j is the number of endogenous
variables in equation j.
Usage
construct_pi_hat_0(x_matrix, z_matrix_j)
Arguments
x_matrix |
A |
z_matrix_j |
A |
Value
\hat{\Pi_0} with dimensions (k \times n_j).
Construct Posterior Matrices from LIBA Estimates
Description
This function constructs posterior system matrices from LIBA estimates.
It produces the structural coefficient matrices \Gamma and B,
the implied reduced-form coefficient matrix \Phi, the structural shock
covariance matrix \Sigma, and the reduced-form innovation covariance
matrix \Omega = (\Gamma^{-1})'\Sigma\Gamma^{-1}.
Usage
construct_posterior(sys_eq, estimate)
Arguments
sys_eq |
A |
estimate |
A draw that contains beta, gamma and omega tilde estimates. |
Details
Identity equations are incorporated via update_estimates_with_weights().
Structural shocks for identities are assumed to have zero variance, implying
corresponding zero rows and columns in \Sigma.
Value
A list containing posterior system matrices:
-
gamma_matrix: Posterior\Gamma(n x n) structural coefficient matrix. -
beta_matrix: PosteriorB(k x n) exogenous coefficient matrix. -
phi_matrix: List of lagged endogenous coefficient matrices (n x n). -
sigma_matrix: Structural shock covariance matrix\Sigma(n x n). -
omega_matrix: Reduced-form innovation covariance matrix\Omega = (\Gamma^{-1})'\Sigma\Gamma^{-1}(n x n).
Construct priors for a single equation
Description
construct_priors_j generates prior hyperparameters for equation jx
based on user-specified priors and the model's coefficient matrices.
Usage
construct_priors_j(priors, character_gamma_matrix, character_beta_matrix, jx)
Arguments
priors |
The priors for |
character_gamma_matrix |
A matrix |
character_beta_matrix |
A matrix |
jx |
The index of equation |
Value
A list with elements:
-
theta_mean: prior means for exogenous coefficients and intercept. -
theta_vcv: prior variance-covariance matrix for exogenous terms. -
omega_df: degrees of freedom for error covariance prior. -
omega_scale: scale matrix for error covariance prior. -
gamma_mean: prior means for endogenous coefficients (if set). -
gamma_vcv: prior variance-covariance for endogenous terms.
Construct Reduced Form Parameters from Companion Matrix
Description
This function computes the reduced form parameters companion_pi, companion_theta, and companion_d using the provided companion_matrix.
Usage
construct_reduced_form(companion_matrix)
Arguments
companion_matrix |
A list containing the matrices beta_tilde_matrix, phi_matrix, gamma_matrix, and c_matrix used to calculate the reduced form parameters. |
Value
A list containing the matrices companion_pi, companion_theta, and companion_d that represent the reduced form parameters
Construct \bar{\Theta}_j
Description
Computes the posterior mean for \hat{\Theta}_j with informative
priors, which is a (k \times (1 + n_j)) matrix, where n_j is
the number of endogenous variables in equation j and k is the number of
exogenous variables.
Usage
construct_theta_bar_j(x_matrix, z_matrix_j, priors_j, omega_tilde_jw)
Arguments
x_matrix |
A |
z_matrix_j |
A |
omega_tilde_jw |
A variance-covariance matrix
|
Details
\bar{\Theta}_j = \overline{\Xi} \left(
kron(\tilde{\Omega},X'X) \hat{\theta} +
\underline{\Xi}^{-1} \underline{\theta}
\right)
Value
\hat{\Theta}_j with dimensions (k \times (1 + n_j)).
Construct \hat{\Theta}_j
Description
Computes the OLS estimate for \hat{\Theta}_j, which
is a (k \times (1 + n_j)) matrix, where n_j is the number
of endogenous variables in equation j and k is the number of
exogenous variables.
Usage
construct_theta_hat_j(x_matrix, z_matrix_j)
Arguments
x_matrix |
A |
z_matrix_j |
A |
Details
\hat{\Theta}_j = (X'X)^{-1}X' Z_j
Value
\hat{\Theta}_j with dimensions (k \times (1 + n_j)).
Constructs a matrix of endogenous variables appearing in equation j
Description
This extracts a (T x n_j) matrix of endogenous variables appearing in
equation j, with T being the number of observations and
n_j the number of endogenous variables in equation j.
Usage
construct_y_matrix_j(y_matrix, character_gamma_matrix, jx)
Arguments
y_matrix |
A |
character_gamma_matrix |
A matrix |
jx |
The index of equation |
Value
If equation j contains \gamma parameters, the function
returns a subset of Y.
If there are no gamma parameters, the function returns NA.
Construct Z_j
Description
Z_j = [ \, y_j - Y_j * \gamma_j, Y_j ] \,
Usage
construct_z_matrix_j(gamma_parameters_j, y_matrix, y_matrix_j, jx)
Arguments
gamma_parameters_j |
A |
y_matrix |
A |
y_matrix_j |
A |
jx |
The index of equation |
Value
Z_j matrix with dimensions T \times 2
Create Plotly Annotations at Ticks
Description
Generates a list of annotations for Plotly plots based on x tick position. This function is designed to create text annotations for specific points on a plot, such as in-sample and out-of-sample ticks, with customizable y positions and formatting.
Usage
create_annotations(
x_ticks,
y_position,
font = list(family = NULL, size = NULL)
)
Arguments
x_ticks |
A data frame containing the tick information. Must include
columns |
y_position |
Numeric value specifying the y-axis position of all annotations, typically in paper coordinates (0 to 1). |
font |
A list specifying font attributes for the annotation text, with
optional |
Value
A list of lists, where each inner list represents an annotation in the format required by Plotly. Each annotation includes properties such as position, text, and formatting.
Create Lagged Variables for Time Series Data
Description
This function creates lagged variables for the given time series data, considering the provided endogenous and exogenous variables along with predetermined variables. The lagged variables are created based on the pattern of the predetermined variables.
Usage
create_lagged_variables(
ts_data,
endogenous_variables,
exogenous_variables,
predetermined_variables
)
Arguments
ts_data |
A named list of time series objects. |
endogenous_variables |
A character vector of names of endogenous variables. |
exogenous_variables |
A character vector of names of exogenous variables. |
predetermined_variables |
A character vector of names of predetermined variables, which contains lag information in the format "var.L(k)" where "var" is the variable name and "k" is the lag (e.g., "var.L(1)" for the first lag of the variable "var"). |
Value
A named list of time series objects with the lagged variables added according to the predetermined pattern.
Convert Date to Numeric Format
Description
This function converts a vector, list, or 2-element numeric vector of years
and quarters to a numeric representation. The format is
year + (quarter - 1) / frequency, where the frequency is the number of
periods in a year (e.g., 4 for quarters).
Usage
dates_to_num(x, frequency, ...)
Arguments
x |
A numeric vector of length 2 (year, quarter), or a list of such vectors. For a single year, pass just the year as a scalar. |
frequency |
A numeric value indicating the number of periods in a year (e.g., 4 for quarters, 12 for months). |
... |
Additional arguments passed to other methods. |
Value
A numeric representation of the date(s).
Convert Dates to String Format
Description
This function converts dates represented as a two-element numeric vector (year, period), Date, POSIXct, or a list of these, to a character. For quarterly data (frequency = 4), returns "YYYY Qn". For monthly data (frequency = 12), returns "YYYY-MM". Otherwise, returns "YYYY-MM-DD".
Usage
dates_to_str(x, frequency, ...)
Arguments
x |
A numeric vector of length 2 (year, period), a Date, POSIXct, or a list of these. |
frequency |
An integer number of periods per year (e.g., 4 = quarters, 12 = months). |
... |
Additional arguments passed to methods. |
Value
A character string or a list of character strings.
Detect the edge of a list of time series
Description
Identify either the earliest end or the latest start date across a set of
ts objects, relative to given start and end bounds.
Usage
detect_edge(ts_data, start, end, direction = c("end", "start"))
Arguments
ts_data |
Named list of |
start |
Numeric lower bound for trimming each series. |
end |
Numeric upper bound for trimming each series. |
direction |
Character; either |
Value
A list with components:
-
date: The detected edge date (numeric). -
variable_names: Names of the series achieving that edge.
Detect Lag Number from Variable Name
Description
This function takes a variable name as input and extracts the lag number from it. The lag number is assumed to be a positive integer preceded by the letter 'L'.
Usage
detect_lag(variable_name)
Arguments
variable_name |
A character string representing the variable name. |
Value
An integer representing the detected lag number from the variable name. Returns NA if no lag detected.
Draw gamma parameters for equation j
Description
draw_gamma_j draws the \gamma parameters from a given posterior
distribution for an equation j, in the Metropolis-Hastings algorithm.
Usage
draw_gamma_j(
y_matrix,
x_matrix,
character_gamma_matrix,
character_beta_matrix,
jx,
gamma_parameters_j,
tau,
cholesky_of_inverse_hessian
)
Arguments
y_matrix |
A |
x_matrix |
A |
character_gamma_matrix |
A matrix |
character_beta_matrix |
A matrix |
jx |
The index of equation |
gamma_parameters_j |
A |
tau |
A tuning scalar |
cholesky_of_inverse_hessian |
The Cholesky factor |
Value
A (n_j \times 1) matrix with the either accepted candidate or
previous gamma parameters. Returns 0 if there are no endogenous
variables in equation j.
Draw gamma parameters for equation j
Description
draw_gamma_j_informative draws the \gamma parameters from a given
posterior distribution for an equation j, in the Metropolis-Hastings
algorithm.
Usage
draw_gamma_j_informative(
y_matrix,
x_matrix,
character_gamma_matrix,
character_beta_matrix,
jx,
gamma_jw,
tau,
cholesky_of_inverse_hessian,
omega_jw,
theta_jw,
priors_j
)
Arguments
y_matrix |
A |
x_matrix |
A |
character_gamma_matrix |
A matrix |
character_beta_matrix |
A matrix |
jx |
The index of equation |
gamma_jw |
A |
tau |
A tuning scalar |
cholesky_of_inverse_hessian |
The Cholesky factor |
omega_jw |
|
theta_jw |
A |
Value
A (n_j \times 1) matrix with the either accepted candidate or
previous gamma parameters. Returns 0 if there are no endogenous
variables in equation j.
Draw Omega from inverse Wishart distribution for equation j
Description
draw_omega_j draws the variance-covariance matrix \tilde{\Omega}_j
for each row of [ u_j, V_j ].
Usage
draw_omega_j(
y_matrix,
x_matrix,
character_gamma_matrix,
character_beta_matrix,
jx,
gamma_parameters_j
)
Arguments
y_matrix |
A |
x_matrix |
A |
character_gamma_matrix |
A matrix |
character_beta_matrix |
A matrix |
jx |
The index of equation |
Value
List containing {\tilde{\Omega}}_j^{(w)} as omega_tilde_jw
and \Omega_j^{(w)} as omega_jw.
Draw Omega from inverse Wishart distribution for equation j
Description
draw_omega_j_informative draws the variance-covariance matrix
\tilde{\Omega}_j for each row of [ u_j, V_j ].
Usage
draw_omega_j_informative(
y_matrix,
x_matrix,
character_gamma_matrix,
character_beta_matrix,
jx,
gamma_jw,
theta_jw,
priors_j
)
Arguments
y_matrix |
A |
x_matrix |
A |
character_gamma_matrix |
A matrix |
character_beta_matrix |
A matrix |
jx |
The index of equation |
gamma_jw |
A |
theta_jw |
A |
priors_j |
The priors for |
Value
List containing {\tilde{\Omega}}_j^{(w)} as omega_tilde_jw
and \Omega_j^{(w)} as omega_jw.
Draw Parameters for equation j
Description
draw_parameters_j simulates from the posterior of the model's parameters
for each equation j separately.
The posterior is simulated using a Metropolis-within-Gibbs sampling
procedure.
Usage
draw_parameters_j(
y_matrix,
x_matrix,
character_gamma_matrix,
character_beta_matrix,
jx,
gibbs_sampler
)
Arguments
y_matrix |
A |
x_matrix |
A |
character_gamma_matrix |
A matrix |
character_beta_matrix |
A matrix |
jx |
The index of equation |
gibbs_sampler |
An object of class |
Details
The sampler works as follows:
Initialize sampler
Conditional on
\Omega^{(w-1)}and the data drawdelta_{\gamma}.Conditional on
delta_{\gamma}^{(w)}draw\Omega^{(w)}.Conditional on
Omega^{(w)}and\delta_{\gamma}^{(w)}draw\delta_\beta^{(w)}.Go back to step 2.
Value
A list containing matrices for the saved draws of parameters and additional diagnostic information.
Draw Parameters for equation j
Description
draw_parameters_j_informative simulates from the posterior of the model's
parameters for each equation j separately using an informative prior.
The posterior is simulated using a Metropolis-within-Gibbs sampling
procedure.
Usage
draw_parameters_j_informative(
y_matrix,
x_matrix,
character_gamma_matrix,
character_beta_matrix,
jx,
gibbs_sampler,
priors
)
Arguments
y_matrix |
A |
x_matrix |
A |
character_gamma_matrix |
A matrix |
character_beta_matrix |
A matrix |
jx |
The index of equation |
gibbs_sampler |
An object of class |
priors |
The priors for |
Details
The sampler works as follows:
Initialize sampler:
delta_{\gamma}^{(0)}and\Omega^{(0)}Conditional on
delta_{\gamma}^{(w-1)}and\Omega^{(w-1)}and the data drawdelta_{\theta}.Conditional on
delta_{\gamma}^{(w-1)},delta_{\theta}^{(w)}draw\Omega^{(w)}.Conditional on
delta_{\theta}^{(w)},Omega^{(w)}draw\delta_{\gamma}^{(w)}.Go back to step 2.
Value
A list containing matrices for the saved draws of parameters and additional diagnostic information.
Draw Theta from multivariate normal distribution for equation j
Description
Draw Theta from multivariate normal distribution for equation j
Usage
draw_theta_j(
y_matrix,
x_matrix,
character_gamma_matrix,
character_beta_matrix,
jx,
gamma_parameters_j,
omega_tilde_jw
)
Arguments
y_matrix |
A |
x_matrix |
A |
character_gamma_matrix |
A matrix |
character_beta_matrix |
A matrix |
jx |
The index of equation |
gamma_parameters_j |
A |
Value
List containing theta_jw and beta_jw
Draw Theta from multivariate normal distribution for equation j
draw_theta_j_informative draw \theta parameters from a given
posterior distribution for an equation j.
Description
Draw Theta from multivariate normal distribution for equation j
draw_theta_j_informative draw \theta parameters from a given
posterior distribution for an equation j.
Usage
draw_theta_j_informative(
y_matrix,
x_matrix,
character_gamma_matrix,
character_beta_matrix,
jx,
gamma_jw,
omega_jw,
priors_j
)
Arguments
y_matrix |
A |
x_matrix |
A |
character_gamma_matrix |
A matrix |
character_beta_matrix |
A matrix |
jx |
The index of equation |
gamma_jw |
A |
omega_jw |
|
Value
List containing theta_jw and beta_jw
Convert Draw Lists to Matrices
Description
Convert a list of MCMC draw objects into a matrix where rows correspond to coefficients and columns correspond to draws. If the draws are 3D arrays, the first slice is used.
Usage
draws_to_matrix(draws)
Arguments
draws |
A list of draws, where each element is a numeric vector or matrix representing coefficient values for a single draw. |
Value
A numeric matrix of draws, or NULL if draws is empty.
Estimate the Simultaneous Equations Model (SEM)
Description
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.
Usage
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
)
Arguments
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 |
Optional. A |
Details
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.
Value
An object of class koma_estimate.
An object of class koma_estimateis a list containing the following
elements:
- estimates
The estimated parameters and other relevant information obtained from the model.
- sys_eq
A
koma_seqobject containing details about the system of equations used in the model.- ts_data
The time-series data used for the estimation, with any
NAvalues removed and lagged variables created.- y_matrix
The Y matrix constructed from the balanced data, used in the estimation process.
- x_matrix
The X matrix constructed from the balanced data, used in the estimation process.
- gibbs_specifications
The specifications used for the Gibbs sampling.
- dates
The date ranges used during estimation.
Parallel
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.
Gibbs Sampler Specifications
-
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. Default is 1. -
tau: Numeric tuning parameter for enforcing an acceptance rate. Default is 1.1.
See Also
To create a
koma_seqobject seesystem_of_equations.For a comprehensive example of using
estimate, seevignette("koma").Related functions within the package that may be of interest:
forecast.
Examples
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)
Estimate Parameters in a System of Equations
Description
This function estimates parameters in a given system of equations using either a single thread or parallel computing.
Usage
estimate_sem(sys_eq, y_matrix, x_matrix, eq_jx = NULL)
Arguments
sys_eq |
A |
y_matrix |
A |
x_matrix |
A |
eq_jx |
A numeric vector indicating the indices of the endogenous
equations |
Details
This function provides the option for parallel computing through
the future::plan() function. For more details, see the
future package documentation.
Value
List of estimates for the endogenous variables.
Extend Time Series List with Forecast Values at New Dates
Description
This function takes a named list of original time series and extends each series with forecast values from a multi-time series (mts) only at dates not already in the original time series.
Usage
extend_ts_with_forecast(ts_list, forecast_mts)
Arguments
ts_list |
A named list of original time series objects. |
forecast_mts |
A multi-time series object with forecast values.
The column names should match the names in |
Details
The function will extend the time series in ts_list by appending
forecast values from forecast_mts. The extension will occur only for dates
that do not already exist in the original time series.
Value
A named list of time series objects, each extended with forecast
values for new dates only. For time series whose names are not present in
forecast_mts, the original time series is returned unmodified.
Extract a texreg summary from a koma_estimate
Description
Builds one or more texreg objects from a koma_estimate, so results
can be rendered with texreg::screenreg() or similar helpers.
Usage
extract.koma_estimate(
model,
variables = NULL,
central_tendency = "mean",
ci_low = 5,
ci_up = 95,
digits = 2,
...
)
Arguments
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 |
Value
A texreg object when one variable is requested, otherwise a named
list of texreg objects.
See Also
summary.koma_estimate for
summary output with optional texreg formatting.
Examples
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")
}
Extract Median Estimates
Description
This function computes either central tendency estimates (median or mean) or
returns estimates from a specific draw for gamma, beta, and sigma matrices.
It is mainly used internally by the construct_posterior function.
Usage
extract_estimates_from_draws(
sys_eq,
estimates,
jx = NULL,
central_tendency = "mean"
)
Arguments
sys_eq |
A list containing detailed components of the
system of equations such as |
estimates |
A list of estimates, obtained from previous estimation procedures. |
jx |
If an index is set then the posterior is constructed for estimate of draw jx, otherwise the posterior is constructed using the median of the estimates. The default is that the posterior is constructed using the median estimates. |
central_tendency |
A character string indicating which central tendency measure ("mean" or "median") to use. Default is "mean". Active only when jx is NULL. |
Value
A list containing:
-
gamma_matrix: Either central tendency estimates or specific draw estimates for gamma values, depending onjx. -
beta_matrix: Either central tendency estimates or specific draw estimates for beta values, depending onjx. -
sigma_matrix: Either central tendency estimates or specific draw estimates for sigma values, depending onjx.
Extract Lagged Variables from Equations
Description
This function extracts lagged variables from a given system of equations using a provided pattern that defines how lagged variables are structured.
It iterates over each equation, finds matching lag expressions, and
standardizes them in the form var.L(lag). It also rewrites each equation
to expand lag expressions and returns both the modified equations and the
set of unique lagged variables found.
Usage
extract_lagged_vars(equations, pattern)
Arguments
equations |
A character vector of equations as strings. |
pattern |
A list defining the regex pattern and capture positions for
variable name and lag specification. Must contain elements |
Value
A list with two elements:
- variables
Character vector of unique lagged variables extracted.
- equations
Character vector of transformed equations.
Fill Ragged Edges in Time Series Data
Description
This function fills in the ragged edges in a time series data set using a system of equations model. It iteratively detects edges, estimates the model, and fills the unobserved series using a one-step ahead conditional forecast until the time series is balanced.
Usage
fill_ragged_edge(ts_data, sys_eq, exogenous_variables, dates, fill_method)
Arguments
ts_data |
Time-series data set for the estimation. |
sys_eq |
A |
exogenous_variables |
A character vector of exogenous variables. |
dates |
Key-value list for date ranges in various model operations. |
fill_method |
Character string indicating which central tendency measure ("mean" or "median") to use when filling ragged edges. |
Value
A list containing the updated time series data.
Filter a koma_ts object by attribute value
Description
Filter a koma_ts object by attribute value
Usage
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, ...)
Arguments
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). |
Value
A koma_ts object or list with the matching series.
Examples
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"
)
Find Extrema Values for Growth Rates and Levels
Description
Computes the minimum and maximum values for growth rates and levels from a given data frame, adjusting these values by a certain percentage to provide a margin. This function is useful for determining the range of y-axis values in plotting functions.
Usage
find_extremas(df_long, whisker_data = NULL)
Arguments
df_long |
A data frame in long format that includes 'data_type' as a column, which should contain the types 'growth' and 'level' for categorizing the data. |
Value
A list with two elements 'growth' and 'level', each containing a 'min' and 'max' sub-element. These represent the adjusted minimum and maximum values for the growth rates and levels, respectively.
Forecast the Simultaneous Equations Model (SEM)
Description
This function produces forecasts for the SEM.
Usage
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")
)
Arguments
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
|
Details
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.
Value
An object of class koma_forecast.
An object of class koma_forecast is a list containing the following
elements:
- mean
Mean point forecasts as a list of time series of class
koma_ts.- median
Median point forecasts as a list of time series of class
koma_ts.- quantiles
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.- ts_data
Time-series data set used in forecasting.
- y_matrix
The Y matrix constructed from the balanced data up to the current quarter, used for forecasting.
- x_matrix
The X matrix used for forecasting.
Parallel
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.
See Also
For a comprehensive example of using
forecast, seevignette("koma").Related functions within the package that may be of interest:
estimate.
Examples
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)
Generate a Forecast for a Single Draw
Description
This function computes a forecast for a single draw of the parameter estimates, supporting both point forecasts (mean or median) and density forecasts. It constructs the posterior distribution, companion matrix, and reduced-form representation of the system before computing forecasts.
Usage
forecast_draw(
sys_eq,
estimates,
jx,
y_matrix,
forecast_x_matrix,
horizon,
freq,
forecast_dates,
restrictions,
state,
conditional_innov_method = "projection",
central_tendency = NULL
)
Arguments
sys_eq |
A |
estimates |
List of parameter estimates for the system. |
y_matrix |
Matrix of the dependent variable time series data. |
forecast_x_matrix |
A matrix with forecasting data for exogenous variables. |
horizon |
Forecasting horizon, specifying the number of periods. |
freq |
Frequency of the time series data. |
forecast_dates |
List containing 'start' and 'end' dates for forecast. |
restrictions |
List of model constraints. Default is empty. |
state |
An environment used to share mutable state between function calls, particularly for issuing warnings only once during the forecasting process. |
Generate Forecasts for a System of Equations
Description
This function performs forecasting based on the provided system of equations, estimates, and other parameters. It supports both density and point forecasting.
Usage
forecast_sem(
sys_eq,
estimates,
restrictions,
y_matrix,
forecast_x_matrix,
horizon,
freq,
forecast_dates,
approximate,
probs,
conditional_innov_method = "projection"
)
Arguments
sys_eq |
A |
estimates |
List of parameter estimates for the system. |
restrictions |
List of model constraints. Default is empty. |
y_matrix |
Matrix of the dependent variable time series data. |
forecast_x_matrix |
A matrix with forecasting data for exogenous variables. |
horizon |
Forecasting horizon, specifying the number of periods. |
freq |
Frequency of the time series data. |
forecast_dates |
List containing 'start' and 'end' dates for forecast. |
Value
A list containing the forecast values.
Compute Forecast Based on Companion Matrix and Reduced Form
Description
This function calculates the forecast for a given set of parameters and data. It computes baseline forecasts and applies certain restrictions if specified.
Usage
forecast_values(
posterior,
companion_matrix,
reduced_form,
y_matrix,
forecast_x_matrix,
horizon,
freq,
start_forecast,
endogenous_variables,
restrictions,
identities,
conditional_innov_method = "projection",
stochastic = FALSE
)
Arguments
posterior |
A list of posterior system matrices from
|
companion_matrix |
A list containing components of the companion matrix. |
reduced_form |
A list containing the reduced form components. |
y_matrix |
Matrix of the dependent variable time series data. |
forecast_x_matrix |
A matrix with forecasting data for exogenous variables. |
horizon |
Forecasting horizon, specifying the number of periods. |
freq |
Frequency of the time series data. |
start_forecast |
A vector of format |
endogenous_variables |
A character vector containing the names of endogenous variables. |
restrictions |
List of model constraints. Default is empty. |
stochastic |
Logical; when |
Value
A matrix with the base forecast of Y.
Format System of Equations
Description
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.
Usage
## S3 method for class 'koma_seq'
format(x, ...)
Arguments
x |
An object of class |
... |
Additional arguments passed to or from other methods. |
Value
A character vector of the formatted equations.
Format ts Time Labels
Description
For quarterly data (frequency = 4), returns "YYYY Qn". For monthly data (frequency = 12), returns "YYYY-MM". Otherwise, falls back to the numeric time values.
Usage
format_ts_time(x)
Arguments
x |
A |
Value
A character vector of formatted time labels.
Vectorize Gamma Matrix
Description
Converts the character representation of the gamma matrix into a transformation matrix and a constant vector, such that vector = transformation_matrix %*% parameters + constant_vector where vector = vec(character_gamma_matrix).
Usage
gamma_vectorization(character_gamma_matrix, identity_weights)
Arguments
character_gamma_matrix |
A character matrix representing the gamma structure of the model. |
identity_weights |
A list of identity weights for adjusting constant vectors. |
Value
A list with three elements:
- transformation_matrix
A numeric matrix used for parameter transformation.
- parameters
A character vector of parameter names.
- constant_vector
A numeric vector for constant terms.
Generate Data for the Simultaneous Equations Model
Description
Compute Y and X matrix (data)
Use reduced form of the model to compute Y
Y = X B \Gamma^{-1} + U \Gamma^{-1}
Usage
generate_sample_data(
sample_size,
sample_start,
burnin,
gamma_matrix,
beta_matrix,
sigma_matrix,
endogenous_variables,
exogenous_variables,
predetermined_variables
)
Arguments
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. |
Details
It creates a sample of data where the relationship between the variables is determined by the defined parameters.
Value
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.
Examples
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)
Get Central Tendency Value from a Named List
Description
This function takes a named list quantiles and a string central_tendency
indicating which central tendency measure (mean or median) to retrieve.
Usage
get_central_tendency(central_tendency, quantiles)
Arguments
central_tendency |
A string, either "mean" or "median". |
quantiles |
A named list containing central tendency values. |
Value
The central tendency value from the list quantiles based on the
central_tendency argument.
Default Gibbs Specfications
Description
Default Gibbs Specfications
Usage
get_default_gibbs_spec()
Gibbs Sampler Specifications
-
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. Default is 1. -
tau: Numeric tuning parameter for enforcing an acceptance rate. Default is 1.1.
Get endogenous variables from a system of equations
Description
This function takes a system of equations and returns it's endogenous variables.
Usage
get_endogenous_variables(equations)
Arguments
equations |
A character string containing the system of equations, where equations are separated by commas. |
Value
A character vector of endogenous variables.
Match Quantile Names into Symmetric Fan Pairs
Description
Match Quantile Names into Symmetric Fan Pairs
Usage
get_fan_pairs(quantile_names, fan_quantiles = NULL)
Arguments
quantile_names |
Character vector of quantile names (e.g., "q_5"). |
fan_quantiles |
Numeric probabilities to constrain pairing. |
Value
A list of lower/upper quantile name pairs.
Extract identities from equations
Description
This function filters out equations containing 'epsilon', then extracts
weights and identities based on character_gamma_matrix and
character_beta_matrix.
Usage
get_identities(equations, character_gamma_matrix, character_beta_matrix)
Arguments
equations |
A character string containing the system of equations, where equations are separated by commas. |
character_gamma_matrix |
A matrix |
character_beta_matrix |
A matrix |
Value
A list of identities extracted from the input equations. Each entry contains:
equation: The raw equation
components: The components extracted from the equation
weights: The corresponding weights for each component
Extract Lagged Values from Y Matrix
Description
This function populates the matrix containing the predetermined variables, i.e. the lagged variables, with the lagged values contained in the Y matrix.
Usage
get_lagged_values(predetermined_matrix, y_matrix, tx)
Arguments
predetermined_matrix |
The predetermined matrix to be populated with lagged values. |
y_matrix |
The y matrix containing the original values. |
tx |
The time index for which the lagged values should be obtained. |
Value
The updated predetermined matrix with lagged values.
Determine the maximum lag of variables
Description
This function calculates the maximum lag among a set of variables.
Usage
get_max_lag(variable_names)
Arguments
variable_names |
A character vector specifying the names of the variables to analyze. |
Value
The maximum lag among the variables. If there are no lags detected NA is returned.
Find Optimal Ticks for y Axis
Description
Find Optimal Ticks for y Axis
Usage
get_optimal_ticks(df_long, x_range, whisker_data = NULL)
Arguments
df_long |
A data frame in long format that includes 'data_type' as a column, which should contain the types 'growth' and 'level' for categorizing the data. |
x_range |
A list with x-axis range with start and end values of format c(YEAR, QUARTER). |
Value
A list with y1 (growth) values and text, y2 (level) text and extremas.
Get Parameter Names from Character Matrix
Description
Extracts unique parameter names from a character matrix based on a given pattern (such as "gamma" or "beta").
Usage
get_parameters(character_matrix, pattern)
Arguments
character_matrix |
A character matrix to extract parameters from. |
pattern |
A string pattern to identify parameter names. |
Value
A character vector of unique parameter names matching the pattern.
Get System of Equations Weights
Description
Calculates dynamic weights for a system of equations and updates the
identities with these weights. The function processes a list of time
series data (ts_data), a list of identities (identities), and a set of
dates (dates) to compute and update weights dynamically.
Usage
get_seq_weights(ts_data, identities, dates, frequency = 4)
Arguments
ts_data |
A named list of |
identities |
A named list of identities, each containing components and their respective weights. The list should include elements with "lhs_weight" in their names. |
dates |
A list with start and end dates for dynamic weight calculations.
The dates list should have a sub-list |
Value
The function updates the identities list with the calculated
dynamic weights and returns nothing explicitly.
Extract Variables from a System of Equations
Description
This function identifies and extracts variable names from a set of
equations. It removes whitespace and splits the equations by common
operators such as ~, ==, +, *, and -. It filters out components
that represent numeric values, only returning variable names.
Usage
get_variables(equations)
Arguments
equations |
A character vector containing the equations to extract variables from. |
Value
A list of character vectors, where each vector contains the variables from a single equation.
Extract Weight Names from Equations
Description
This function takes a vector of equations and extracts the names of the variables that appear within parentheses.
Usage
get_weight_variables(equations)
Arguments
equations |
A character string or vector containing the system of equations. If a single string, equations should be separated by commas. |
Value
A character vector of unique weight names that appeared within parentheses in the input equations.
Extract Component Weights from an Equation
Description
Given a mathematical equation, this function identifies its individual
components and their associated weights. For components paired with a numeric
value via a *, that numeric value is considered its weight. Otherwise, the
weight is set to NULL.
Usage
get_weights_and_comps(raw_eq, weights_list)
Arguments
raw_eq |
A character string of a mathematical equation. The equation is expected to have a format like "lhs == rhs", where the right-hand side (rhs) might contain components combined using '+' or '-'. |
weights_list |
A pre-constructed list containing character
representations of weights derived from both |
Value
A list with the following elements:
-
equation: The original equation provided as input. -
components: A list of components extracted from the rhs of the equation. -
weights: A list of weights, corresponding to each component. If a component doesn't have an explicit weight in the equation, its weight is NULL.
See Also
get_identities for a function that uses this function's
outputs.
Generate Tick Text and Values for a Plot
Description
This function generates tick text and values based on a provided data frame and an optional existing plot figure. The tick text and values are specifically structured for showcasing annual growth rates on a timeline.
Usage
get_x_ticks(df_long, fig = NULL)
Arguments
df_long |
A data frame in a long format, containing at least the columns
|
fig |
An optional existing plotly figure object to which new ticks will be added. If provided, the function will integrate new tick text and values with the existing ticks on the figure. Default is NULL, indicating no existing figure. |
Value
A list containing two elements: ticktext and tickvals. The
ticktext element is a character vector of HTML formatted strings for
each tick, showcasing the year and annual growth rate. The tickvals element
is an integer vector of years corresponding to each tick.
Get Y Position for Annotations in a Figure
Description
Calculates the y-axis position for the next annotation to be added to a figure based on the number of existing annotations. This function automates the adjustment of the y-axis position for annotations, ensuring they are placed without overlap by starting with a base y position and modifying it according to the current count of annotations within the figure.
Usage
get_y_position_for_annotations(fig)
Arguments
fig |
A figure object that potentially contains annotations within its
layout attributes. The figure object should adhere to the expected structure,
including a list of layout attributes accessible via |
Value
Numeric value indicating the y-axis position for placing the next annotation. This position is calculated based on a predefined base position, with adjustments made for each existing annotation to prevent overlap.
Calculate Y-Axis Tick Marks for Multiple Axes in Plotly
Description
This function computes the tick marks for y-axes on a Plotly graph, ensuring that gridlines align across multiple y-axes by matching dtick ratios. It adjusts the maximum range of the axes based on these ratios to align gridlines correctly.
Usage
get_y_ticks(extremas, num_ticks, center_around)
Arguments
extremas |
A list with 'min' and 'max' values for each y-axis. |
num_ticks |
The desired number of ticks on each y-axis. |
center_around |
A numeric value to center the axis ranges. |
Details
The function calculates tick mark spacing (dtick) and ratios, then adjusts
axis ranges to match the largest dtick ratio, ensuring gridlines align across
axes. It avoids reducing the axis range maximum to prevent cutting off data
points.
Value
A list with dtick, min, and max for each y-axis, adjusted for alignment.
References
Implements the gridline-alignment approach described by Victor Bezak in the GitHub repository https://github.com/VictorBezak/Plotly_Multi-Axes_Gridlines.
Highest Density Intervals from Draws
Description
Computes highest density intervals (HDIs) for a numeric sample. The HDI is defined as the shortest interval containing a target probability mass.
Usage
hdi(x, ...)
## Default S3 method:
hdi(x, probs = c(0.5, 0.99), ...)
Arguments
x |
A numeric vector of draws. |
... |
Unused. |
probs |
Numeric vector of target mass levels. Values in |
Value
A list with class "koma_hdi" containing:
- intervals
Named list of matrices with columns
lowerandupper, one matrix perprobslevel.- mode
Sample median of the draws (used as a center reference).
- cutoff
Named numeric vector of
NAvalues (not defined for HDI).- mass
Named numeric vector of achieved mass for each level.
- probs
Numeric vector of target masses in (0, 1].
Examples
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)
Highest Density Intervals for koma_estimate Objects
Description
Computes highest density intervals (HDIs) for coefficient draws from a
koma_estimate object.
Usage
## S3 method for class 'koma_estimate'
hdi(x, variables = NULL, probs = c(0.5, 0.99), include_sigma = FALSE, ...)
Arguments
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. |
Value
A list with class c("koma_estimate_hdi", "koma_hdi")
containing HDI intervals per coefficient.
Highest Density Intervals for koma_forecast Objects
Description
Computes highest density intervals (HDIs) for predictive draws in a
koma_forecast object.
Usage
## S3 method for class 'koma_forecast'
hdi(x, variables = NULL, probs = c(0.5, 0.99), ...)
Arguments
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. |
Value
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.
Highest Density Regions from a Kernel Density Estimate
Description
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.
Usage
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",
...
)
Arguments
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 |
Details
The Monte Carlo integration option follows the approach described by Hyndman (1996) for computing HDRs from an estimated density.
Value
A list with class "koma_hdr" containing:
- intervals
Named list of matrices with columns
lowerandupper, one matrix perprobslevel.- mode
Location of the KDE mode.
- density
The density object returned by
stats::density.- cutoff
Named numeric vector of density cutoffs for each level.
- mass
Named numeric vector of achieved mass for each level. For
integration = "grid", this is the area under the KDE above the cutoff (grid-based). Forintegration = "monte_carlo", this is the Monte Carlo coverage, i.e. the fraction of sampled points with density above the cutoff.- probs
Numeric vector of target masses in (0, 1].
References
Hyndman, R. J. (1996). Computing and graphing highest density regions. The American Statistician, 50(2), 120–126. doi:10.2307/2684423
Examples
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)
Highest Density Regions for koma_estimate Objects
Description
Computes highest density regions (HDRs) for coefficient draws from a
koma_estimate object.
Usage
## 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,
...
)
Arguments
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 |
Value
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.
Highest Density Regions for koma_forecast Objects
Description
Computes highest density regions (HDRs) for predictive draws in a
koma_forecast object.
Usage
## 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",
...
)
Arguments
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
|
Value
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
Description
Initiate default theme used to plot forecasts.
Usage
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)),
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"))
)
Arguments
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.
|
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).
|
Value
A named list containing the theme settings.
Examples
theme <- init_koma_theme()
names(theme)
Compute initial omega for the jth equation
Description
initial_omega_j computes OLS quantity for initial omega_j using initialized
gamma_j'
Usage
initial_omega_j(
y_matrix,
x_matrix,
character_gamma_matrix,
character_beta_matrix,
jx,
gamma_jw
)
Arguments
y_matrix |
A |
x_matrix |
A |
character_gamma_matrix |
A matrix |
character_beta_matrix |
A matrix |
jx |
The index of equation |
gamma_jw |
A |
Value
The function returns the evaluation of the target function, which is used to decide whether to accept or reject proposed states in the MH algorithm. Returns NA if there are no gamma parameters.
Initialize the sampler
Description
initialize_sampler initializes the sampler for the Metropolis Hastings
algorithm. It obtains the initial gamma parameters by numerically
maximizing the target function. It then calculates the Cholesky factor
L of the inverse of the Hessian M^{-1} of the target function.
This Cholesky factor, along with the gamma parameter for equation j, is
returned. The Cholesky factor is used to draw the candidate gamma in the MH
algorithm.
Usage
initialize_sampler(
y_matrix,
x_matrix,
character_gamma_matrix,
character_beta_matrix,
jx
)
Arguments
y_matrix |
A |
x_matrix |
A |
character_gamma_matrix |
A matrix |
character_beta_matrix |
A matrix |
jx |
The index of equation |
Value
A list containing the initial parameters for gamma
(gamma_parameters_j) and the Cholesky factor of the
inverse of the Hessian (cholesky_of_inverse_hessian) if
number_endogenous_in_j is greater than 0.
If not, only the gamma_parameters_j parameter is returned as 0.
Initialize the sampler
Description
initialize_sampler_informative initializes the sampler for the
Metropolis-Hastings algorithm. It obtains the initial gamma parameters
by numerically maximizing the target function. It then calculates the
Cholesky factor L of the inverse of the Hessian M^{-1} of the
target function.
This Cholesky factor, along with the gamma parameter for equation j, is
returned. The Cholesky factor is used to draw the candidate gamma in the MH
algorithm.
Usage
initialize_sampler_informative(
y_matrix,
x_matrix,
character_gamma_matrix,
character_beta_matrix,
jx
)
Arguments
y_matrix |
A |
x_matrix |
A |
character_gamma_matrix |
A matrix |
character_beta_matrix |
A matrix |
jx |
The index of equation |
Value
A list containing the initial parameters for gamma
(gamma_jw) and the Cholesky factor of the
inverse of the Hessian (cholesky_of_inverse_hessian) if
number_endogenous_in_j is greater than 0.
If not, only the gamma_jw parameter is returned as 0.
Check if Object is a System of Equations
Description
This function checks if the given object inherits from the class koma_seq,
indicating that it represents a system of equations.
Usage
is_system_of_equations(x)
Arguments
x |
An object to be checked. |
Value
Logical. Returns TRUE if the object inherits from the class
koma_seq, and FALSE otherwise.
Examples
sys <- system_of_equations("y ~ x", exogenous_variables = "x")
is_system_of_equations(sys)
Add Periods to Numeric Date Representation
Description
This function iterates a numeric date representation by a given number of periods (e.g., years, quarters or months). It accepts a date in either vector format (year, period) or its numeric representation and adds the specified number of periods to it.
Usage
iterate_n_periods(x, n, frequency)
Arguments
x |
A numeric value or a 2-element vector (year, period). The vector should represent a year and a period (e.g., quarter or month). |
n |
The number of periods to add. This can be positive or negative. |
frequency |
A numeric value indicating the number of periods in a year (e.g., 1, for years, 4 for quarters, 12 for months). |
Value
A numeric representation of the date after adding the periods.
Klein macroeconomic time series (1970 Q1 onward)
Description
A list of U.S. macro series from FRED (14 quarterly series).
Usage
klein
Format
A list of 14 ts objects:
- gdp
Real GDP (bil. 2017 USD, SAAR; FRED: GDPC1)
- consumption
Real PCE (bil. 2017 USD, SAAR; FRED: PCECC96)
- investment
Real private investment (bil. 2017 USD, SAAR; FRED: GPDIC1)
- government
Real government spending (bil. 2017 USD, SAAR; FRED: GCEC1)
- net_exports
Real net exports (bil. 2017 USD, SAAR; FRED: NETEXC)
- n_gdp
Nominal GDP (bil. USD, SAAR; FRED: GDP)
- n_consumption
Nominal PCE (bil. USD, SAAR; FRED: PCEC)
- n_investment
Nominal private investment (bil. USD, SAAR; FRED: GPDI)
- n_government
Nominal government spending (bil. USD, SAAR; FRED: GCE)
- n_profits
Nominal profits after tax (bil. USD, SAAR; FRED: CP)
- n_wages
Nominal private wages & salaries (bil. USD; FRED: A132RC1Q027SBEA)
- n_government_wages
Nominal government wages & salaries (bil. USD; FRED: B202RC1Q027SBEA)
- n_taxes
Nominal fed tax receipts (bil. USD; FRED: W007RC1Q027SBEA)
- gdp_deflator
GDP implicit price deflator (2017=100, SAAR; FRED: GDPDEF)
Source
Federal Reserve Economic Data (FRED), Federal Reserve Bank of St. Louis.
Extended Time-Series Object
Description
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.
Usage
ets(
data = NA,
start = NULL,
end = NULL,
frequency = NULL,
deltat = NULL,
ts.eps = getOption("ts.eps"),
...
)
as_ets(x = stats::ts(), ...)
is_ets(x)
Arguments
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. |
Details
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.
Value
A koma_ts object.
A koma_ts object.
TRUE if the object is of class koma_ts, otherwise FALSE.
See Also
Examples
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)
Compute the level for a time series
Description
Required attributes of the input time series are:
-
series_type- "rate" or "level" -
method- "percentage", "diff_log", "none", or an expression
Usage
level(x, ...)
## S3 method for class 'ts'
level(x, ...)
## S3 method for class 'mts'
level(x, ...)
## S3 method for class 'list'
level(x, ...)
Arguments
x |
A time series object. Supported classes are |
... |
arguments passed to methods (unused for the default method). |
Value
An ets object.
Examples
x <- ets(c(0.3, 0.1, 0.2, -0.1), series_type = "rate", method = "percentage")
level(x)
Merge custom metadata from two koma_ts objects
Description
Merge custom metadata from two koma_ts objects
Usage
merge_koma_attrs(e1, e2 = NULL, op = NULL, template = NULL)
Arguments
e1 |
First operand. |
e2 |
Second operand. |
op |
Name of the operation. |
template |
Result template used for alignment. |
Value
A named list of merged custom attributes.
Merge a Partial Theme with the Default Theme
Description
Recursively merges a user-supplied (possibly incomplete) theme list with the
defaults from init_koma_theme(), so that any omitted fields fall back to
their default values.
Usage
merge_theme(user_theme)
Arguments
user_theme |
A (possibly partial) named list of theme overrides. |
Value
A complete theme list equivalent to init_koma_theme() with the
user's values applied on top.
Calculate Out-of-Sample RMSE for a Specified Horizon
Description
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.
Usage
model_evaluation(
sys_eq,
variables,
horizon,
ts_data,
dates,
...,
evaluate_on_levels = TRUE,
options = list(gibbs = list(), summary = "mean", approximate = FALSE),
restrictions = NULL
)
Arguments
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. |
Details
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.
Value
DataFrame containing the RMSE of the selected Variables up to the desired horizon.
Examples
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)
Identify Model Parameters from Character Matrices
Description
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.
Usage
model_identification(
character_gamma_matrix,
character_beta_matrix,
identity_weights,
call = rlang::caller_env()
)
Arguments
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
|
Value
NULL. This function is used for side effects, stopping execution if model identification conditions are not met.
Examples
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
)
Simulate from a Multivariate Normal Distribution
Description
Produces one or more samples from the specified multivariate normal
distribution. Adapted from MASS::mvrnorm in the CRAN package
MASS, licensed GPL-2 | GPL-3 as declared on CRAN.
Usage
multivariate_norm(n = 1, mu, sigma, tol = 1e-06, empirical = FALSE)
Arguments
n |
The number of samples required. |
mu |
A vector giving the means of the variables. |
sigma |
A positive-definite symmetric matrix specifying the covariance matrix of the variables. |
tol |
Tolerance (relative to the largest variance) for numerical lack
of positive-definiteness in |
empirical |
Logical. If true, mu and sigma specify the empirical not population mean and covariance matrix. |
Details
The matrix decomposition is done vai eigen; although a Choleski
decomposition might be faster, the eigendecomposition is stabler.
Value
If n = 1 a vector of the same length as mu, otherwise
an n by length(mu) matrix with one sample in each row.
References
Venables, W. N. & Ripley, B. D. (2002) Modern Applied Statistics with S. Fourth Edition. Springer, New York. ISBN 0-387-95457-0
See Also
Evaluate Multivariate Normal Density at x
Description
Evaluate Multivariate Normal Density at x
Usage
multivariate_norm_pdf(x, mu, sigma)
Arguments
x |
A vector at which to evaluate the density. |
mu |
A vector giving the means of the variables. |
sigma |
A positive-definite symmetric matrix specifying the covariance matrix of the variables. |
Value
The density of the multivariate normal distribution at x.
Normalize Coefficient Names
Description
Internal helper that aligns coefficient names to the number of matrix rows.
Usage
normalize_coef_names(coef_names, n_coef)
Arguments
coef_names |
Character vector of coefficient names. |
n_coef |
Integer number of coefficients (rows). |
Value
A character vector of length n_coef.
Normalize Quantile Probabilities
Description
Normalize Quantile Probabilities
Usage
normalize_quantile_probs(fan_quantiles)
Arguments
fan_quantiles |
Numeric probabilities in (0, 1] or percentages in
|
Value
A numeric vector of probabilities in (0, 1].
Convert Numeric to Date Format
Description
This function converts a numeric representation of a date back to a vector
or list of vectors with year and period (e.g., quarter or month).
The function supports input as a single numeric value, or a list of numeric
values. The numeric representation should match the format produced by
dates_to_num.
Usage
num_to_dates(x, frequency, ...)
Arguments
x |
A numeric value or list of numeric values representing the date(s).
If |
frequency |
A numeric value indicating the number of periods in a year (e.g., 1 for years, 4 for quarters, 12 for months). |
... |
Additional arguments passed to other methods. |
Value
A numeric vector of length 2 (year, period) or a list of such vectors.
Parse Lagged Variables in Equation Strings
Description
Identifies and standardizes lagged variable references in a system of
equations. Supports both var.L(lag) and lag(var, lag) notation.
The function processes each equation, detects lag patterns, and rewrites them in a unified form. It returns both the modified equations and the list of unique lagged variables.
Usage
parse_lags(equations)
Arguments
equations |
A character vector of equation strings. |
Value
A list with components:
- variables
A sorted character vector of unique lagged variables.
- equations
A character vector of equations with standardized lags.
Parse Quantile Names into Probabilities
Description
Parse Quantile Names into Probabilities
Usage
parse_quantile_name(name)
Arguments
name |
A quantile name like "q_5" or a numeric string. |
Value
A probability in (0, 1] or NA_real_ on failure.
Plot HDRs for koma_estimate Objects
Description
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.
Usage
## S3 method for class 'koma_estimate_hdr'
plot(x, y = NULL, ...)
Arguments
x |
A |
y |
Ignored. Included for compatibility with the generic function. |
... |
Additional arguments controlling the plot. See Details. |
Details
Additional arguments supported in ...:
- variables
Optional character vector of endogenous variables to plot.
- params
Optional character vector of parameter groups to plot (e.g., "beta", "gamma", "sigma").
- box_levels
Optional numeric probabilities in (0, 1] (or
[0, 100]) defining the inner and outer HDRs. By default, uses the available HDR levels closest to 50% and the maximum probability.- interactive
Logical. If TRUE and plotly is available, return an interactive plot via
plotly::ggplotly. Default is FALSE.
Value
A ggplot object, or a plotly object when interactive = TRUE and
plotly is available.
Plot koma Forecasts
Description
Plot koma forecasts
Usage
## S3 method for class 'koma_forecast'
plot(x, y = NULL, ...)
Arguments
x |
A |
y |
Ignored. Included for compatibility with the generic function. |
... |
Additional parameters:
|
Value
A Plotly figure object displaying the data.
Examples
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")
}
Plotting Function
Description
This function processes the data and creates a plot using Plotly and the theme provided.
Usage
plotli(
df_long,
fig = NULL,
theme = NULL,
fan_data = NULL,
whisker_data = NULL,
...
)
Arguments
df_long |
A data frame in long format, containing the data to be plotted. |
fig |
Optional. A Plotly figure object to update, otherwise creates a new one. |
theme |
List of default plot output parameters. Defaults to NULL, which
leads to |
... |
Directly pass additional arguments to plotly::layout. For documentation, see https://plotly.com/r/reference/#Layout_and_layout_style_objects |
Value
A Plotly figure object displaying the data with the specified formatting.
References
https://plotly.com/r/reference/#Layout_and_layout_style_objects
Prepare Data for Plotting
Description
This function prepares time series data by converting the data from wide to long format.
Usage
prepare_data_to_plot(mts_list, start)
Arguments
mts_list |
A list with named multivariate time series objects: growth, level and / or growth_annual. |
start |
A numeric value representing the forecast start date. |
Value
A single tibble in long format combining growth rates, annualized growth rates, and level data.
Prepare Draw Matrix and Indices
Description
Internal helper that applies thinning, converts draw lists to a matrix, and applies an optional matrix transformation.
Usage
prepare_draw_matrix(draws, thin = 1L, mat_transform = NULL)
Arguments
draws |
A list of MCMC draws. |
thin |
Positive integer thinning interval. |
mat_transform |
Optional function to transform the draw matrix. |
Value
A list with elements mat (numeric matrix) and draw_idx
(integer vector), or NULL when no draws are available.
Print method for koma_estimate objects
Description
Provides a concise, console-friendly overview of the estimated system.
Usage
## S3 method for class 'koma_estimate'
print(
x,
...,
variables = NULL,
central_tendency = "mean",
ci_low = 5,
ci_up = 95,
digits = 2
)
Arguments
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. |
Value
Invisibly returns x after printing.
See Also
summary.koma_estimate for
detailed posterior summaries.
Print Method for koma_forecast Objects
Description
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.
Usage
## S3 method for class 'koma_forecast'
print(x, ..., variables = NULL, central_tendency = NULL, digits = 4)
Arguments
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. |
Details
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.
Value
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.
Print method for koma_hdi objects
Description
Delegates to summary() for console output.
Usage
## S3 method for class 'koma_hdi'
print(x, ...)
Arguments
x |
A |
... |
Additional arguments forwarded to |
Value
Invisibly returns x.
Print method for koma_hdr objects
Description
Delegates to summary() for console output.
Usage
## S3 method for class 'koma_hdr'
print(x, ...)
Arguments
x |
A |
... |
Additional arguments forwarded to |
Value
Invisibly returns x.
Print System of Equations
Description
This function prints an object of class koma_seq
to ensure the equations are displayed in a readable format.
Usage
## S3 method for class 'koma_seq'
print(x, ...)
Arguments
x |
An object of class |
... |
Additional arguments passed to or from other methods. |
Value
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.
Display Current Gibbs Sampler Specifications
Description
This function prints the current settings of the Gibbs sampler in a readable format. It includes information such as the number of draws, burn-in ratio, number of saved draws, and tuning parameter tau.
Usage
print_gibbs_settings(global_settings)
Value
Prints a formatted message with the current Gibbs sampler settings. This function does not return any values.
Build Quantile Names from Probabilities
Description
Build Quantile Names from Probabilities
Usage
quantile_names_from_probs(probs)
Arguments
probs |
Numeric probabilities. |
Value
A character vector of quantile names.
Compute Quantiles of Coefficients from Estimations
Description
This function takes the results of an estimation process, typically stored in a data matrix or array, and computes specified quantiles. It supports 1D, 2D, and 3D data structures and makes necessary adjustments before calculations. For multi-dimensional data, the function performs the percentile computation across each column, retaining only the first column if the data is 3D.
Usage
quantiles_from_estimates(data, include_mean = FALSE, probs = NULL)
Arguments
data |
A list or array. If multi-dimensional, it should be either 2D or 3D. |
include_mean |
Logical. If TRUE, the mean of the coefficients will also be computed and returned along with the quantiles. Default is FALSE. |
probs |
A numerical vector specifying the probabilities for which
percentiles should be computed. Default is obtained from |
Value
A named list of computed percentiles for each coefficient. The names
are prefixed with "q_" and suffixed with the percentile value multiplied by
100 (e.g., "q_5", "q_50", "q_95"). If include_mean is TRUE, "q_mean" is
also included in the list.
Calculate Quantiles from Multiple Forecast Matrices
Description
This function calculates specified quantiles for each variable-time combination across all draws.
Usage
quantiles_from_forecasts(forecasts, freq, probs = NULL, include_mean = FALSE)
Arguments
forecasts |
A list of matrices. Each matrix should represent a forecasts with the same dimensions (rows and columns) for comparison. |
freq |
The frequency of the data. |
probs |
A numeric vector specifying which quantiles to compute. Default is c(0.25, 0.5, 0.75, 1). |
include_mean |
Logical. If TRUE, the mean of the forecasts will also be computed and returned along with the quantiles. Default is FALSE. |
Value
A named list of matrices, where each matrix corresponds to an
original matrix in forecasts. Each output matrix has an additional
dimension corresponding to the computed quantiles, with dimnames
indicating the quantile levels (e.g., "q_25" for the 25th percentile).
Compute the rate of change for a time series
Description
Required attributes of the input time series are:
-
series_type- "rate" or "level" -
method- "percentage", "diff_log", "none", or an expression
Usage
rate(x, ...)
## S3 method for class 'ts'
rate(x, ...)
## S3 method for class 'list'
rate(x, ...)
## S3 method for class 'mts'
rate(x, ...)
Arguments
x |
A time series object. Supported classes are |
... |
arguments passed to methods (unused for the default method). |
Value
An ets object.
Examples
x <- ets(1:10, series_type = "level", method = "diff_log")
rate(x)
Rebase Time Series Data Relative to a Base Period
Description
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.
Usage
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, ...)
Arguments
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). |
Value
An ets object with the level computed.
Examples
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))
Restore custom metadata onto a time series
Description
Restore custom metadata onto a time series
Usage
restore_koma_attrs(x, attrs)
Arguments
x |
A time series object. |
attrs |
A named list of custom attributes. |
Value
A koma_ts object.
Random Inverse-Wishart Draw
Description
Generates a random draw from the Inverse-Wishart distribution.
Usage
riwish(v, S)
Arguments
v |
Degrees of freedom (scalar). Must be >= dimension of S. |
S |
Positive-definite scale matrix (p x p). |
Details
This function is adapted from MCMCpack::riwish
(Martin et al., 2011) under GPL-3. The Inverse-Wishart
distribution is commonly used as a prior for covariance matrices.
Value
A single random draw (matrix) from the Inverse-Wishart distribution.
References
Martin, R., Quinn, K., & Park, J. (2011). MCMCpack: Markov Chain Monte Carlo in R. Journal of Statistical Software, 42(9), 1-21.
Running Means for koma_estimate Objects
Description
Compute running means (cumulative averages) for coefficient draws from a
koma_estimate object. By default, beta, gamma, and sigma draws are
included when available.
Usage
running_mean(x, ...)
Arguments
x |
A |
... |
Additional arguments controlling the output. See Details. |
Details
Additional arguments supported in ...:
- variables
Optional character vector of endogenous variables to include.
- params
Optional character vector of parameter groups to include (e.g., "beta", "gamma", "sigma"). Defaults to all available.
- thin
Optional integer thinning interval for the stored draws. Default is 1 (no thinning).
- max_draws
Optional integer cap on the number of draws returned. When set, the most recent draws are kept.
- grace_draws
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.
Value
A data.frame with columns draw, value, variable, param,
coef, draw_position, in_grace_window, and label.
Examples
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)
Running Mean Plots for koma_estimate Objects
Description
Visualize running means (cumulative averages) from running_mean() with a
light grey
band over the grace-window region.
Usage
running_mean_plot(x, ...)
Arguments
x |
A |
... |
Additional arguments controlling the plot. See Details in
|
Details
Additional plot arguments in ...:
- scales
Facet scale option passed to
ggplot2::facet_wrap. Default is "free_y".- facet_ncol
Optional integer number of columns for facets.
- interactive
Logical. If TRUE and plotly is available, return an interactive plot via
plotly::ggplotly. Default is FALSE.
Value
A ggplot object, or a plotly object when interactive = TRUE and
plotly is available.
Examples
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)
}
Random Wishart Draw
Description
Generates a random draw from the Wishart distribution.
Adapted from MCMCpack::rwish (Martin et al., 2011) under GPL-3.
Usage
rwish(v, S)
Arguments
v |
Degrees of freedom (scalar). Must be >= dimension of S. |
S |
Positive-definite scale matrix (p x p). |
Value
A single random draw (matrix) from the Wishart distribution.
References
Martin, R., Quinn, K., & Park, J. (2011). MCMCpack: Markov Chain Monte Carlo in R. Journal of Statistical Software, 42(9), 1-21.
Update Alpha Channel for RGB/RGBA Colors
Description
Converts rgb/rgba strings to rgba with the provided alpha value.
Usage
set_alpha(color, alpha)
Arguments
color |
A color string in "rgb(...)" or "rgba(...)" format. |
alpha |
Numeric alpha value in |
Value
A color string with the updated alpha.
Set Gibbs Settings
Description
Set Gibbs Settings
Usage
set_gibbs_settings(settings, equation_settings, envir = the)
Arguments
settings |
List with system-wide/global settings. |
equation_settings |
List with equation specific settings. |
envir |
Environment to create the gibbs_sampler in. Defaults to "the". |
Set Gibbs Sampler Specifications
Description
This class updates the Gibbs sampler specifications in the global
environment variable the$gibbs_sampler.
Usage
set_gibbs_spec(
ndraws = NULL,
burnin_ratio = NULL,
nstore = NULL,
tau = NULL,
...
)
Arguments
ndraws |
Integer specifying the number of Gibbs sampler draws. |
burnin_ratio |
Numeric specifying the ratio for the burn-in period. |
nstore |
Integer specifying the frequency of stored draws. |
tau |
Numeric tuning parameter for enforcing an acceptance rate. |
... |
Unused arguments that get discarded. |
Value
Invisible NULL. The function updates the$gibbs_sampler in place.
Gibbs Sampler Specifications
-
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. Default is 1. -
tau: Numeric tuning parameter for enforcing an acceptance rate. Default is 1.1.
Register metadata behavior for a koma_ts attribute
Description
Register metadata behavior for a koma_ts attribute
Usage
set_koma_attr_policy(
attr,
merge = NULL,
lag = NULL,
window = NULL,
na_omit = NULL
)
Arguments
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 |
Value
The registered policy, invisibly.
Set Restrictions for Observed Variables in Time Series Data
Description
This function generates a list of restrictions for specified variables in a time series data frame, based on their values between specified start and end dates.
Usage
set_restrictions(ts_data, variables_to_restrict, start, end)
Arguments
ts_data |
A list containing the time series data. |
variables_to_restrict |
A vector of strings specifying the names of the
variables in |
start |
The starting date for the restrictions. |
end |
The ending date for the restrictions. |
Value
A named list of restrictions, where the names are the names of the
variables in variables_to_restrict. Each element is a list containing
horizon, a sequence from 1 to the length of value_at_date, and value,
the truncated values of the variable between start and
end.
Simulated SEM example data
Description
A compact simulated example bundle for documentation and quick-start
workflows with estimate(), forecast(), and diagnostic plots.
Usage
simulated_sem
Format
A list with three elements:
- ts_data
A named list of
etstime-series objects.- sys_eq
A
koma_seqobject defining the simulated system of equations.- dates
A named list of date ranges for estimation examples.
Source
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)
Description
Quarterly time series of key macro variables for a small open economy (Switzerland)
Usage
small_open_economy
Format
A list of 12 ts objects (quarterly):
- consumption
Private consumption \(C_t\).
- investment
Gross fixed capital formation \(I_t\).
- exports
Exports \(X_t\).
- imports
Imports \(M_t\).
- prices
Price level \(P_t\).
- interest_rate
Short‐term domestic interest rate \(R_t\).
- gdp
Equilibrium output \(GDP_t\).
- domestic_demand
Domestic demand \(D_t\).
- world_gdp
World GDP (exogenous) \(WGDP_t\).
- interest_rate_germany
German short‐term rate (exog)
R_{GE,t}.- exchange_rate
Nominal exchange rate (exog) \(ER_t\).
- oil_price
Oil price (exogenous) \(OP_t\).
Source
https://www.seco.admin.ch/, https://kof.ethz.ch/
Remove custom metadata from a koma_ts object
Description
Remove custom metadata from a koma_ts object
Usage
strip_koma_attrs(x)
Arguments
x |
A time series object. |
Value
A plain ts object when x is koma_ts, otherwise x.
Summary method for koma_estimate objects
Description
This function provides a summary for koma_estimate objects. It can return either a texreg object or an ASCII table.
Usage
## S3 method for class 'koma_estimate'
summary(object, ...)
Arguments
object |
A koma_estimate object. |
... |
Additional parameters:
Additional arguments are forwarded to texreg output helpers (for example,
arguments accepted by |
Value
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.
Summary for koma_estimate_hdi Objects
Description
Prints HDI intervals for coefficients in a table per equation.
Usage
## S3 method for class 'koma_estimate_hdi'
summary(object, ..., variables = NULL, params = NULL, digits = 3)
Arguments
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. |
Value
Invisibly returns object.
Summary for koma_estimate_hdr Objects
Description
Prints HDR intervals for coefficients in a table per equation.
Usage
## S3 method for class 'koma_estimate_hdr'
summary(object, ..., variables = NULL, params = NULL, digits = 3)
Arguments
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. |
Value
Invisibly returns object.
Summary for koma_forecast Objects
Description
Prints a summary table for forecast horizons, including available central tendencies (mean/median) and quantiles.
Usage
## S3 method for class 'koma_forecast'
summary(object, ..., variables = NULL, horizon = NULL, digits = 3)
Arguments
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. |
Value
Invisibly returns object.
Summary for koma_forecast_hdi Objects
Description
Prints HDI intervals for forecast horizons.
Usage
## S3 method for class 'koma_forecast_hdi'
summary(object, ..., variables = NULL, horizon = NULL, digits = 3)
Arguments
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. |
Value
Invisibly returns object.
Summary for koma_forecast_hdr Objects
Description
Prints HDR intervals for forecast horizons.
Usage
## S3 method for class 'koma_forecast_hdr'
summary(object, ..., variables = NULL, horizon = NULL, digits = 3)
Arguments
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. |
Value
Invisibly returns object.
Summary for koma_hdi Objects
Description
Prints HDI intervals for a single numeric sample.
Usage
## S3 method for class 'koma_hdi'
summary(object, ..., digits = 3)
Arguments
object |
A |
... |
Unused. |
digits |
Number of digits to round numeric values. Default is 3. |
Value
Invisibly returns object.
Summary for koma_hdr Objects
Description
Prints HDR intervals for a single numeric sample.
Usage
## S3 method for class 'koma_hdr'
summary(object, ..., digits = 3)
Arguments
object |
A |
... |
Unused. |
digits |
Number of digits to round numeric values. Default is 3. |
Value
Invisibly returns object.
Forecast Summary Helpers
Description
Shared helpers for forecast summary tables.
Usage
summary_forecast_format_num(x, digits)
Summarize Interval Estimates for koma_estimate_* Objects
Description
Summarize Interval Estimates for koma_estimate_* Objects
Usage
summary_interval_table(
object,
variables = NULL,
params = NULL,
digits = 3,
center_label = "Mode",
interval_label = "HDR"
)
Arguments
object |
A koma_estimate_* object with interval output. |
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. |
center_label |
Label for the center statistic (e.g., "Mode", "Median"). |
interval_label |
Label for the interval type (e.g., "HDR", "HDI"). |
Value
Invisibly returns object.
Calculate Summary Statistics for Estimates
Description
Computes summary statistics for a specified endogenous variable within a system of equations. It returns the coefficients and standard errors of the equation's variables.
Usage
summary_statistics(
endogenous_variables,
estimates,
sys_eq,
central_tendency = "mean",
ci_low = 5,
ci_up = 95
)
Arguments
endogenous_variables |
A character vector of name(s) of the stochastic endogenous variable to summarize. |
estimates |
A list of estimates for each stochastic endogenous variable. |
sys_eq |
A list containing endogenous and exogenous variables, character_gamma_matrix, and character_beta_matrix. |
central_tendency |
A character string indicating which central tendency measure ("mean" or "median") to use for summary statistics. Default is "mean". |
ci_low |
The lower bound for the confidence interval as a percentile. Default is 5. |
ci_up |
The upper bound for the confidence interval as a percentile. Default is 95. |
Value
A list of summary statistics for each endogenous variable.
System of Equations Class
Description
Create and manipulate a system of equations.
Usage
system_of_equations(equations = vector(), exogenous_variables = vector(), ...)
Arguments
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. |
Details
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.
Value
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.
Equations
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 variableXand lagL(x)(e.g..L(1),.L(2)).Intercept are included by default, you can also explicitly specify the constant by adding
constantto the equation (e.g.y ~ constant + x1). To exclude the intercept, add+0or-1to the equation (e.g.y ~ 0 + x1).
For more details on the equation syntax, see
vignette("equations").
See Also
get_endogenous_variables(), get_identities(),
construct_gamma_matrix(), extract_lagged_vars(),
construct_beta_matrix(), get_max_lag()
Examples
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)
Compute the target function for the jth equation
Description
target_j calculates the target function used in the Metropolis-Hastings
(MH) algorithm for a given equation j. The target function is used
in the MH algorithm to accept or reject proposed new states in the
Markov chain.
Usage
target_j(
y_matrix,
x_matrix,
character_gamma_matrix,
character_beta_matrix,
jx,
gamma_parameters_j
)
Arguments
y_matrix |
A |
x_matrix |
A |
character_gamma_matrix |
A matrix |
character_beta_matrix |
A matrix |
jx |
The index of equation |
gamma_parameters_j |
A |
Value
The function returns the evaluation of the target function, which is used to decide whether to accept or reject proposed states in the MH algorithm. Returns NA if there are no gamma parameters.
Compute the target function for the jth equation for informative priors
Description
target_j_informative calculates the target function used in the
Metropolis-Hastings (MH) algorithm for a given equation j.
The target function is used in the MH algorithm to accept or reject proposed
new states in the Markov chain.
Usage
target_j_informative(
y_matrix,
x_matrix,
character_gamma_matrix,
character_beta_matrix,
jx,
gamma_jw,
omega_jw,
theta_jw,
priors_j
)
Arguments
y_matrix |
A |
x_matrix |
A |
character_gamma_matrix |
A matrix |
character_beta_matrix |
A matrix |
jx |
The index of equation |
gamma_jw |
A |
omega_jw |
|
theta_jw |
A |
Value
The function returns the evaluation of the target function, which is used to decide whether to accept or reject proposed states in the MH algorithm. Returns NA if there are no gamma parameters.
Compute the target function for the jth equation
Description
target_j_informative_initial calculates the target function used in the
Metropolis-Hastings (MH) algorithm for a given equation j.
The target function is used in the MH algorithm to accept or reject proposed
new states in the Markov chain.
Usage
target_j_informative_initial(
y_matrix,
x_matrix,
character_gamma_matrix,
character_beta_matrix,
jx,
gamma_jw
)
Arguments
y_matrix |
A |
x_matrix |
A |
character_gamma_matrix |
A matrix |
character_beta_matrix |
A matrix |
jx |
The index of equation |
gamma_jw |
A |
Value
The function returns the evaluation of the target function, which is used to decide whether to accept or reject proposed states in the MH algorithm. Returns NA if there are no gamma parameters.
Define the internal environment of the package
Description
Define the internal environment of the package
Usage
the
Format
An object of class environment of length 2.
Convert Time Series from Wide to Long Format
Description
This function returns the data in long format.
Usage
to_long(mts, start)
Arguments
mts |
A multivariate time series object. |
start |
A numeric value representing the forecast start date. |
Value
A data frame in long format containing the original data along with the sample status, dates, and frame identifiers.
Trace Plots for koma_estimate Objects
Description
Visualize MCMC trace plots for coefficient draws from a koma_estimate
object. By default, beta, gamma, and sigma draws are shown when available.
Usage
trace_plot(x, ...)
Arguments
x |
A |
... |
Additional arguments controlling the plot. See Details. |
Details
Additional arguments supported in ...:
- variables
Optional character vector of endogenous variables to plot.
- params
Optional character vector of parameter groups to plot (e.g., "beta", "gamma", "sigma"). Defaults to all available.
- thin
Optional integer thinning interval for the stored draws. Default is 1 (no thinning).
- max_draws
Optional integer cap on the number of draws per trace. When set, the most recent draws are kept.
- scales
Facet scale option passed to
ggplot2::facet_wrap. Default is "free_y".- facet_ncol
Optional integer number of columns for facets.
- interactive
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.
Value
A ggplot object, or a plotly object when interactive = TRUE and
plotly is available.
Examples
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)
}
Update anker
Description
This function updates the anker to the last observation of the realized data.
Usage
update_anker(x, y)
Arguments
x |
Time series object of class |
y |
Time series object of class |
Value
Return y of class koma_ts with updated anker.
Update Gamma and Beta Matrices with Identity Weights
Description
This function injects identity weights into the structural coefficient
matrices. For each identity component, it finds the target entry encoded in
the theta name (e.g., "theta6_4") and replaces the corresponding value in
\Gamma or B.
Usage
update_estimates_with_weights(identities, gamma_matrix, beta_matrix)
Arguments
identities |
A list of identity equations. |
gamma_matrix |
Initial |
beta_matrix |
Initial |
Value
A list containing:
-
gamma_matrix:\Gammaupdated with identity weights. -
beta_matrix:Bupdated with identity weights.
See Also
construct_posterior for a function that uses this function's
outputs.
Update Identity Weights
Description
Iteratively updates the weights in an identity list (identities) based on
the last value of the corresponding weights found in the weights list.
Usage
update_identity_weights(weights, identities)
Arguments
weights |
A named list where each entry represents an equation (e.g., "gdp"). Each equation is itself a named list, containing variable names (e.g., "manufacturing") and their dynamic weight values. Example:
|
identities |
A named list, where each entry represents an equation
similar to Example:
|
Value
A named list containing the updated identity weights for each
equation and its variables, in the same structure as the input identities.
Validate Completeness
Description
The function checks if all exogenous variables are declared.
Usage
validate_completeness(equations, exogenous_variables)
Arguments
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. |
Value
Logical. Returns TRUE if the equation is valid.
Throws an error with a specific message if any checks fail.
Validate Individual Equation
Description
This function validates an individual equation to ensure that it follows a
specific structure. The expected format for the equation is "left_variable ==
right_variables", where right_variables can be a combination of variables
separated by '+', '-', or '*'. The function checks the following:
Validity of the variable names.
Correct structure (exactly one '==' separator).
Stochastic error term
epsilonmust be the last element.Duplicate regressors within a single equation are not allowed.
Usage
validate_equation(equation)
Arguments
equation |
A character string representing an equation in the format "left_variable == right_variables". |
Value
Logical. Returns TRUE if the equation is valid.
Throws an error with a specific message if any checks fail.
Check Identity Equations in Forecast Output
Description
Recomputes each identity from its component series and weights, then warns if
deviations exceed tol. Intended as a safeguard against identity drift.
Usage
validate_identities(ts_out, identities, tol = 1e-08, x_matrix = NULL)
Arguments
ts_out |
A forecast output time-series matrix. |
identities |
A named list of identity definitions produced by
|
tol |
Numeric tolerance for deviations between the identity and its reconstructed value. |
x_matrix |
Optional matrix of exogenous variables to include when checking identities. |
Value
Invisibly returns NULL.
Validate Equations
Description
This function validates a character vector of equations, ensuring that they adhere to a specific format. The equations should be in the format "left_variable==right_variables", where right variables can be separated by '+', '-', or '*'. The function checks for valid equation structure, valid variable names, no duplicate regressors in a single equation, and no duplicate dependent variables across all equations.
Usage
validate_system_of_equations(x)
Value
Returns object.
Convert Vector to Matrix
Description
Given a transformation matrix, a vector of parameters, and a constant vector, this function constructs a matrix with specified row and column dimensions. vector = transformation_matrix %*% parameters, constant_vector where vector = vec(matrix)
Usage
vector_to_matrix(
transformation_matrix,
parameters,
constant_vector,
nrow,
ncol
)
Arguments
transformation_matrix |
A numeric matrix used for parameter transformation. |
parameters |
A numeric vector of parameters. |
constant_vector |
A numeric vector for constant terms. |
nrow |
Number of rows for the resulting matrix. |
ncol |
Number of columns for the resulting matrix. |
Value
A numeric matrix with specified row and column dimensions.