Type: Package
Title: Consistent Economic Trend Cycle Decomposition
Version: 0.1.0
Description: Determining potential output and the output gap - two inherently unobservable variables - is a major challenge for macroeconomists. 'sectorgap' features a flexible modeling and estimation framework for a multivariate Bayesian state space model identifying economic output fluctuations consistent with subsectors of the economy. The proposed model is able to capture various correlations between output and a set of aggregate as well as subsector indicators. Estimation of the latent states and parameters is achieved using a simple Gibbs sampling procedure and various plotting options facilitate the assessment of the results. For details on the methodology and an illustrative example, see Streicher (2024) https://www.research-collection.ethz.ch/handle/20.500.11850/653682.
License: GPL-3
Encoding: UTF-8
RoxygenNote: 7.2.3
Imports: stats, KFAS, zoo, ggplot2, MCMCpack, dplyr, tidyr, tempdisagg
Depends: R (≥ 2.10)
LazyData: true
NeedsCompilation: no
Packaged: 2024-01-21 14:21:36 UTC; Sina
Author: Sina Streicher ORCID iD [aut, cre]
Maintainer: Sina Streicher <streicher.sina@gmail.com>
Repository: CRAN
Date/Publication: 2024-01-22 17:40:02 UTC

Add a cycle to a state space model

Description

Add a cycle to a state space model

Usage

add_cycle(sys, p, name, lags = NULL)

Arguments

sys

list with system matrices

p

integer with autoregressive order, p <= 2

name

name ob observation equation

lags

(optional) number of lags added to state equation, e.g. since other equations load on them

Value

The input list sys with updated matrices.


Add error to state equation

Description

Add error to state equation

Usage

add_error(sys, name, type)

Arguments

sys

list with system matrices

name

name ob observation equation

type

type of trend, see details

Value

The input list sys with updated matrices.


Add initialization matrices to state space model

Description

Add initialization matrices to state space model

Usage

add_init_mat(sys)

Arguments

sys

list with system matrices

Value

The input list sys with updated matrices.


Add lags to state equation

Description

Add lags to state equation

Usage

add_lag(sys, name, type, lags = NULL)

Arguments

sys

list with system matrices

name

name ob observation equation

type

type of trend, see details

lags

(optional) number of lags added to state equation, e.g. since other equations load on them

Value

The input list sys with updated matrices.


Add a trend to a state space model

Description

Add a trend to a state space model

Usage

add_trend(sys, type, name, const = FALSE)

Arguments

sys

list with system matrices

type

type of trend, see details

name

name ob observation equation

const

logical indicating if there is a constant

Details

type = 1 denotes a random walk, type = 2 an integrated random walk, type = 3 and random walk with AR drift, and type = 4 a local linear trend. type = 3 is currently not implemented.

Value

The input list sys with updated matrices.


Output gap contributions

Description

Computes chain aggregated output gap contributions.

Usage

aggregate_gap(
  tsl_p,
  tsl_t,
  tsl_g,
  idx,
  error_name = "gap_error",
  idx_neg = NULL,
  previous_year = TRUE
)

Arguments

tsl_p

time series list with prices

tsl_t

time series list with trends

tsl_g

time series list with gaps

idx

index of aggregate

error_name

character string with name for aggregation error

idx_neg

index of negative sub sectors

previous_year

boolean indicating if previous year prices should be used instead of pervious period prices

Value

A multiple time series object containing the contributions.


Gaps of observation equations

Description

Computes the gap of each observable, i.e., it sums up the respective cycle and all cycles the observable additionally loads on.

Usage

compute_gaps(model, state, idx_state, idx_obs)

Arguments

model

state space model object, returned by the function define_ssmodel

state

state vector

idx_state

names of all cycle states

idx_obs

names of all observations (excluding constraints)

Value

A multiple time series object with gaps.


Results for sampled parameters and states

Description

Computes estimation results for the MCMC sampling output for a specific HPDI and evaluation function (e.g. mean or median).

Usage

compute_mcmc_results(
  model,
  settings,
  mcmc,
  data,
  HPDIprob = NULL,
  fit = NULL,
  ...
)

Arguments

model

state space model object, returned by the function define_ssmodel

settings

list with model setting, in the format returned by the function initialize_settings

mcmc

list with draws of parameters and states (including burnin phase)

data

list with at least two named components: tsm is a multiple time series object that contains all observation series, weights is a named list of time series with (nominal) weights, the list names correspond to the different groups, i.e., group1, group2, subgroup1, if present in the model

HPDIprob

probability of highest posterior density interval, optional if fit is supplied

fit

(optional) an object of class fit (returned by the function estimate_ssmodel and this function).

...

additional arguments (in case fit is supplied)

Details

If fit is supplied, the arguments model, settings, mcmc will be taken from this object.

Value

An object of class ss_fit.


Computes weights from sub sector data

Description

This function computes weights for linear growth or non-linear level constraints.

Usage

compute_weights(tsl_r, tsl_n, idx, pos, neg, weight_type = "growth")

Arguments

tsl_r

time series list with real level series

tsl_n

time series list with nominal level series

idx

index for aggregate

pos

sectors to be added

neg

sectors to be substracted

weight_type

type of weights, either growth or level, default is growth

Value

A time series list with weights.


Swiss data set

Description

A dataset containing quarterly Swiss economic data, sourced on November 20, 2023.

Usage

data_ch

Format

A list object with two lists. The first list cotains all untransformed endogenous variables:

output

Gross domestic product at 2020 prices, in million

vaA

value added in sector A: Goods-producing industries, at 2020 prices in million

vaB

value added in sector B: Service industries, at 2020 prices in million

vaC

value added in sector C: Government and adjustments,at 2020 prices in million

exp1

expenditure side sector i: Total consumption, at 2020 prices in million

exp2

expenditure side sector ii: Investment, at 2020 prices in million

exp3

expenditure side sector iii: Exports, at 2020 prices in million

exp4

expenditure side sector iv: Imports, at 2020 prices in million

fteA

full-time equivalent empoyment in sector A: Goods-producing industries, in thousand

fteB

full-time equivalent empoyment in sector B: Service industries, in thousand

fteC

full-time equivalent empoyment in government sector, in thousand

employment

full-time equivalent empoyment, in thousand

urate

ILO unemployment rate, in percent

inflation

consumer price inflation, year on year in percent

Source

KOF Swiss Economic Institute, ETH Zurich, Switzerland


State space model

Description

Defines a state space model for the provided settings and data.

Usage

define_ssmodel(settings, data)

Arguments

settings

list with model setting, in the format returned by the function initialize_settings

data

list with at least two named components: tsm is a multiple time series object that contains all observation series, weights is a named list of time series with (nominal) weights, the list names correspond to the different groups, i.e., group1, group2, subgroup1, if present in the model

Details

data is preferably the output of funtion prepare_data.

Value

A state space model object of class ss_model, which consists of an object returned by the function SSModel of the package KFAS and in addition a list item called names which contains information on the parameters to be estimated.

Examples

data("data_ch")
settings <- initialize_settings()
data <- prepate_data(
  settings = settings,
  tsl = data_ch$tsl,
  tsl_n = data_ch$tsl_n
)
model <- define_ssmodel(
  settings = settings, 
  data = data
)

Draws the parameters of the output gap..

Description

This is a wrapper function that draws the parameters of the output gap for different cycle specifications

Usage

draw_output_gap(Y, phi, phiDistr, sigma, sigmaDistr)

Arguments

Y

dependent variable

phi

autoregressive coefficient vector

phiDistr

prior distribution of autoregressive coefficient vector

sigma

innovation variance

sigmaDistr

prior distribution of innovation variance

Value

A named vector of drawn parameters.


Draws (correlated) trend variances.

Description

Draws (correlated) trend variances.

Usage

draw_trend_innovations(model, state, df_var, df_cov, df_prior)

Arguments

model

state space model object

state

time series matrix with states

df_var

data frame with trend and drift variance settings

df_cov

data frame with trend and drift covariance settings

df_prior

prior distribution matrix

Value

A named vector of drawn parameters.


Draws a variance from an inverse Wishart distribution. .

Description

Draws a variance from an inverse Wishart distribution. .

Usage

draw_variance_multi(Y, nu, Phi)

Arguments

Y

dependent variable

nu

degrees of freedom, nu>p-1

Phi

scale matrix, p x p

Details

The mean is given by Phi / (nu+p-1) for nu>p+1.

Value

A named vector of drawn parameters.


Draws a variance from an inverse Wishart distribution.

Description

Draws a variance from an inverse Wishart distribution.

Usage

draw_variance_scalar(Y, nu, s)

Arguments

Y

dependent variable

nu

degrees of freedom, nu>p-1

s

scale matrix, p x p

Details

The mean is given by s / (nu+p-1) for nu>p+1.

Value

A named vector of drawn parameters.


Bayesian estimation via Gibbs sampling

Description

Estimates the parameters and states of a multi-dimensional state space model by Bayesian methods using a Gibbs sampling procedure.

Usage

estimate_ssmodel(
  model,
  settings,
  data,
  prior = initialize_prior(model),
  R = 10000,
  burnin = 0.5,
  thin = 1,
  HPDIprob = 0.68,
  fit = NULL
)

Arguments

model

state space model object, returned by the function define_ssmodel

settings

list with model setting, in the format returned by the function initialize_settings

data

list with at least two named components: tsm is a multiple time series object that contains all observation series, weights is a named list of time series with (nominal) weights, the list names correspond to the different groups, i.e., group1, group2, subgroup1, if present in the model

prior

list of matrices, each list item corresponds to one endogenous variable. See initialize_prior

R

number of draws, the default is 10000

burnin

share of draws as burnin period, the default is 0.5

thin

thinning parameter defining how many draws are discarded. 1 means no draw is discarded, 2 means each second draw is kept, and so on

HPDIprob

probability of highest posterior density interval, the default is HPDIprob = 0.68

fit

already fitted object of class ss_fit, to continue drawing, see details

Details

If fit is supplied, the function will continue drawing R additional repetitions. In this case, all input variables except for fit and R are ignored.

Value

An object of class ss_fit.

Examples

data("data_ch")
settings <- initialize_settings()
data <- prepate_data(
  settings = settings,
  tsl = data_ch$tsl,
  tsl_n = data_ch$tsl_n
)
model <- define_ssmodel(
  settings = settings, 
  data = data
)
prior <- initialize_prior(
  model = model, 
  settings = settings
) 

fit <- estimate_ssmodel(
  model = model, 
  settings = settings, 
  data = data,
  prior = prior,
  R = 100
)


Geweke test for convergence

Description

Conducts a Geweke test for convergence of the draws.

Usage

geweke_test(x, frac1 = 0.1, frac2 = 0.5, alpha = 0.05)

Arguments

x

R x n matrix with R draws of n variables

frac1

probability mass of the first interval, a scalar between zero and one

frac2

probability mass of the second interval, a scalar between zero and one

alpha

significance level used to compute the test decision, a scalar between zero and one

Details

Under the H0 of convergence, the test statistic is standard normally distributed.

Naturally, frac1 + frac2 is between zero and one.

Value

A list with the following items

h

Test decision.

CD

Convergence Diagnostic (test statistic).

pvalue

The p-value.

alpha

The applied signifcicance level.

frac1

The fraction of data contained in the first interval.

frac2

The fraction of data contained in the second interval.


Settings for draws from posterior

Description

Creates a list of settings used during the Gibbs sampling algorithm.

Usage

helper_posterior_assignment(model, df_set, prior, endo)

Arguments

model

state space model object (unassigned)

df_set

data frame with model settings

endo

character vector of endogenous variable names

Value

A list of items necessary to run each each step of the Gibbs sampler.


Highest posterior density interval (HPDI)

Description

Computes the approximate highest posterior density interval (HPDI).

Usage

hpd_interval(x, prob = 0.95)

Arguments

x

A R x n matrix with R draws of n variables

prob

The probability mass of the interval, a scalar between zero and one

Value

n x 2 matrix with lower and upper boundary of the HPDI.


HP filter

Description

Applies the Hodrick Prescott Filter.

Usage

hpfilter(x, lambda)

Arguments

x

A univariate time series object.

lambda

The smoothing parameter.

Value

A univariate time series object containing the trend of the original time series.


Prior distribution

Description

Initializes the prior distributions.

Usage

initialize_prior(model, settings, lambda_d = 100, lambda_t = 100, df = 6)

Arguments

model

state space model object, returned by the function define_ssmodel

settings

list with model setting, in the format returned by the function initialize_settings

lambda_d

drift smoothing constant (default: 100)

lambda_t

trend smoothing constant (default: 100)

df

degrees of freedom for inverse gamma distributions

Details

All loadings and autoregressive parameters are assumed to be normal with mean zero and variance 1000.

All variance parameters are assumed to be inverse gamma distributed. The cycle variance has prior mean 1, and the trend variances have prior mean 1/100.

The normal distribution is parametrized via mean and variance.

the inverse gamma distribution is parametrized degrees of freedom nu and scale s.

The mean of the inverse gamma distribution is given by beta / (alpha - 1) = beta / 2 = s, where s = 2 beta, nu = 2 alpha.

Value

A data frame with one row per parameter and the following columns:

variable

name of endogneous variable of equation

parameter_name

name of parameter

par1

first parameter of specified distribution, mean for normal parameters and scale for inverse gamma parameters

par2

second parameter of specified distribution, variance for normal parameters and degrees of freedom for inverse gamma parameters

ini

initial value for Gibbs sampler, i.e. mean of distribution given par1 and par2

distribution

name of prior distribution

Examples

data("data_ch")
settings <- initialize_settings()
data <- prepate_data(
  settings = settings,
  tsl = data_ch$tsl,
  tsl_n = data_ch$tsl_n
)
model <- define_ssmodel(
  settings = settings, 
  data = data
)
prior <- initialize_prior(
  model = model, 
  settings = settings
) 

Model settings

Description

Initializes settings with a basic example.

Usage

initialize_settings(
  FUN_transform = function(x) 100 * log(x),
  FUN_transform_inv = function(x) exp(x/100),
  DFUN_transform_inv = function(x) 1/100 * exp(x/100)
)

Arguments

FUN_transform

transformation function, the default is function(x) 100 * log(x)

FUN_transform_inv

inverse transformation function, the default is function(x) exp(x / 100)

DFUN_transform_inv

derivative of inverse transformation function, the default is function(x) 1 exp(x / 100), only used if non-linear constraints are present

Value

A nested list with settings for the following groups:

agg

settings for the aggregate variable

group1

settings for group1, all variables in this group load on the aggregate variable, unless otherwise specified

group2

settings for group2, all variables in this group load on the aggregate variable, unless otherwise specified

subgroup1

settings for subgroup1, each variable in this group loads on the respective variable in group1

agggroup

settings for a group of variables that all load on the same variable

misc

settings for variables that require individual settings

Each group contains at least the following list items:

trend

4 is a local linear trend, 3 a local linear trend with AR(1) drift, 2 a local linear drift without shocks to trend growth, 0 implies no trend (e.g. if a variable shares a trend with another one)

cycle

2 is an AR(2) cycle, 1 an AR(1) cycle, and 0 a white noise cycle, each with normal innovations

transform

logical indicating if the transformation function should be applied to the variable or group of variables

variable

variable name(s)

variable_label

variable label(s)

label

label of group

The blocks group1, group2, subgroup1 additionally contain the following list items:

corr

4 implies that trends and drifts are correlated, 2 that only dirfts are correlated, 1 that only trends are correlated, and 0 or NA implies no correlation. Only applicable for group1, group2, subgroup1

load_name

name of the variable that all variables in the group load (for group1, group2) and which is used for the aggregation

load_lag

lags of the of the variable that all variables in the group load (for group1, group2)

constr_drift

logical indicating if constraints for the drifts should be enforced

constr_trends

logical indicating if constraints for the trends should be enforced

constr_trends_linear

logical indicating if constraints for the trends are linear or nonlinear, the default is FALSE in which case the constraint is enforced on the level series, else, it is enforced on the growth rates.

variable_neg

variable names that are negative and thus need to be subtracted when constructing weights

The block subgroup1 additionally contain the following list item:

match_group1

a character vector of the same length as variable indicating the matching variables in group1, in the same order as variable, NA indicates no match


Initializes a state space model

Description

Initializes a state space model

Usage

initialize_ss(name, df_settings)

Arguments

name

names of observations

df_settings

list of data frames with settings


Settings object validity check

Description

Checks if settings are a valid object of class settings.

Usage

is.settings(x, dfl = NULL, return.logical = FALSE)

Arguments

x

settings object

dfl

list of data frames, returned by function settings_to_df

return.logical

If return.logical = FALSE (default), an error message is printed if the object is not of class settings, if return.logical = TRUE, a logical value is returned

Value

A logical value or nothing, depending on the value of return.logical.


array multiplication

Description

array multiplication

Usage

matmult3d(a, b)

Arguments

a

A matrix.


MCMC summary statistics

Description

Computes MCMC summary statistics.

Usage

mcmc_summary(x, HPDIprob, frac1 = 0.1, frac2 = 0.5)

Arguments

x

R x n matrix with R draws of n variables

HPDIprob

Tprobability mass of the HPDI, a scalar between zero and one

frac1

probability mass of the first interval used for the Geweke test, a scalar between zero and one

frac2

probability mass of the second interval used for the Geweke test, a scalar between zero and one

Details

Naturally, frac1 + frac2 is between zero and one.

Value

A data frame with the following columns

Mean

The posterior mean.

Median

The posterior median.

SD

Standard deviation.

HPDI-LB

Highest posterior density credible interval lower bound

HPDI-UB

Highest posterior density credible interval upper bound

Naive SE

Naive Standard error of the mean (ignoring chain autocorrelation.

Time-series SE

Time-series standard error (based on spectral density at 0).

Geweke statistic

The Geweke test statistic.

frac1

The fraction of data contained in the first interval.

frac2

The fraction of data contained in the second interval.


Draws from the multivariate normal distribution.

Description

Draws from the multivariate normal distribution.

Usage

mvrnorm(mu, sigma)

Arguments

mu

A n x 1 vector, the mean vector.

sigma

A n x n matrix, the covariance matrix.

Value

A n x 1 named vector of drawn parameters.


Computes the period on period percentage change

Description

Computes the period on period percentage change

Usage

pct(x)

Arguments

x

(multiple) time series object


Plots of results

Description

Creates a set of time series, density, or trace plots.

Usage

## S3 method for class 'ss_fit'
plot(
  x,
  plot_type = "timeseries",
  estimate = "median",
  data = data,
  n_col = 3,
  n_sep = 5,
  file_path = NULL,
  title = TRUE,
  save = FALSE,
  device = "jpg",
  width = 10,
  height = 3,
  units = "in",
  highlighted_area = NULL,
  plot_start = NULL,
  plot_end = NULL,
  alpha = 0.05,
  include_burnin = FALSE,
  ...
)

Arguments

x

object of class ss_fit

plot_type

type of plots, options are "timeseries", "density", "trace"

estimate

character specifying the posterior estimate. Valid options are "mean" and "median", the default is estimate = "median".

data

list with at least two named components: tsm is a multiple time series object that contains all observation series, weights is a named list of time series with (nominal) weights, the list names correspond to the different groups, i.e., group1, group2, subgroup1, if present in the model

n_col

number of columns for grid plots

n_sep

increments of x axis ticks in years

file_path

file path for plots

title

boolean indicating if plots should contain titles

save

boolean indicating if plots should be saved, if FALSE, the plots will be printed instead, default is save = FALSE (ignored if file_path is provided)

device

character string with format used in ggsave

width

plot width in units, for grid plots adjusted for the number of plot columns n_col

height

plot height in units, for grid plots adjusted for the number of plot rows implied by n_col

units

units for plot size ("in", "cm", "mm", or "px")

highlighted_area

data frame with two columns called start and end containing start and end date, e.g. 1990.25 and 1992.75 for 1990 Q2 until 1992 Q4 (only used if plot_type = "timeseries")

plot_start

start of x axis in years, e.g., 1990.5 (only used if plot_type = "timeseries")

plot_end

end of x axis in years, e.g., 2010.25 (only used if plot_type = "timeseries")

alpha

cut off value for posterior (only used if plot_type = "density")

include_burnin

logical indicating if burnin phase should be included (only used if plot_type = "trace")

...

ignored

Value

nothing


Prior and posterior plots

Description

Creates diagnostic plots of the posterior distribution.

Usage

plot_densities(
  fit,
  file_path,
  n_col = 4,
  alpha = 0.05,
  save = TRUE,
  title = TRUE,
  device = "jpg",
  width = 10,
  height = 2,
  units = "in"
)

Arguments

fit

fitted object

file_path

file path for plots

n_col

number of columns for grid plots

alpha

cut off value for posterior (only used if plot_type = "density")

save

boolean indicating if plots should be saved, if FALSE, the plots will be printed instead, default is save = FALSE (ignored if file_path is provided)

title

boolean indicating if plots should contain titles

device

character string with format used in ggsave

width

plot width in units, for grid plots adjusted for the number of plot columns n_col

height

plot height in units, for grid plots adjusted for the number of plot rows implied by n_col

units

units for plot size ("in", "cm", "mm", or "px")

Value

nothing


Time series plots

Description

Creates a set of time series plots of the results.

Usage

plot_time_series(
  df,
  settings = settings,
  n_col = 3,
  n_sep = 5,
  highlighted_area = NULL,
  plot_start = NULL,
  plot_end = NULL,
  file_path = NULL,
  title = TRUE,
  save = TRUE,
  device = "jpg",
  width = 10,
  height = 3,
  units = "in"
)

Arguments

settings

list with model setting, in the format returned by the function initialize_settings

n_col

number of columns for grid plots

n_sep

increments of x axis ticks in years

highlighted_area

data frame with two columns called start and end containing start and end date, e.g. 1990.25 and 1992.75 for 1990 Q2 until 1992 Q4 (only used if plot_type = "timeseries")

plot_start

start of x axis in years, e.g., 1990.5 (only used if plot_type = "timeseries")

plot_end

end of x axis in years, e.g., 2010.25 (only used if plot_type = "timeseries")

file_path

file path for plots

title

boolean indicating if plots should contain titles

save

boolean indicating if plots should be saved, if FALSE, the plots will be printed instead, default is save = FALSE (ignored if file_path is provided)

device

character string with format used in ggsave

width

plot width in units, for grid plots adjusted for the number of plot columns n_col

height

plot height in units, for grid plots adjusted for the number of plot rows implied by n_col

units

units for plot size ("in", "cm", "mm", or "px")

Value

nothing


Prior and posterior plots

Description

Creates trace plots for the draws of the posterior distribution.

Usage

plot_trace(
  fit,
  file_path,
  include_burnin = FALSE,
  n_col = 4,
  alpha = 0.05,
  save = TRUE,
  title = TRUE,
  device = "jpg",
  width = 10,
  height = 2,
  units = "in"
)

Arguments

fit

fitted object

file_path

file path for plots

include_burnin

logical indicating if burnin phase should be included (only used if plot_type = "trace")

n_col

number of columns for grid plots

alpha

cut off value for posterior (only used if plot_type = "density")

save

boolean indicating if plots should be saved, if FALSE, the plots will be printed instead, default is save = FALSE (ignored if file_path is provided)

title

boolean indicating if plots should contain titles

device

character string with format used in ggsave

width

plot width in units, for grid plots adjusted for the number of plot columns n_col

height

plot height in units, for grid plots adjusted for the number of plot rows implied by n_col

units

units for plot size ("in", "cm", "mm", or "px")

Value

nothing


Draws the parameters of an AR process (AR parameters and variance).

Description

Draws the parameters of an AR process (AR parameters and variance).

Usage

postARp(Y, phi, phiDistr, sigma, sigmaDistr, const = NULL, constDistr = NULL)

Arguments

Y

dependent variable

phi

autoregressive coefficient vector

phiDistr

prior distribution of autoregressive coefficient vector

sigma

innovation variance

sigmaDistr

prior distribution of innovation variance

const

constant

constDistr

prior distribution of constant

Details

See "Chib, Siddhartha. "Bayes regression with autoregressive errors: A Gibbs sampling approach." Journal of econometrics 58.3 (1993): 275-294."

Value

A named vector of drawn parameters.


Draws the autoregressive parameters of an AR process (AR parameters only). .

Description

Draws the autoregressive parameters of an AR process (AR parameters only). .

Usage

postARp_phi(Y, phi, phiDistr, sigma, const = NULL, constDistr = NULL)

Arguments

Y

dependent variable

phi

autoregressive coefficient vector

phiDistr

prior distribution of autoregressive coefficient vector

sigma

innovation variance

const

constant

constDistr

prior distribution of constant

Details

See "Chib, Siddhartha. "Bayes regression with autoregressive errors: A Gibbs sampling approach." Journal of econometrics 58.3 (1993): 275-294."

Value

A named vector of drawn parameters.


Draws the parameters in a regression equation with AR errors, if specified.

Description

Draws the parameters in a regression equation with AR errors, if specified.

Usage

post_regression(
  Y,
  X,
  beta = NULL,
  betaDistr,
  sigma,
  sigmaDistr,
  phi = NULL,
  phiDistr = NULL,
  indep = TRUE,
  const = NULL,
  constDistr = NULL
)

Arguments

Y

dependent variable

X

explanatory variable(s)

beta

coefficient vector

betaDistr

prior distribution of coefficient vector

sigma

innovation variance

sigmaDistr

prior distribution of innovation variance

phi

autoregressive coefficient vector

phiDistr

prior distribution of autoregressive coefficient vector

indep

logical, should beta and sigma be independent

const

constant

constDistr

prior distribution of constant

Details

See "Chib, Siddhartha. "Bayes regression with autoregressive errors: A Gibbs sampling approach." Journal of econometrics 58.3 (1993): 275-294."

Value

A named vector of drawn parameters.


Input data

Description

Prepares the required input data, it performs the transformations to the raw data and computes the necessary weights for the constraints.

Usage

prepate_data(
  settings,
  tsl,
  tsl_n = NULL,
  tsl_p = NULL,
  ts_start = NULL,
  ts_end = NULL,
  extend_weights = FALSE
)

Arguments

settings

list with model setting, in the format returned by the function initialize_settings

tsl

time series list with all untransformed endogenous series

tsl_n

time series list with nominal level series for aggregate output agg and its subcomponents in group1, group2

tsl_p

time series list with price series for aggregate output agg and its subcomponents in group1, group2

ts_start

start date, e.g. c(2000, 2) or 2000.25

ts_end

end date, e.g. c(2000, 2) or 2000.25

extend_weights

logical indicating if missing weights at beginning/end of sample should be filled with the last/first available value

Details

Either tsl_n or tsl_p must be supplied.

Weights are forward/backward extended with the first/last value if the supplied time series do not cover the entire period.

Value

A list with five components:

tsm

multiple time series object with all (transformed) endogeneous variables

real

multiple time series object with real series of agg, group1, group2

nominal

multiple time series object with nominal series of agg, group1, group2

prices

multiple time series object with price series of agg, group1, group2

weights_growth

list of multiple time series objects with weights for the growth constraints, i.e., for series group1, group2, subgroup1 if applicable

weights_level

list of multiple time series objects with weights for the non linear level constraints, i.e., for series group1, group2, subgroup1 if applicable

Examples

data("data_ch")
settings <- initialize_settings()
data <- prepate_data(
  settings = settings,
  tsl = data_ch$tsl,
  tsl_n = data_ch$tsl_n
)

Print prior object

Description

Prints the model specifications of an object of class prior.

Usage

## S3 method for class 'prior'
print(x, call = TRUE, check = TRUE, ...)

Arguments

x

object of class prior

call

logical, if TRUE, the call will be printed

check

logical, if TRUE, the model class will be checked

...

ignored.

Value

No return value


Print settings object

Description

Prints the model settings.

Usage

## S3 method for class 'settings'
print(x, call = TRUE, check = TRUE, ...)

Arguments

x

object of class settings

call

logical, if TRUE, the call will be printed

check

logical, if TRUE, the model class will be checked

...

ignored.

Value

No return value


Print ss_fit object.

Description

Prints the model specifications of an object of class ss_fit.

Usage

## S3 method for class 'ss_fit'
print(x, call = TRUE, check = TRUE, ...)

Arguments

x

object of class ss_fit

call

logical, if TRUE, the call will be printed

check

logical, if TRUE, the model class will be checked

...

ignored.

Value

No return value


Print ss_model object

Description

Prints the model specifications of an object of class ss_model.

Usage

## S3 method for class 'ss_model'
print(x, call = TRUE, check = TRUE, ...)

Arguments

x

object of class ss_model

call

logical, if TRUE, the call will be printed

check

logical, if TRUE, the model class will be checked

...

ignored.

Value

No return value


Swiss recessions

Description

Recession periods in Switzerland since 1990.

Usage

recessions_ch

Format

A data frame with two columns:

start

start date of recession, in quarters

end

end date of recession, in quarters


US recessions

Description

Recession periods in the United States since 1960.

Usage

recessions_us

Format

A data frame with two columns:

start

start date of recession, in quarters

end

end date of recession, in quarters

Source

National Bureau of Economic Research (NBER)


MCMC summary statistics for states

Description

Computes MCMC summary statistics for each state.

Usage

results_state(model, HPDIprob, state)

Arguments

model

The return object of the function fitSSM from the package KFAS

HPDIprob

probability of highest posterior density interval, the default is HPDIprob = 0.68

state

An array with the smoothed state

Value

List of time series.


Data frames with model settings

Description

Creates a list of data frames with model settings regarding the state space model.

Usage

settings_to_df(x)

Arguments

x

list with model setting

Value

A list with data frames containing model settings.


Extracts last letter in string

Description

Extracts last letter in string

Usage

substr_r(x, n)

Arguments

x

character string

n

number of letters to extract


Format results

Description

Formats the output series into a tibble in long format and computes contribution series.

Usage

transform_results(
  fit,
  data,
  settings,
  estimate = "median",
  HPDIprob = 0.68,
  transformed = TRUE
)

Arguments

fit

fitted object

data

list with at least two named components: prices is a multiple time series object that contains price indices for all relevant series, weights, is a named list of time series with (nominal) weights, the list names correspond to the different groups, i.e., group1, group2, subgroup1, if present in the model

settings

list with model setting, in the format returned by the function initialize_settings

estimate

character specifying the posterior estimate. Valid options are "mean" and "median", the default is estimate = "median".

HPDIprob

probability of highest posterior density interval, the default is HPDIprob = 0.68

transformed

boolean indicating if the transformed series should be used.

Details

data is preferably the output of funtion prepare_data.

Value

A data frame with results in long format.

Examples

data("data_ch")
settings <- initialize_settings()
data <- prepate_data(
  settings = settings,
  tsl = data_ch$tsl,
  tsl_n = data_ch$tsl_n
)
model <- define_ssmodel(
  settings = settings, 
  data = data
)
prior <- initialize_prior(
  model = model, 
  settings = settings
) 

fit <- estimate_ssmodel(
  model = model, 
  settings = settings, 
  data = data,
  prior = prior,
  R = 100
)
df <- transform_results(
  fit = fit, 
  data = data,
  estimate = "median"
)


Creates a constant time series with same dates and frequency as the one given.

Description

Creates a constant time series with same dates and frequency as the one given.

Usage

ts_c(c = 0, tsm)

Arguments

c

constant scalar

tsm

(multiple) time series object


Non linear constraints update

Description

Updates the system matrices of a state space model to include non linear constraints.

Usage

update_nonlinear_constraints(state, model, settings, df_constr, data)

Arguments

state

multiple time series object with states

model

state space model object (with assigned parameters)

settings

list with model setting, in the format returned by the function initialize_settings

df_constr

data frame with constraint settings

data

list with at least two named components: tsm is a multiple time series object that contains all observation series, weights is a named list of time series with (nominal) weights, the list names correspond to the different groups, i.e., group1, group2, subgroup1, if present in the model

Details

data is preferably the output of funtion prepare_data.

Value

The state space model object model with updates matrices.

Examples

data("data_ch")
settings <- initialize_settings()
data <- prepate_data(
  settings = settings,
  tsl = data_ch$tsl,
  tsl_n = data_ch$tsl_n
)
model <- define_ssmodel(
  settings = settings, 
  data = data
)

State space model update

Description

Updates the system matrices of a state space model.

Usage

update_ssmodel(pars, model, model_last, settings, df_set)

Arguments

pars

named vector with all parameters

model

state space model object (unassigned)

model_last

state space model object (previous draw)

settings

list with model setting, in the format returned by the function initialize_settings

df_set

data frame with model settings

Details

data is preferably the output of funtion prepare_data.

Value

The state space model object model with updates matrices.

Examples

data("data_ch")
settings <- initialize_settings()
data <- prepate_data(
  settings = settings,
  tsl = data_ch$tsl,
  tsl_n = data_ch$tsl_n
)
model <- define_ssmodel(
  settings = settings, 
  data = data
)