---
title: "Estimating Small Macro Model for Switzerland"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{small_open_economy}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

# Equations of the Small Macro Model

**Stochastic equations**

$$
\begin{aligned}
\text{Consumption}\quad C_t &= \beta_1 + \beta_{1,2} C_{t-1} + \gamma_{1,7} Y_t + \varepsilon_{1t},\\
\text{Investment}\quad I_t &= \beta_2 + \beta_{2,3} I_{t-1} + \varepsilon_{2t},\\
\text{Exports}\quad X_t &= \beta_3 + \beta_{3,4} X_{t-1} + \beta_{3,7} WGDP_t + \varepsilon_{3t},\\
\text{Imports}\quad M_t &= \beta_4 + \gamma_{4,8} D_t + \beta_{4,5} I_{t-1} + \varepsilon_{4t},\\
\text{Prices}\quad P_t &= \beta_5 + \beta_{5,9} ER_t + \beta_{5,10} OP_t 
     + \beta_{5,6} P_{t-1} + \varepsilon_{5t},\\
\text{Interest Rate}\quad R_t &= \beta_6 + \beta_{6,6} P_{t-1} + \beta_{6,8} R_{GE,t} 
     + \gamma_{6,5} P_t + \varepsilon_{6t}.
\end{aligned}
$$

**Equilibrium condition**

$$
\begin{aligned}
\text{Equilibrium Ouput}\quad GDP_t &= 0.6*C_t + 0.6*D_t + 0.5*X_t - 0.4*I_t
\end{aligned}
$$

**Identities**

$$
\begin{aligned}
\text{Domestic Demand}\quad D_t &= 0.6*C_t + 0.4*I_t
\end{aligned}
$$

**Coefficients**  
- The $\beta$’s and $\gamma$’s are structural coefficients to be estimated.

**Endogenous variables**  

- $C_t$: Consumption at time $t$.
- $I_t$: Gross fixed capital formation (investment) at time $t$.
- $X_t$: Exports at time $t$.
- $M_t$: Imports at time $t$.
- $P_t$: Price level at time $t$.
- $R_t$: Short-term interest rate at time $t$.
- $D_t$: Domestic demand, defined by $D_t = 0.6 * C_t + 0.4 * I_t$.
- $GDP_t$: Equilibrium output (demand), defined by
  $GDP_t = 0.6 * C_t + 0.6 * D_t + 0.5 * X_t - 0.4 * I_t$.

**Exogenous variables**  

- $WGDP_t$: World GDP at time $t$.
- $ER_t$: Exchange rate at time $t$.
- $OP_t$: Oil price at time $t$.
- $R_{GE,t}$: German interest rate at time $t$.

**Other variables**  

- $G_t$: Government spending at time $t$.
- $T_t$: Taxes at time $t$.
- $\varepsilon_{it}$: Stochastic error term for equation $i$ at time $t$.


# Defining the SEM in R
To estimate and forecast this model, we need to specify the equations, the exogenous variables, and the date ranges for estimation and forecasting.

```{R}
equations <- "consumption ~ gdp + consumption.L(1),
investment ~ investment.L(1),
exports ~ world_gdp + exports.L(1),
imports ~ domestic_demand + imports.L(1),
prices ~ exchange_rate + oil_price + prices.L(1),
interest_rate ~ prices + interest_rate_germany + prices.L(1),
gdp == 0.6*consumption + 0.6*domestic_demand + 0.5*exports - 0.4*imports,
domestic_demand == 0.6*consumption + 0.4*investment"

exogenous_variables <- c("world_gdp", "interest_rate_germany", "exchange_rate", "oil_price")
```

The `equations` string contains the model equations, while `exogenous_variables` lists the exogenous variables. The `.L(1)` notation indicates a lag of one period.
For further details on the syntax, please refer to the [equation syntax documentation](koma-equations.html).

# Creating the SEM

The `system_of_equations` function is used to create a system of equations object, which can then be used for estimation and forecasting.
```{R, collapse=TRUE}
library(koma)

sys_eq <- system_of_equations(
  equations = equations,
  exogenous_variables = exogenous_variables
)

print(sys_eq)
```

# Defing the Estimation and Forecast Dates
Now, we need to specify the dates for estimation and forecasting.

```{R}
dates <- list(
  estimation = list(start = c(1996, 1), end = c(2019, 4)),
  forecast = list(start = c(2023, 1), end = c(2023, 4))
)
```

# Preparing the Data

We will use the `small_open_economy` dataset, which contains the required variables for the model. 
This dataset is a list of standard time series (`ts`) objects, where each object corresponds to a variable in the model. 
You can explore the dataset by using the `?small_open_economy` command to view its documentation and structure.

```{R}
?small_open_economy
```

To prepare the dataset for use with the `koma` package, we need to convert the `ts` objects to the `ets` format using the `as_ets` function.

The model is estimated in growth rates. The `small_open_economy` dataset is in levels. We use the `ets` to tell the model that the data is in levels and how to convert it to growth rates.
`ets` is generalized to accept any additional attributes. Below we use this feature to save the series' value_type (real or nominal).

```{R}
series <- names(small_open_economy)
series <- series[!series %in% c("interest_rate", "interest_rate_germany")]

ts_data <- lapply(series, function(x) {
  as_ets(small_open_economy[[x]],
    series_type = "level", method = "diff_log"
  )
})
names(ts_data) <- series

ts_data$interest_rate <- as_ets(small_open_economy$interest_rate,
  series_type = "rate", method = "none"
)
ts_data$interest_rate_germany <- as_ets(small_open_economy$interest_rate_germany,
  series_type = "rate", method = "none"
)
```

With the data prepared, we can now proceed to estimate the model. 
Before forecasting, however, we need to truncate the endogenous variables to ensure they only include data up to the forecast start date.

```{R}
ts_data[sys_eq$endogenous_variables] <-
  lapply(sys_eq$endogenous_variables, function(x) {
    stats::window(ts_data[[x]], end = c(2019, 4))
  })
```

# Estimating the Model

The names of the list elements should match the variable names used in the equations.
Now, we can estimate the model using the `estimate` function. 

```{R, collapse=TRUE}
estimates <- estimate(
  sys_eq,
  ts_data = ts_data,
  dates = dates
)
print(estimates)
```

```{R, collapse=TRUE}
summary(estimates)
```

```{R, collapse=TRUE}
summary(estimates, variables = "investment")
```

To see how to run the estimation in parallel, refer to the [parallel estimation vignette](koma-parallel.html).

# Diagnostics

You can visualize MCMC diagnostics for coefficient draws using `trace_plot()`.

```{R, eval=FALSE}
if (requireNamespace("ggplot2", quietly = TRUE)) {
  trace_plot(estimates, variables = c("consumption", "investment"))
}
```

You can also inspect running means (cumulative averages) with `running_mean_plot()`.

```{R, eval=FALSE}
if (requireNamespace("ggplot2", quietly = TRUE)) {
  running_mean_plot(estimates, variables = c("consumption", "investment"))
}
```

You can inspect autocorrelation diagnostics with `acf_plot()`.

```{R, eval=FALSE}
if (requireNamespace("ggplot2", quietly = TRUE)) {
  acf_plot(estimates, variables = c("consumption", "investment"))
}
```

# Forecasting

To forecast the model, we can use the `forecast` function. This function will generate forecasts for the specified date range.
```{R, collapse=TRUE}
forecasts <- forecast(
  estimates,
  dates = dates
)
print(forecasts)
```

```{R, collapse=TRUE}
rate(forecasts$mean$gdp)
level(forecasts$mean$gdp)
```

## Conditional Forecasting

Conditional forecasting allows you to impose restrictions on certain variables during the forecast period to fix their values. This is useful for scenario analysis and policy evaluation, as the forecasts will reflect these user-defined conditions.

```{R, eval=FALSE}
fig <- plot(forecasts, variables = "prices")
fig

restrictions <- list(prices = list(value = 0.5, horizon = 1))

forecasts <- forecast(estimates,
  dates = dates,
  restrictions = restrictions
)
plot(forecasts, fig = fig, variables = "prices")
forecasts$mean$prices
```
