Documentation

# simulate

Monte Carlo simulation of vector autoregression (VAR) model

## Syntax

``Y = simulate(Mdl,numobs)``
``Y = simulate(Mdl,numobs,Name,Value)``
``````[Y,E] = simulate(___)``````

## Description

example

````Y = simulate(Mdl,numobs)` returns a random `numobs`-period path of multivariate response series (`Y`) from simulating the fully specified VAR(p) model `Mdl`.```

example

````Y = simulate(Mdl,numobs,Name,Value)` uses additional options specified by one or more name-value pair arguments. For example, you can specify simulation of multiple paths, exogenous predictor data, or inclusion of future responses for conditional simulation.```

example

``````[Y,E] = simulate(___)``` returns the model innovations `E` using any of the input arguments in the previous syntaxes.```

## Examples

collapse all

Fit a VAR(4) model to the consumer price index (CPI) and unemployment rate data. Then, simulate responses from the estimated model.

Load the `Data_USEconModel` data set.

`load Data_USEconModel`

Plot the two series on separate plots.

```figure; plot(DataTable.Time,DataTable.CPIAUCSL); title('Consumer Price Index'); ylabel('Index'); xlabel('Date');``` ```figure; plot(DataTable.Time,DataTable.UNRATE); title('Unemployment Rate'); ylabel('Percent'); xlabel('Date');``` Stabilize the CPI by converting it to a series of growth rates. Synchronize the two series by removing the first observation from the unemployment rate series. Create a new data set containing the transformed variables, and do not include any rows containing at least one missing observation.

```rcpi = price2ret(DataTable.CPIAUCSL); unrate = DataTable.UNRATE(2:end); dates = DataTable.Time(2:end); idx = all(~ismissing([rcpi unrate]),2); Data = array2timetable([rcpi(idx) unrate(idx)],... 'RowTimes',DataTable.Time(idx),'VariableNames',{'rcpi','unrate'});```

Create a default VAR(4) model using the shorthand syntax.

`Mdl = varm(2,4);`

Estimate the model using the entire data set.

`EstMdl = estimate(Mdl,Data.Variables);`

`EstMdl` is a fully specified, estimated `varm` model object.

Simulate a response series path from the estimated model with length equal to the path in the data.

```rng(1); % For reproducibility numobs = size(Data,1); Y = simulate(EstMdl,numobs);```

`Y` is a 245-by-2 matrix of simulated responses. The first and second columns contain the simulated CPI growth rate and unemployment rate, respectively.

Plot the simulated and true responses.

```figure; plot(Data.Time,Y(:,1)); hold on; plot(Data.Time,Data.rcpi) title('CPI Growth Rate'); ylabel('Growth rate'); xlabel('Date'); legend('Simulation','True')``` ```figure; plot(Data.Time,Y(:,2)); hold on; plot(Data.Time,Data.unrate) ylabel('Percent'); xlabel('Date'); title('Unemployment Rate'); legend('Simulation','True')``` Illustrate the relationship between `simulate` and `filter` by estimating a 4-dimensional VAR(2) model of the four response series in Johansen's Danish data set. Simulate a single path of responses using the fitted model and the historical data as initial values, and then filter a random set of Gaussian disturbances through the estimated model using the same presample responses.

Load Johansen's Danish economic data.

`load Data_JDanish`

For details on the variables, enter `Description`.

Create a default 4-D VAR(2) model.

`Mdl = varm(4,2);`

Estimate the VAR(2) model using the entire data set.

`EstMdl = estimate(Mdl,Data);`

When reproducing the results of `simulate` and `filter`, it is important to take these actions.

• Set the same random number seed using `rng`.

• Specify the same presample response data using the `'Y0'` name-value pair argument.

Set the default random seed. Simulate 100 observations by passing the estimated model to `simulate`. Specify the entire data set as the presample.

```rng default YSim = simulate(EstMdl,100,'Y0',Data);```

`YSim` is a 100-by-4 matrix of simulated responses. Columns correspond to the columns of the variables in `Data`.

Set the default random seed. Simulate 4 series of 100 observations from the standard Gaussian distribution.

```rng default Z = randn(100,4);```

Filter the Gaussian values through the estimated model. Specify the entire data set as the presample.

`YFilter = filter(EstMdl,Z,'Y0',Data);`

`YFilter` is a 100-by-4 matrix of simulated responses. Columns correspond to the columns of the variables in the data `Data`. Before filtering the disturbances, `filter` scales `Z` by the lower triangular Cholesky factor of the model covariance in `EstMdl.Covariance`.

Compare the resulting responses between `filter` and `simulate`.

`(YSim - YFilter)'*(YSim - YFilter)`
```ans = 4×4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ```

The results are identical.

Estimate a VAR(4) model of the consumer price index (CPI), the unemployment rate, and the gross domestic product (GDP). Include a linear regression component containing the current and the last 4 quarters of government consumption expenditures and investment. Simulate multiple paths from the estimated model.

Load the `Data_USEconModel` data set. Compute the real GDP.

```load Data_USEconModel DataTable.RGDP = DataTable.GDP./DataTable.GDPDEF*100;```

Plot all variables on separate plots.

```figure; subplot(2,2,1) plot(DataTable.Time,DataTable.CPIAUCSL); ylabel('Index'); title('Consumer Price Index'); subplot(2,2,2) plot(DataTable.Time,DataTable.UNRATE); ylabel('Percent'); title('Unemployment Rate'); subplot(2,2,3) plot(DataTable.Time,DataTable.RGDP); ylabel('Output'); title('Real Gross Domestic Product'); subplot(2,2,4) plot(DataTable.Time,DataTable.GCE); ylabel('Billions of \$'); title('Government Expenditures');``` Stabilize the CPI, GDP, and GCE by converting each to a series of growth rates. Synchronize the unemployment rate series with the others by removing its first observation. Create a new data set containing the transformed variables.

```inputVariables = {'CPIAUCSL' 'RGDP' 'GCE'}; Data = varfun(@price2ret,DataTable,'InputVariables',inputVariables); Data.Properties.VariableNames = inputVariables; Data.UNRATE = DataTable.UNRATE(2:end); dates = DataTable.Time(2:end);```

Expand the GCE rate series to a matrix that includes its current value and up through four lagged values. Remove `GCE` and observations containing any missing values from `Data`.

```rgcelag4 = lagmatrix(Data.GCE,0:4); idx = all(~ismissing([Data table(rgcelag4)]),2); Data = Data(idx,:); Data.GCE = [];```

Create a default VAR(4) model using the shorthand syntax.

```Mdl = varm(3,4); Mdl.SeriesNames = ["rcpi" "unrate" "rgdpg"];```

Estimate the model using the entire sample. Specify the GCE matrix as data for the regression component.

`EstMdl = estimate(Mdl,Data.Variables,'X',rgcelag4);`

Simulate 1000 paths from the estimated model. Specify that the length of the paths is the same as the length of the data without any missing values. Supply the predictor data. Return the innovations (scaled disturbances).

```numpaths = 1000; numobs = size(Data,1); rng(1); % For reproducibility [Y,E] = simulate(EstMdl,numobs,'X',rgcelag4,'NumPaths',numpaths);```

`Y` is a 244-by-3-by-1000 matrix of simulated responses. `E` is a matrix whose dimensions correspond to the dimensions of `Y`, but represents the simulated, scaled disturbances. The columns correspond to the CPI growth rate, unemployment rate, and GDP growth rate, respectively. `simulate` applies the same predictor data to all paths.

For each time point, compute the mean vector of the simulated responses among all paths.

`MeanSim = mean(Y,3);`

`MeanSim` is a 244-by-3 matrix containing the average of the simulated responses at each time point.

Plot the simulated responses, their averages, and the data.

```figure; for j = 1:Mdl.NumSeries subplot(2,2,j) plot(Data.Time,squeeze(Y(:,j,:)),'Color',[0.8,0.8,0.8]) title(Mdl.SeriesNames{j}); hold on h1 = plot(Data.Time,Data{:,j}); h2 = plot(Data.Time,MeanSim(:,j)); hold off end hl = legend([h1 h2],'Data','Mean'); hl.Position = [0.6 0.25 hl.Position(3:4)];``` ## Input Arguments

collapse all

VAR model, specified as a `varm` model object created by `varm` or `estimate`. `Mdl` must be fully specified.

Number of random observations to generate per output path, specified as a positive integer. The output arguments `Y` and `E` have `numobs` rows.

Data Types: `double`

### Name-Value Pair Arguments

Specify optional comma-separated pairs of `Name,Value` arguments. `Name` is the argument name and `Value` is the corresponding value. `Name` must appear inside quotes. You can specify several name and value pair arguments in any order as `Name1,Value1,...,NameN,ValueN`.

Example: `'Y0',Y0,'X',X` uses the matrix `Y0` as presample responses and the matrix `X` as predictor data in the regression component.

Number of sample paths to generate, specified as the comma-separated pair consisting of `'NumPaths'` and a positive integer. The output arguments `Y` and `E` have `NumPaths` pages.

Example: `'NumPaths',1000`

Data Types: `double`

Presample responses providing initial values for the model, specified as the comma-separated pair consisting of `'Y0'` and a `numpreobs`-by-`numseries` numeric matrix or a `numpreobs`-by-`numseries`-by-`numprepaths` numeric array.

`numpreobs` is the number of presample observations. `numseries` is the number of response series (`Mdl.NumSeries`). `numprepaths` is the number of presample response paths.

Rows correspond to presample observations, and the last row contains the latest presample observation. `Y0` must have at least `Mdl.P` rows. If you supply more rows than necessary, `simulate` uses the latest `Mdl.P` observations only.

Columns must correspond to the response series names in `Mdl.SeriesNames`.

Pages correspond to separate, independent paths.

• If `Y0` is a matrix, then `simulate` applies it to simulate each sample path (page). Therefore, all paths in the output argument `Y` derive from common initial conditions.

• Otherwise, `simulate` applies `Y0(:,:,j)` to initialize simulating path `j`. `Y0` must have at least `numpaths` pages (see `NumPaths`), and `simulate` uses only the first `numpaths` pages.

By default, `simulate` sets any necessary presample observations.

• For stationary VAR processes without regression components, `simulate` sets presample observations to the unconditional mean $\mu ={\Phi }^{-1}\left(L\right)c.$

• For nonstationary processes or models that contain a regression component, `simulate` sets presample observations to zero.

Data Types: `double`

Predictor data for the regression component in the model, specified as the comma-separated pair consisting of `'X'` and a numeric matrix containing `numpreds` columns.

`numpreds` is the number of predictor variables (`size(Mdl.Beta,2)`).

Rows correspond to observations, and the last row contains the latest observation. `X` must have at least `numobs` rows. If you supply more rows than necessary, `simulate` uses only the latest `numobs` observations. `simulate` does not use the regression component in the presample period.

Columns correspond to individual predictor variables. All predictor variables are present in the regression component of each response equation.

`simulate` applies `X` to each path (page); that is, `X` represents one path of observed predictors.

By default, `simulate` excludes the regression component, regardless of its presence in `Mdl`.

Data Types: `double`

Future multivariate response series for conditional simulation, specified as the comma-separated pair consisting of `'YF'` and a numeric matrix or array containing `numseries` columns.

Rows correspond to observations in the simulation horizon, and the first row is the earliest observation. Specifically, row `j` in sample path `k` (`YF(j,:,k)`) contains the responses `j` periods into the future. `YF` must have at least `numobs` rows to cover the simulation horizon. If you supply more rows than necessary, `simulate` uses only the first `numobs` rows.

Columns must correspond to the response variable names in `Mdl.SeriesNames`.

Pages correspond to sample paths. Specifically, path `k` (`YF(:,:,k)`) captures the state, or knowledge, of the response series as they evolve from the presample past (`Y0`) into the future.

• If `YF` is a matrix, then `simulate` applies `YF` to each of the `numpaths` output paths (see `NumPaths`).

• Otherwise, `YF` must have at least `numpaths` pages. If you supply more pages than necessary, `simulate` uses only the first `numpaths` pages.

Elements of `YF` can be numeric scalars or missing values (indicated by `NaN` values). `simulate` treats numeric scalars as deterministic future responses that are known in advance, for example, set by policy. `simulate` simulates responses for corresponding `NaN` values conditional on the known values.

By default, `YF` is an array composed of `NaN` values indicating a complete lack of knowledge of the future state of all simulated responses. Therefore, `simulate` obtains the output responses `Y` from a conventional, unconditional Monte Carlo simulation.

For more details, see Algorithms.

Example: Consider simulating one path of a VAR model composed of four response series three periods into the future. Suppose that you have prior knowledge about some of the future values of the responses, and you want to simulate the unknown responses conditional on your knowledge. Specify `YF` as a matrix containing the values that you know, and use `NaN` for values you do not know but want to simulate. For example, ```'YF',[NaN 2 5 NaN; NaN NaN 0.1 NaN; NaN NaN NaN NaN]``` specifies that you have no knowledge of the future values of the first and fourth response series; you know the value for period 1 in the second response series, but no other value; and you know the values for periods 1 and 2 in the third response series, but not the value for period 3.

Data Types: `double`

### Note

`NaN` values in `Y0` and `X` indicate missing values. `simulate` removes missing values from the data by list-wise deletion. If `Y0` is a 3-D array, then `simulate` performs these steps.

1. Horizontally concatenate pages to form a `numpreobs`-by-`numpaths*numseries` matrix.

2. Remove any row that contains at least one `NaN` from the concatenated data.

In the case of missing observations, the results obtained from multiple paths of `Y0` can differ from the results obtained from each path individually.

For conditional simulation (see `YF`), if `X` contains any missing values in the latest `numobs` observations, then `simulate` throws an error.

## Output Arguments

collapse all

Simulated multivariate response series, returned as a `numobs`-by-`numseries` numeric matrix or a `numobs`-by-`numseries`-by-`numpaths` numeric array. `Y` represents the continuation of the presample responses in `Y0`.

If you specify future responses for conditional simulation using the `YF` name-value pair argument, then the known values in `YF` appear in the same positions in `Y`. However, `Y` contains simulated values for the missing observations in `YF`.

Simulated multivariate model innovations series, returned as a `numobs`-by-`numseries` numeric matrix or a `numobs`-by-`numseries`-by-`numpaths` numeric array.

If you specify future responses for conditional simulation (see the `YF` name-value pair argument), then `simulate` infers the innovations from the known values in `YF` and places the inferred innovations in the corresponding positions in `E`. For the missing observations in `YF`, `simulate` draws from the Gaussian distribution conditional on any known values, and places the draws in the corresponding positions in `E`.

## Algorithms

• `simulate` performs conditional simulation using this process for all pages `k` = 1,...,`numpaths` and for each time `t` = 1,...,`numobs`.

1. `simulate` infers (or inverse filters) the innovations `E(t,:,k)` from the known future responses `YF(t,:,k)`. For `E(t,:,k)`, `simulate` mimics the pattern of `NaN` values that appears in `YF(t,:,k)`.

2. For the missing elements of `E(t,:,k)`, `simulate` performs these steps.

1. Draw `Z1`, the random, standard Gaussian distribution disturbances conditional on the known elements of `E(t,:,k)`.

2. Scale `Z1` by the lower triangular Cholesky factor of the conditional covariance matrix. That is, `Z2` = `L*Z1`, where `L` = `chol(C,'lower')` and `C` is the covariance of the conditional Gaussian distribution.

3. Impute `Z2` in place of the corresponding missing values in `E(t,:,k)`.

3. For the missing values in `YF(t,:,k)`, `simulate` filters the corresponding random innovations through the model `Mdl`.

• `simulate` uses this process to determine the time origin t0 of models that include linear time trends.

• If you do not specify `Y0`, then t0 = 0.

• Otherwise, `simulate` sets t0 to `size(Y0,1)``Mdl.P`. Therefore, the times in the trend component are t = t0 + 1, t0 + 2,..., t0 + `numobs`. This convention is consistent with the default behavior of model estimation in which `estimate` removes the first `Mdl.P` responses, reducing the effective sample size. Although `simulate` explicitly uses the first `Mdl.P` presample responses in `Y0` to initialize the model, the total number of observations in `Y0` (excluding any missing values) determines t0.

 Hamilton, J. D. Time Series Analysis. Princeton, NJ: Princeton University Press, 1994.

 Johansen, S. Likelihood-Based Inference in Cointegrated Vector Autoregressive Models. Oxford: Oxford University Press, 1995.

 Juselius, K. The Cointegrated VAR Model. Oxford: Oxford University Press, 2006.

 Lütkepohl, H. New Introduction to Multiple Time Series Analysis. Berlin: Springer, 2005.