Dynarewp080 Manual 2024
Dynarewp080 Manual 2024
net/publication/378309678
CITATIONS READS
12 908
7 authors, including:
All content following this page was uploaded by Willi Mutschler on 19 February 2024.
Stéphane Adjemian
Michel Juillard
Fréderic Karamé
Willi Mutschler
Johannes Pfeifer
Marco Ratto
Normann Rion
Sébastien Villemot
October 2024-02
Dynare Team
1 Introduction 3
1.1 What is Dynare? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Documentation sources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3 Citing Dynare in your research . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
3 Running Dynare 11
3.1 Dynare invocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
3.2 Dynare hooks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
3.3 Understanding Preprocessor Error Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
i
4.4 Parameter initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4.5 Model declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
4.6 Auxiliary variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
4.7 Initial and terminal conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
4.8 Shocks on exogenous variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
4.9 Other general declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
4.10 Steady state . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
4.10.1 Finding the steady state with Dynare nonlinear solver . . . . . . . . . . . . . . . . . . . 55
4.10.2 Providing the steady state to Dynare . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
4.10.3 Replace some equations during steady state computations . . . . . . . . . . . . . . . . . 61
4.11 Getting information about the model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
4.12 Deterministic simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
4.12.1 Perfect foresight . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
4.12.2 Perfect foresight with expectation errors . . . . . . . . . . . . . . . . . . . . . . . . . . 69
4.13 Stochastic solution and simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
4.13.1 Computing the stochastic solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
4.13.2 Typology and ordering of variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
4.13.3 First-order approximation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
4.13.4 Second-order approximation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
4.13.5 Third-order approximation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
4.13.6 Higher-order approximation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
4.14 Occasionally binding constraints (OCCBIN) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
4.15 Estimation based on likelihood . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
4.16 Estimation based on moments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
4.16.1 Method of moments specific blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
4.16.2 method_of_moments command . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
4.16.2.1 Necessary Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
4.16.2.2 Common Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
4.16.2.3 SMM specific options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
4.16.2.4 GMM specific options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
4.16.2.5 IRF matching specific options . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
4.16.2.6 General options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
4.16.2.7 Data options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
4.16.2.8 Optimization options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
4.16.2.9 Bayesian estimation options . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
4.16.2.10 Numerical algorithms options . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
4.16.3 Method of moments specific outputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
4.17 Model Comparison . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
4.18 Shock Decomposition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
4.19 Calibrated Smoother . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
4.20 Forecasting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
4.21 Optimal policy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
4.21.1 Optimal policy under commitment (Ramsey) . . . . . . . . . . . . . . . . . . . . . . . 161
4.21.2 Optimal policy under discretion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
4.21.3 Optimal Simple Rules (OSR) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
4.22 Sensitivity and identification analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
4.22.1 Performing sensitivity analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
4.22.2 IRF/Moment calibration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
4.22.3 Performing identification analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
4.22.4 Types of analysis and output files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
4.22.4.1 Sampling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
4.22.4.2 Stability Mapping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
4.22.4.3 IRF/Moment restrictions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
4.22.4.4 Reduced Form Mapping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
4.22.4.5 RMSE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
4.22.4.6 Screening Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
4.22.4.7 Identification Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
4.23 Markov-switching SBVAR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
ii
4.24 Epilogue Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
4.25 Semi-structural models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
4.25.1 Auxiliary models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
4.25.2 VAR expectations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
4.25.3 PAC equation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
4.25.4 Estimation of a PAC equation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
4.26 Displaying and saving results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
4.27 Macro processing language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
4.27.1 Macro expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
4.27.2 Macro directives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204
4.27.3 Typical usages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
4.27.3.1 Modularization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
4.27.3.2 Indexed sums of products . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
4.27.3.3 Multi-country models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
4.27.3.4 Endogeneizing parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
4.27.4 MATLAB/Octave loops versus macro processor loops . . . . . . . . . . . . . . . . . . . 210
4.28 Verbatim inclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
4.29 Misc commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
7 Reporting 265
8 Examples 277
10 Bibliography 283
Index 287
iii
iv
Dynare Reference Manual, Release 6.0
CONTENTS 1
Dynare Reference Manual, Release 6.0
2 CONTENTS
CHAPTER
ONE
INTRODUCTION
Dynare is a software platform for handling a wide class of economic models, in particular dynamic stochastic
general equilibrium (DSGE) and overlapping generations (OLG) models. The models solved by Dynare include
those relying on the rational expectations hypothesis, wherein agents form their expectations about the future
in a way consistent with the model. But Dynare is also able to handle models where expectations are formed
differently: on one extreme, models where agents perfectly anticipate the future; on the other extreme, models
where agents have limited rationality or imperfect knowledge of the state of the economy and, hence, form their
expectations through a learning process. In terms of types of agents, models solved by Dynare can incorporate
consumers, productive firms, governments, monetary authorities, investors and financial intermediaries. Some
degree of heterogeneity can be achieved by including several distinct classes of agents in each of the aforementioned
agent categories.
Dynare offers a user-friendly and intuitive way of describing these models. It is able to perform simulations of the
model given a calibration of the model parameters and is also able to estimate these parameters given a dataset. In
practice, the user will write a text file containing the list of model variables, the dynamic equations linking these
variables together, the computing tasks to be performed and the desired graphical or numerical outputs.
A large panel of applied mathematics and computer science techniques are internally employed by Dynare: mul-
tivariate nonlinear solving and optimization, matrix factorizations, local functional approximation, Kalman filters
and smoothers, MCMC techniques for Bayesian estimation, graph algorithms, optimal control, . . .
Various public bodies (central banks, ministries of economy and finance, international organisations) and some pri-
vate financial institutions use Dynare for performing policy analysis exercises and as a support tool for forecasting
exercises. In the academic world, Dynare is used for research and teaching purposes in postgraduate macroeco-
nomics courses.
Dynare is a free software, which means that it can be downloaded free of charge, that its source code is freely
available, and that it can be used for both non-profit and for-profit purposes. Most of the source files are covered by
the GNU General Public Licence (GPL) version 3 or later (there are some exceptions to this, see the file license.txt
in Dynare distribution). It is available for the Windows, macOS, and Linux platforms and is fully documented
through a reference manual. Part of Dynare is programmed in C++, while the rest is written using the MATLAB
programming language. The latter implies that commercially-available MATLAB software is required in order to
run Dynare. However, as an alternative to MATLAB, Dynare is also able to run on top of GNU Octave (basically
a free clone of MATLAB): this possibility is particularly interesting for students or institutions who cannot afford,
or do not want to pay for, MATLAB and are willing to bear the concomitant performance loss.
The development of Dynare is mainly done at CEPREMAP by a core team of researchers who devote part of their
time to software development. Increasingly, the developer base is expanding, as tools developed by researchers
outside of CEPREMAP are integrated into Dynare. Financial support is provided by CEPREMAP, Banque de
France and DSGE-net (an international research network for DSGE modeling).
Interaction between developers and users of Dynare is central to the project. A web forum is available for users
who have questions about the usage of Dynare or who want to report bugs. Current known and fixed bugs are listed
on the Dynare wiki. Issues or whishes can be reported on our Git repository. Training sessions are given through
the Dynare Summer School, which is organized every year and is attended by about 40 people. Finally, priorities
3
Dynare Reference Manual, Release 6.0
in terms of future developments and features to be added are decided in cooperation with the institutions providing
financial support.
The present document is the reference manual for Dynare. It documents all commands and features in a systematic
fashion.
Other useful sources of information include the Dynare wiki and the Dynare forums.
You should cite Dynare if you use it in your research. The recommended way todo this is to cite the present manual,
as:
Stéphane Adjemian, Michel Juillard, Frédéric Karamé, Willi Mutschler, Johannes Pfeifer, Marco
Ratto, Normann Rion and Sébastien Villemot (2024), “Dynare: Reference Manual, Version 6,” Dynare
Working Papers, 80, CEPREMAP
For convenience, you can copy and paste the following into your BibTeX file:
@TechReport{Adjemianetal2024,
author = {Adjemian, St\'ephane and Juillard, Michel and
Karam\'e, Fr\'ederic and Mutschler, Willi and
Pfeifer, Johannes and Ratto, Marco and
Rion, Normann and Villemot, S\'ebastien},
title = {Dynare: Reference Manual, Version 6},
year = {2024},
institution = {CEPREMAP},
type = {Dynare Working Papers},
number = {80},
}
If you want to give a URL, use the address of the Dynare website: https://www.dynare.org.
4 Chapter 1. Introduction
CHAPTER
TWO
Packaged versions of Dynare are available for Windows (10 and 11), several GNU/Linux distributions (Debian,
Ubuntu, Linux Mint, Arch Linux), macOS (13 Ventura), and FreeBSD. Dynare should work on other systems, but
some compilation steps are necessary in that case.
In order to run Dynare, you need one of the following:
• MATLAB, any version ranging from 9.5 (R2018b) to 23.2 (R2023b);
• GNU Octave, any version ranging from 7.1.0 to 8.4.0, with the statistics package from Octave-Forge.
Note however that the Dynare installer for Windows requires a more specific version of Octave, as indicated
on the download page.
The following optional extensions are also useful to benefit from extra features, but are in no way required:
• If under MATLAB: the Optimization Toolbox, the Statistics Toolbox, the Control System Toolbox;
• If under Octave, the following Octave-Forge packages: optim, io, control.
After installation, Dynare can be used in any directory on your computer. It is best practice to keep your model
files in directories different from the one containing the Dynare toolbox. That way you can upgrade Dynare and
discard the previous version without having to worry about your own files.
2.2.1 On Windows
Execute the automated installer called dynare-x.y-win.exe (where x.y is the version number), and follow the
instructions. The default installation directory is c:\dynare\x.y.
After installation, this directory will contain several sub-directories, among which are matlab, mex and doc.
The installer will also add an entry in your Start Menu with a shortcut to the documentation files and uninstaller.
Note that you can have several versions of Dynare coexisting (for example in c:\dynare), as long as you correctly
adjust your path settings (see see Some words of warning).
Also note that it is possible to do a silent installation, by passing the /S flag to the installer on the command line.
This can be useful when doing an unattended installation of Dynare on a computer pool.
5
Dynare Reference Manual, Release 6.0
2.2.2 On GNU/Linux
On Debian, Ubuntu and Linux Mint, the Dynare package can be installed with: apt install dynare. This will
give a fully-functional Dynare installation usable with Octave. If you have MATLAB installed, you should also
do: apt install dynare-matlab (under Debian, this package is in the contrib section). Documentation can
be installed with apt install dynare-doc. The status of those packages can be checked at those pages:
• Package status in Debian
• Package status in Ubuntu
• Package status in Linux Mint
On Arch Linux, the Dynare package is not in the official repositories, but is available in the Arch User Repository.
The needed sources can be downloaded from the package status in Arch Linux.
There is also a Dynare package for openSUSE, see the package status in openSUSE.
Dynare will be installed under /usr/lib/dynare (or /usr/lib64/dynare on openSUSE). Documentation will
be under /usr/share/doc/dynare (only on Debian, Ubuntu and Linux Mint).
2.2.3 On macOS
To install Dynare for use with MATLAB, execute the automated installer called dynare-x.y-arch.pkg (where
x.y is the version number and arch is either arm64 for Apple Silicon or x86_64 for Intel architectures), and fol-
low the instructions. This installation does not require administrative privileges. If for some reason admin rights
are requested, use Change Install Location and select Install for me only. The default installation directory is
/Applications/Dynare/x.y-arch. Installing into /Applications/dynare might fail if you have older ver-
sions of Dynare already installed in /Applications/Dynare. To fix this, modify the ownership by executing the
following command in Terminal.app:
Alternatively, you can modify the installation path in the automated installed using Customize and Location. Af-
ter installation, the folder will contain several sub-directories, among which are matlab, mex, and doc. Several
versions of Dynare can coexist (by default in /Applications/Dynare), as long as you correctly adjust your path
settings (see Some words of warning).
It is recommended to install the Xcode Command Line Tools (this is an Apple product) and GCC via Homebrew
(see Prerequisites on macOS).
We don’t provide Dynare packages for macOS with Octave support, but there is a Dynare package with Octave
support in Homebrew.
Once Homebrew is installed, run a terminal and install Dynare (and Octave) by typing the following:
octave --gui
Finally, at the Octave prompt, install some add-ons (you only have to do it once):
2.2.4 On FreeBSD
You need to download Dynare source code from the Dynare website and unpack it somewhere.
Then you will need to recompile the pre-processor and the dynamic loadable libraries. Please refer to
README.md.
There are no prerequisites on Windows. Dynare now ships a compilation environment that can be used with the
use_dll option.
Users of MATLAB under GNU/Linux need a working compilation environment installed. Under Debian, Ubuntu
or Linux Mint, it can be installed via apt install build-essential.
Users of Octave under GNU/Linux should install the package for MEX file compilation (under Debian, Ubuntu or
Linux Mint, it can be done via apt install liboctave-dev).
Dynare now ships a compilation environment that can be used with the use_dll option. To install this environment
correctly, the Dynare installer ensures that the Xcode Command Line Tools (an Apple product) have been installed
on a system folder. To install the Xcode Command Line Tools yourself, simply type xcode-select --install
into the terminal (/Applications/Utilities/Terminal.app) prompt. Additionally, to make MATLAB aware
that you agree to the terms of Xcode, run the following two commands in the Terminal prompt:
Otherwise you will see a warning that Xcode is installed, but its license has not been accepted. You can check this
e.g. by running the following command in the MATLAB command window:
mex -setup
Moreover, we recommend making use of optimized compilation flags when using use_dll and for this you need
to install GCC via Homebrew:
If you already have installed GCC, Dynare will automatically prefer it for use_dll if the binaries are either in
/opt/homebrew/bin on Apple Silicon (arm64) or in /usr/local/bin on Intel (x86_64) systems. Otherwise, it
will fall back to Clang in /usr/bin/clang, which works both on arm64 and x86_64 systems.
2.4 Configuration
You need to add the matlab subdirectory of your Dynare installation to MATLAB path. You have two options for
doing that:
• Using the addpath command in the MATLAB command window:
Under Windows, assuming that you have installed Dynare in the standard location, and replacing x.y with
the correct version number, type:
Under macOS, assuming that you have installed Dynare in the standard location, and replacing x.y with the
correct version number, type:
MATLAB will not remember this setting next time you run it, and you will have to do it again.
• Via the menu entries:
Select the “Set Path” entry in the “File” menu, then click on “Add Folder. . . ”, and select the matlab sub-
directory of ‘your Dynare installation. Note that you should not use “Add with Subfolders. . . ”. Apply the
settings by clicking on “Save”. Note that MATLAB will remember this setting next time you run it.
You need to add the matlab subdirectory of your Dynare installation to Octave path, using the addpath at the
Octave command prompt.
Under Windows, assuming that you have installed Dynare in the standard location, and replacing “x.y” with the
correct version number, type:
Under Debian, Ubuntu or Linux Mint, there is no need to use the addpath command; the packaging does it for
you. Under Arch Linux, you need to do:
If you don’t want to type this command every time you run Octave, you can put it in a file called .octaverc
in your home directory (under Windows this will generally be c:\Users\USERNAME while under macOS it is
/Users/USERNAME/). This file is run by Octave at every startup.
You should be very careful about the content of your MATLAB or Octave path. You can display its content by
simply typing path in the command window.
The path should normally contain system directories of MATLAB or Octave, and some subdirectories of your
Dynare installation. You have to manually add the matlab subdirectory, and Dynare will automatically add a
few other subdirectories at runtime (depending on your configuration). You must verify that there is no directory
coming from another version of Dynare than the one you are planning to use.
You have to be aware that adding other directories (on top of the dynare folders) to your MATLAB or Octave path
can potentially create problems if any of your M-files have the same name as a Dynare file. Your routine would
then override the Dynare routine, making Dynare unusable.
Warning: Never add all the subdirectories of the matlab folder to the MATLAB or Octave path. You must
let Dynare decide which subdirectories have to be added to the MATLAB or Octave path. Otherwise, you may
end up with a non optimal or un-usable installation of Dynare.
2.4. Configuration 9
Dynare Reference Manual, Release 6.0
THREE
RUNNING DYNARE
In order to give instructions to Dynare, the user has to write a model file whose filename extension must be .mod
or .dyn. This file contains the description of the model and the computing tasks required by the user. Its contents
are described in The model file.
Once the model file is written, Dynare is invoked using the dynare command at the MATLAB or Octave prompt
(with the filename of the .mod given as argument).
In practice, the handling of the model file is done in two steps: in the first one, the model and the processing
instructions written by the user in a model file are interpreted and the proper MATLAB or Octave instructions are
generated; in the second step, the program actually runs the computations. Both steps are triggered automatically
by the dynare command.
MATLAB/Octave command: dynare FILENAME[.mod] [OPTIONS...]
This command launches Dynare and executes the instructions included in FILENAME.mod. This user-
supplied file contains the model and the processing instructions, as described in The model file. The
options, listed below, can be passed on the command line, following the name of the .mod file or in
the first line of the .mod file itself (see below).
dynare begins by launching the preprocessor on the .mod file. By default (unless the use_dll
option has been given to model), the preprocessor creates three intermediary files:
• +FILENAME/driver.m
Contains variable declarations, and computing tasks.
• +FILENAME/dynamic.m
Contains the dynamic model equations. Note that Dynare might introduce auxiliary
equations and variables (see Auxiliary variables). Outputs are the residuals of the
dynamic model equations in the order the equations were declared and the Jacobian
of the dynamic model equations. For higher order approximations also the Hessian
and the third-order derivatives are provided. When computing the Jacobian of the dy-
namic model, the order of the endogenous variables in the columns is stored in M_.
lead_lag_incidence. The rows of this matrix represent time periods: the first row
denotes a lagged (time t-1) variable, the second row a contemporaneous (time t) vari-
able, and the third row a leaded (time t+1) variable. The columns of the matrix represent
the endogenous variables in their order of declaration. A zero in the matrix means that
this endogenous does not appear in the model in this time period. The value in the
M_.lead_lag_incidence matrix corresponds to the column of that variable in the
Jacobian of the dynamic model. Example: Let the second declared variable be c and
the (3,2) entry of M_.lead_lag_incidence be 15. Then the 15th column of the
Jacobian is the derivative with respect to c(+1).
• +FILENAME/static.m
11
Dynare Reference Manual, Release 6.0
Contains the long run static model equations. Note that Dynare might introduce auxil-
iary equations and variables (see Auxiliary variables). Outputs are the residuals of the
static model equations in the order the equations were declared and the Jacobian of the
static equations. Entry (i,j) of the Jacobian represents the derivative of the ith static
model equation with respect to the jth model variable in declaration order.
These files may be looked at to understand errors reported at the simulation stage.
dynare will then run the computing tasks by executing +FILENAME/driver.m. If a user needs to
rerun the computing tasks without calling the preprocessor (or without calling the dynare command),
for instance because he has modified the script, he just have to type the following on the command
line:
>> FILENAME.driver
A few words of warning are warranted here: under Octave the filename of the .mod file should be
chosen in such a way that the generated .m files described above do not conflict with .m files provided
by Octave or by Dynare. Not respecting this rule could cause crashes or unexpected behaviour. In
particular, it means that the .mod file cannot be given the name of an Octave or Dynare command. For
instance, under Octave, it also means that the .mod file cannot be named test.mod or example.mod.
Options
noclearall
By default, dynare will issue a clear all command to MATLAB (<R2015b) or Octave,
thereby deleting all workspace variables and functions; this option instructs dynare not to clear
the workspace. Note that starting with MATLAB 2015b dynare only deletes the global vari-
ables and the functions using persistent variables, in order to benefit from the JIT (Just In Time)
compilation. In this case the option instructs dynare not to clear the globals and functions.
onlyclearglobals
By default, dynare will issue a clear all command to MATLAB versions before 2015b
and to Octave, thereby deleting all workspace variables; this option instructs dynare to clear
only the global variables (i.e. M_, options_, oo_, estim_params_, bayestopt_, and
dataset_), leaving the other variables in the workspace.
debug
Instructs the preprocessor to write some debugging information about the scanning and parsing
of the .mod file.
notmpterms
Instructs the preprocessor to omit temporary terms in the static and dynamic files; this generally
decreases performance, but is used for debugging purposes since it makes the static and dynamic
files more readable.
savemacro[=FILENAME]
Instructs dynare to save the intermediary file which is obtained after macro processing (see
Macro processing language); the saved output will go in the file specified, or if no file is specified
in FILENAME-macroexp.mod. See the note on quotes for info on passing a FILENAME argument
containing spaces.
onlymacro
Instructs the preprocessor to only perform the macro processing step, and stop just after. Useful
for debugging purposes or for using the macro processor independently of the rest of Dynare
toolbox.
linemacro
Instructs the macro preprocessor include @#line directives specifying the line on which macro
directives were encountered and expanded from. Only useful in conjunction with savemacro.
onlymodel
Instructs the preprocessor to print only information about the model in the driver file; no Dynare
commands (other than the shocks statement and parameter initializations) are printed and hence
no computational tasks performed. The same ancillary files are created as would otherwise be
created (dynamic, static files, etc.).
nolog
Instructs Dynare to no create a logfile of this run in FILENAME.log. The default is to create the
logfile.
output=second|third
Instructs the preprocessor to output derivatives of the dynamic model at least up to the given
order.
language=matlab|julia
Instructs the preprocessor to write output for MATLAB or Julia. Default: MATLAB
params_derivs_order=0|1|2
When identification, dynare_sensitivity (with identification), or estimation are
present, this option is used to limit the order of the derivatives with respect to the parameters
that are calculated by the preprocessor. 0 means no derivatives, 1 means first derivatives, and 2
means second derivatives. Default: 2
nowarn
Suppresses all warnings.
notime
Do not print the total computing time at the end of the driver, and do not save that total computing
time to oo_.time.
transform_unary_ops
Transform the following operators in the model block into auxiliary variables: exp, log, log10,
cos, sin, tan, acos, asin, atan, cosh, sinh, tanh, acosh, asinh, atanh, sqrt, cbrt, abs,
sign, erf. Default: no obligatory transformation
json = parse|check|transform|compute
Causes the preprocessor to output a version of the .mod file in JSON format to <<M_.fname>>/
model/json/. When the JSON output is created depends on the value passed. These values
represent various steps of processing in the preprocessor.
If parse is passed, the output will be written after the parsing of the .mod file to a file called
FILENAME.json but before file has been checked (e.g. if there are unused exogenous in the
model block, the JSON output will be created before the preprocessor exits).
If check is passed, the output will be written to a file called FILENAME.json after the model
has been checked.
If transform is passed, the JSON output of the transformed model (maximum lead of 1, mini-
mum lag of -1, expectation operators substituted, etc.) will be written to a file called FILENAME.
json and the original, untransformed model will be written in FILENAME_original.json.
And if compute is passed, the output is written after the computing pass. In this
case, the transformed model is written to FILENAME.json, the original model is writ-
ten to FILENAME_original.json, and the dynamic and static files are written to
FILENAME_dynamic.json and FILENAME_static.json.
jsonstdout
Instead of writing output requested by json to files, write to standard out, i.e. to the MAT-
LAB/Octave command window (and the log-file).
onlyjson
Quit processing once the output requested by json has been written.
jsonderivsimple
Print a simplified version (excluding variable name(s) and lag information) of the static and
dynamic files in FILENAME_static.json and FILENAME_dynamic..
warn_uninit
Display a warning for each variable or parameter which is not initialized. See Parameter initial-
ization, or load_params_and_steady_state for initialization of parameters. See Initial and
terminal conditions, or load_params_and_steady_state for initialization of endogenous and
exogenous variables.
console
Activate console mode. In addition to the behavior of nodisplay, Dynare will not use graphical
waitbars for long computations.
nograph
Activate the nograph option (see nograph ), so that Dynare will not produce any graph.
nointeractive
Instructs Dynare to not request user input.
nopathchange
By default Dynare will change MATLAB/Octave’s path if dynare/matlab directory is not on
top and if Dynare’s routines are overriden by routines provided in other toolboxes. If one wishes
to override Dynare’s routines, the nopathchange options can be used. Alternatively, the path
can be temporarly modified by the user at the top of the .mod file (using MATLAB/Octave’s
addpath command).
nopreprocessoroutput
Prevent Dynare from printing the output of the steps leading up to the preprocessor as well as
the preprocessor output itself.
mexext=mex|mexw64|mexmaci64|mexmaca64|mexa64
The mex extension associated with your platform to be used when compiling output associated
with use_dll. Dynare is able to set this automatically, so you should not need to set it yourself.
matlabroot=<<path>>
The path to the MATLAB installation for use with use_dll. Dynare is able to set this auto-
matically, so you should not need to set it yourself. See the note on quotes for info on passing a
<<path>> argument containing spaces.
parallel[=CLUSTER_NAME]
Tells Dynare to perform computations in parallel. If CLUSTER_NAME is passed, Dynare will
use the specified cluster to perform parallel computations. Otherwise, Dynare will use the first
cluster specified in the configuration file. See The configuration file, for more information about
the configuration file.
conffile=FILENAME
Specifies the location of the configuration file if it differs from the default. See The configuration
file, for more information about the configuration file and its default location. See the note on
quotes for info on passing a FILENAME argument containing spaces.
parallel_follower_open_mode
Instructs Dynare to leave the connection to the follower node open after computation is complete,
closing this connection only when Dynare finishes processing.
parallel_test
Tests the parallel setup specified in the configuration file without executing the .mod file. See
The configuration file, for more information about the configuration file.
parallel_use_psexec=true|false
For local execution under Windows operating system, set parallel_use_psexec=false to
use start instead of psexec, to properly allocate affinity when there are more than 32 cores
in the local machine. This option is also helpful if psexec cannot be executed due to missing
admininstrator privileges. [default=true]
-DMACRO_VARIABLE[=MACRO_EXPRESSION]
Defines a macro-variable from the command line (the same effect as using the Macro directive
@#define in a model file, see Macro processing language). See the note on quotes for info on
passing a MACRO_EXPRESSION argument containing spaces. Note that an expression passed on
the command line can reference variables defined before it. If MACRO_EXPRESSION is omitted,
the variable is assigned the true logical value. Strings assigned to a macro variable need to be
enclosed in double quoted strings. This also allows for passing single quotes within the strings.
Example
Call dynare with command line defines
˓→'my_data_file.mat'"
-I<<path>>
Defines a path to search for files to be included by the macro processor (using the @#include
command). Multiple -I flags can be passed on the command line. The paths will be searched in
the order that the -I flags are passed and the first matching file will be used. The flags passed here
take priority over those passed to @#includepath. See the note on quotes for info on passing a
<<path>> argument containing spaces.
nostrict
Allows Dynare to issue a warning and continue processing when
1. there are more endogenous variables than equations.
2. an undeclared symbol is assigned in initval or endval.
3. an undeclared symbol is found in the model block in this case, it is automatically declared
exogenous.
4. exogenous variables were declared but not used in the model block.
fast
Don’t rewrite the output files otherwise written to the disk by the preprocessor when re-running
the same model file while the lists of variables and the equations haven’t changed. Note that
the whole model still needs to be preprocessed. This option is most useful with model option
use_dll, because the time-consuming compilation of the MEX files will be skipped. We use
a 32 bit checksum, stored in <model filename>/checksum. There is a very small probability
that the preprocessor misses a change in the model. In case of doubt, re-run without the fast
option.
minimal_workspace
Instructs Dynare not to write parameter assignments to parameter names in the .m file produced
by the preprocessor. This is potentially useful when running dynare on a large .mod file that
runs into workspace size limitations imposed by MATLAB.
compute_xrefs
Tells Dynare to compute the equation cross references, writing them to the output .m file.
stochastic
Tells Dynare that the model to be solved is stochastic. If no Dynare commands related to stochas-
tic models (stoch_simul, estimation, . . . ) are present in the .mod file, Dynare understands
by default that the model to be solved is deterministic.
exclude_eqs=<<equation_tags_to_exclude>>
Tells Dynare to exclude all equations specified by the argument. As a .mod file must have the
same number of endogenous variables as equations, when exclude_eqs is passed, certain rules
are followed for excluding endogenous variables. If the endogenous tag has been set for the
excluded equation, the variable it specifies is excluded. Otherwise, if the left hand side of the
excluded equation is an expression that contains only one endogenous variable, that variable is
excluded. If neither of these conditions hold, processing stops with an error. If an endogenous
variable has been excluded by the exclude_eqs option and it exists in an equation that has not
been excluded, it is transformed into an exogenous variable.
To specify which equations to exclude, you must pass the argument
<<equation_tags_to_exclude>>. This argument takes either a list of equation tags
specifying the equations to be excluded or a filename that contains those tags.
If <<equation_tags_to_exclude>> is a list of equation tags, it can take one of the following
forms:
1. Given a single argument, e.g. exclude_eqs=eq1, the equation with the tag [name='eq1']
will be excluded. Note that if there is a file called eq1 in the current directory, Dynare will
instead try to open this and read equations to exclude from it (see info on filename argument
to exclude_eqs below). Further note that if the tag value contains a space, you must use
the variant specified in 2 below, i.e. exclude_eqs=[eq 1].
2. Given two or more arguments, e.g. exclude_eqs=[eq1, eq 2], the equations with the
tags [name='eq1'] and [name='eq 2'] will be excluded.
3. If you’d like to exclude equations based on another tag name (as opposed to the de-
fault name), you can pass the argument as either e.g. exclude_eqs=[tagname=a
tag] if a single equation with tag [tagname='a tag'] is to be excluded or as e.g.
exclude_eqs=[tagname=(a tag, 'a tag with a, comma')] if more than one equa-
tion with tags [tagname='a tag'] and [tagname='a tag with a, comma'] will be
excluded (note the parenthesis, which are required when more than one equation is spec-
ified). Note that if the value of a tag contains a comma, it must be included inside single
quotes.
If <<equation_tags_to_exclude>> is a filename, the file can take one of the following forms:
1. One equation per line of the file, where every line represents the value passed to the name
tag. e.g., a file such as:
eq1
eq 2
tagname=
a tag
a tag with a, comma
would exclude equations with tags [tagname='a tag'] and [tagname='a tag with
a, comma']. Here note that the first line must end in an equal sign.
include_eqs=<<equation_tags_to_include>>
Tells Dynare to run with only those equations specified by the argument; in other
words, Dynare will exclude all equations not specified by the argument. The argument
<<equation_tags_to_include>> is specified in the same way as the argument to ex-
clude_eqs. The functionality of include_eqs is to find which equations to exclude then take
actions in accord with exclude_eqs.
use_dll
Instructs the preprocessor to create dynamic loadable libraries (DLL) containing the model equa-
tions and derivatives, instead of writing those in M-files. This is equivalent to the use_dll option
of the model block.
nocommutativity
This option tells the preprocessor not to use the commutativity of addition and multiplication
when looking for common subexpressions. As a consequence, when using this option, equations
in various outputs (LaTeX, JSON. . . ) will appear as the user entered them (without terms or fac-
tors swapped). Note that using this option may have a performance impact on the preprocessing
stage, though it is likely to be small.
These options can be passed to the preprocessor by listing them after the name of the .mod file. They
can alternatively be defined in the first line of the .mod file, this avoids typing them on the command
line each time a .mod file is to be run. This line must be a Dynare one-line comment (i.e. must begin
with //) and the options must be whitespace separated between --+ options: and +--. Note that
any text after the +-- will be discarded. As in the command line, if an option admits a value the equal
symbol must not be surrounded by spaces. For instance json = compute is not correct, and should
be written json=compute. The nopathchange option cannot be specified in this way, it must be
passed on the command-line.
Output
Depending on the computing tasks requested in the .mod file, executing the dynare command will
leave variables containing results in the workspace available for further processing. More details
are given under the relevant computing tasks. The M_, oo_, and options_ structures are saved in
a file called FILENAME_results.mat located in the MODFILENAME/Output folder. If they exist,
estim_params_, bayestopt_, dataset_, oo_recursive_ and estimation_info are saved in
the same file. Note that MATLAB by default only allows .mat files up to 2GB. You can lift this
restriction by enabling the save -v7.3 option in Preferences -> General -> MAT-Files.
MATLAB/Octave variable: M_
Structure containing various information about the model.
MATLAB/Octave variable: options_
Structure contains the values of the various options used by Dynare during the computation.
MATLAB/Octave variable: oo_
Structure containing the various results of the computations.
MATLAB/Octave variable: dataset_
A dseries object containing the data used for estimation.
MATLAB/Octave variable: oo_recursive_
Cell array containing the oo_ structures obtained when estimating the model for the different
samples when performing recursive estimation and forecasting. The oo_ structure obtained for
the sample ranging to the i -th observation is saved in the i -th field. The fields for non-estimated
endpoints are empty.
MATLAB/Octave variable: oo_.time
Total computing time of the Dynare run, in seconds. This field is not set if the notime option
has been used.
Example
Call dynare from the MATLAB or Octave prompt, without or with options:
and then dynare called without passing options on the command line:
It is possible to call pre and post Dynare preprocessor hooks written as MATLAB scripts. The script
MODFILENAME/hooks/priorprocessing.m is executed before the call to Dynare’s preprocessor, and can be used
to programmatically transform the mod file that will be read by the preprocessor. The script MODFILENAME/hooks/
postprocessing.m is gexecuted just after the call to Dynare’s preprocessor, and can be used to programmatically
transform the files generated by Dynare’s preprocessor before actual computations start. The pre and/or post dynare
preprocessor hooks are executed if and only if the aforementioned scripts are detected in the same folder as the the
model file, FILENAME.mod.
If the preprocessor runs into an error while processing your .mod file, it will issue an error. Due to the way that a
parser works, sometimes these errors can be misleading. Here, we aim to demystify these error messages.
The preprocessor issues error messages of the form:
1. ERROR: <<file.mod>>: line A, col B: <<error message>>
2. ERROR: <<file.mod>>: line A, cols B-C: <<error message>>
3. ERROR: <<file.mod>>: line A, col B - line C, col D: <<error message>>
The first two errors occur on a single line, with error two spanning multiple columns. Error three spans multiple
rows.
Often, the line and column numbers are precise, leading you directly to the offending syntax. Infrequently however,
because of the way the parser works, this is not the case. The most common example of misleading line and column
numbers (and error message for that matter) is the case of a missing semicolon, as seen in the following example:
varexo a, b
parameters c, ...;
In this case, the parser doesn’t know a semicolon is missing at the end of the varexo command until it begins
parsing the second line and bumps into the parameters command. This is because we allow commands to span
multiple lines and, hence, the parser cannot know that the second line will not have a semicolon on it until it gets
there. Once the parser begins parsing the second line, it realizes that it has encountered a keyword, parameters,
which it did not expect. Hence, it throws an error of the form: ERROR: <<file.mod>>: line 2, cols 0-9:
syntax error, unexpected PARAMETERS. In this case, you would simply place a semicolon at the end of line
one and the parser would continue processing.
It is also helpful to keep in mind that any piece of code that does not violate Dynare syntax, but at the same time
is not recognized by the parser, is interpreted as native MATLAB code. This code will be directly passed to the
driver script. Investigating the driver.m file then helps with debugging. Such problems most often occur when
defined variable or parameter names have been misspelled so that Dynare’s parser is unable to recognize them.
FOUR
4.1 Conventions
A model file contains a list of commands and of blocks. Each command and each element of a block is terminated
by a semicolon (;). Blocks are terminated by end;.
If Dynare encounters an unknown expression at the beginning of a line or after a semicolon, it will parse the rest of
that line as native MATLAB code, even if there are more statements separated by semicolons present. To prevent
cryptic error messages, it is strongly recommended to always only put one statement/command into each line and
start a new line after each semicolon.1
Lines of codes can be commented out line by line or as a block. Single-line comments begin with // and stop at
the end of the line. Multiline comments are introduced by /* and terminated by */.
Examples
/*
This comment is spanning
two lines.
*/
Note that these comment marks should not be used in native MATLAB code regions where the % should be
preferred instead to introduce a comment. In a verbatim block, see Verbatim inclusion, this would result in a
crash since // is not a valid MATLAB statement).
Most Dynare commands have arguments and several accept options, indicated in parentheses after the command
keyword. Several options are separated by commas.
In the description of Dynare commands, the following conventions are observed:
• Optional arguments or options are indicated between square brackets: ‘[]’;
• Repeated arguments are indicated by ellipses: “. . . ”;
• Mutually exclusive arguments are separated by vertical bars: ‘|’;
• INTEGER indicates an integer number;
• INTEGER_VECTOR indicates a vector of integer numbers separated by spaces, enclosed by square brackets;
1 A .mod file must have lines that end with a line feed character, which is not commonly visible in text editors. Files created on Windows
and Unix-based systems have always conformed to this requirement, as have files created on OS X and macOS. Files created on old, pre-OS
X Macs used carriage returns as end of line characters. If you get a Dynare parsing error of the form ERROR: <<mod file>>: line 1,
cols 341-347: syntax error,... and there’s more than one line in your .mod file, know that it uses the carriage return as an end of line
character. To get more helpful error messages, the carriage returns should be changed to line feeds.
19
Dynare Reference Manual, Release 6.0
• DOUBLE indicates a double precision number. The following syntaxes are valid: 1.1e3, 1.1E3, 1.1d3,
1.1D3. In some places, infinite Values Inf and -Inf are also allowed;
• NUMERICAL_VECTOR indicates a vector of numbers separated by spaces, enclosed by square brackets;
• EXPRESSION indicates a mathematical expression valid outside the model description (see Expressions);
• MODEL_EXPRESSION (sometimes MODEL_EXP) indicates a mathematical expression valid in the model
description (see Expressions and Model declaration);
• MACRO_EXPRESSION designates an expression of the macro processor (see Macro expressions);
• VARIABLE_NAME (sometimes VAR_NAME) indicates a variable name starting with an alphabetical char-
acter and can’t contain: ‘()+-*/^=!;:@#.’ or accentuated characters;
• PARAMETER_NAME (sometimes PARAM_NAME) indicates a parameter name starting with an alpha-
betical character and can’t contain: ‘()+-*/^=!;:@#.’ or accentuated characters;
• LATEX_NAME (sometimes TEX_NAME) indicates a valid LaTeX expression in math mode (not including
the dollar signs);
• FUNCTION_NAME indicates a valid MATLAB function name;
• FILENAME indicates a filename valid in the underlying operating system; it is necessary to put it between
quotes when specifying the extension or if the filename contains a non-alphanumeric character;
• QUOTED_STRING indicates an arbitrary string enclosed between (single) quotes.
While Dynare allows the user to choose their own variable names, there are some restrictions to be kept in mind.
First, variables and parameters must not have the same name as Dynare commands or built-in functions. In this
respect, Dynare is not case-sensitive. For example, do not use Ln or shocks to name your variable. Not conforming
to this rule might yield hard-to-debug error messages or crashes. Second, when employing user-defined steady state
files it is recommended to avoid using the name of MATLAB functions as this may cause conflicts. In particular,
when working with user-defined steady state files, do not use correctly-spelled greek names like alpha, because
there are MATLAB functions of the same name. Rather go for alppha or alph. Lastly, please do not name a
variable or parameter i. This may interfere with the imaginary number i and the index in many loops. Rather, name
investment invest. Using inv is also not recommended as it already denotes the inverse operator. Commands for
declaring variables and parameters are described below.
Command: var VAR_NAME [$TEX_NAME$] [(long_name=QUOTED_STRING|NAME=QUOTED_STRING)]...;
Command:
var(log) VAR_NAME [$TEX_NAME$] [(long_name=QUOTED_STRING|NAME=QUOTED_STRING)]...;
Command: var(deflator=MODEL_EXPR) VAR_NAME (... same options apply)
Command: var(log, deflator=MODEL_EXPR) VAR_NAME (... same options apply)
Command: var(log_deflator=MODEL_EXPR) VAR_NAME (... same options apply)
This required command declares the endogenous variables in the model. See Conventions for the syntax of
VAR_NAME and MODEL_EXPR. Optionally it is possible to give a LaTeX name to the variable or, if it is
nonstationary, provide information regarding its deflator. The variables in the list can be separated by spaces
or by commas. var commands can appear several times in the file and Dynare will concatenate them. Dynare
stores the list of declared parameters, in the order of declaration, in a column cell array M_.endo_names.
If the model is nonstationary and is to be written as such in the model block, Dynare will need the trend
deflator for the appropriate endogenous variables in order to stationarize the model. The trend deflator must
be provided alongside the variables that follow this trend.
Options
log
In addition to the endogenous variable(s) thus declared, this option also triggers the creation of aux-
iliary variable(s) equal to the log of the corresponding endogenous variable(s). For example, given
a var(log) y statement, two endogenous will be created (y and LOG_y), and an auxiliary equation
linking the two will also be added (equal to LOG_y = log(y)). Moreover, every occurence of y in the
model will be replaced by exp(LOG_y). This option is for example useful when one wants to perform
a loglinear approximation of some variable(s) in the context of a first-order stochastic approximation;
or when one wants to ensure the variable(s) stay(s) in the definition domain of the function defining
the steady state or the dynamic residuals when the nonlinear solver is used.
deflator = MODEL_EXPR
The expression used to detrend an endogenous variable. All trend variables, endogenous variables
and parameters referenced in MODEL_EXPR must already have been declared by the trend_var,
log_trend_var, var and parameters commands. The deflator is assumed to be multiplicative; for
an additive deflator, use log_deflator. This option can be used together with the log option (the
latter must come first).
log_deflator = MODEL_EXPR
Same as deflator, except that the deflator is assumed to be additive instead of multiplicative (or, to
put it otherwise, the declared variable is equal to the log of a variable with a multiplicative trend). This
option cannot be used together with the log option, because it would not make much sense from an
economic point of view (the corresponding auxiliary variable would correspond to the log taken two
times on a variable with a multiplicative trend).
long_name = QUOTED_STRING
This is the long version of the variable name. Its value is stored in M_.endo_names_long (a column
cell array, in the same order as M_.endo_names). In case multiple long_name options are provided,
the last one will be used. Default: VAR_NAME.
NAME = QUOTED_STRING
This is used to create a partitioning of variables. It results in the direct output in the .m file analogous
to: M_.endo_partitions.NAME = QUOTED_STRING;.
Example (variable partitioning)
Command:
varexo VAR_NAME [$TEX_NAME$] [(long_name=QUOTED_STRING|NAME=QUOTED_STRING)...];
This optional command declares the exogenous variables in the model. See Conventions for the syntax of
VAR_NAME. Optionally it is possible to give a LaTeX name to the variable. Exogenous variables are required
if the user wants to be able to apply shocks to her model. The variables in the list can be separated by spaces
or by commas. varexo commands can appear several times in the file and Dynare will concatenate them.
Options
long_name = QUOTED_STRING
Like long_name but value stored in M_.exo_names_long.
NAME = QUOTED_STRING
Like partitioning but QUOTED_STRING stored in M_.exo_partitions.NAME.
Example
varexo m gov;
Remarks
An exogenous variable is an innovation, in the sense that this variable cannot be predicted from the knowledge
of the current state of the economy. For instance, if logged TFP is a first order autoregressive process:
𝑎𝑡 = 𝜌𝑎𝑡−1 + 𝜀𝑡
then logged TFP 𝑎𝑡 is an endogenous variable to be declared with var, its best prediction is 𝜌𝑎𝑡−1 , while
the innovation 𝜀𝑡 is to be declared with varexo.
Command:
varexo_det VAR_NAME [$TEX_NAME$] [(long_name=QUOTED_STRING|NAME=QUOTED_STRING)...];
This optional command declares exogenous deterministic variables in a stochastic model. See Conventions
for the syntax of VARIABLE_NAME. Optionally it is possible to give a LaTeX name to the variable. The
variables in the list can be separated by spaces or by commas. varexo_det commands can appear several
times in the file and Dynare will concatenate them.
It is possible to mix deterministic and stochastic shocks to build models where agents know from the start of
the simulation about future exogenous changes. In that case stoch_simul will compute the rational expec-
tation solution adding future information to the state space (nothing is shown in the output of stoch_simul)
and forecast will compute a simulation conditional on initial conditions and future information.
Note that exogenous deterministic variables cannot appear with a lead or a lag in the model.
Options
long_name = QUOTED_STRING
Like long_name but value stored in M_.exo_det_names_long.
NAME = QUOTED_STRING
Like partitioning but QUOTED_STRING stored in M_.exo_det_partitions.NAME.
Example
varexo m gov;
varexo_det tau;
Command:
parameters PARAM_NAME [$TEX_NAME$] [(long_name=QUOTED_STRING|NAME=QUOTED_STRING)...];
This command declares parameters used in the model, in variable initialization or in shocks declarations. See
Conventions for the syntax of PARAM_NAME. Optionally it is possible to give a LaTeX name to the parameter.
The parameters must subsequently be assigned values (see Parameter initialization).
The parameters in the list can be separated by spaces or by commas. parameters commands can appear
several times in the file and Dynare will concatenate them.
Options
long_name = QUOTED_STRING
Like long_name but value stored in M_.param_names_long.
NAME = QUOTED_STRING
Like partitioning but QUOTED_STRING stored in M_.param_partitions.NAME.
Example
Example
var y, w;
parameters alpha, beta;
...
change_type(var) alpha, beta;
change_type(parameters) y, w;
Here, in the whole model file, alpha and beta will be endogenous and y and w will be parameters.
Command: var_remove VAR_NAME | PARAM_NAME...;
Removes the listed variables (or parameters) from the model. Removing a variable that has already been
used in a model equation or elsewhere will lead to an error.
Command: predetermined_variables VAR_NAME...;
In Dynare, the default convention is that the timing of a variable reflects when this variable is decided. The
typical example is for capital stock: since the capital stock used at current period is actually decided at the
previous period, then the capital stock entering the production function is k(-1), and the law of motion of
capital must be written:
k = i + (1-delta)*k(-1)
Put another way, for stock variables, the default in Dynare is to use a “stock at the end of the period” concept,
instead of a “stock at the beginning of the period” convention.
The predetermined_variables is used to change that convention. The endogenous variables declared as
predetermined variables are supposed to be decided one period ahead of all other endogenous variables. For
stock variables, they are supposed to follow a “stock at the beginning of the period” convention.
Note that Dynare internally always uses the “stock at the end of the period” concept, even when the model
has been entered using the predetermined_variables command. Thus, when plotting, computing or
simulating variables, Dynare will follow the convention to use variables that are decided in the current period.
For example, when generating impulse response functions for capital, Dynare will plot k, which is the capital
stock decided upon by investment today (and which will be used in tomorrow’s production function). This is
the reason that capital is shown to be moving on impact, because it is k and not the predetermined k(-1) that
is displayed. It is important to remember that this also affects simulated time series and output from smoother
routines for predetermined variables. Compared to non-predetermined variables they might otherwise appear
to be falsely shifted to the future by one period.
Example
The following two program snippets are strictly equivalent.
Using default Dynare timing convention:
var y, k, i;
...
model;
y = k(-1)^alpha;
k = i + (1-delta)*k(-1);
...
end;
var y, k, i;
predetermined_variables k;
...
model;
y = k^alpha;
k(+1) = i + (1-delta)*k;
(continues on next page)
trend_var (growth_factor=gA) A;
Endogenous variables, exogenous variables, and parameters can also be declared inside the model block. You can
do this in two different ways: either via the equation tag (only for endogenous variables) or directly in an equation
(for endogenous, exogenous or parameters).
To declare an endogenous variable on-the-fly in an equation tag, simply write endogenous followed by an equal
sign and the variable name in single quotes. Hence, to declare a variable c as endogenous in an equation tag, you
can type [endogenous='c'].
To perform on-the-fly variable declaration in an equation, simply follow the symbol name with a vertical line (|,
pipe character) and either an e (for endogenous), an x (for exogenous), or a p (for parameter). For example, to
declare a parameter named alphaa in the model block, you could write alphaa|p directly in an equation where
it appears. Similarly, to declare an endogenous variable c in the model block you could write c|e. Note that
in-equation on-the-fly variable declarations must be made on contemporaneous variables.
On-the-fly variable declarations do not have to appear in the first place where this variable is encountered.
Example
The following two snippets are equivalent:
model;
[endogenous='k',name='law of motion of capital']
k(+1) = i|e + (1-delta|p)*k;
y|e = k^alpha|p;
...
end;
delta = 0.025;
alpha = 0.36;
var k, i, y;
parameters delta, alpha;
delta = 0.025;
alpha = 0.36;
...
model;
[name='law of motion of capital']
k(1) = i|e + (1-delta|p)*k;
y|e = k|e^alpha|p;
...
end;
4.3 Expressions
Dynare distinguishes between two types of mathematical expressions: those that are used to describe the model,
and those that are used outside the model block (e.g. for initializing parameters or variables, or as command
options). In this manual, those two types of expressions are respectively denoted by MODEL_EXPRESSION and
EXPRESSION.
Unlike MATLAB or Octave expressions, Dynare expressions are necessarily scalar ones: they cannot contain
matrices or evaluate to matrices.2
Expressions can be constructed using integers (INTEGER), floating point numbers (DOUBLE), parameter names
(PARAMETER_NAME), variable names (VARIABLE_NAME), operators and functions.
The following special constants are also accepted in some contexts:
Constant: inf
Represents infinity.
Constant: nan
“Not a number”: represents an undefined or unrepresentable value.
Parameters and variables can be introduced in expressions by simply typing their names. The semantics of param-
eters and variables is quite different whether they are used inside or outside the model block.
2 Note that arbitrary MATLAB or Octave expressions can be put in a .mod file, but those expressions have to be on separate lines, generally
at the end of the file for post-processing purposes. They are not interpreted by Dynare, and are simply passed on unmodified to MATLAB or
Octave. Those constructions are not addresses in this section.
4.3. Expressions 25
Dynare Reference Manual, Release 6.0
Parameters used inside the model refer to the value given through parameter initialization (see Parameter initial-
ization) or homotopy_setup when doing a simulation, or are the estimated variables when doing an estimation.
Variables used in a MODEL_EXPRESSION denote current period values when neither a lead or a lag is given.
A lead or a lag can be given by enclosing an integer between parenthesis just after the variable name: a positive
integer means a lead, a negative one means a lag. Leads or lags of more than one period are allowed. For example,
if c is an endogenous variable, then c(+1) is the variable one period ahead, and c(-2) is the variable two periods
before.
When specifying the leads and lags of endogenous variables, it is important to respect the following convention: in
Dynare, the timing of a variable reflects when that variable is decided. A control variable — which by definition
is decided in the current period — must have no lead. A predetermined variable — which by definition has been
decided in a previous period — must have a lag. A consequence of this is that all stock variables must use the
“stock at the end of the period” convention.
Leads and lags are primarily used for endogenous variables, but can be used for exogenous variables. They have
no effect on parameters and are forbidden for local model variables (see Model declaration).
When used in an expression outside the model block, a parameter or a variable simply refers to the last value
given to that variable. More precisely, for a parameter it refers to the value given in the corresponding parameter
initialization (see Parameter initialization); for an endogenous or exogenous variable, it refers to the value given
in the most recent initval or endval block.
4.3.2 Operators
Warning: The concept of a steady state is ambiguous in a perfect foresight context with permament
and potentially anticipated shocks occuring. Dynare will use the contents of oo_.steady_state as its
reference for calls to the STEADY_STATE() operator. In the presence of endval, this implies that the
terminal state provided by the user is used. This may be a steady state computed by Dynare (if endval
is followed by steady) or simply the terminal state provided by the user (if endval is not followed
by steady). Put differently, Dynare will not automatically compute the steady state conditional on the
specificed value of the exogenous variables in the respective periods.
4.3.3 Functions
The following standard functions are supported internally for both MODEL_EXPRESSION and EXPRESSION:
Function: exp(x)
Natural exponential.
Function: log(x)
Function: ln(x)
Natural logarithm.
Function: log10(x)
Base 10 logarithm.
Function: sqrt(x)
Square root.
Function: cbrt(x)
Cube root.
Function: sign(x)
Signum function, defined as:
⎧
⎨−1
⎪ if 𝑥 < 0
sign(𝑥) = 0 if 𝑥 = 0
if 𝑥 > 0
⎪
1
⎩
Note that this function is not continuous, hence not differentiable, at 𝑥 = 0. However, for facilitating conver-
gence of Newton-type methods, Dynare assumes that the derivative at 𝑥 = 0 is equal to 0. This assumption
comes from the observation that both the right- and left-derivatives at this point exist and are equal to 0, so
we can remove the singularity by postulating that the derivative at 𝑥 = 0 is 0.
Function: abs(x)
Absolute value.
Note that this continuous function is not differentiable at 𝑥 = 0. However, for facilitating convergence of
Newton-type methods, Dynare assumes that the derivative at 𝑥 = 0 is equal to 0 (even if the derivative
does not exist). The rational for this mathematically unfounded definition, rely on the observation that the
derivative of abs(𝑥) is equal to sign(𝑥) for any 𝑥 ̸= 0 in R and from the convention for the value of sign(𝑥)
at 𝑥 = 0).
Function: sin(x)
Function: cos(x)
Function: tan(x)
Function: asin(x)
4.3. Expressions 27
Dynare Reference Manual, Release 6.0
Function: acos(x)
Function: atan(x)
Trigonometric functions.
Function: sinh(x)
Function: cosh(x)
Function: tanh(x)
Function: asinh(x)
Function: acosh(x)
Function: atanh(x)
Hyperbolic functions.
Function: max(a, b)
Function: min(a, b)
Maximum and minimum of two reals.
Note that these functions are differentiable everywhere except on a line of the 2-dimensional real plane
defined by 𝑎 = 𝑏. However for facilitating convergence of Newton-type methods, Dynare assumes that,
at the points of non-differentiability, the partial derivative of these functions with respect to the first (resp.
the second) argument is equal to 1 (resp. to 0) (i.e. the derivatives at the kink are equal to the derivatives
observed on the half-plane where the function is equal to its first argument).
Function: normcdf(x)
Function: normcdf(x, mu, sigma)
Gaussian cumulative density function, with mean mu and standard deviation sigma. Note that normcdf(x)
is equivalent to normcdf(x,0,1).
Function: normpdf(x)
Function: normpdf(x, mu, sigma)
Gaussian probability density function, with mean mu and standard deviation sigma. Note that normpdf(x)
is equivalent to normpdf(x,0,1).
Function: erf(x)
Gauss error function.
Function: erfc(x)
Complementary error function, i.e. erfc(𝑥) = 1 − erf(𝑥).
Any other user-defined (or built-in) MATLAB or Octave function may be used in both a MODEL_EXPRESSION
and an EXPRESSION, provided that this function has a scalar argument as a return value.
To use an external function in a MODEL_EXPRESSION, one must declare the function using the
external_function statement. This is not required for external functions used in an EXPRESSION outside
of a model block or steady_state_model block.
Command: external_function(OPTIONS...);
This command declares the external functions used in the model block. It is required for every unique
function used in the model block.
external_function commands can appear several times in the file and must come before the model block.
Options
name = NAME
The name of the function, which must also be the name of the M-/MEX file implementing it. This
option is mandatory.
nargs = INTEGER
The number of arguments of the function. If this option is not provided, Dynare assumes nargs = 1.
first_deriv_provided [= NAME]
If NAME is provided, this tells Dynare that the Jacobian is provided as the only output of the M-
/MEX file given as the option argument. If NAME is not provided, this tells Dynare that the M-/MEX
file specified by the argument passed to NAME returns the Jacobian as its second output argument.
When this option is not provided, Dynare will use finite difference approximations for computing the
derivatives of the function, whenever needed.
second_deriv_provided [= NAME]
If NAME is provided, this tells Dynare that the Hessian is provided as the only output of the M-/MEX
file given as the option argument. If NAME is not provided, this tells Dynare that the M-/MEX file spec-
ified by the argument passed to NAME returns the Hessian as its third output argument. NB: This op-
tion can only be used if the first_deriv_provided option is used in the same external_function
command. When this option is not provided, Dynare will use finite difference approximations for com-
puting the Hessian derivatives of the function, whenever needed.
Example
external_function(name = funcname);
external_function(name = otherfuncname, nargs = 2, first_deriv_provided,␣
˓→second_deriv_provided);
The use of the following functions and operators is strongly discouraged in a stochastic context: max, min, abs,
sign, <, >, <=, >=, ==, !=.
The reason is that the local approximation used by stoch_simul or estimation will by nature ignore the non-
linearities introduced by these functions if the steady state is away from the kink. And, if the steady state is exactly
at the kink, then the approximation will be bogus because the derivative of these functions at the kink is bogus (as
explained in the respective documentations of these functions and operators).
Note that extended_path is not affected by this problem, because it does not rely on a local approximation of the
mode.
When using Dynare for computing simulations, it is necessary to calibrate the parameters of the model. This is
done through parameter initialization.
The syntax is the following:
PARAMETER_NAME = EXPRESSION;
beta = 0.99;
(continues on next page)
The equations of the model are written in a block delimited by model and end keywords.
There must be as many equations as there are endogenous variables in the model, except
when computing the unconstrained optimal policy with ramsey_model, ramsey_policy or
discretionary_policy.
The syntax of equations must follow the conventions for MODEL_EXPRESSION as described
in Expressions. Each equation must be terminated by a semicolon (‘;’). A normal equation looks
like:
MODEL_EXPRESSION = MODEL_EXPRESSION;
When the equations are written in homogenous form, it is possible to omit the ‘=0’ part and write
only the left hand side of the equation. A homogenous equation looks like:
MODEL_EXPRESSION;
Inside the model block, Dynare allows the creation of model-local variables, which constitute
a simple way to share a common expression between several equations. The syntax consists
of a pound sign (#) followed by the name of the new model local variable (which must not be
declared as in Variable declarations, but may have been declared by model_local_variable),
an equal sign, and the expression for which this new variable will stand. Later on, every time
this variable appears in the model, Dynare will substitute it by the expression assigned to the
variable. Note that the scope of this variable is restricted to the model block; it cannot be used
outside. To assign a LaTeX name to the model local variable, use the declaration syntax outlined
by model_local_variable. A model local variable declaration looks like:
#VARIABLE_NAME = MODEL_EXPRESSION;
It is possible to tag equations written in the model block. A tag can serve different purposes by
allowing the user to attach arbitrary informations to each equation and to recover them at runtime.
For instance, it is possible to name the equations with a name tag, using a syntax like:
model;
end;
Here, name is the keyword indicating that the tag names the equation. If an equation of the model
is tagged with a name, the resid command will display the name of the equations (which may
be more informative than the equation numbers) in addition to the equation number. Several tags
for one equation can be separated using a comma:
model;
end;
cases.
Controls the handling of minimum feedback set of endogenous variables for the
dynamic model. Only available with option block. Possible values:
0
All the endogenous variables are considered as feedback variables.
1
The endogenous variables assigned to equation naturally normalized (i.e. of
the form 𝑥 = 𝑓 (𝑌 ) where 𝑥 does not appear in 𝑌 ) are potentially recursive
variables. All the other variables are forced to belong to the set of feedback
variables.
2
In addition of variables with mfs = 1 the endogenous variables related to lin-
ear equations which could be normalized are potential recursive variables. All
the other variables are forced to belong to the set of feedback variables.
3
In addition of variables with mfs = 2 the endogenous variables related to non-
linear equations which could be normalized are potential recursive variables.
All the other variables are forced to belong to the set of feedback variables.
Default value is 1.
static_mfs
Controls the handling of minimum feedback set of endogenous variables for the static model.
Only available with option block. See the mfs option for the possible values. Default value
is 0.
no_static
Don’t create the static model file. This can be useful for models which don’t have a steady
state.
differentiate_forward_vars
differentiate_forward_vars = ( VARIABLE_NAME [VARIABLE_NAME ...] )
Tells Dynare to create a new auxiliary variable for each endogenous variable that appears
with a lead, such that the new variable is the time differentiate of the original one. More
precisely, if the model contains x(+1), then a variable AUX_DIFF_VAR will be created such
that AUX_DIFF_VAR=x-x(-1), and x(+1) will be replaced with x+AUX_DIFF_VAR(+1).
The transformation is applied to all endogenous variables with a lead if the option is given
without a list of variables. If there is a list, the transformation is restricted to endogenous
with a lead that also appear in the list.
This option can useful for some deterministic simulations where convergence is hard to ob-
tain. Bad values for terminal conditions in the case of very persistent dynamics or permanent
shocks can hinder correct solutions or any convergence. The new differentiated variables
have obvious zero terminal conditions (if the terminal condition is a steady state) and this in
many cases helps convergence of simulations.
parallel_local_files = ( FILENAME [, FILENAME]... )
Declares a list of extra files that should be transferred to follower nodes when doing a parallel
computation (see Parallel Configuration).
balanced_growth_test_tol = DOUBLE
Tolerance used for determining whether cross-derivatives are zero in the test for bal-
anced growth path (the latter is documented on https://archives.dynare.org/DynareWiki/
RemovingTrends). Default: 1e-6
Example (Elementary RBC model)
var c k;
varexo x;
parameters aa alph bet delt gam;
end;
model;
# gamma = 1 - 1/sigma;
u1 = c1^gamma/gamma;
u2 = c2^gamma/gamma;
end;
model;
u1 = c1^(1-1/sigma)/(1-1/sigma);
u2 = c2^(1-1/sigma)/(1-1/sigma);
end;
model(linear);
x = a*x(-1)+b*y(+1)+e_x;
y = d*y(-1)+e_y;
end;
Command: model_options(OPTIONS...);
This command accepts the same options as the model block.
The purpose of this statement is to specify the options that apply to the whole model, when there are several
model blocks, so as to restore the symmetry between those blocks (since otherwise one model block would
typically bear the options, while the other ones would typically have no option).
Command: model_remove(TAGS...);
This command removes equations that appeared in a previous model block.
The equations must be specified by a list of tag values, separated by commas. Each element of the list is
either a simple quoted string, in which case it designates an equation by its name tag; or a tag name (without
quotes), followed by an equal sign, then by the tag value (within quotes); or a list of tag-equals-value pairs
separated by commas and enclosed within brackets, in which case this element removes the equation(s) that
has all these tags with the corresponding values.
Each removed equation must either have an endogenous tag, or have a left hand side containing a single
endogenous variable. The corresponding endogenous variable will be either turned into an exogenous (if it
is still used in somewhere in the model at that point), otherwise it will be removed from the model.
Example
model;
c + k - aa*x*k(-1)^alph - (1-delt)*k(-1) + dummy1;
c^(-gam) - (1+bet)^(-1)*(aa*alph*x(+1)*k^(alph-1) + 1 - delt)*c(+1)^(-
˓→gam);
In the above example, the last three equations will be removed, dummy1 will be turned into an
exogenous, and dummy2 and dummy3 will be removed.
Block: model_replace(TAGS...);
This block replaces several equations in the model. It removes the equations given by the tags list (with the
same syntax as in model_remove), and it adds equations given within the block (with the same syntax as
model).
No variable is removed or has its type changed in the process.
Example
var c k;
model;
c + k - aa*x*k(-1)^alph - (1-delt)*k(-1);
[ name = 'dummy' ]
c*k = 1;
end;
model_replace('dummy');
c^(-gam) = (1+bet)^(-1)*(aa*alph*x(+1)*k^(alph-1) + 1 - delt)*c(+1)^(-
˓→gam);
end;
In the above example, the dummy equation is replaced by a proper Euler equation.
Dynare has the ability to output the original list of model equations to a LaTeX file, us-
ing the write_latex_original_model command, the list of transformed model equations us-
ing the write_latex_dynamic_model command, and the list of static model equations using the
write_latex_static_model command.
Command: write_latex_original_model ;
Command: write_latex_original_model(OPTIONS);
This command creates two LaTeX files: one containing the model as defined in the model block and one
containing the LaTeX document header information.
If your .mod file is FILENAME.mod, then Dynare will create a file called FILENAME/latex/original.
tex, which includes a file called FILENAME/latex/original_content.tex (also created by Dynare)
containing the list of all the original model equations.
If LaTeX names were given for variables and parameters (see Variable declarations), then those will be used;
otherwise, the plain text names will be used.
Time subscripts (t, t+1, t-1, . . . ) will be appended to the variable names, as LaTeX subscripts.
Compiling the TeX file requires the following LaTeX packages: geometry, fullpage, breqn.
Options
write_equation_tags
Write the equation tags in the LaTeX output. The equation tags will be interpreted with LaTeX markups.
Command: write_latex_dynamic_model ;
Command: write_latex_dynamic_model(OPTIONS);
This command creates two LaTeX files: one containing the dynamic model and one containing the LaTeX
document header information.
If your .mod file is FILENAME.mod, then Dynare will create a file called FILENAME/latex/dynamic.tex,
which includes a file called FILENAME/latex/dynamic_content.tex (also created by Dynare) containing
the list of all the dynamic model equations.
If LaTeX names were given for variables and parameters (see Variable declarations), then those will be used;
otherwise, the plain text names will be used.
Time subscripts (t, t+1, t-1, . . . ) will be appended to the variable names, as LaTeX subscripts.
Note that the model written in the TeX file will differ from the model declared by the user in the following
dimensions:
• The timing convention of predetermined variables (see predetermined_variables) will have been
changed to the default Dynare timing convention; in other words, variables declared as predetermined
will be lagged on period back,
• The EXPECTATION operators will have been removed, replaced by auxiliary variables and new equa-
tions (as explained in the documentation of EXPECTATION),
• Endogenous variables with leads or lags greater or equal than two will have been removed, replaced by
new auxiliary variables and equations,
• Exogenous variables with leads or lags will also have been replaced by new auxiliary variables and
equations.
For the required LaTeX packages, see write_latex_original_model.
Options
write_equation_tags
See write_equation_tags
Command: write_latex_static_model ;
Command: write_latex_static_model(OPTIONS);
This command creates two LaTeX files: one containing the static model and one containing the LaTeX
document header information.
If your .mod file is FILENAME.mod, then Dynare will create a file called FILENAME/latex/static.tex,
which includes a file called FILENAME/latex/static_content.tex (also created by Dynare) containing
the list of all the steady state model equations.
If LaTeX names were given for variables and parameters (see Variable declarations), then those will be used;
otherwise, the plain text names will be used.
Note that the model written in the TeX file will differ from the model declared by the user in the some
dimensions (see write_latex_dynamic_model for details).
Also note that this command will not output the contents of the optional steady_state_model block
(see steady_state_model); it will rather output a static version (i.e. without leads and lags) of the dy-
namic model declared in the model block. To write the LaTeX contents of the steady_state_model see
write_latex_steady_state_model.
For the required LaTeX packages, see write_latex_original_model.
Options
write_equation_tags
See write_equation_tags.
Command: write_latex_steady_state_model ;
This command creates two LaTeX files: one containing the steady state model and one containing the LaTeX
document header information.
If your .mod file is FILENAME.mod, then Dynare will create a file called FILENAME/latex/steady_state.
tex, which includes a file called FILENAME/latex/steady_state_content.tex (also created by
Dynare) containing the list of all the steady state model equations.
If LaTeX names were given for variables and parameters (see Variable declarations), then those will be used;
otherwise, the plain text names will be used.
Note that the model written in the .tex file will differ from the model declared by the user in some dimensions
(see write_latex_dynamic_model for details).
For the required LaTeX packages, see write_latex_original_model.
The model which is solved internally by Dynare is not exactly the model declared by the user. In some cases, Dynare
will introduce auxiliary endogenous variables—along with corresponding auxiliary equations—which will appear
in the final output.
The main transformation concerns leads and lags. Dynare will perform a transformation of the model so that there
is only one lead and one lag on endogenous variables and no leads/lags on exogenous variables.
This transformation is achieved by the creation of auxiliary variables and corresponding equations. For example,
if x(+2) exists in the model, Dynare will create one auxiliary variable AUX_ENDO_LEAD = x(+1), and replace
x(+2) by AUX_ENDO_LEAD(+1).
A similar transformation is done for lags greater than 2 on endogenous (auxiliary variables will have a name
beginning with AUX_ENDO_LAG), and for exogenous with leads and lags (auxiliary variables will have a name
beginning with AUX_EXO_LEAD or AUX_EXO_LAG respectively).
Another transformation is done for the EXPECTATION operator. For each occurrence of this operator, Dynare creates
an auxiliary variable defined by a new equation, and replaces the expectation operator by a reference to the new aux-
iliary variable. For example, the expression EXPECTATION(-1)(x(+1)) is replaced by AUX_EXPECT_LAG_1(-1),
and the new auxiliary variable is declared as AUX_EXPECT_LAG_1 = x(+2).
Auxiliary variables are also introduced by the preprocessor for the ramsey_model and ramsey_policy com-
mands. In this case, they are used to represent the Lagrange multipliers when first order conditions of the Ramsey
problem are computed. The new variables take the form MULT_i, where i represents the constraint with which the
multiplier is associated (counted from the order of declaration in the model block).
Auxiliary variables are also introduced by the differentiate_forward_vars option of the model block. The
new variables take the form AUX_DIFF_FWRD_i, and are equal to x-x(-1) for some endogenous variable x.
Finally, auxiliary variables will arise in the context of employing the diff operator.
Once created, all auxiliary variables are included in the set of endogenous variables. The output of decision rules
(see below) is such that auxiliary variable names are replaced by the original variables they refer to.
The number of endogenous variables before the creation of auxiliary variables is stored in M_.orig_endo_nbr,
and the number of endogenous variables after the creation of auxiliary variables is stored in M_.endo_nbr.
See https://git.dynare.org/Dynare/dynare/-/wikis/Auxiliary-variables for more technical details on auxiliary vari-
ables.
For most simulation exercises, it is necessary to provide initial (and possibly terminal) conditions. It is also nec-
essary to provide initial guess values for non-linear solvers. This section describes the statements used for those
purposes.
In many contexts (deterministic or stochastic), it is necessary to compute the steady state of a non-linear model:
initval then specifies numerical initial values for the non-linear solver. The command resid can be used to
compute the equation residuals for the given initial values.
Used in perfect foresight mode, the types of forward-looking models for which Dynare was designed require both
initial and terminal conditions. Most often these initial and terminal conditions are static equilibria, but not neces-
sarily.
One typical application is to consider an economy at the equilibrium at time 0, trigger a shock in first period, and
study the trajectory of return to the initial equilibrium. To do that, one needs initval and shocks (see Shocks on
exogenous variables).
Another one is to study how an economy, starting from arbitrary initial conditions at time 0 converges towards
equilibrium. In this case models, the command histval permits to specify different historical initial values for
variables with lags for the periods before the beginning of the simulation. Due to the design of Dynare, in this case
initval is used to specify the terminal conditions.
Block: initval ;
Block: initval(OPTIONS...);
The initval block has two main purposes: providing guess values for non-linear solvers in the context
of perfect foresight simulations and providing guess values for steady state computations in both perfect
foresight and stochastic simulations. Depending on the presence of histval and endval blocks it is also
used for declaring the initial and terminal conditions in a perfect foresight simulation exercise. Because of
this interaction of the meaning of an initval block with the presence of histval and endval blocks in
perfect foresight simulations, it is strongly recommended to check that the constructed oo_.endo_simul
and oo_.exo_simul variables contain the desired values after running perfect_foresight_setup and
before running perfect_foresight_solver. In the presence of leads and lags, these subfields of the
results structure will store the historical values for the lags in the first column/row and the terminal values
for the leads in the last column/row.
The initval block is terminated by end; and contains lines of the form:
VARIABLE_NAME = EXPRESSION;
In a deterministic (i.e. perfect foresight) model
First, both the oo_.endo_simul and oo_.exo_simul variables storing the endogenous and exogenous
variables will be filled with the values provided by this block. If there are no other blocks present, it will
therefore provide the initial and terminal conditions for all the endogenous and exogenous variables, because
it will also fill the last column/row of these matrices. For the intermediate simulation periods it thereby
provides the starting values for the solver. In the presence of a histval block (and therefore absence of an
endval block), this histval block will provide/overwrite the historical values for the state variables (lags)
by setting the first column/row of oo_.endo_simul and oo_.exo_simul. This implies that the initval
block in the presence of histval only sets the terminal values for the variables with leads and provides
initial values for the perfect foresight solver.
Because of these various functions of initval it is often necessary to provide values for all the endoge-
nous variables in an initval block. Initial and terminal conditions are strictly necessary for lagged/leaded
variables, while feasible starting values are required for the solver. It is important to be aware that if some
variables, endogenous or exogenous, are not mentioned in the initval block, a zero value is assumed. It is
particularly important to keep this in mind when specifying exogenous variables using varexo that are not
allowed to take on the value of zero, like e.g. TFP.
Note that if the initval block is immediately followed by a steady command, its semantics are slightly
changed. The steady command will compute the steady state of the model for all the endogenous variables,
assuming that exogenous variables are kept constant at the value declared in the initval block. These
steady state values conditional on the declared exogenous variables are then written into oo_.endo_simul
and take up the potential roles as historical and terminal conditions as well as starting values for the solver. An
initval block followed by steady is therefore formally equivalent to an initval block with the specified
values for the exogenous variables, and the endogenous variables set to the associated steady state values
conditional on the exogenous variables.
In a stochastic model
The main purpose of initval is to provide initial guess values for the non-linear solver in the steady state
computation. Note that if the initval block is not followed by steady, the steady state computation will
still be triggered by subsequent commands (stoch_simul, estimation. . . ).
As such, initval allows specifying the initial instrument value for steady state finding when providing an
analytical conditional steady state file for ramsey_model-computations.
It is not necessary to declare 0 as initial value for exogenous stochastic variables, since it is the only possible
value.
The subsequently computed steady state (not the initial values, use histval for this) will be used as the initial
condition at all the periods preceeding the first simulation period for the three possible types of simulations
in stochastic mode:
• stoch_simul, if the periods option is specified.
• forecast as the initial point at which the forecasts are computed.
• conditional_forecast as the initial point at which the conditional forecasts are computed.
To start simulations at a particular set of starting values that are not a computed steady state, use histval.
Options
all_values_required
Issues an error and stops processing the .mod file if there is at least one endogenous or exogenous
variable that has not been set in the initval block.
Example
initval;
c = 1.2;
k = 12;
x = 1;
end;
steady;
Block: endval ;
Block: endval(OPTIONS...);
This block is terminated by end; and contains lines of the form:
VARIABLE_NAME = EXPRESSION;
The endval block makes only sense in a deterministic model and cannot be used together with histval.
Similar to the initval command, it will fill both the oo_.endo_simul and oo_.exo_simul variables
storing the endogenous and exogenous variables with the values provided by this block. If no initval
block is present, it will fill the whole matrices, therefore providing the initial and terminal conditions for
all the endogenous and exogenous variables, because it will also fill the first and last column/row of these
matrices. Due to also filling the intermediate simulation periods it will provide the starting values for the
solver as well.
If an initval block is present, initval will provide the historical values for the variables (if there are
states/lags), while endval will fill the remainder of the matrices, thereby still providing i) the terminal
conditions for variables entering the model with a lead and ii) the initial guess values for all endogenous
variables at all the simulation dates for the perfect foresight solver.
Note that if some variables, endogenous or exogenous, are NOT mentioned in the endval block, the
value assumed is that of the last initval block or steady command (if present). Therefore, in contrast
to initval, omitted variables are not automatically assumed to be 0 in this case. Again, it is strongly
recommended to check the constructed oo_.endo_simul and oo_.exo_simul variables after running
perfect_foresight_setup and before running perfect_foresight_solver to see whether the desired
outcome has been achieved.
Like initval, if the endval block is immediately followed by a steady command, its semantics are slightly
changed. The steady command will compute the steady state of the model for all the endogenous variables,
assuming that exogenous variables are kept constant to the value declared in the endval block. These steady
state values conditional on the declared exogenous variables are then written into oo_.endo_simul and
therefore take up the potential roles as historical and terminal conditions as well as starting values for the
solver. An endval block followed by steady is therefore formally equivalent to an endval block with the
specified values for the exogenous variables, and the endogenous variables set to the associated steady state
values.
Options
all_values_required
See all_values_required.
Example
var c k;
varexo x;
model;
c + k - aa*x*k(-1)^alph - (1-delt)*k(-1);
c^(-gam) - (1+bet)^(-1)*(aa*alph*x(+1)*k^(alph-1) + 1 - delt)*c(+1)^(-
˓→gam);
end;
initval;
c = 1.2;
k = 12;
x = 1;
end;
steady;
endval;
c = 2;
k = 20;
x = 2;
end;
steady;
perfect_foresight_setup(periods=200);
perfect_foresight_solver;
In this example, the problem is finding the optimal path for consumption and capital for the periods
𝑡 = 1 to 𝑇 = 200, given the path of the exogenous technology level x. c is a forward-looking
variable and the exogenous variable x appears with a lead in the expected return of physical capital,
while k is a purely backward-looking (state) variable.
The initial equilibrium is computed by steady conditional on x=1, and the terminal one condi-
tional on x=2. The initval block sets the initial condition for k (since it is the only backward-
looking variable), while the endval block sets the terminal condition for c (since it is the only
forward-looking endogenous variable). The starting values for the perfect foresight solver are
given by the endval block. See below for more details.
Example
var c k;
varexo x;
model;
c + k - aa*x*k(-1)^alph - (1-delt)*k(-1);
c^(-gam) - (1+bet)^(-1)*(aa*alph*x(+1)*k^(alph-1) + 1 - delt)*c(+1)^(-
˓→gam);
end;
initval;
k = 12;
end;
endval;
c = 2;
x = 1.1;
end;
perfect_foresight_setup(periods=200);
perfect_foresight_solver;
In this example, there is no steady command, hence the conditions are exactly those specified in
the initval and endval blocks. We need terminal conditions for c and x, since both appear with a
lead, and an initial condition for k, since it appears with a lag.
Setting x=1.1 in the endval block without a shocks block implies that technology is at 1.1
in 𝑡 = 1 and stays there forever, because endval is filling all entries of oo_.endo_simul and
oo_.exo_simul except for the very first one, which stores the initial conditions and was set to 0
by the initval block when not explicitly specifying a value for it.
Because the law of motion for capital is backward-looking, we need an initial condition for k at
time 0. Due to the presence of endval, this cannot be done via a histval block, but rather must
be specified in the initval block. Similarly, because the Euler equation is forward-looking, we
need a terminal condition for c at 𝑡 = 201, which is specified in the endval block.
As can be seen, it is not necessary to specify c and x in the initval block and k in the endval
block, because they have no impact on the results. Due to the optimization problem in the first
period being to choose c,k at 𝑡 = 1 given the predetermined capital stock k inherited from 𝑡 = 0
as well as the current and future values for technology x, the values for c and x at time 𝑡 = 0
play no role. The same applies to the choice of c,k at time 𝑡 = 200, which does not depend on
k at 𝑡 = 201. As the Euler equation shows, that choice only depends on current capital as well as
future consumption c and technology x, but not on future capital k. The intuitive reason is that
those variables are the consequence of optimization problems taking place in at periods 𝑡 = 0
and 𝑡 = 201, respectively, which are not modeled here.
Example
initval;
c = 1.2;
k = 12;
x = 1;
end;
endval;
c = 2;
k = 20;
x = 1.1;
end;
In this example, initial conditions for the forward-looking variables x and c are provided, together
with a terminal condition for the backward-looking variable k. As shown in the previous example,
these values will not affect the simulation results. Dynare simply takes them as given and basically
assumes that there were realizations of exogenous variables and states that make those choices
equilibrium values (basically initial/terminal conditions at the unspecified time periods 𝑡 < 0 and
𝑡 > 201).
The above example suggests another way of looking at the use of steady after initval and
endval. Instead of saying that the implicit unspecified conditions before and after the simulation
range have to fit the initial/terminal conditions of the endogenous variables in those blocks, steady
specifies that those conditions at 𝑡 < 0 and 𝑡 > 201 are equal to being at the steady state given
the exogenous variables in the initval and endval blocks. The endogenous variables at 𝑡 = 0
and 𝑡 = 201 are then set to the corresponding steady state equilibrium values.
The fact that c at 𝑡 = 0 and k at 𝑡 = 201 specified in initval and endval are taken as given
has an important implication for plotting the simulated vector for the endogenous variables, i.e.
the rows of oo_.endo_simul: this vector will also contain the initial and terminal conditions
and thus is 202 periods long in the example. When you specify arbitrary values for the initial
and terminal conditions for forward- and backward-looking variables, respectively, these values
can be very far away from the endogenously determined values at 𝑡 = 1 and 𝑡 = 200. While the
values at 𝑡 = 0 and 𝑡 = 201 are unrelated to the dynamics for 0 < 𝑡 < 201, they may result in
strange-looking large jumps. In the example above, consumption will display a large jump from
𝑡 = 0 to 𝑡 = 1 and capital will jump from 𝑡 = 200 to 𝑡 = 201 when using rplot or manually
plotting oo_.endo_simul.
Block: histval ;
Block: histval(OPTIONS...);
In a deterministic perfect foresight context
In models with lags on more than one period, the histval block permits to specify different historical
initial values for different periods of the state variables. In this case, the initval block takes over the role
of specifying terminal conditions and starting values for the solver. Note that the histval block does not
take non-state variables.
This block is terminated by end; and contains lines of the form:
VARIABLE_NAME(INTEGER) = EXPRESSION;
EXPRESSION is any valid expression returning a numerical value and can contain already initialized vari-
able names.
By convention in Dynare, period 1 is the first period of the simulation. Going backward in time, the first
period before the start of the simulation is period 0, then period -1, and so on.
State variables not initialized in the histval block are assumed to have a value of zero at period 0 and
before. Note that histval cannot be followed by steady.
Example
model;
x=1.5*x(-1)-0.6*x(-2)+epsilon;
log(c)=0.5*x+0.5*log(c(+1));
end;
histval;
x(0)=-1;
x(-1)=0.2;
end;
initval;
c=1;
(continues on next page)
In this example, histval is used to set the historical conditions for the two lags of the endoge-
nous variable x, stored in the first column of oo_.endo_simul. The initval block is used to
set the terminal condition for the forward looking variable c, stored in the last column of oo_.
endo_simul. Moreover, the initval block defines the starting values for the perfect foresight
solver for both endogenous variables c and x.
In a stochastic simulation context
In the context of stochastic simulations, histval allows setting the starting point of those simulations in the
state space. As for the case of perfect foresight simulations, all not explicitly specified variables are set to 0.
Moreover, as only states enter the recursive policy functions, all values specified for control variables will
be ignored. This can be used
• In stoch_simul, if the periods option is specified. Note that this only affects the starting point for the
simulation, but not for the impulse response functions. When using the loglinear option, the histval
block nevertheless takes the unlogged starting values.
• In forecast as the initial point at which the forecasts are computed. When using the loglinear option,
the histval block nevertheless takes the unlogged starting values.
• In conditional_forecast for a calibrated model as the initial point at which the conditional forecasts
are computed. When using the loglinear option, the histval block nevertheless takes the unlogged
starting values.
• In Ramsey policy, where it also specifies the values of the endogenous states (including lagged
exogenous) at which the objective function of the planner is computed. Note that the ini-
tial values of the Lagrange multipliers associated with the planner’s problem cannot be set (see
evaluate_planner_objective).
Options
all_values_required
See all_values_required.
Example
var x y;
varexo e;
model;
x = y(-1)^alpha*y(-2)^(1-alpha)+e;
end;
initval;
x = 1;
y = 1;
e = 0.5;
end;
steady;
histval;
y(0) = 1.1;
y(-1) = 0.9;
end;
stoch_simul(periods=100);
Command: resid ;
This command will display the residuals of the static equations of the model, using the values given for the
endogenous in the last initval or endval block (or the steady state file if you provided one, see Steady
state).
Options
non_zero
Only display non-zero residuals.
Command: initval_file(OPTIONS...);
In a deterministic setup, this command is used to specify a path for all endogenous and exogenous variables.
The length of these paths must be equal to the number of simulation periods, plus the number of leads and
the number of lags of the model (for example, with 50 simulation periods, in a model with 2 lags and 1 lead,
the paths must have a length of 53). Note that these paths cover two different things:
• The constraints of the problem, which are given by the path for exogenous and the initial and terminal
values for endogenous
• The initial guess for the non-linear solver, which is given by the path for endogenous variables for the
simulation periods (excluding initial and terminal conditions)
In perfect foresight and stochastic contexts, steady uses the first observation loaded by initval_file as
guess value to solve for the steady state of the model. This first observation is determined by the first_obs
option when it is used.
Don’t mix initval_file with initval statements. However, after initval_file, you can modify the
historical initial values with histval or histval_file statement.
There can be several initval_file statements in a model file. Each statement resets oo_.
initval_series.
Options
datafile = FILENAME
filename = FILENAME (deprecated)
The name of the file containing the data. It must be included in quotes if the filename contains a path
or an extension. The command accepts the following file formats:
• M-file (extension .m): for each endogenous and exogenous variable, the file must contain a row or
column vector of the same name.
• MAT-file (extension .mat): same as for M-files.
• Excel file (extension .xls or .xlsx): for each endogenous and exogenous variable, the file must
contain a column of the same name. NB: Octave only supports the .xlsx file extension and must
have the io package installed (easily done via octave by typing ‘pkg install -forge io’). The
first column may contain the date of each observation.
• CSV files (extension .csv): for each endogenous and exogenous variable, the file must contain a
column of the same name. The first column may contain the date of each observation.
first_obs = {INTEGER | DATE}
The observation number or the date (see The dates class) of the first observation to be used in the file
first_simulation_period = {INTEGER | DATE}
The observation number in the file or the date (see dates) at which the simulation (or the forecast)
is starting. This option avoids to have to compute the maximum number of lags in the model. The
observation corresponding to the first period of simulation doesn’t need to exist in the file as the only
dates necessary for initialization are before that date.
last_simulation_period = {INTEGER | DATE}
The observation number in the file or the date (see dates) at which the simulation (or the forecast) is
ending. This option avoids to have to compute the maximum number of leads in the model.
var c x;
varexo e;
parameters a b c d;
a = 1.5;
b = -0,6;
c = 0.5;
d = 0.5;
model;
x = a*x(-1) + b*x(-2) + e;
log(c) = c*x + d*log(c(+1));
end;
initval_file(datafile=mydata.csv);
perfect_foresight_setup(periods=200);
perfect_foresight_solver;
The initial and terminal values are taken from file mydata.csv (nothing guarantees that
these vales are the steady state of the model). The guess value for the trajectories are also
taken from the file. The file must contain at least 203 observations of variables c, x and
e. If there are more than 203 observations available in the file, the first 203 are used by
perfect_foresight_setup(periods=200). Note that the values for the auxiliary variable
corresponding to x(-2) are automatically computed by initval_file.
Example 2
var c x;
varexo e;
parameters a b c d;
a = 1.5;
b = -0,6;
c = 0.5;
d = 0.5;
model;
x = a*x(-1) + b*x(-2) + e;
log(c) = c*x + d*log(c(+1));
end;
initval_file(datafile=mydata.csv,
first_obs=10);
perfect_foresight_setup(periods=200);
perfect_foresight_solver;
The initial and terminal values are taken from file mydata.csv starting with the 10th observation
in the file. There must be at least 212 observations in the file.
Example 3
var c x;
varexo e;
parameters a b c d;
a = 1.5;
b = -0,6;
c = 0.5;
d = 0.5;
model;
x = a*x(-1) + b*x(-2) + e;
log(c) = c*x + d*log(c(+1));
end;
ds = dseries(mydata.csv);
lds = log(ds);
initval_file(series=lds,
first_obs=2010Q1);
perfect_foresight_setup(periods=200);
perfect_foresight_solver;
The initial and terminal values are taken from dseries lds. All observations are loaded starting
with the 1st quarter of 2010 until the end of the file. There must be data available at least until
2050Q3.
Example 4
var c x;
varexo e;
parameters a b c d;
a = 1.5;
b = -0,6;
c = 0.5;
d = 0.5;
model;
x = a*x(-1) + b*x(-2) + e;
log(c) = c*x + d*log(c(+1));
end;
initval_file(datafile=mydata.csv,
first_simulation_period=2010Q1);
perfect_foresight_setup(periods=200);
perfect_foresight_solver;
The initial and terminal values are taken from file mydata.csv. The observations in the file must
have dates. All observations are loaded from the 3rd quarter of 2009 until the end of the file.
There must be data available in the file at least until 2050Q1.
Example 5
var c x;
varexo e;
parameters a b c d;
a = 1.5;
b = -0,6;
c = 0.5;
d = 0.5;
model;
x = a*x(-1) + b*x(-2) + e;
log(c) = c*x + d*log(c(+1));
end;
initval_file(datafile=mydata.csv,
last_obs = 212);
perfect_foresight_setup(periods=200);
perfect_foresight_solver;
The initial and terminal values are taken from file mydata.csv. The first
212 observations are loaded and the first 203 observations will be used by
perfect_foresight_setup(periods=200).
Example 6
var c x;
varexo e;
parameters a b c d;
a = 1.5;
b = -0,6;
c = 0.5;
d = 0.5;
model;
x = a*x(-1) + b*x(-2) + e;
log(c) = c*x + d*log(c(+1));
end;
initval_file(datafile=mydata.csv,
first_obs = 10,
nobs = 203);
perfect_foresight_setup(periods=200);
perfect_foresight_solver;
The initial and terminal values are taken from file mydata.csv. Observations 10 to 212 are
loaded.
Example 7
var c x;
varexo e;
parameters a b c d;
a = 1.5;
b = -0,6;
(continues on next page)
model;
x = a*x(-1) + b*x(-2) + e;
log(c) = c*x + d*log(c(+1));
end;
initval_file(datafile=mydata.csv,
first_obs = 10);
steady;
The values of the 10th observation of mydata.csv are used as guess value to compute the steady
state. The exogenous variables are set to values found in the file or zero if these variables aren’t
present.
Command: histval_file(OPTIONS...);
This command is equivalent to histval, except that it reads its input from a file, and is typically used in
conjunction with smoother2histval.
Options
datafile = FILENAME
filename = FILENAME (deprecated)
The name of the file containing the data. The command accepts the following file formats:
• M-file (extension .m): for each endogenous and exogenous variable, the file must contain a row or
column vector of the same name.
• MAT-file (extension .mat): same as for M-files.
• Excel file (extension .xls or .xlsx): for each endogenous and exogenous variable, the file must
contain a column of the same name. NB: Octave only supports the .xlsx file extension and must
have the io package installed (easily done via octave by typing ‘pkg install -forge io’). The
first column may contain the date of each observation.
• CSV files (extension .csv): for each endogenous and exogenous variable, the file must contain a
column of the same name. The first column may contain the date of each observation.
first_obs = {INTEGER | DATE}
The observation number or the date (see The dates class) of the first observation to be used in the file
first_simulation_period = {INTEGER | DATE}
The observation number in the file or the date (see The dates class) at which the simulation (or the
forecast) is starting. This option avoids to have to compute the maximum number of lags in the model.
The observation corresponding to the first period of simulation doesn’t need to exist in the file as the
only dates necessary for initialization are before that date.
last_simulation_period = {INTEGER | DATE}
The observation number in the file or the date (see dates) at which the simulation (or the forecast) is
ending. This option avoids to have to compute the maximum number of leads in the model.
last_obs = {INTEGER | DATE}
The observation number or the date (see The dates class) of the last observation to be used in the file.
nobs = INTEGER
The number of observations to be used in the file (starting with first of first_obs observation).
series = DSERIES NAME
The name of a DSERIES containing the data (see The dseries class)
Example 1
var c x;
varexo e;
parameters a b c d;
a = 1.5;
b = -0,6;
c = 0.5;
d = 0.5;
model;
x = a*x(-1) + b*x(-2) + e;
log(c) = c*x + d*log(c(+1));
end;
steady_state_model;
x = 0;
c = exp(c*x/(1 - d));
end;
histval_file(datafile=mydata.csv);
stoch_simul(order=1,periods=100);
The initial values for the stochastic simulation are taken from the two first rows of file mydata.
csv.
Example 2
var c x;
varexo e;
parameters a b c d;
a = 1.5;
b = -0,6;
c = 0.5;
d = 0.5;
model;
x = a*x(-1) + b*x(-2) + e;
log(c) = c*x + d*log(c(+1));
end;
histval_file(datafile=mydata.csv,
first_obs=10);
stoch_simul(order=1,periods=100);
The initial values for the stochastic simulation are taken from rows 10 and 11 of file mydata.csv.
Example 3
var c x;
varexo e;
parameters a b c d;
a = 1.5;
b = -0,6;
(continues on next page)
model;
x = a*x(-1) + b*x(-2) + e;
log(c) = c*x + d*log(c(+1));
end;
histval_file(datafile=mydata.csv,
first_obs=2010Q1);
stoch_simul(order=1,periods=100);
The initial values for the stochastic simulation are taken from observations 2010Q1 and 2010Q2
of file mydata.csv.
Example 4
var c x;
varexo e;
parameters a b c d;
a = 1.5;
b = -0,6;
c = 0.5;
d = 0.5;
model;
x = a*x(-1) + b*x(-2) + e;
log(c) = c*x + d*log(c(+1));
end;
histval_file(datafile=mydata.csv,
first_simulation_period=2010Q1)
stoch_simul(order=1,periods=100);
The initial values for the stochastic simulation are taken from observations 2009Q3 and 2009Q4
of file mydata.csv.
Example 5
var c x;
varexo e;
parameters a b c d;
a = 1.5;
b = -0,6;
c = 0.5;
d = 0.5;
model;
x = a*x(-1) + b*x(-2) + e;
log(c) = c*x + d*log(c(+1));
end;
histval_file(datafile=mydata.csv,
last_obs = 4);
(continues on next page)
stoch_simul(order=1,periods=100);
The initial values for the stochastic simulation are taken from the two first rows of file mydata.
csv.
Example 6
var c x;
varexo e;
parameters a b c d;
a = 1.5;
b = -0,6;
c = 0.5;
d = 0.5;
model;
x = a*x(-1) + b*x(-2) + e;
log(c) = c*x + d*log(c(+1));
end;
initval_file(datafile=mydata.csv,
first_obs = 10,
nobs = 4);
stoch_simul(order=1,periods=100);
The initial values for the stochastic simulation are taken from rows 10 and 11 of file mydata.csv.
Example 7
var c x;
varexo e;
parameters a b c d;
a = 1.5;
b = -0,6;
c = 0.5;
d = 0.5;
model;
x = a*x(-1) + b*x(-2) + e;
log(c) = c*x + d*log(c(+1));
end;
initval_file(datafile=mydata.csv,
first_obs=10);
histval_file(datafile=myotherdata.csv);
perfect_foresight_setup(periods=200);
perfect_foresight_solver;
Historical initial values for the simulation are taken from the two first rows of file myotherdata.
csv.
Terminal values and guess values for the simulation are taken from file mydata.csv starting with
the 12th observation in the file. There must be at least 212 observations in the file.
In a deterministic context, when one wants to study the transition of one equilibrium position to another, it is
equivalent to analyze the consequences of a permanent shock and this in done in Dynare through the proper use of
initval and endval.
Another typical experiment is to study the effects of a temporary shock after which the system goes back to the
original equilibrium (if the model is stable. . . ). A temporary shock is a temporary change of value of one or several
exogenous variables in the model. Temporary shocks are specified with the command shocks.
In a stochastic framework, the exogenous variables take random values in each period. In Dynare, these random
values follow a normal distribution with zero mean, but it belongs to the user to specify the variability of these
shocks. The non-zero elements of the matrix of variance-covariance of the shocks can be entered with the shocks
command.
If the variance of an exogenous variable is set to zero, this variable will appear in the report on policy and transition
functions, but isn’t used in the computation of moments and of Impulse Response Functions. Setting a variance to
zero is an easy way of removing an exogenous shock.
Note that, by default, if there are several shocks or mshocks blocks in the same .mod file, then they are cumulative:
all the shocks declared in all the blocks are considered; however, if a shocks or mshocks block is declared with
the overwrite option, then it replaces all the previous shocks and mshocks blocks.
Block: shocks ;
Block: shocks(overwrite);
See above for the meaning of the overwrite option.
In deterministic context
For deterministic simulations, the shocks block specifies temporary changes in the value of exogenous
variables. For permanent shocks, use an endval block.
The block should contain one or more occurrences of the following group of three lines:
var VARIABLE_NAME;
periods INTEGER[:INTEGER] [[,] INTEGER[:INTEGER]]...;
values DOUBLE | (EXPRESSION) [[,] DOUBLE | (EXPRESSION) ]...;
It is possible to specify shocks which last several periods and which can vary over time. The periods
keyword accepts a list of several dates or date ranges, which must be matched by as many shock values in
the values keyword. Note that a range in the periods keyword can be matched by only one value in the
values keyword. If values represents a scalar, the same value applies to the whole range. If values
represents a vector, it must have as many elements as there are periods in the range.
Note that shock values are not restricted to numerical constants: arbitrary expressions are also allowed, but
you have to enclose them inside parentheses.
The feasible range of periods is from 0 to the number of periods specified in
perfect_foresight_setup.
Warning: Note that the first endogenous simulation period is period 1. Thus, a shock value specified
for the initial period 0 may conflict with (i.e. may overwrite or be overwritten by) values for the initial
period specified with initval or endval (depending on the exact context). Users should always verify
the correct setting of oo_.exo_simul after perfect_foresight_setup.
shocks;
var e;
(continues on next page)
end;
shocks;
var e;
periods 1:3;
values (xx);
end;
In stochastic context
For stochastic simulations, the shocks block specifies the non zero elements of the covariance matrix of the
shocks of exogenous variables.
You can use the following types of entries in the block:
• Specification of the standard error of an exogenous variable.
In an estimation context, it is also possible to specify variances and covariances on endogenous variables: in
that case, these values are interpreted as the calibration of the measurement errors on these variables. This
requires the varobs command to be specified before the shocks block.
Example
shocks;
var e = 0.000081;
var u; stderr 0.009;
corr e, u = 0.8;
var v, w = 2;
end;
shocks;
var u; stderr 0.008;
var u;
periods 1;
values 1;
end;
varexo_det tau;
varexo e;
...
shocks;
var e; stderr 0.01;
var tau;
periods 1:9;
values -0.15;
end;
stoch_simul(irf=0);
forecast;
Block: mshocks ;
Block: mshocks(OPTIONS...);
The purpose of this block is similar to that of the shocks block for deterministic shocks, except that the
numeric values given will be interpreted in a multiplicative way. For example, if a value of 1.05 is given as
shock value for some exogenous at some date, it means 5% above its steady state value.
If no endval block is present, the steady state as specified in the initval block is used as the basis for the
multiplication. If an endval block is present, the terminal steady state as specified in the endval block will
be used as the basis for the multiplication (unless the relative_to_initval option is passed).
The syntax is the same as shocks in a deterministic context.
This command is only meaningful in two situations:
• on exogenous variables with a non-zero steady state, in a deterministic setup,
• on deterministic exogenous variables with a non-zero steady state, in a stochastic setup.
Options
overwrite
Same meaning as in the shocks block.
relative_to_initval
If an endval block is present, the initial steady state as specified in the initval block will be used as
the basis for multiplication (instead of the terminal steady state).
Block: heteroskedastic_shocks ;
Block: heteroskedastic_shocks(overwrite);
In estimation context, it implements heteroskedastic filters, where the standard error of shocks may unexpect-
edly change in every period. The standard deviation of shocks may be either provided directly or set/modified
in each observed period by a scale factor. If std0 is the usual standard error for shock1, then:
• using a scale factor in period t implies: std(shock1|t)=std0(shock1)*scale(t)
• using a provided value in period t implies: std(shock1|t)=value(t).
The block has a similar syntax as the shocks block in a perfect foresight context. It should contain one or
more occurrences of the following group of three lines (for setting values):
var VARIABLE_NAME;
periods INTEGER[:INTEGER] [[,] INTEGER[:INTEGER]]...;
values DOUBLE | (EXPRESSION) [[,] DOUBLE | (EXPRESSION) ]...;
var VARIABLE_NAME;
periods INTEGER[:INTEGER] [[,] INTEGER[:INTEGER]]...;
scales DOUBLE | (EXPRESSION) [[,] DOUBLE | (EXPRESSION) ]...;
NOTE: scales and values cannot be simultaneously set for the same shock in the same period, but it is
possible to set values for some periods and scales for other periods for the same shock. There can be
only one scales and values directive each for a given shock, so all affected periods must be set in one
statement.
Example
heteroskedastic_shocks;
var e1;
periods 86:87, 89:97;
scales 0.5, 0;
var e1;
periods 88;
values 0.1;
var e2;
periods 86:87 88:97;
values 0.04 0.01;
end;
There are two ways of computing the steady state (i.e. the static equilibrium) of a model. The first way is to let
Dynare compute the steady state using a nonlinear Newton-type solver; this should work for most models, and is
relatively simple to use. The second way is to give more guidance to Dynare, using your knowledge of the model,
by providing it with a method to compute the steady state, either using a steady_state_model block or writing
matlab routine.
Command: steady ;
Command: steady(OPTIONS...);
This command computes the steady state of a model using a nonlinear Newton-type solver and displays it.
When a steady state file is used steady displays the steady state and checks that it is a solution of the static
model.
More precisely, it computes the equilibrium value of the endogenous variables for the value of the exogenous
variables specified in the previous initval or endval block.
steady uses an iterative procedure and takes as initial guess the value of the endogenous variables set in the
previous initval or endval block.
For complicated models, finding good numerical initial values for the endogenous variables is the trickiest
part of finding the equilibrium of that model. Often, it is better to start with a smaller model and add new
variables one by one.
Options
maxit = INTEGER
Determines the maximum number of iterations used in the non-linear solver. The default value of
maxit is 50.
tolf = DOUBLE
Convergence criterion for termination based on the function value. Iteration will cease when the resid-
uals are smaller than tolf. Default: eps^(1/3)
tolx = DOUBLE
Convergence criterion for termination based on the step tolerance along. Iteration will cease when the
attempted step size is smaller than tolx. Default: eps^(2/3)
solve_algo = INTEGER
Determines the non-linear solver to use. Possible values for the option are:
0
Use fsolve (under MATLAB, only available if you have the Optimization Toolbox;
always available under Octave).
1
Use a Newton-like algorithm with line-search.
2
Splits the model into recursive blocks and solves each block in turn using the same
solver as value 1.
3
Use Chris Sims’ solver.
4
Splits the model into recursive blocks and solves each block in turn using a trust-
region solver with autoscaling.
5
Newton algorithm with a sparse Gaussian elimination (SPE) solver at each iteration
(requires bytecode option, see Model declaration).
6
Newton algorithm with a sparse LU solver at each iteration (requires bytecode
and/or block option, see Model declaration).
7
Newton algorithm with a Generalized Minimal Residual (GMRES) solver at each
iteration (requires bytecode and/or block option, see Model declaration).
8
Newton algorithm with a Stabilized Bi-Conjugate Gradient (BiCGStab) solver at each
iteration (requires bytecode and/or block option, see Model declaration).
9
Trust-region algorithm with autoscaling (same as value 4, but applied to the entire
model, without splitting).
10
Levenberg-Marquardt mixed complementarity problem (LMMCP) solver (Kanzow
and Petra (2004)). The complementarity conditions are specified with an mcp equa-
tion tag, see lmmcp.
11
PATH mixed complementarity problem solver of Ferris and Munson (1999). The
complementarity conditions are specified with an mcp equation tag, see lmmcp.
Dynare only provides the interface for using the solver. Due to licence restric-
tions, you have to download the solver’s most current version yourself from http:
//pages.cs.wisc.edu/~ferris/path.html and place it in MATLAB’s search path.
12
Computes a block decomposition and then applies a Newton-type solver on those
smaller blocks rather than on the full nonlinear system. This is similar to 2, but is
typically more efficient. The block decomposition is done at the preprocessor level,
which brings two benefits: it identifies blocks that can be evaluated rather than solved;
and evaluations of the residual and Jacobian of the model are more efficient because
only the relevant elements are recomputed at every iteration. This option is typically
used with the perfect_foresight_solver command with purely backward, for-
ward or static models, or with routines for semi-structural models, and it must not be
combined with option block of the model block. Also note that for those models, the
block decomposition is performed as if mfs=3 had been passed to the model block,
and the decomposition is slightly different because it is computed in a time-recursive
fashion (i.e. in such a way that the simulation is meant to be done with the outer loop
on periods and the inner loop on blocks; while for models with both leads and lags,
the outer loop is on blocks and the inner loop is on periods).
14
Same as 12, except that it applies a trust region solver (similar to 4) to the blocks.
Default value is 4.
homotopy_mode = INTEGER
Use a homotopy (or divide-and-conquer) technique to solve for the steady state. If you use this option,
you must specify a homotopy_setup block. This option can take three possible values:
0
Do not use homotopy.
1
In this mode, all the parameters are changed simultaneously, and the distance between
the boundaries for each parameter is divided in as many intervals as there are steps
(as defined by the homotopy_steps option); the problem is solved as many times as
there are steps.
2
Same as mode 1, except that only one parameter is changed at a time; the problem is
solved as many times as steps times number of parameters.
3
Dynare tries first the most extreme values. If it fails to compute the steady state, the
interval between initial and desired values is divided by two for all parameters. Every
time that it is impossible to find a steady state, the previous interval is divided by two.
When it succeeds to find a steady state, the previous interval is multiplied by two.
In that last case homotopy_steps contains the maximum number of computations
attempted before giving up.
Default value is 0.
homotopy_steps = INTEGER
Defines the number of steps when performing a homotopy. See homotopy_mode option for more
details. Default is 10.
homotopy_force_continue = INTEGER
This option controls what happens when homotopy fails.
0
steady fails with an error message
1
steady keeps the values of the last homotopy step that was successful and contin-
ues. BE CAREFUL: parameters and/or exogenous variables are NOT at the value
expected by the user
Default is 0.
nocheck
Don’t check the steady state values when they are provided explicitly either by a steady state file or a
steady_state_model block. This is useful for models with unit roots as, in this case, the steady state
is not unique or doesn’t exist.
markowitz = DOUBLE
Value of the Markowitz criterion (in the interval (0, ∞)) used to select the pivot with sparse Gaus-
sian elimination (solve_algo = 5). This criterion governs the tradeoff between selecting the pivot
resulting in the most accurate solution (low markowitz values) and the one that preserves maximum
sparsity (high markowitz values). Default: 0.5.
This syntax specifies the initial and final values of a given parameter/exogenous.
There is an alternative syntax:
VARIABLE_NAME, EXPRESSION;
Here only the final value is specified for a given parameter/exogenous; the initial value is taken from the
preceeding initval block (or from the preceeding endval block if there is one before the homotopy_setup
block).
A necessary condition for a successful homotopy is that Dynare must be able to solve the steady state for
the initial parameters/exogenous without additional help (using the guess values given in the initval or
endval block).
The from_initval_to_endval option can be used in the context of a permanent shock, when the initial
steady state has already been computed. This option can be used following the endval block that describes
the terminal steady state. In that case, in the subsequent steady command, Dynare will perform a ho-
motopy from the initial to the terminal steady state (technically, using this option is equivalent to writing
a homotopy_setup block where all exogenous variables are asked to transition from their values in the
initval to their values in the endval block). When this option is used, the homotopy_setup block is
typically empty (but it’s nevertheless possible to add explicit directives for moving exogenous or parameters;
these will be added on top of those implicitly generated by the from_initval_to_endval option).
If the homotopy fails, a possible solution is to increase the number of steps (given in homotopy_steps
option of steady).
Example
In the following example, Dynare will first compute the steady state for the initial values (gam=0.5 and x=1),
and then subdivide the problem into 50 smaller problems to find the steady state for the final values (gam=2
and x=2):
var c k;
varexo x;
model;
c + k - aa*x*k(-1)^alph - (1-delt)*k(-1);
c^(-gam) - (1+bet)^(-1)*(aa*alph*x(+1)*k^(alph-1) + 1 - delt)*c(+1)^(-gam);
end;
initval;
x = 1;
k = ((delt+bet)/(aa*x*alph))^(1/(alph-1));
c = aa*x*k^alph-delt*k;
end;
homotopy_setup;
gam, 0.5, 2;
x, 2;
end;
If you know how to compute the steady state for your model, you can provide a MATLAB/Octave function doing
the computation instead of using steady. Again, there are two options for doing that:
• The easiest way is to write a steady_state_model block, which is described below in more details. See
also fs2000.mod in the examples directory for an example. The steady state file generated by Dynare will
be called +FILENAME/steadystate.m.
• You can write the corresponding MATLAB function by hand. If your .mod file is called FILENAME.mod,
the steady state file must be called FILENAME_steadystate.m. See NK_baseline_steadystate.m in the
examples directory for an example. This option gives a bit more flexibility (loops and conditional structures
can be used), at the expense of a heavier programming burden and a lesser efficiency.
Note that both files allow to update parameters in each call of the function. This allows for example to calibrate a
model to a labor supply of 0.2 in steady state by setting the labor disutility parameter to a corresponding value (see
NK_baseline_steadystate.m in the examples directory). They can also be used in estimation where some
parameter may be a function of an estimated parameter and needs to be updated for every parameter draw. For
example, one might want to set the capital utilization cost parameter as a function of the discount rate to ensure
that capacity utilization is 1 in steady state. Treating both parameters as independent or not updating one as a
function of the other would lead to wrong results. But this also means that care is required. Do not accidentally
overwrite your parameters with new values as it will lead to wrong results.
Block: steady_state_model ;
When the analytical solution of the model is known, this command can be used to help Dynare find the
steady state in a more efficient and reliable way, especially during estimation where the steady state has to
be recomputed for every point in the parameter space.
Each line of this block consists of a variable (either an endogenous, a temporary variable or a parameter)
which is assigned an expression (which can contain parameters, exogenous at the steady state, or any en-
dogenous or temporary variable already declared above). Each line therefore looks like:
VARIABLE_NAME = EXPRESSION;
Note that it is also possible to assign several variables at the same time, if the main function in the right hand
side is a MATLAB/Octave function returning several arguments:
Dynare will automatically generate a steady state file (of the form +FILENAME/steadystate.m) using the
information provided in this block.
Steady state file for deterministic models
The steady_state_model block also works with deterministic models. An initval block and, when
necessary, an endval block, is used to set the value of the exogenous variables. Each initval or endval
block must be followed by steady to execute the function created by steady_state_model and set the
initial, respectively terminal, steady state.
Example
...
// parameter calibration, (dynamic) model declaration, shock calibration.
˓→..
...
steady_state_model;
dA = exp(gam);
gst = 1/dA; // A temporary variable
m = mst;
n = xist/(nust+xist);
P = xist + nust;
k = khst*n;
l = psi*mst*n/( (1-psi)*(1-n) );
c = mst/P;
d = l - mst + 1;
y = k^alp*n^(1-alp)*gst^alp;
R = mst/bet;
(continues on next page)
gp_obs = m/dA;
gy_obs = dA;
end;
steady;
When there is no steady state file, Dynare computes the steady state by solving the static model, i.e. the model
from the .mod file from which leads and lags have been removed.
In some specific cases, one may want to have more control over the way this static model is created. Dynare
therefore offers the possibility to explicitly give the form of equations that should be in the static model.
More precisely, if an equation is prepended by a [static] tag, then it will appear in the static model used for steady
state computation, but that equation will not be used for other computations. For every equation tagged in this way,
you must tag another equation with [dynamic]: that equation will not be used for steady state computation, but
will be used for other computations.
This functionality can be useful on models with a unit root, where there is an infinity of steady states. An equation
(tagged [dynamic]) would give the law of motion of the nonstationary variable (like a random walk). To pin down
one specific steady state, an equation tagged [static] would affect a constant value to the nonstationary variable.
Another situation where the [static] tag can be useful is when one has only a partial closed form solution for
the steady state.
Example
This is a trivial example with two endogenous variables. The second equation takes a different form in the static
model:
var c k;
varexo x;
...
model;
c + k - aa*x*k(-1)^alph - (1-delt)*k(-1);
[dynamic] c^(-gam) - (1+bet)^(-1)*(aa*alph*x(+1)*k^(alph-1) + 1 - delt)*c(+1)^(-gam);
[static] k = ((delt+bet)/(x*aa*alph))^(1/(alph-1));
end;
Command: check ;
Command: check(OPTIONS...);
Computes the eigenvalues of the model linearized around the values specified by the last initval, endval
or steady statement. Generally, the eigenvalues are only meaningful if the linearization is done around a
steady state of the model. It is a device for local analysis in the neighborhood of this steady state.
A necessary condition for the uniqueness of a stable equilibrium in the neighborhood of the steady state is that
there are as many eigenvalues larger than one in modulus as there are forward looking variables in the system.
An additional rank condition requires that the square submatrix of the right Schur vectors corresponding to
the forward looking variables (jumpers) and to the explosive eigenvalues must have full rank.
Note that the outcome may be different from what would be suggested by sum(abs(oo_.dr.eigval))
when eigenvalues are very close to qz_criterium.
Options
solve_algo = INTEGER
See solve_algo, for the possible values and their meaning.
qz_zero_threshold = DOUBLE
Value used to test if a generalized eigenvalue is 0/0 in the generalized Schur decomposition (in which
case the model does not admit a unique solution). Default: 1e-6.
Output
check returns the eigenvalues in the global variable oo_.dr.eigval.
MATLAB/Octave variable: oo_.dr.eigval
Contains the eigenvalues of the model, as computed by the check command.
Command: model_diagnostics ;
This command performs various sanity checks on the model, and prints a message if a problem is detected
(missing variables at current period, invalid steady state, singular Jacobian of static model).
Command: model_info ;
Command: model_info(OPTIONS...);
This command provides information about the model. By default, it will provide a list of predetermined state
variables, forward-looking variables, and purely static variables.
The command also allows to display information on the dynamic and static versions of the block decompo-
sition of the model:
• The normalization of the model: an endogenous variable is attributed to each equation of the model
(the dependent variable);
• The block structure of the model: for each block model_info indicates its type, size as well as the
equation number(s) or name tags and endogenous variables belonging to this block.
There are five different types of blocks depending on the simulation method used:
• EVALUATE FORWARD
In this case the block contains only equations where the dependent variable 𝑗 attributed to the equation
appears contemporaneously on the left hand side and where no forward looking endogenous variables
appear. The block has the form: 𝑦𝑗,𝑡 = 𝑓𝑗 (𝑦𝑡 , 𝑦𝑡−1 , . . . , 𝑦𝑡−𝑘 ).
• EVALUATE BACKWARD
The block contains only equations where the dependent variable 𝑗 attributed to the equation appears
contemporaneously on the left hand side and where no backward looking endogenous variables appear.
The block has the form: 𝑦𝑗,𝑡 = 𝑓𝑗 (𝑦𝑡 , 𝑦𝑡+1 , . . . , 𝑦𝑡+𝑘 ).
• SOLVE BACKWARD x
The block contains only equations where the dependent variable 𝑗 attributed to the equation does not
appear contemporaneously on the left hand side and where no forward looking endogenous variables
appear. The block has the form: 𝑔𝑗 (𝑦𝑗,𝑡 , 𝑦𝑡 , 𝑦𝑡−1 , . . . , 𝑦𝑡−𝑘 ) = 0. Here, x denotes the subtype of the
block. x is equal to SIMPLE if the block has only one equation. If several equations appear in the block,
x is equal to COMPLETE.
• SOLVE FORWARD x
The block contains only equations where the dependent variable 𝑗 attributed to the equation does not
appear contemporaneously on the left hand side and where no backward looking endogenous variables
appear. The block has the form: 𝑔𝑗 (𝑦𝑗,𝑡 , 𝑦𝑡 , 𝑦𝑡+1 , . . . , 𝑦𝑡+𝑘 ) = 0. Here, x denotes the subtype of the
block. x is equal to SIMPLE if the block has only one equation. If several equations appear in the block,
x is equal to COMPLETE.
When the framework is deterministic, Dynare can be used for models with the assumption of perfect foresight. Typ-
ically, the system is supposed to be in a state of equilibrium before a period 1 when the news of a contemporaneous
or of a future shock is learned by the agents in the model. The purpose of the simulation is to describe the reaction
in anticipation of, then in reaction to the shock, until the system returns to the old or to a new state of equilibrium.
In most models, this return to equilibrium is only an asymptotic phenomenon, which one must approximate by an
horizon of simulation far enough in the future. Another exercise for which Dynare is well suited is to study the
transition path to a new equilibrium following a permanent shock. For deterministic simulations, the numerical
problem consists of solving a nonlinear system of simultaneous equations in n endogenous variables in T periods.
Dynare offers several algorithms for solving this problem, which can be chosen via the stack_solve_algo op-
tion. By default (stack_solve_algo=0), Dynare uses a Newton-type method to solve the simultaneous equation
system. Because the resulting Jacobian is in the order of n by T and hence will be very large for long simulations
with many variables, Dynare makes use of the sparse matrix capacities of MATLAB/Octave. A slower but po-
tentially less memory consuming alternative (stack_solve_algo=1) is based on a Newton-type algorithm first
proposed by Laffargue (1990) and Boucekkine (1995), which avoids ever storing the full Jacobian. The details of
the algorithm can be found in Juillard (1996). The third type of algorithms makes use of block decomposition
techniques (divide-and-conquer methods) that exploit the structure of the model. The principle is to identify re-
cursive and simultaneous blocks in the model structure and use this information to aid the solution process. These
solution algorithms can provide a significant speed-up on large models.
Warning: Be careful when employing auxiliary variables in the context of perfect foresight computations.
The same model may work for stochastic simulations, but fail for perfect foresight simulations. The issue arises
when an equation suddenly only contains variables dated t+1 (or t-1 for that matter). In this case, the derivative
in the last (first) period with respect to all variables will be 0, rendering the stacked Jacobian singular.
Example
Consider the following specification of an Euler equation with log utility:
Lambda = beta*C(-1)/C;
Lambda(+1)*R(+1)= 1;
Clearly, the derivative of the second equation with respect to all endogenous variables at time t
is zero, causing perfect_foresight_solver to generally fail. This is due to the use of the
Lagrange multiplier Lambda as an auxiliary variable. Instead, employing the identical
beta*C/C(+1)*R(+1)= 1;
will work.
Command: perfect_foresight_setup ;
Command: perfect_foresight_setup(OPTIONS...);
Prepares a perfect foresight simulation, by extracting the information in the initval, endval and shocks
blocks and converting them into simulation paths for exogenous and endogenous variables.
This command must always be called before running the simulation with perfect_foresight_solver.
Options
periods = INTEGER
Number of periods of the simulation.
datafile = FILENAME
Used to specify path for all endogenous and exogenous variables. Strictly equivalent to initval_file.
Output
The paths for the exogenous variables are stored into oo_.exo_simul.
The initial and terminal conditions for the endogenous variables and the initial guess for the path of endoge-
nous variables are stored into oo_.endo_simul.
Command: perfect_foresight_solver ;
Command: perfect_foresight_solver(OPTIONS...);
Computes the perfect foresight (or deterministic) simulation of the model.
Note that perfect_foresight_setup must be called before this command, in order to setup the environ-
ment for the simulation.
If the perfect foresight solver cannot directly find the solution of the problem, it subsequently tries a homotopy
technique (unless the no_homotopy option is given). Concretely, this technique consists in dividing the
problem into smaller steps by diminishing the size of shocks and increasing them progressively until the
problem converges.
Options
maxit = INTEGER
Determines the maximum number of iterations used in the non-linear solver. The default value of
maxit is 50.
tolf = DOUBLE
Convergence criterion for termination based on the function value. Iteration will cease when it proves
impossible to improve the function value by more than tolf. Default: 1e-5
tolx = DOUBLE
Convergence criterion for termination based on the change in the function argument. Iteration will
cease when the solver attempts to take a step that is smaller than tolx. Default: 1e-5
noprint
Don’t print anything. Useful for loops.
print
Print results (opposite of noprint).
stack_solve_algo = INTEGER
Algorithm used for computing the solution. Possible values are:
0
Use a Newton algorithm with a direct sparse LU solver at each iteration, applied to
the stacked system of all equations in all periods (Default).
1
Use the Laffargue-Boucekkine-Juillard (LBJ) algorithm proposed in Juillard (1996)
on top of a LU solver. It is slower than stack_solve_algo=0, but may be less
memory consuming on big models. Note that if the block option is used (see Model
declaration), a simple Newton algorithm with sparse matrices, applied to the stacked
system of all block equations in all periods, is used for blocks which are purely back-
ward or forward (of type SOLVE BACKWARD or SOLVE FORWARD, see model_info),
since LBJ only makes sense on blocks with both leads and lags (of type SOLVE TWO
BOUNDARIES).
2
Use a Newton algorithm with a Generalized Minimal Residual (GMRES) solver at
each iteration, applied on the stacked system of all equations in all periods (requires
bytecode and/or block option, see Model declaration)
3
Use a Newton algorithm with a Stabilized Bi-Conjugate Gradient (BiCGStab) solver
at each iteration, applied on the stacked system of all equations in all periods (requires
bytecode and/or block option, see Model declaration).
4
Use a Newton algorithm with a direct sparse LU solver and an optimal path length at
each iteration, applied on the stacked system of all equations in all periods (requires
bytecode and/or block option, see Model declaration).
5
Use the Laffargue-Boucekkine-Juillard (LBJ) algorithm proposed in Juillard (1996)
on top of a sparse Gaussian elimination (SPE) solver. The latter takes advantage of
the similarity of the Jacobian across periods when searching for the pivots (requires
bytecode option, see Model declaration).
6
Synonymous for stack_solve_algo=1. Kept for backward compatibility.
7
Allows the user to solve the perfect foresight model with the solvers available through
option solve_algo, applied on the stacked system of all equations in all periods (See
solve_algo for a list of possible values, note that values 5, 6, 7 and 8, which require
bytecode and/or block options, are not allowed). For instance, the following com-
mands:
perfect_foresight_setup(periods=400);
perfect_foresight_solver(stack_solve_algo=7, solve_algo=9)
solve_algo
See solve_algo. Allows selecting the solver used with stack_solve_algo=7. Also used for purely
backward, forward and static models (when neither the block nor the bytecode option of the model
block is specified); for those models, the values 12 and 14 are especially relevant.
no_homotopy
This option tells Dynare to not try a homotopy technique (as described above) if the problem cannot
be solved directly.
homotopy_initial_step_size = DOUBLE
Specifies which share of the shock should be applied in the first iteration of the homotopy procedure.
This option is useful when it is known that immediately trying 100% of the shock will fail, so as to
save computing time. Must be between 0 and 1. Default: 1.
homotopy_min_step_size = DOUBLE
The homotopy procedure halves the size of the step whenever there is a failure. This option specifies
the minimum step size under which the homotopy procedure is considered to have failed. Default:
0.001.
homotopy_step_size_increase_success_count = INTEGER
Specifies after how many consecutive successful iterations the homotopy procedure should double the
size of the step. A zero value means that the step size should never be increased. Default: 3.
homotopy_linearization_fallback
Whenever the homotopy procedure is not able to find a solution for 100% of the shock, but is able
to find one for a smaller share, instructs Dynare to compute an approximate solution by rescaling the
solution obtained for a fraction of the shock, as if the reaction of the model to the shock was a linear
function of the size of that shock. More formally, if 𝑠 is the share of the shock applied (between 0 and
1), 𝑦(𝑠) is the value of a given endogenous variable at a given period as a function of 𝑠 (in particular,
𝑦(1) corresponds to the exact solution of the problem), and 𝑠* is the greatest share of the shock for
which the homotopy procedure has been able to find a solution, then the approximate solution returned
*
is 𝑦(𝑠 )−𝑦(0)
𝑠* .
homotopy_marginal_linearization_fallback [= DOUBLE]
Whenever the homotopy procedure is not able to find a solution for 100% of the shock, but is able to
find one for a smaller share, instructs Dynare to compute an approximate solution obtained by rescaling
the solution obtained for a fraction of the shock, obtained as if the reaction of the model to the shock
was, at the margin, a linear function of the size of that shock. More formally, if 𝑠 is the share of the
shock applied (between 0 and 1), 𝑦(𝑠) is the value of a given endogenous variable at a given period as
a function of 𝑠 (in particular, 𝑦(1) corresponds to the exact solution of the problem), 𝑠* is the greatest
share of the shock for which the homotopy procedure has been able to find a solution, and 𝜖 is a small
* *
−𝜖)
step size, then the approximate solution returned is 𝑦(𝑠* ) + (1 − 𝑠* ) 𝑦(𝑠 )−𝑦(𝑠
𝜖 . The value of 𝜖 is
0.01 by default, but can be modified by passing some other value to the option.
homotopy_max_completion_share = DOUBLE
Instructs Dynare, within the homotopy procedure, to not try to compute the solution for
a greater share than the one given as the option value. This option only makes sense
when used in conjunction with either the homotopy_linearization_fallback or the
homotopy_marginal_linearization_fallback option. It is typically used in situations
where it is known that homotopy will fail to go beyond a certain point, so as to save computing time,
while at the same time getting an approximate solution.
markowitz = DOUBLE
Value of the Markowitz criterion, used to select the pivot. Only used when stack_solve_algo = 5.
Default: 0.5.
minimal_solving_periods = INTEGER
Specify the minimal number of periods where the model has to be solved, before using a constant set
of operations for the remaining periods. Only used when stack_solve_algo = 5. Default: 1.
lmmcp
Solves the perfect foresight model with a Levenberg-Marquardt mixed complementarity problem
(LMMCP) solver (Kanzow and Petra (2004)), which allows to consider inequality constraints on the en-
dogenous variables (such as a ZLB on the nominal interest rate or a model with irreversible investment).
This option is equivalent to stack_solve_algo=7 and solve_algo=10. Using the LMMCP solver
avoids the need for min/max operators and explicit complementary slackness conditions in the model
as they will typically introduce a singularity into the Jacobian. This is done by setting the problem up
as a mixed complementarity problem (MCP) of the form:
𝐿𝐵 = 𝑋 ⇒ 𝐹 (𝑋) > 0
𝐿𝐵 ≤ 𝑋 ≤ 𝑈 𝐵 ⇒ 𝐹 (𝑋) = 0
𝑋 = 𝑈 𝐵 ⇒ 𝐹 (𝑋) < 0.
where 𝑋 denotes the vector of endogenous variables, 𝐹 (𝑋) the equations of the model, 𝐿𝐵 denotes a
lower bound, and 𝑈 𝐵 an upper bound. Such a setup is implemented by attaching an equation tag (see
Model declaration) with the mcp keyword to the affected equations. This tag states that the equation to
which the tag is attached has to hold unless the inequality constraint within the tag is binding.
For instance, a ZLB on the nominal interest rate would be specified as follows in the model block:
model;
...
[mcp = 'r > -1.94478']
r = rho*r(-1) + (1-rho)*(gpi*Infl+gy*YGap) + e;
...
end;
where 1.94478 is the steady state level of the nominal interest rate and r is the nominal interest rate
in deviation from the steady state. This construct implies that the Taylor rule is operative, unless the
implied interest rate r<=-1.94478, in which case the r is fixed at -1.94478 (thereby being equivalent
to a complementary slackness condition). By restricting the value of r coming out of this equation, the
mcp tag also avoids using max(r,-1.94478) for other occurrences of r in the rest of the model. Two
things are important to keep in mind. First, because the mcp tag effectively replaces a complementary
slackness condition, it cannot be simply attached to any equation. Rather, it must be attached to the
correct affected equation as otherwise the solver will solve a different problem than originally intended.
Second, the sign of the residual of the dynamic equation must conform to the MCP setup outlined
above. In case of the ZLB, we are dealing with a lower bound. Consequently, the dynamic equation
needs to return a positive residual. Dynare by default computes the residual of an equation LHS=RHS as
residual=LHS-RHS, while an implicit equation LHS is interpreted as LHS=0. For the above equation
this implies
residual= r - (rho*r(-1) + (1-rho)*(gpi*Infl+gy*YGap) + e);
which is correct, since it will be positive if the implied interest rate rho*r(-1) +
(1-rho)*(gpi*Infl+gy*YGap) + e is below r=-1.94478. In contrast, specifying the equa-
tion as
rho*r(-1) + (1-rho)*(gpi*Infl+gy*YGap) + e = r;`
would be wrong.
Note that in the current implementation, the content of the mcp equation tag is not parsed by the pre-
processor. The inequalities must therefore be as simple as possible: an endogenous variable, followed
by a relational operator, followed by a number (not a variable, parameter or expression).
endogenous_terminal_period
The number of periods is not constant across Newton iterations when solving the perfect foresight
model. The size of the nonlinear system of equations is reduced by removing the portion of the paths
(and associated equations) for which the solution has already been identified (up to the tolerance pa-
rameter). This strategy can be interpreted as a mix of the shooting and relaxation approaches. Note
that round off errors are more important with this mixed strategy (user should check the reported value
of the maximum absolute error). Only available with option stack_solve_algo==0.
linear_approximation
Solves the linearized version of the perfect foresight model. The model must be stationary and a
steady state needs to be provided. Linearization is conducted about the last defined steady state,
which can derive from initval, endval or a subsequent steady. Only available with option
stack_solve_algo==0 or stack_solve_algo==7.
endval_steady
In scenarios with a permanent shock, specifies that the terminal condition is a steady state, even
if the steady command has not been called after the endval block. As a consequence, the
perfect_foresight_solver command will compute the terminal steady state itself (given the value
of the exogenous variables given in the endval block). In practice, this option is useful when the perma-
nent shock is very large, in which case the homotopy procedure inside perfect_foresight_solver
will find both the terminal steady state and the transitional dynamics within the same loop (which is
less costly than first computing the terminal steady state by homotopy, then computing the transitional
dynamics by homotopy).
steady_solve_algo = INTEGER
See solve_algo. Used when computing the terminal steady state when option endval_steady has
been specified to the perfect_foresight_setup command.
steady_tolf = DOUBLE
See tolf . Used when computing the terminal steady state when option endval_steady has been
specified to the perfect_foresight_setup command.
steady_tolx = DOUBLE
See tolx. Used when computing the terminal steady state when option endval_steady has been
specified to the perfect_foresight_setup command.
steady_maxit = INTEGER
See maxit. Used when computing the terminal steady state when option endval_steady has been
specified to the perfect_foresight_setup command.
steady_markowitz = DOUBLE
See markowitz. Used when computing the terminal steady state when option endval_steady has
been specified to the perfect_foresight_setup command.
Output
The simulated endogenous variables are available in global matrix oo_.endo_simul.
Command: simul ;
Command: simul(OPTIONS...);
This command is deprecated. It is strictly equivalent to a call to perfect_foresight_setup followed by
a call to perfect_foresight_solver.
Options
Accepts all the options of perfect_foresight_setup and perfect_foresight_solver.
MATLAB/Octave variable: oo_.endo_simul
This variable stores the result of a deterministic simulation (computed by perfect_foresight_solver
or simul) or of a stochastic simulation (computed by stoch_simul with the periods option or by
extended_path). The variables are arranged row by row, in order of declaration (as in M_.endo_names).
Note that this variable also contains initial and terminal conditions, so it has more columns than the value of
the periods option: the first simulation period is in column 1+M_.maximum_lag, and the total number of
columns is M_.maximum_lag+periods+M_.maximum_lead.
The solution under perfect foresight that was presented in the previous section makes the assumption that agents
learn the complete path of future shocks in period 1, without making any expectation errors.
One may however want to study a scenario where it turns out that agents make expectation errors, in the sense that
the path they had anticipated in period 1 does not realize exactly. More precisely, in some simulation periods, they
may receive new information that makes them revise their anticipation for the path of future shocks. Also, under
this scenario, it is assumed that agents behave as under perfect foresight, i.e. they take their decisions as if there
was no uncertainty and they knew exactly the path of future shocks; the new information that they may receive
comes as a total surprise to them.
Such a scenario can be solved by Dynare using the perfect_foresight_with_expectation_errors_setup
and perfect_foresight_with_expectation_errors_solver commands, alongside shocks and endval
blocks which are given a special learnt_in option.
Block: shocks(learnt_in=INTEGER) ;
Block: shocks(learnt_in=INTEGER,overwrite) ;
The shocks(learnt_in=INTEGER) syntax can be used to specify temporary shocks that are learnt in a
specific period. It should contain one or more occurences of the following group of three lines, with the
same semantics as a regular shocks block:
var VARIABLE_NAME;
periods INTEGER[:INTEGER] [[,] INTEGER[:INTEGER]]...;
values DOUBLE | (EXPRESSION) [[,] DOUBLE | (EXPRESSION) ]...;
If the period in which information is learnt is greater or equal than 2, then it is possible to specify the shock
values in deviation with respect to the values that were expected from the perspective of the previous period.
If the new information consists of an addition to the previously-anticipated value, the values keyword can be
replaced by the add keyword; similarly, if the new information consists of a multiplication of the previously-
anticipated value, the values keyword can be replaced by the multiply keyword.
The overwrite option says that this block cancels and replaces previous shocks and mshocks blocks that
have the same learnt_in option.
Note that a shocks(learnt_in=1) block is equivalent to a regular shocks block.
Example
shocks(learnt_in=1);
var x;
periods 1:2 3:4 5;
values 1 1.2 1.4;
end;
shocks(learnt_in=2);
var x;
periods 3:4;
add 0.1;
end;
shocks(learnt_in=4);
var x;
periods 5;
multiply 2;
end;
endval(learnt_in = 3);
x = 1.1;
y += 0.1;
z *= 2;
end;
var VARIABLE_NAME;
periods INTEGER[:INTEGER] [[,] INTEGER[:INTEGER]]...;
values DOUBLE | (EXPRESSION) [[,] DOUBLE | (EXPRESSION) ]...;
As in the regular mshocks block (without the learnt_in option), the values are interpreted as a multi-
plicative factor over the steady state value of the exogenous variable (the latter being taken either from the
initval or endval, see mshocks for the details).
If the terminal steady state as specified in the endval block is used as a basis for the multiplication, its value
as anticipated from the period given in the learnt_in option will be used.
Note that a mshocks(learnt_in=1) block is equivalent to a regular mshocks block.
Options
overwrite
This block cancels and replaces previous shocks and mshocks blocks that have the same learnt_in
option.
relative_to_initval
Same meaning as in the regular mshocks block.
Example
mshocks(learnt_in=2);
var x;
periods 3:4;
values 1.1;
end;
This syntax means that from the perspective of period 2, x in periods 3 and 4 is expected to be equal to 1.1
times its steady state. If there is no endval block, the initial steady state as given by initval is used; if
there is an endval block, the terminal steady state as anticipated from the perspective of period 2 is used (as
specified in the relevant endval(learnt_in=... block)).
Command: perfect_foresight_with_expectation_errors_setup ;
Command: perfect_foresight_with_expectation_errors_setup(OPTIONS...);
Prepares a perfect foresight simulation with expectation errors, by extracting the contents of the initval,
endval and shocks blocks (the latter two types of blocks typically used with the learnt_in option);
alternatively, the information about future shocks can be given in a CSV file using the datafile option.
This command must always be called before running the simulation with
perfect_foresight_with_expectation_errors_solver.
Note that this command makes the assumption that the terminal condition is always a steady state. Hence,
it will recompute the terminal steady state as many times as the anticipation about the terminal condition
changes. In particular, the information about endogenous variables that may be given in the endval block
is ignored. Said otherwise, the equivalent of option endval_steady of the perfect_foresight_setup
command is always implicitly enabled.
Options
periods = INTEGER
Number of periods of the simulation.
datafile = FILENAME
Used to specify the information about future shocks and their anticipation through a CSV file, as an
alternative to shocks and endval blocks.
The file has the following format:
• the first column is ignored (can be used to add descriptive labels)
• the first line contains names of exogenous variables
• the second line contains, in columns, indices of periods at which expectations are formed; the
information set used in a given period is described by all the columns for which that line is equal
to the period index
• the subsequent lines correspond to the periods for which expectations are formed, one period per
line; each line gives the values of present and future exogenous variables, as seen from the period
given in the second line
• the last line corresponds to the terminal condition for exogenous variables, as anticipated in the
various informational periods
If p is the value of the periods option and k is the number of exogenous variables, then the CSV file
has p+3 lines and k×p+1 columns.
Concretely, the value of a given exogenous in period t, as anticipated from period s, is given in line
t+2, and in the column which has the name of the variable on the first line and s on the second line.
Of course, values in cells corresponding to t<s are ignored.
Output
oo_.exo_simul and oo_.endo_simul are initialized before the simulation. Temporary shocks are stored
in oo_.pfwee.shocks_info, terminal conditions for exogenous variables are stored in oo_.pfwee.
terminal_info.
Example
Here is a CSV file example that could be given to the datafile option (adding some extra padding space
for clarity):
Exogenous , x, x, x, x, x, x, x
Period (info), 1, 2, 3, 4, 5, 6, 7
Period 1 (real), 1.2, , , , , ,
Period 2 (real), 1, 1.3, , , , ,
(continues on next page)
In this example, there is only one exogenous variable (x), and 7 simulation periods. In the first period, agents
learn a contemporary shock (1.2), but anticipate no further shock. In period 2, they learn an unexpected
contemporary shock (1.3), and also a change in the terminal condition (1.1). In period 3 again there is an
unexpected contemporary shock and a change in the terminal condition. No new information comes in period
4 and 5. In period 6, an unexpected permanent shock is learnt. No new information comes in period 7.
Alternatively, instead of using a CSV file, the same sequence of information sets could be described using
the following blocks:
initval;
x = 1;
end;
steady;
shocks(learnt_in = 1);
var x;
periods 1;
values 1.2;
end;
shocks(learnt_in = 2);
var x;
periods 2;
values 1.3;
end;
endval(learnt_in = 2);
x = 1.1;
end;
shocks(learnt_in = 3);
var x;
periods 3;
values 1.4;
end;
endval(learnt_in = 3);
x = 1.2;
end;
shocks(learnt_in = 6);
var x;
periods 6:7;
values 1.1;
end;
endval(learnt_in = 6);
x = 1.1;
end;
Command: perfect_foresight_with_expectation_errors_solver ;
Command: perfect_foresight_with_expectation_errors_solver(OPTIONS...);
Computes the perfect foresight simulation with expectation errors of the model.
Note that perfect_foresight_with_expectation_errors_setup must be called before this com-
mand, in order to setup the environment for the simulation.
Options
This command accepts all the options of perfect_foresight_solver, with the same semantics, plus the
following one:
constant_simulation_length
By default, every time the information set changes, the simulation with the new information set
is shorter than the previous one (because the terminal date is getting closer). When this op-
tion is set, every new simulation has the same length (as specified by the periods` option of
perfect_foresight_with_expectation_errors_setup; as a consequence, the simulated paths
as stored in oo_.endo_simul will be longer when this option is set (if s is the last period in which the
information set is modified, then they will contain s+periods-1 periods, excluding initial and terminal
conditions).
Output
The simulated paths of endogenous variables are available in oo_.endo_simul. The terminal steady state
values corresponding to the last period of the information set are available in oo_.steady_state and oo_.
exo_steady_state.
MATLAB/Octave variable: oo_.pfwee.shocks_info
This variable stores the temporary shocks used during perfect foresight simulations with expectation errors,
after perfect_foresight_with_expectation_errors_setup has been run. It is a three-dimensional
matrix: first dimension correspond to exogenous variables (in declaration order); second dimension corre-
sponds to real time; third dimension corresponds to informational time. In other words, the value of exoge-
nous indexed k in period t, as anticipated from period s, is stored in oo_.pfwee.shocks_info(k,t,s).
MATLAB/Octave variable: oo_.pfwee.terminal_info
This variable stores the terminal conditions for exogenous variables used during perfect foresight simulations
with expectation errors, after perfect_foresight_with_expectation_errors_setup has been run. It
is a matrix, whose lines correspond to exogenous variables (in declaration order), and whose columns corre-
spond to informational time. In other words, the terminal condition for exogenous indexed k, as anticipated
from period s, is stored in oo_.pfwee.terminal_info(k,s).
In a stochastic context, Dynare computes one or several simulations corresponding to a random draw of the shocks.
The main algorithm for solving stochastic models relies on a Taylor approximation, up to third order, of the ex-
pectation functions (see Judd (1996), Collard and Juillard (2001a, 2001b), and Schmitt-Grohé and Uríbe (2004)).
The details of the Dynare implementation of the first order solution are given in Villemot (2011). Such a solution
is computed using the stoch_simul command.
As an alternative, it is possible to compute a simulation to a stochastic model using the extended path method
presented by Fair and Taylor (1983). This method is especially useful when there are strong nonlinearities or
binding constraints. Such a solution is computed using the extended_path command.
filtered_theoretical_moments_grid = INTEGER
When computing filtered theoretical moments (with either option hp_filter or option
bandpass_filter), this option governs the number of points in the grid for the discrete In-
verse Fast Fourier Transform. It may be necessary to increase it for highly autocorrelated processes.
Default: 512.
irf = INTEGER
Number of periods on which to compute the IRFs. Setting irf=0 suppresses the plotting of IRFs.
Default: 40.
irf_shocks = ( VARIABLE_NAME [[,] VARIABLE_NAME ...] )
The exogenous variables for which to compute IRFs. Default: all.
relative_irf
Requests the computation of normalized IRFs. At first order, the normal shock vector of size one
standard deviation is divided by the standard deviation of the current shock and multiplied by 100. The
impulse responses are hence the responses to a unit shock of size 1 (as opposed to the regular shock size
of one standard deviation), multiplied by 100. Thus, for a loglinearized model where the variables are
measured in percent, the IRFs have the interpretation of the percent responses to a 100 percent shock.
For example, a response of 400 of output to a TFP shock shows that output increases by 400 percent
after a 100 percent TFP shock (you will see that TFP increases by 100 on impact). Given linearity at
order=1, it is straightforward to rescale the IRFs stored in oo_.irfs to any desired size. At higher
order, the interpretation is different. The relative_irf option then triggers the generation of IRFs as
the response to a 0.01 unit shock (corresponding to 1 percent for shocks measured in percent) and no
multiplication with 100 is performed. That is, the normal shock vector of size one standard deviation
is divided by the standard deviation of the current shock and divided by 100. For example, a response
of 0.04 of log output (thus measured in percent of the steady state output level) to a TFP shock also
measured in percent then shows that output increases by 4 percent after a 1 percent TFP shock (you
will see that TFP increases by 0.01 on impact).
irf_plot_threshold = DOUBLE
Threshold size for plotting IRFs. All IRFs for a particular variable with a maximum absolute deviation
from the steady state smaller than this value are not displayed. Default: 1e-10.
nocorr
Don’t print the correlation matrix (printing them is the default).
nodecomposition
Don’t compute (and don’t print) unconditional variance decomposition.
nofunctions
Don’t print the coefficients of the approximated solution (printing them is the default).
nomoments
Don’t print moments of the endogenous variables (printing them is the default).
nomodelsummary
Don’t print the model summary and the covariance of the exogenous shocks (printing them is the de-
fault).
nograph
Do not create graphs (which implies that they are not saved to the disk nor displayed). If this option
is not used, graphs will be saved to disk (to the format specified by graph_format option, except if
graph_format=none) and displayed to screen (unless nodisplay option is used).
graph
Re-enables the generation of graphs previously shut off with nograph.
nodisplay
Do not display the graphs, but still save them to disk (unless nograph is used).
graph_format = FORMAT
loglinear
See loglinear. Note that ALL variables are log-transformed by using the Jacobian transformation, not
only selected ones. Thus, you have to make sure that your variables have strictly positive steady states.
stoch_simul will display the moments, decision rules, and impulse responses for the log-linearized
variables. The decision rules saved in oo_.dr and the simulated variables will also be the ones for the
log-linear variables.
tex
Requests the printing of results and graphs in TeX tables and graphics that can be later directly included
in LaTeX files.
dr_display_tol = DOUBLE
Tolerance for the suppression of small terms in the display of decision rules. Rows where all terms are
smaller than dr_display_tol are not displayed. Default value: 1e-6.
contemporaneous_correlation
Saves the contemporaneous correlation between the endogenous variables in oo_.
contemporaneous_correlation. Requires the nocorr option not to be set.
spectral_density
Triggers the computation and display of the theoretical spectral density of the (filtered) model variables.
Results are stored in oo_.SpectralDensity, defined below. Default: do not request spectral density
estimates.
hp_ngrid = INTEGER
Deprecated option. It has the same effect as filtered_theoretical_moments_grid.
Output
This command sets oo_.dr, oo_.mean, oo_.var, oo_.var_list, and oo_.autocorr, which are de-
scribed below.
If the periods option is present, sets oo_.skewness, oo_.kurtosis, and oo_.endo_simul (see oo_.
endo_simul).
If option irf is different from zero, sets oo_.irfs (see below).
If the option contemporaneous_correlation is different from 0, sets oo_.
contemporaneous_correlation, which is described below.
Example
shocks;
var e;
stderr 0.0348;
end;
stoch_simul;
Performs the simulation of the 2nd-order approximation of a model with a single stochastic shock
e, with a standard error of 0.0348.
Example
stoch_simul(irf=60) y k;
Performs the simulation of a model and displays impulse response functions on 60 periods for
variables y and k.
MATLAB/Octave variable: oo_.mean
After a run of stoch_simul, contains the mean of the endogenous variables. Contains theoretical mean if
the periods option is not present, and simulated mean otherwise. The variables are arranged in declaration
order.
and sum up to 100 across columns. In the presence of measurement error, the field will contain the variance
contribution after measurement error has been taken out, i.e. the decomposition will be conducted of the
actual as opposed to the measured variables.
MATLAB/Octave variable: oo_.variance_decomposition_ME
Field set after a run of stoch_simul when requesting theoretical moments (periods=0) if measurement
error is present. It is similar to oo_.variance_decomposition, but the decomposition will be conducted
of the measured variables. The field contains a matrix with the result of the unconditional variance decom-
position (i.e. at horizon infinity). The first dimension corresponds to the observed endoogenous variables (in
the order of declaration after the command) and the second dimension corresponds to exogenous variables
(in the order of declaration), with the last column corresponding to the contribution of measurement error.
Numbers are in percent and sum up to 100 across columns.
MATLAB/Octave variable: oo_.conditional_variance_decomposition
After a run of stoch_simul with the conditional_variance_decomposition option, contains a three-
dimensional array with the result of the decomposition. The first dimension corresponds to the endogenous
variables (in the order of declaration after the command or in M_.endo_names if not specified), the second
dimension corresponds to the forecast horizons (as declared with the option), and the third dimension cor-
responds to the exogenous variables (in the order of declaration). In the presence of measurement error, the
field will contain the variance contribution after measurement error has been taken out, i.e. the decomposi-
tion will be conductedof the actual as opposed to the measured variables.
MATLAB/Octave variable: oo_.conditional_variance_decomposition_ME
Field set after a run of stoch_simul with the conditional_variance_decomposition option if mea-
surement error is present. It is similar to oo_.conditional_variance_decomposition, but the decom-
position will be conducted of the measured variables. It contains a three-dimensional array with the result of
the decomposition. The first dimension corresponds to the endogenous variables (in the order of declaration
after the command or in M_.endo_names if not specified), the second dimension corresponds to the forecast
horizons (as declared with the option), and the third dimension corresponds to the exogenous variables (in
the order of declaration), with the last column corresponding to the contribution of the measurement error.
MATLAB/Octave variable: oo_.contemporaneous_correlation
After a run of stoch_simul with the contemporaneous_correlation option, contains theoretical con-
temporaneous correlations if the periods option is not present, and simulated contemporaneous correlations
otherwise. Only available for order<4. At order=2 it will be be a second-order accurate approximation. At
order=3, theoretical moments are only available with pruning. The variables are arranged in declaration
order.
MATLAB/Octave variable: oo_.SpectralDensity
After a run of stoch_simul with option spectral_density, contains the spectral density of the model
variables. There will be a nvars by nfrequencies subfield freqs storing the respective frequency grid
points ranging from 0 to 2𝜋 and a same sized subfield density storing the corresponding density.
MATLAB/Octave variable: oo_.irfs
After a run of stoch_simul with option irf different from zero, contains the impulse responses, with the
following naming convention: VARIABLE_NAME_SHOCK_NAME.
For example, oo_.irfs.gnp_ea contains the effect on gnp of a one-standard deviation shock on
ea.
MATLAB/Octave command:
IRF_MATRIX=get_irf('EXOGENOUS_NAME' [, 'ENDOGENOUS_NAME']... );
Given the name of an exogenous variable, returns the IRFs for the requested endogenous variable(s) (as they
are stored in oo_.irfs) in the output IRF_MATRIX. The periods are stored along the first dimension, with
the steady state in the first row. The variables are stored along the second dimension. If no endogenous
variables were specified, the matrix contains all variables stored in oo_.irfs.
The approximated solution of a model takes the form of a set of decision rules or transition equations expressing
the current value of the endogenous variables of the model as function of the previous state of the model and shocks
observed at the beginning of the period. The decision rules are stored in the structure oo_.dr which is described
below.
Note that all endogenous variables fall into one of these four categories, since after the creation of auxiliary variables
(see Auxiliary variables), all endogenous have at most one lead and one lag. We therefore have the following
identity:
𝑦𝑡 = 𝑦 𝑠 + 𝐴𝑦𝑡−1
ℎ
+ 𝐵𝑢𝑡
where k2 selects the state variables, 𝑦𝑡 and 𝑦 𝑠 are in declaration order and the coefficient matrices are in DR-order.
Effectively, all variables on the right hand side are brought into DR order for computations and then assigned to 𝑦𝑡
in declaration order.
𝑦𝑡 = 𝑦 𝑠 + 0.5∆2 + 𝐴𝑦𝑡−1
ℎ ℎ
+ 𝐵𝑢𝑡 + 0.5𝐶(𝑦𝑡−1 ℎ
⊗ 𝑦𝑡−1 ℎ
) + 0.5𝐷(𝑢𝑡 ⊗ 𝑢𝑡 ) + 𝐸(𝑦𝑡−1 ⊗ 𝑢𝑡 )
where 𝑦 𝑠 is the steady state value of 𝑦, 𝑦𝑡ℎ = 𝑦𝑡 − 𝑦 𝑠 , and ∆2 is the shift effect of the variance of future shocks.
For the reordering required due to differences in declaration and DR order, see the first order approximation.
The coefficients of the decision rules are stored in the variables described for first order approximation, plus the
following variables:
• ∆2 is stored in oo_.dr.ghs2. The vector rows correspond to all endogenous in DR-order.
• 𝐶 is stored in oo_.dr.ghxx. The matrix rows correspond to all endogenous in DR-order. The matrix
columns correspond to the Kronecker product of the vector of state variables in DR-order.
• 𝐷 is stored in oo_.dr.ghuu. The matrix rows correspond to all endogenous in DR-order. The matrix
columns correspond to the Kronecker product of exogenous variables in declaration order.
• 𝐸 is stored in oo_.dr.ghxu. The matrix rows correspond to all endogenous in DR-order. The matrix
columns correspond to the Kronecker product of the vector of state variables (in DR-order) by the vector of
exogenous variables (in declaration order).
𝑦𝑡 = 𝑦 𝑠 + 𝐺0 + 𝐺1 𝑧𝑡 + 𝐺2 (𝑧𝑡 ⊗ 𝑧𝑡 ) + 𝐺3 (𝑧𝑡 ⊗ 𝑧𝑡 ⊗ 𝑧𝑡 )
where 𝑦 𝑠 is the steady state value of 𝑦, and 𝑧𝑡 is a vector consisting of the deviation from the steady state of the
state variables (in DR-order) at date 𝑡 − 1 followed by the exogenous variables at date 𝑡 (in declaration order). The
vector 𝑧𝑡 is therefore of size 𝑛𝑧 = M_.nspred + M_.exo_nbr.
The coefficients of the decision rules are stored as follows:
• 𝑦 𝑠 is stored in oo_.dr.ys. The vector rows correspond to all endogenous in the declaration order.
• 𝐺0 is stored in oo_.dr.g_0. The vector rows correspond to all endogenous in DR-order.
• 𝐺1 is stored in oo_.dr.g_1. The matrix rows correspond to all endogenous in DR-order. The matrix
columns correspond to state variables in DR-order, followed by exogenous in declaration order.
• 𝐺2 is stored in oo_.dr.g_2. The matrix rows correspond to all endogenous in DR-order. The matrix
columns correspond to the Kronecker product of state variables (in DR-order), followed by exogenous (in
declaration order). Note that the Kronecker product is stored in a folded way, i.e. symmetric elements are
stored only once, which implies that the matrix has 𝑛𝑧 (𝑛𝑧 + 1)/2 columns. More precisely, each column
of this matrix corresponds to a pair (𝑖1 , 𝑖2 ) where each index represents an element of 𝑧𝑡 and is therefore
between 1 and 𝑛𝑧 . Only non-decreasing pairs are stored, i.e. those for which 𝑖1 ≤ 𝑖2 . The columns are
arranged in the lexicographical order of non-decreasing pairs. Also note that for those pairs where 𝑖1 ̸= 𝑖2 ,
since the element is stored only once but appears two times in the unfolded 𝐺2 matrix, it must be multiplied
by 2 when computing the decision rules.
• 𝐺3 is stored in oo_.dr.g_3. The matrix rows correspond to all endogenous in DR-order. The matrix
columns correspond to the third Kronecker power of state variables (in DR-order), followed by exogenous
(in declaration order). Note that the third Kronecker power is stored in a folded way, i.e. symmetric elements
are stored only once, which implies that the matrix has 𝑛𝑧 (𝑛𝑧 + 1)(𝑛𝑧 + 2)/6 columns. More precisely, each
column of this matrix corresponds to a tuple (𝑖1 , 𝑖2 , 𝑖3 ) where each index represents an element of 𝑧𝑡 and is
therefore between 1 and 𝑛𝑧 . Only non-decreasing tuples are stored, i.e. those for which 𝑖1 ≤ 𝑖2 ≤ 𝑖3 . The
columns are arranged in the lexicographical order of non-decreasing tuples. Also note that for tuples that
have three distinct indices (i.e. 𝑖1 ̸= 𝑖2 and 𝑖1 ̸= 𝑖3 and 𝑖2 ̸= 𝑖3 ), since these elements are stored only once
but appears six times in the unfolded 𝐺3 matrix, they must be multiplied by 6 when computing the decision
rules. Similarly, for those tuples that have two equal indices (i.e. of the form (𝑎, 𝑎, 𝑏) or (𝑎, 𝑏, 𝑎) or (𝑏, 𝑎, 𝑎)),
since these elements are stored only once but appears three times in the unfolded 𝐺3 matrix, they must be
multiplied by 3 when computing the decision rules.
Dynare allows simulating models with up to two occasionally-binding constraints by relying on a piecewise linear
solution as in Guerrieri and Iacoviello (2015). It also allows estimating such models employing either the inversion
filter of Cuba-Borda, Guerrieri, Iacoviello, and Zhong (2019) or the piecewise Kalman filter of Giovannini, Pfeiffer,
and Ratto (2021). To trigger computations involving occasionally-binding constraints requires
1. defining and naming the occasionally-binding constraints using an occbin_constraints block
2. specifying the model equations for the respective regimes in the model block using appropriate equation
tags.
3. potentially specifying a sequence of surprise shocks using a shocks(surprise) block
4. setting up Occbin simulations or estimation with occbin_setup
5. triggering a simulation with occbin_solver or running estimation or calib_smoother.
All of these elements are discussed in the following.
Block: occbin_constraints ;
The occbin_constraints block specifies the occasionally-binding constraints. It contains one or two of
the following lines:
name ‘STRING’; bind EXPRESSION; [relax EXPRESSION;] [error_bind EXPRESSION;] [er-
ror_relax EXPRESSION;]
STRING is the name of constraint that is used to reference the constraint in relax / bind equation tags to
identify the respective regime (see below). The bind expression is mandatory and defines a logical condi-
tion that is evaluated in the baseline/steady state regime to check whether the specified constraint becomes
binding. In contrast, the relax expression is optional and specifies a logical condition that is evaluated in
the binding regime to check whether the regime returns to the baseline/steady state regime. If not specified,
Dynare will simply check in the binding regime whether the bind expression evaluates to false. However,
there are cases where the bind expression cannot be evaluated in the binding regime(s), because the variables
involved are constant by definition so that e.g. the value of the Lagrange multiplier on the complementary
slackness condition needs to be checked. In these cases, it is necessary to provide an explicit condition that
can be evaluated in the binding regime that allows to check whether it should be left.
Note that the baseline regime denotes the steady state of the model where the economy will settle in the
long-run without shocks. For that matter, it may be one where e.g. a borrowing constraint is binding. In that
type of setup, the bind condition is used to specify the condition when this borrowing constraint becomes
non-binding so that the alternative regime is entered.
Three things are important to keep in mind when specifying the expressions. First, feasible expressions
may only contain contemporaneous endogenous variables. If you want to include leads/lags or exogenous
variables, you need to define an auxiliary variable. Second, Dynare will at the current stage not linearly
approximate the entered expressions. Because Occbin will work with a linearized model, consistency will
often require the user to enter a linearized constraint. Otherwise, the condition employed for checking con-
straint violations may differ from the one employed within model simulations based on the piecewise-linear
model solution. Third, in contrast to the original Occbin replication codes, the variables used in expressions
are not automatically demeaned, i.e. they refer to the levels, not deviations from the steady state. To access
the steady state level of a variable, the STEADY_STATE() operator can be used.
Finally, it’s worth keeping in mind that for each simulation period, Occbin will check the respective condi-
tions for whether the current regime should be left. Small numerical differences from the cutoff point for
a regime can sometimes lead to oscillations between regimes and cause a spurious periodic solution. Such
cases may be prevented by introducing a small buffer between the two regimes, e.g.
occbin_constraints;
name 'ELB'; bind inom <= iss-1e8; relax inom > iss+1e-8;
end;
The error_bind and error_relax options are optional and allow specifying numerical criteria for the
size of the respective constraint violations employed in numerical routines. By default, Dynare will simply
use the absolute value of the bind and relax inequalities. But occasionnally, user-specified expressions
perform better.
Example
occbin_constraints;
name 'IRR'; bind log_Invest-log(steady_state(Invest))<log(phi);␣
˓→relax Lambda<0;
IRR is a constraint for irreversible investment that becomes binding if investment drops below its
steady state by more than 0.025 percent in the non-binding regime. The constraint will be relaxed
whenever the associated Lagrange multiplier Lambda in the binding regime becomes negative.
Note that the constraint here takes on a linear form to be consistent with a piecewise linear model
solution
The specification of the model equations belonging to the respective regimes is done in the model block,
with equation tags indicating to which regime a particular equation belongs. All equations that differ across
regimes must have a name tag attached to them that allows uniquely identifying different versions of the
same equation. The name of the constraints specified is then used in conjunction with a bind or relax tag
to indicate to which regime a particular equation belongs. In case of more than one occasionally-binding
constraint, if an equation belongs to several regimes (e.g. both constraints binding), the constraint name tags
must be separated by a comma. If only one name tag is present, the respective equation is assumed to hold
for both states of the other constraint.
Example
[name='investment',bind='IRR,INEG']
(log_Invest - log(phi*steady_state(Invest))) = 0;
[name='investment',relax='IRR']
Lambda=0;
[name='investment',bind='IRR',relax='INEG']
(log_Invest - log(phi*steady_state(Invest))) = 0;
The three entered equations for the investment condition define the model equation for all four
possible combinations of the two constraints. The first equation defines the model equation in the
regime where both the IRR and INEG constraint are binding. The second equation defines the
model equation for the regimes where the IRR constraint is non-binding, regardless of whether
the INEG constraint is binding or not. Finally, the last equation defines the model equation for
the final regime where the IRR constraint is binding, but the INEG one is not.
Block: shocks(surprise) ;
Block: shocks(surprise,overwrite);
The shocks(surprise) block allows specifying a sequence of temporary changes in the value of exogenous
variables that in each period come as a surprise to agents, i.e. are not anticipated. Note that to actually use
the specified shocks in subsequent commands like occbin_solver, the block needs to be followed by a call
to occbin_setup.
The block mirrors the perfect foresight syntax in that it should contain one or more occurrences of the
following group of three lines:
var VARIABLE_NAME;
periods INTEGER[:INTEGER] [[,] INTEGER[:INTEGER]]...;
values DOUBLE | (EXPRESSION) [[,] DOUBLE | (EXPRESSION) ]...;
shockssequence = randn(100,1)*0.02;
shocks(surprise,overwrite);
var epsilon;
periods 1:100;
values (shockssequence);
end;
Command: occbin_setup ;
Command: occbin_setup(OPTIONS...);
Prepares a simulation with occasionally binding constraints. This command will also translate
the contents of a shocks(surprise) block for use in subsequent commands.
In order to conduct estimation with occasionally binding constraints, it needs to be prefaced by
a call to occbin_setup to trigger the use of either the inversion filter or the piecewise Kalman
filter (default). An issue that can arise in the context of estimation is a structural shock dropping
out of the model in a particular regime. For example, at the zero lower bound on interest rates, the
monetary policy shock in the Taylor rule will not appear anymore. This may create a problem of
stochastic singularity if there are then more observables than shocks. To avoid this issue, the data
points for the zero interest rate should be set to NaN and the standard deviation of the associated
shock set to 0 for the corresponding periods using the heteroskedastic_shocks block.
Note that models with unit roots will require the user to specify the diffuse_filter option
as otherwise Blanchard-Kahn errors will be triggered. For the piecewise Kalman filter, the ini-
tialization steps in the diffuse filter will always rely on the model solved for the baseline regime,
without checking whether this is the actual regime in the first period(s).
Example
occbin_setup(likelihood_inversion_filter,smoother_inversion_
˓→filter);
estimation(smoother,heteroskedastic_filter,...);
The above piece of code sets up an estimation employing the inversion filter for both the likelihood
evaluation and the smoother, while also accounting for heteroskedastic_shocks using the
heteroskedastic_filter option.
Be aware that Occbin has largely command-specific options, i.e. there are separate options to
control the behavior of Occbin when called by the smoother or when computing the likelihood.
These latter commands will not inherit the options potentially previously set for simulations.
Options
simul_periods = INTEGER
Number of periods of the simulation. Default: 100.
simul_maxit = INTEGER
Maximum number of iterations when trying to find the regimes of the piecewise solution.
Default: 30.
simul_check_ahead_periods = INTEGER
Number of periods for which to check ahead for return to the baseline regime. This num-
ber should be chosen large enough, because Occbin requires the simulation to return to the
baseline regime at the end of time. Default: 200.
simul_reset_check_ahead_periods
Allows to reset simul_check_ahead_periods to its specified value at the beginning of
each simulation period. Otherwise, the original value may permanently increase endoge-
nously at some point due to regimes that last very long in expectations. This may consider-
ably slow down convergence in subsequent periods. Default: not enabled.
simul_max_check_ahead_periods = INTEGER
If set to a finite number, it enforces the OccBin algorithm to check ahead only for the maxi-
mum number of periods (i.e. when we want agents to be myopic beyond some future period)
instead of potentially endogenously increasing simul_check_ahead_periods ever further.
Default: Inf.
simul_curb_retrench
Instead of basing the initial regime guess for the current iteration on the last iteration, update
the guess only one period at a time. This will slow down the iterations, but may lead to more
robust convergence behavior. Default: not enabled.
simul_periodic_solution
Accept a periodic solution where the solution alternates between two sets of results across
iterations, i.e. is not found to be unique. This is sometimes caused by spurious numerical
errors that lead to oscillations between regiems and may be prevented by allowing for a small
buffer in regime transitions. Default: not enabled.
simul_debug
Provide additional debugging information during solving. Default: not enabled.
smoother_periods = INTEGER
Number of periods employed during the simulation when called by the smoother (equivalent
of simul_periods). Default: 100.
smoother_maxit = INTEGER
Maximum number of iterations employed during the simulation when called by the smoother
(equivalent of simul_maxit). Default: 30.
smoother_check_ahead_periods = INTEGER
Number of periods for which to check ahead for return to the baseline regime during the
simulation when called by the smoother (equivalent of simul_check_ahead_periods).
Default: 200.
smoother_max_check_ahead_periods = INTEGER
If set to a finite number, it enforces the OccBin algorithm to check ahead only for the maxi-
mum number of periods (i.e. when we want agents to be myopic beyond some future period)
instead of potentially endogenously increasing smoother_check_ahead_periods ever fur-
ther. Equivalent of simul_max_check_ahead_periods. Default: Inf.
smoother_curb_retrench
Have the smoother invoke the simul_curb_retrench option during simulations. Default:
not enabled.
smoother_periodic_solution
Accept periodic solution where solution alternates between two sets of results (equivalent of
simul_periodic_solution). Default: not enabled.
likelihood_periods = INTEGER
Number of periods employed during the simulation when computing the likelihood (equiv-
alent of simul_periods). Default: 100.
likelihood_maxit = INTEGER
Maximum number of iterations employed during the simulation when computing the likeli-
hood (equivalent of simul_maxit). Default: 30.
likelihood_check_ahead_periods = INTEGER
Number of periods for which to check ahead for return to the baseline regime during the
simulation when computing the likelihood (equivalent of simul_check_ahead_periods).
Default: 200.
smoother_max_check_ahead_periods = INTEGER
If set to a finite number, it enforces the OccBin algorithm to check ahead only for the maxi-
mum number of periods (i.e. when we want agents to be myopic beyond some future period)
instead of potentially endogenously increasing likelihood_check_ahead_periods ever
further. Equivalent of simul_max_check_ahead_periods. Default: Inf.
likelihood_curb_retrench
Have the likelihood computation invoke the simul_curb_retrench option during simula-
tions. Default: not enabled.
likelihood_periodic_solution
Accept periodic solution where solution alternates between two sets of results (equivalent of
simul_periodic_solution). Default: not enabled.
likelihood_inversion_filter
Employ the inversion filter of Cuba-Borda, Guerrieri, Iacoviello, and Zhong (2019) when
estimating the model. Default: not enabled.
likelihood_piecewise_kalman_filter
Employ the piecewise Kalman filter of Giovannini, Pfeiffer, and Ratto (2021) when esti-
mating the model. Note that this filter is incompatible with univariate Kalman filters, i.e.
kalman_algo=2,4. Default: enabled.
likelihood_max_kalman_iterations
Maximum number of iterations of the outer loop for the piecewise Kalman filter. Default:
10.
smoother_inversion_filter
Employ the inversion filter of Cuba-Borda, Guerrieri, Iacoviello, and Zhong (2019) when
running the smoother. The underlying assumption is that the system starts at the steady state.
In this case, the inversion filter will provide the required smoother output. Default: not
enabled.
smoother_piecewise_kalman_filter
Employ the piecewise Kalman filter of Giovannini, Pfeiffer, and Ratto (2021) when running
the smoother. Default: enabled.
filter_use_relaxation
Triggers relaxation within the guess and verify algorithm used in the update step of the piece-
wise Kalman filter. When old and new guess regime differ to much, use a new guess closer
to the previous guess. In case of multiple solutions, tends to provide an occasionally binding
regime with a shorter duration (typically preferable). Specifying this option may slow down
convergence. Default: not enabled.
Output
The paths for the exogenous variables are stored into options_.occbin.simul.SHOCKS.
Command: occbin_solver ;
Command: occbin_solver(OPTIONS...);
Computes a simulation with occasionally-binding constraints based on a piecewise-linear solution.
Note that occbin_setup must be called before this command in order for the simulation to take into account
previous shocks(surprise) blocks.
Options
simul_periods = INTEGER
See simul_periods.
simul_maxit = INTEGER
See simul_maxit.
simul_check_ahead_periods = INTEGER
See simul_check_ahead_periods.
simul_reset_check_ahead_periods
See simul_reset_check_ahead_periods.
simul_max_check_ahead_periods
See simul_max_check_ahead_periods.
simul_curb_retrench
See simul_curb_retrench .
simul_debug
See simul_debug.
Output
The command outputs various objects into oo_.occbin.
MATLAB/Octave variable: oo_.occbin.simul.piecewise
Matrix storing the simulations based on the piecewise-linear solution. The variables are arranged by column,
in order of declaration (as in M_.endo_names), while the the rows correspond to the simul_periods.
MATLAB/Octave variable: oo_.occbin.simul.linear
Matrix storing the simulations based on the linear solution, i.e. ignoring the occasionally binding con-
straint(s). The variables are arranged column by column, in order of declaration (as in M_.endo_names),
while the the rows correspond to the simul_periods.
MATLAB/Octave variable: oo_.occbin.simul.shocks_sequence
Matrix storing the shock sequence employed during the simulation. The shocks are arranged column by
column, with their order in M_.exo_names stored in oo_.occbin.exo_pos. The the rows correspond
to the number of shock periods specified in a shocks(surprise) block, which may be smaller than
simul_periods.
MATLAB/Octave variable: oo_.occbin.simul.regime_history
Structure storing information on the regime history, conditional on the shock that happened in the respective
period (stored along the rows). type is equal to either smoother or simul, depending on whether the
output comes from a run of simulations or the smoother. The subfield regime contains a vector storing the
regime state, while the the subfield regimestart indicates the expected start of the respective regime state.
For example, if row 40 contains [1,0] for regime2 and [1,6] for regimestart2, it indicates that - after
the shock in period 40 has occurred - the second constraint became binding (1) and is expected to revert to
non-binding (0) after six periods including the current one, i.e. period 45.
MATLAB/Octave variable: oo_.occbin.simul.ys
Vector of steady state values
Command: occbin_graph [VARIABLE_NAME...];
Provided that you have observations on some endogenous variables, it is possible to use Dynare to estimate some
or all parameters. Both maximum likelihood (as in Ireland (2004)) and Bayesian techniques (as in Fernández-
Villaverde and Rubio-Ramírez (2004), Rabanal and Rubio-Ramirez (2003), Schorfheide (2000) or Smets and
Wouters (2003)) are available. Using Bayesian methods, it is possible to estimate DSGE models, VAR models, or
a combination of the two techniques called DSGE-VAR.
Note that in order to avoid stochastic singularity, you must have at least as many shocks or measurement errors in
your model as you have observed variables.
Command: varobs VARIABLE_NAME...;
This command lists the name of observed endogenous variables for the estimation procedure. These variables
must be available in the data file (see estimation).
Alternatively, this command is also used in conjunction with the partial_information option of
stoch_simul, for declaring the set of observed variables when solving the model under partial informa-
tion.
Only one instance of varobs is allowed in a model file. If one needs to declare observed variables in a loop,
the macro processor can be used as shown in the second example below.
Example
varobs C y rr;
varobs
@#for co in countries
GDP_@{co}
@#endfor
;
Block: observation_trends ;
This block specifies linear trends for observed variables as functions of model parameters. In case the
loglinear option is used, this corresponds to a linear trend in the logged observables, i.e. an exponen-
tial trend in the level of the observables.
Each line inside of the block should be of the form:
VARIABLE_NAME(EXPRESSION);
observation_trends;
Y (eta);
P (mu/eta);
end;
Block: estimated_params ;
Block: estimated_params(overwrite) ;
This block lists all parameters to be estimated and specifies bounds and priors as necessary.
Each line corresponds to an estimated parameter.
In a maximum likelihood or a method of moments estimation, each line follows this syntax:
In a Bayesian MCMC or a penalized method of moments estimation, each line follows this syntax:
The first part of the line consists of one of the four following alternatives:
• stderr VARIABLE_NAME
Indicates that the standard error of the exogenous variable VARIABLE_NAME, or of the observation
error/measurement errors associated with endogenous observed variable VARIABLE_NAME, is to be
estimated.
• corr VARIABLE_NAME1, VARIABLE_NAME2
Indicates that the correlation between the exogenous variables VARIABLE_NAME1 and VARI-
ABLE_NAME2, or the correlation of the observation errors/measurement errors associated with en-
dogenous observed variables VARIABLE_NAME1 and VARIABLE_NAME2, is to be estimated. Note
that correlations set by previous shocks blocks or estimation commands are kept at their value set prior
to estimation if they are not estimated again subsequently. Thus, the treatment is the same as in the
case of deep parameters set during model calibration and not estimated.
• PARAMETER_NAME
The name of a model parameter to be estimated
• DSGE_PRIOR_WEIGHT
Special name for the weigh of the DSGE model in DSGE-VAR model.
The rest of the line consists of the following fields, some of them being optional:
INITIAL_VALUE
Specifies a starting value for the posterior mode optimizer or the maximum likelihood estimation. If
unset, defaults to the prior mean.
LOWER_BOUND
Specifies a lower bound for the parameter value in maximum likelihood estimation. In a Bayesian es-
timation context, sets a lower bound only effective while maximizing the posterior kernel. This lower
bound does not modify the shape of the prior density, and is only aimed at helping the optimizer in iden-
tifying the posterior mode (no consequences for the MCMC). For some prior densities (namely inverse
gamma, gamma, uniform, beta or Weibull) it is possible to shift the support of the prior distributions to
the left or the right using prior_3rd_parameter. In this case the prior density is effectively modified
(note that the truncated Gaussian density is not implemented in Dynare). If unset, defaults to minus
infinity (ML) or the natural lower bound of the prior (Bayesian estimation).
UPPER_BOUND
Same as lower_bound, but specifying an upper bound instead.
PRIOR_SHAPE
A keyword specifying the shape of the prior density. The possible values are: beta_pdf,
gamma_pdf, normal_pdf, uniform_pdf, inv_gamma_pdf, inv_gamma1_pdf, inv_gamma2_pdf
and weibull_pdf. Note that inv_gamma_pdf is equivalent to inv_gamma1_pdf.
PRIOR_MEAN
The mean of the prior distribution.
PRIOR_STANDARD_ERROR
The standard error of the prior distribution.
PRIOR_3RD_PARAMETER
A third parameter of the prior used for generalized beta distribution, generalized gamma, generalized
Weibull, the truncated normal, and for the uniform distribution. Default: -Inf for normal distribution,
0 otherwise.
PRIOR_4TH_PARAMETER
A fourth parameter of the prior used for generalized beta distribution, the truncated normal, and for the
uniform distribution. Default: Inf for normal distribution, 1 otherwise.
SCALE_PARAMETER
A parameter specific scale parameter for the jumping distribution’s covariance matrix of the Metropolis-
Hasting algorithm.
Note that INITIAL_VALUE, LOWER_BOUND, UPPER_BOUND, PRIOR_MEAN,
PRIOR_STANDARD_ERROR, PRIOR_3RD_PARAMETER, PRIOR_4TH_PARAMETER and
SCALE_PARAMETER can be any valid EXPRESSION. Some of them can be empty, in which Dynare will
select a default value depending on the context and the prior shape.
In case of the uniform distribution, it can be specified either by providing an upper and a lower bound
using PRIOR_3RD_PARAMETER and PRIOR_4TH_PARAMETER or via mean and standard deviation using
PRIOR_MEAN, PRIOR_STANDARD_ERROR. The other two will automatically be filled out. Note that providing
both sets of hyperparameters will yield an error message.
As one uses options more towards the end of the list, all previous options must be filled: for ex-
ample, if you want to specify SCALE_PARAMETER, you must specify PRIOR_3RD_PARAMETER and
PRIOR_4TH_PARAMETER. Use empty values, if these parameters don’t apply.
Example
Sets a generalized beta prior for the correlation between eps_1 and eps_2 with mean 0 and
variance 0.3. By setting PRIOR_3RD_PARAMETER to -1 and PRIOR_4TH_PARAMETER to 1 the
standard beta distribution with support [0,1] is changed to a generalized beta with support [-1,
1]. Note that LOWER_BOUND and UPPER_BOUND are left empty and thus default to -1 and
1, respectively. The initial value is set to 0.5.
Example
Sets the same generalized beta distribution as before, but now truncates this distribution to [-0.
5,1] through the use of LOWER_BOUND and UPPER_BOUND.
Parameter transformation
Sometimes, it is desirable to estimate a transformation of a parameter appearing in the model, rather than
the parameter itself. It is of course possible to replace the original parameter by a function of the estimated
parameter everywhere is the model, but it is often unpractical.
In such a case, it is possible to declare the parameter to be estimated in the parameters statement and to define
the transformation, using a pound sign (#) expression (see Model declaration).
Example
parameters bet;
model;
# sig = 1/bet;
c = sig*c(+1)*mpk;
end;
estimated_params;
bet, normal_pdf, 1, 0.05;
end;
It is possible to have several estimated_params blocks. By default, subsequent blocks are concate-
nated with the previous ones; this can be useful when building models in a modular fashion (see also
estimated_params_remove for that use case). However, if an estimated_params block has the
overwrite option, its contents becomes the new list of estimated parameters, cancelling previous blocks;
this can be useful when doing several estimations in a single .mod file.
Block: estimated_params_init ;
Block: estimated_params_init(OPTIONS...);
This block declares numerical initial values for the optimizer when these ones are different from the prior
mean. It should be specified after the estimated_params block as otherwise the specified starting values
are overwritten by the latter.
Each line has the following syntax:
Options
use_calibration
For not specifically initialized parameters, use the deep parameters and the elements of the covariance
matrix specified in the shocks block from calibration as starting values for estimation. For components
of the shocks block that were not explicitly specified during calibration or which violate the prior, the
prior mean is used.
See estimated_params, for the meaning and syntax of the various components.
Block: estimated_params_bounds ;
This block declares lower and upper bounds for parameters in maximum likelihood estimation.
Each line has the following syntax:
See estimated_params, for the meaning and syntax of the various components.
Block: estimated_params_remove ;
This block partially undoes the effect of a previous estimated_params block, by removing some parameters
from the estimation.
Each line has the following syntax:
set_dynare_seed('clock');
estimation(datafile='../fsdat_simul.mat',...);
dirname = FILENAME
Directory in which to store estimation output. To pass a subdirectory of a directory, you must quote
the argument. Default: <mod_file>.
xls_sheet = QUOTED_STRING
The name of the sheet with the data in an Excel file.
xls_range = RANGE
The range with the data in an Excel file. For example, xls_range=B2:D200.
nobs = INTEGER
The number of observations following first_obs to be used. Default: all observations in the file after
first_obs.
nobs = [INTEGER1:INTEGER2]
Runs a recursive estimation and forecast for samples of size ranging of INTEGER1 to INTEGER2. Op-
tion forecast must also be specified. The forecasts are stored in the RecursiveForecast field of
the results structure (see RecursiveForecast). The respective results structures oo_ are saved in
oo_recursive_ (see oo_recursive_) and are indexed with the respective sample length.
first_obs = INTEGER
The number of the first observation to be used. In case of estimating a DSGE-VAR, first_obs needs
to be larger than the number of lags. Default: 1.
first_obs = [INTEGER1:INTEGER2]
Runs a rolling window estimation and forecast for samples of fixed size nobs starting with the first
observation ranging from INTEGER1 to INTEGER2. Option forecast must also be specified. This
option is incompatible with requesting recursive forecasts using an expanding window (see nobs). The
respective results structures oo_ are saved in oo_recursive_ (see oo_recursive_) and are indexed
with the respective first observation of the rolling window.
prefilter = INTEGER
A value of 1 means that the estimation procedure will demean each data series by its empirical mean.
If the loglinear option without the logdata option is requested, the data will first be logged and then
demeaned. Default: 0, i.e. no prefiltering.
presample = INTEGER
The number of observations after first_obs to be skipped before evaluating the likelihood. These
presample observations do not enter the likelihood, but are used as a training sample for starting the
Kalman filter iterations. This option is incompatible with estimating a DSGE-VAR. Default: 0.
loglinear
Computes a log-linear approximation of the model instead of a linear approximation. As always in
the context of estimation, the data must correspond to the definition of the variables used in the model
(see Pfeifer (2013) for more details on how to correctly specify observation equations linking model
variables and the data). If you specify the loglinear option, Dynare will take the logarithm of both
your model variables and of your data as it assumes the data to correspond to the original non-logged
model variables. The displayed posterior results like impulse responses, smoothed variables, and mo-
ments will be for the logged variables, not the original un-logged ones. Default: computes a linear
approximation.
logdata
Dynare applies the 𝑙𝑜𝑔 transformation to the provided data if a log-linearization of the model is re-
quested (loglinear) unless logdata option is used. This option is necessary if the user provides
data already in logs, otherwise the 𝑙𝑜𝑔 transformation will be applied twice (this may result in complex
data).
plot_priors = INTEGER
Control the plotting of priors.
0
No prior plot.
1
Prior density for each estimated parameter is plotted. It is important to check that the
actual shape of prior densities matches what you have in mind. Ill-chosen values for
the prior standard density can result in absurd prior densities.
Default value is 1.
nograph
See nograph .
posterior_nograph
Suppresses the generation of graphs associated with Bayesian IRFs (bayesian_irf ), posterior
smoothed objects (smoother), and posterior forecasts (forecast).
posterior_graph
Re-enables the generation of graphs previously shut off with posterior_nograph .
nodisplay
See nodisplay.
graph_format = FORMAT
graph_format = ( FORMAT, FORMAT... )
See graph_format.
no_init_estimation_check_first_obs
Do not check for stochastic singularity in first period. If used, ESTIMATION CHECKS does not return
an error if the check fails only in first observation. This should only be used when observing stock
variables (e.g. capital) in first period, on top of their associated flow (e.g. investment). Using this
option may lead to a crash or provide undesired/wrong results for badly specified problems (e.g. the
additional variable observed in first period is not predetermined).
For advanced use only.
lik_init = INTEGER
Type of initialization of Kalman filter:
1
For stationary models, the initial matrix of variance of the error of forecast is set
equal to the unconditional variance of the state variables.
2
For nonstationary models: a wide prior is used with an initial matrix of variance
of the error of forecast diagonal with 10 on the diagonal (follows the suggestion of
Harvey and Phillips(1979)).
3
For nonstationary models: use a diffuse filter (use rather the diffuse_filter op-
tion).
4
The filter is initialized with the fixed point of the Riccati equation.
5
Use i) option 2 for the non-stationary elements by setting their initial variance in the
forecast error matrix to 10 on the diagonal and all covariances to 0 and ii) option 1
for the stationary elements.
Default value is 1. For advanced use only.
conditional_likelihood
Do not use the kalman filter to evaluate the likelihood, but instead evaluate the conditional likelihood,
based on the first order reduced form of the model, by assuming that the initial state vector is at its
steady state. This approach requires that:
1. The number of structural innovations be equal to the number of observed variables.
2. The absence of measurement errors (as introduced by the Dynare interface, see documentation
about the estimated_params block).
3. The absence of missing observations.
The evaluation of the conditional likelihood is faster and more stable than the evaluation of the likeli-
hood with the Kalman filter. Also this approach does not require special treatment for models with unit
roots. Note however that the conditional likelihood is sensitive to the choice for the initial condition,
which can be an issue if the data are initially far from the steady state. This option is not compatible
with analytic_derivation.
conf_sig = DOUBLE
Level of significance of the confidence interval used for classical forecasting after estimation. Default:
0.9.
mh_conf_sig = DOUBLE
Confidence/HPD interval used for the computation of prior and posterior statistics like: parameter dis-
tributions, prior/posterior moments, conditional variance decomposition, impulse response functions,
Bayesian forecasting. Default: 0.9.
mh_replic = INTEGER
Number of replications for each chain of the Metropolis-Hastings algorithm. The number of draws
should be sufficient to achieve convergence of the MCMC and to meaningfully compute posterior ob-
jects. Default: 20000.
sub_draws = INTEGER
Number of draws from the MCMC that are used to compute posterior distribution of various ob-
jects (smoothed variable, smoothed shocks, forecast, moments, IRF). The draws used to compute
these posterior moments are sampled uniformly in the estimated empirical posterior distribution (i.e.
draws of the MCMC). sub_draws should be smaller than the total number of MCMC draws avail-
able. Default: min(posterior_max_subsample_draws, (Total number of draws)*(number
of chains) ).
posterior_max_subsample_draws = INTEGER
Maximum number of draws from the MCMC used to compute posterior distribution of various objects
(smoothed variable, smoothed shocks, forecast, moments, IRF), if not overriden by option sub_draws.
Default: 1200.
mh_nblocks = INTEGER
Number of parallel chains for Metropolis-Hastings algorithm. Default: 2.
mh_drop = DOUBLE
The fraction of initially generated parameter vectors to be dropped as a burn-in before using posterior
simulations. Default: 0.5.
mh_jscale = DOUBLE
The scale parameter of the jumping distribution’s covariance matrix (Metropolis-Hastings or TaRB-
algorithm). This option must be tuned to obtain, ideally, an acceptance ratio of 25%-33%. Basically,
the idea is to increase the variance of the jumping distribution if the acceptance ratio is too high, and
decrease the same variance if the acceptance ratio is too low. In some situations it may help to consider
parameter-specific values for this scale parameter. This can be done in the estimated_params block.
Note that mode_compute=6 will tune the scale parameter to achieve an acceptance rate of AcceptanceR-
ateTarget. The resulting scale parameter will be saved into a file named MODEL_FILENAME_mh_scale.
mat in the FILENAME/Output folder. This file can be loaded in subsequent runs via the
posterior_sampler_options option scale_file. Both mode_compute=6 and scale_file will
overwrite any value specified in estimated_params with the tuned value. Default: 2.38/sqrt(n).
Note also that for the Random Walk Metropolis Hastings algorithm, it is possible to use option
mh_tune_jscale, to automatically tune the value of mh_jscale. In this case, the mh_jscale option
must not be used.
mh_init_scale = DOUBLE (deprecated)
The scale to be used for drawing the initial value of the Metropolis-Hastings chain. Generally, the
starting points should be overdispersed for the Brooks and Gelman (1998) convergence diagnostics to
be meaningful. Default: 2*mh_jscale.
It is important to keep in mind that mh_init_scale is set at the beginning of Dynare execu-
tion, i.e. the default will not take into account potential changes in mh_jscale introduced by ei-
ther mode_compute=6 or the posterior_sampler_options option scale_file. If mh_init_scale
is too wide during initalization of the posterior sampler so that 100 tested draws are inadmissi-
ble (e.g. Blanchard-Kahn conditions are always violated), Dynare will request user input of a new
mh_init_scale value with which the next 100 draws will be drawn and tested. If the nointeractive
option has been invoked, the program will instead automatically decrease mh_init_scale by 10 per-
cent after 100 futile draws and try another 100 draws. This iterative procedure will take place at most
10 times, at which point Dynare will abort with an error message.
mh_init_scale_factor = DOUBLE
The multiple of mh_jscale used for drawing the initial value of the Metropolis-Hastings chain. Gen-
erally, the starting points should be overdispersed for the Brooks and Gelman (1998) convergence di-
agnostics to be meaningful. Default: 2
If mh_init_scale_factor is too wide during initalization of the posterior sampler so that 100 tested
draws are inadmissible (e.g. Blanchard-Kahn conditions are always violated), Dynare will request
user input of a new mh_init_scale_factor value with which the next 100 draws will be drawn
and tested. If the nointeractive option has been invoked, the program will instead automatically
decrease mh_init_scale_factor by 10 percent after 100 futile draws and try another 100 draws.
This iterative procedure will take place at most 10 times, at which point Dynare will abort with an
error message.
mh_tune_jscale [= DOUBLE]
Automatically tunes the scale parameter of the jumping distribution’s covariance matrix (Metropolis-
Hastings), so that the overall acceptance ratio is close to the desired level. Default value is 0.33. It is not
possible to match exactly the desired acceptance ratio because of the stochastic nature of the algorithm
(the proposals and the initial conditions of the markov chains if mh_nblocks>1). This option is only
available for the Random Walk Metropolis Hastings algorithm. Must not be used in conjunction with
mh_jscale = DOUBLE.
mh_tune_guess = DOUBLE
Specifies the initial value for the mh_tune_jscale option. Default: 2.38/sqrt(n). Must not be set
if mh_tune_jscale is not used.
mh_recover
Attempts to recover a Metropolis-Hastings simulation that crashed prematurely, starting with the last
available saved mh-file. Shouldn’t be used together with load_mh_file or a different mh_replic
than in the crashed run. Since Dynare 4.5 the proposal density from the previous run will automat-
ically be loaded. In older versions, to assure a neat continuation of the chain with the same pro-
posal density, you should provide the mode_file used in the previous run or the same user-defined
mcmc_jumping_covariance when using this option. Note that under Octave, a neat continuation of
the crashed chain with the respective last random number generator state is currently not supported.
mh_posterior_mode_estimation
Skip optimizer-based mode-finding and instead compute the mode based on a run of a MCMC. The
MCMC will start at the prior mode and use the prior variances to compute the inverse Hessian.
mode_file = FILENAME
Name of the file containing previous value for the mode. When computing the mode, Dynare
stores the mode (xparam1) and the hessian (hh, only if cova_compute=1) in a file called
MODEL_FILENAME_mode.mat in the FILENAME/Output folder. After a successful run of the estima-
tion command, the mode_file will be disabled to prevent other function calls from implicitly using an
updated mode file. Thus, if the .mod file contains subsequent estimation commands, the mode_file
option, if desired, needs to be specified again.
mode_compute = INTEGER | FUNCTION_NAME
Specifies the optimizer for the mode computation:
0
The mode isn’t computed. When the mode_file option is specified, the mode is
simply read from that file.
When mode_file option is not specified, Dynare reports the value of the log poste-
rior (log likelihood) evaluated at the initial value of the parameters.
mode_check_neighbourhood_size = DOUBLE
Used in conjunction with option mode_check, gives the width of the window around the posterior mode
to be displayed on the diagnostic plots. This width is expressed in percentage deviation. The Inf value
is allowed, and will trigger a plot over the entire domain (see also mode_check_symmetric_plots).
Default:0.5.
mode_check_symmetric_plots = INTEGER
Used in conjunction with option mode_check, if set to 1, tells Dynare to ensure that the check
plots are symmetric around the posterior mode. A value of 0 allows to have asymmetric plots,
which can be useful if the posterior mode is close to a domain boundary, or in conjunction with
mode_check_neighbourhood_size = Inf when the domain in not the entire real line. Default:
1.
mode_check_number_of_points = INTEGER
Number of points around the posterior mode where the posterior kernel is evaluated (for each parame-
ter). Default is 20.
prior_trunc = DOUBLE
Probability of extreme values of the prior density that is ignored when computing bounds for the pa-
rameters. Default: 1e-32.
huge_number = DOUBLE
Value for replacing infinite values in the definition of (prior) bounds when finite values are required for
computational reasons. Default: 1e7.
load_mh_file
Tells Dynare to add to previous Metropolis-Hastings simulations instead of starting from scratch. Since
Dynare 4.5 the proposal density from the previous run will automatically be loaded. In older ver-
sions, to assure a neat continuation of the chain with the same proposal density, you should provide
the mode_file used in the previous run or the same user-defined mcmc_jumping_covariance when
using this option. Shouldn’t be used together with mh_recover. Note that under Octave, a neat contin-
uation of the chain with the last random number generator state of the already present draws is currently
not supported.
load_results_after_load_mh
This option is available when loading a previous MCMC run without adding additional draws, i.e.
when load_mh_file is specified with mh_replic=0. It tells Dynare to load the previously computed
convergence diagnostics, marginal data density, and posterior statistics from an existing _results file
instead of recomputing them.
mh_initialize_from_previous_mcmc
This option allows to pick initial values for new MCMC from a previous one, where the model spec-
ification, the number of estimated parameters, (some) prior might have changed (so a situation where
load_mh_file would not work). If an additional parameter is estimated, it is automatically initial-
ized from prior_draw. Note that, if this option is used to skip the optimization step, you should use a
sampling method which does not require a proposal density, like slice. Otherwise, optimization should
always be done beforehand or a mode file with an appropriate posterior covariance matrix should be
used.
mh_initialize_from_previous_mcmc_directory = FILENAME
If mh_initialize_from_previous_mcmc is set, users must provide here the path to the standard
FNAME folder from where to load prior definitions and last MCMC values to be used to initialize the
new MCMC.
Example: if previous project directory is /my_previous_dir and FNAME is mymodel, users should
set the option as
mh_initialize_from_previous_mcmc_directory = '/my_previous_dir/mymodel'
Dynare will then look for the last record file into
/my_previous_dir/mymodel/metropolis/mymodel_mh_history_<LAST>.mat
'TolGstep'
Tolerance parameter used for tuning gradient step. Default: same value as
TolFun.
'TolGstepRel'
Parameter used for tuning gradient step, governing the tolerance relative to the
functions value. Default: not triggered.
'verbosity'
Controls verbosity of display during optimization. Set to 0 to set to silent. De-
fault: 1.
'SaveFiles'
Controls saving of intermediate results during optimization. Set to 0 to shut off
saving. Default: 1.
6
Available options are:
'AcceptanceRateTarget'
A real number between zero and one. The scale parameter of the jumping
distribution is adjusted so that the effective acceptance rate matches the
value of option 'AcceptanceRateTarget'. Default: 1.0/3.0.
'InitialCovarianceMatrix'
Initial covariance matrix of the jumping distribution. It is also used to
initialize the covariance matrix during recursive updating. Default is
'previous' if option mode_file is used, 'prior' otherwise. The user
can also specify 'identity', which will use an identity matrix with a
diagonal of 0.1.
'nclimb-mh'
Number of iterations in the last MCMC (climbing mode). Default:
200000.
'ncov-mh'
Number of iterations used for updating the covariance matrix of the jump-
ing distribution. Default: 20000.
'nscale-mh'
Maximum number of iterations used for adjusting the scale parameter of
the jumping distribution. Default: 200000.
'NumberOfMh'
Number of MCMC run sequentially. Default: 3.
8
Available options are:
'InitialSimplexSize'
Initial size of the simplex, expressed as percentage deviation from the pro-
vided initial guess in each direction. Default: .05.
'MaxIter'
Maximum number of iterations. Default: 5000.
'MaxFunEvals'
Maximum number of objective function evaluations. No default.
'MaxFunvEvalFactor'
Set MaxFunvEvals equal to MaxFunvEvalFactor times the number of
estimated parameters. Default: 500.
'TolFun'
Tolerance parameter (w.r.t the objective function). Default: 1e-4.
'TolX'
Tolerance parameter (w.r.t the instruments). Default: 1e-4.
'verbosity'
Controls verbosity of display during optimization. Set to 0 to set to silent.
Default: 1.
9
Available options are:
'CMAESResume'
Resume previous run. Requires the variablescmaes.mat from the last
run. Set to 1 to enable. Default: 0.
'MaxIter'
Maximum number of iterations.
'MaxFunEvals'
Maximum number of objective function evaluations. Default: Inf.
'TolFun'
Tolerance parameter (w.r.t the objective function). Default: 1e-7.
'TolX'
Tolerance parameter (w.r.t the instruments). Default: 1e-7.
'verbosity'
Controls verbosity of display during optimization. Set to 0 to set to silent.
Default: 1.
'SaveFiles'
Controls saving of intermediate results during optimization. Set to 0 to
shut off saving. Default: 1.
10
Available options are:
'EndTemperature'
Terminal condition w.r.t the temperature. When the temperature reaches
EndTemperature, the temperature is set to zero and the algorithm falls
back into a standard simplex algorithm. Default: 0.1.
'MaxIter'
Maximum number of iterations. Default: 5000.
'MaxFunvEvals'
Maximum number of objective function evaluations. No default.
'TolFun'
Tolerance parameter (w.r.t the objective function). Default: 1e-4.
'TolX'
Tolerance parameter (w.r.t the instruments). Default: 1e-4.
'verbosity'
Controls verbosity of display during optimization. Set to 0 to set to silent.
Default: 1.
101
Available options are:
'LBGradientStep'
Lower bound for the stepsize used for the difference approximation of gra-
dients. Default: 1e-11.
'MaxIter'
Maximum number of iterations. Default: 15000
'SpaceDilation'
Coefficient of space dilation. Default: 2.5.
'TolFun'
Tolerance parameter (w.r.t the objective function). Default: 1e-6.
'TolX'
Tolerance parameter (w.r.t the instruments). Default: 1e-6.
'verbosity'
Controls verbosity of display during optimization. Set to 0 to set to silent.
Default: 1.
102
Available options are given in the documentation of the MATLAB Global Optimiza-
tion Toolbox.
Example
To change the defaults of csminwel (mode_compute=4):
estimation(..., mode_compute=4,optim=('NumgradAlgorithm',3,'TolFun',
˓→1e-5),...);
nodiagnostic
Does not compute the convergence diagnostics for Metropolis-Hastings. Default: diagnostics are com-
puted and displayed.
bayesian_irf
Triggers the computation of the posterior distribution of IRFs. The length of the IRFs are controlled
by the irf option. Results are stored in oo_.PosteriorIRF.dsge (see below for a description of this
variable).
relative_irf
See relative_irf .
dsge_var = DOUBLE
Triggers the estimation of a DSGE-VAR model, where the weight of the DSGE prior of the VAR
model is calibrated to the value passed (see Del Negro and Schorfheide (2004)). It represents the ratio
of dummy over actual observations. To assure that the prior is proper, the value must be bigger than
(𝑘 + 𝑛)/𝑇 , where 𝑘 is the number of estimated parameters, 𝑛 is the number of observables, and 𝑇 is
the number of observations.
NB: The previous method of declaring dsge_prior_weight as a parameter and then cal-
ibrating it is now deprecated and will be removed in a future release of Dynare. Some of
objects arising during estimation are stored with their values at the mode in oo_.dsge_var.
posterior_mode.
dsge_var
Triggers the estimation of a DSGE-VAR model, where the weight of the DSGE prior of the VAR
model will be estimated (as in Adjemian et al.(2008)). The prior on the weight of the DSGE prior,
dsge_prior_weight, must be defined in the estimated_params section.
NB: The previous method of declaring dsge_prior_weight as a parameter and then placing it in
estimated_params is now deprecated and will be removed in a future release of Dynare.
dsge_varlag = INTEGER
The number of lags used to estimate a DSGE-VAR model. Default: 4.
posterior_sampling_method = NAME
Selects the sampler used to sample from the posterior distribution during Bayesian estimation. De-
fault:’random_walk_metropolis_hastings’.
'random_walk_metropolis_hastings'
Instructs Dynare to use the Random-Walk Metropolis-Hastings. In this algorithm,
the proposal density is recentered to the previous draw in every step.
'tailored_random_block_metropolis_hastings'
Instructs Dynare to use the Tailored randomized block (TaRB) Metropolis-Hastings
algorithm proposed by Chib and Ramamurthy (2010) instead of the standard
Random-Walk Metropolis-Hastings. In this algorithm, at each iteration the estimated
parameters are randomly assigned to different blocks. For each of these blocks a
mode-finding step is conducted. The inverse Hessian at this mode is then used as the
covariance of the proposal density for a Random-Walk Metropolis-Hastings step. If
the numerical Hessian is not positive definite, the generalized Cholesky decompo-
sition of Schnabel and Eskow (1990) is used, but without pivoting. The TaRB-MH
algorithm massively reduces the autocorrelation in the MH draws and thus reduces
the number of draws required to representatively sample from the posterior. However,
this comes at a computational cost as the algorithm takes more time to run.
'independent_metropolis_hastings'
Use the Independent Metropolis-Hastings algorithm where the proposal distribution
- in contrast to the Random Walk Metropolis-Hastings algorithm - does not depend
on the state of the chain.
'slice'
Instructs Dynare to use the Slice sampler of Planas, Ratto, and Rossi (2015). Note
that 'slice' is incompatible with prior_trunc=0.
Whereas one Metropolis-Hastings iteration requires one evaluation of the posterior,
one slice iteration requires 𝑛𝑒𝑣𝑎𝑙 evaluations, where as a rule of thumb 𝑛𝑒𝑣𝑎𝑙 =
7×𝑛𝑝𝑎𝑟 with 𝑛𝑝𝑎𝑟 denoting the number of estimated parameters. Spending the same
computational budget of 𝑁 posterior evaluations in the slice sampler then implies
setting mh_replic=N/neval.
Note that the slice sampler will typically return less autocorrelated Monte Carlo
Markov Chain draws than the MH-algorithm. Its relative (in)efficiency can be in-
vestigated via the reported inefficiency factors.
'hssmc'
Instructs Dynare to use the Herbst and Schorfheide (2014) version of the Sequential
Monte-Carlo sampler instead of the standard Random-Walk Metropolis-Hastings.
'initial_step_size'
Sets the initial size of the interval in the stepping-out procedure as fraction
of the prior support, i.e. the size will be initial_step_size * (UB-LB).
initial_step_size must be a real number in the interval [0,1]. Default:
0.8.
'use_mh_covariance_matrix'
See use_mh_covariance_matrix. Must be used with 'rotated'. Default: 0.
'save_tmp_file'
See save_tmp_file. Default: 1.
'tailored_random_block_metropolis_hastings'
Available options are:
'proposal_distribution'
Specifies the statistical distribution used for the proposal density. See pro-
posal_distribution.
new_block_probability = DOUBLE
Specifies the probability of the next parameter belonging to a new block when
the random blocking in the TaRB Metropolis-Hastings algorithm is conducted.
The higher this number, the smaller is the average block size and the more ran-
dom blocks are formed during each parameter sweep. Default: 0.25.
mode_compute = INTEGER
Specifies the mode-finder run in every iteration for every block of the TaRB
Metropolis-Hastings algorithm. See mode_compute. Default: 4.
optim = (NAME, VALUE,...)
Specifies the options for the mode-finder used in the TaRB Metropolis-Hastings
algorithm. See optim.
'scale_file'
See scale_file..
'save_tmp_file'
See save_tmp_file. Default: 1.
'hssmc'
Available options are:
'particles'
Number of particles. Default value is: 20000.
'steps'
Number of weights 𝜑𝑖 ∈ [0, 1] on the likelihood function used to define a se-
quence of tempered likelihoods. This parameter is denoted 𝑁𝜑 in Herbst and
Schorfheide (2014), and we have 𝜑1 = 0 and 𝜑𝑁𝜑 = 1. Default value is: 25.
'lambda'
Positive parameter controling the sequence of weights 𝜑𝑖 , Default value is: 2.
Weights are defined by:
(︂ )︂𝜆
𝑖−1
𝜑𝑖 =
𝑁𝜑 − 1
0
Automatically use the Multivariate Kalman Filter for stationary models and the Mul-
tivariate Diffuse Kalman Filter for non-stationary models.
1
Use the Multivariate Kalman Filter.
2
Use the Univariate Kalman Filter.
3
Use the Multivariate Diffuse Kalman Filter.
4
Use the Univariate Diffuse Kalman Filter.
Default value is 0. In case of missing observations of single or all series, Dynare treats those miss-
ing values as unobserved states and uses the Kalman filter to infer their value (see e.g. Durbin and
Koopman (2012), Ch. 4.10) This procedure has the advantage of being capable of dealing with ob-
servations where the forecast error variance matrix becomes singular for some variable(s). If this
happens, the respective observation enters with a weight of zero in the log-likelihood, i.e. this ob-
servation for the respective variable(s) is dropped from the likelihood computations (for details see
Durbin and Koopman (2012), Ch. 6.4 and 7.2.5 and Koopman and Durbin (2000)). If the use of a
multivariate Kalman filter is specified and a singularity is encountered, Dynare by default automati-
cally switches to the univariate Kalman filter for this parameter draw. This behavior can be changed
via the use_univariate_filters_if_singularity_is_detected option.
fast_kalman_filter
Select the fast Kalman filter using Chandrasekhar recursions as described by Herbst (2015). This
setting is only used with kalman_algo=1 or kalman_algo=3. In case of using the diffuse Kalman
filter (kalman_algo=3/lik_init=3), the observables must be stationary. This option is not yet com-
patible with analytic_derivation.
kalman_tol = DOUBLE
Numerical tolerance for determining the singularity of the covariance matrix of the prediction errors
during the Kalman filter (minimum allowed reciprocal of the matrix condition number). Default value
is 1e-10.
diffuse_kalman_tol = DOUBLE
Numerical tolerance for determining the singularity of the covariance matrix of the prediction errors
(𝐹∞ ) and the rank of the covariance matrix of the non-stationary state variables (𝑃∞ ) during the Diffuse
Kalman filter. Default value is 1e-6.
filter_covariance
Saves the series of one step ahead error of forecast covariance matrices. With Metropolis, they are
saved in oo_.FilterCovariance, otherwise in oo_.Smoother.Variance. Saves also k-step ahead
error of forecast covariance matrices if filter_step_ahead is set.
filter_step_ahead = [INTEGER1:INTEGER2]
filter_step_ahead = [INTEGER1 INTEGER2 ...]
Triggers the computation k-step ahead filtered values, i.e. 𝐸𝑡 𝑦𝑡+𝑘 . Stores results in oo_.
FilteredVariablesKStepAhead. Also stores 1-step ahead values in oo_.FilteredVariables.
oo_.FilteredVariablesKStepAheadVariances is stored if filter_covariance.
filter_decomposition
Triggers the computation of the shock decomposition of the above k-step ahead filtered values. Stores
results in oo_.FilteredVariablesShockDecomposition.
smoothed_state_uncertainty
Triggers the computation of the variance of smoothed estimates, i.e. 𝑣𝑎𝑟𝑇 (𝑦𝑡 ). Stores results in oo_.
Smoother.State_uncertainty.
diffuse_filter
Uses the diffuse Kalman filter (as described in Durbin and Koopman (2012) and Koopman and Durbin
(2003) for the multivariate and Koopman and Durbin (2000) for the univariate filter) to estimate models
with non-stationary observed variables. This option will also reset the qz_criterium to count unit
root variables towards the stable variables. Trying to estimate a model with unit roots will otherwise
result in a Blanchard-Kahn error.
When diffuse_filter is used the lik_init option of estimation has no effect.
When there are nonstationary exogenous variables in a model, there is no unique deterministic steady
state. For instance, if productivity is a pure random walk:
𝑎𝑡 = 𝑎𝑡−1 + 𝑒𝑡
any value of 𝑎 ¯ of 𝑎 is a deterministic steady state for productivity. Consequently, the model admits an
infinity of steady states. In this situation, the user must help Dynare in selecting one steady state, except
if zero is a trivial model’s steady state, which happens when the linear option is used in the model
declaration. The user can either provide the steady state to Dynare using a steady_state_model
block (or writing a steady state file) if a closed form solution is available, see steady_state_model,
or specify some constraints on the steady state, see equation_tag_for_conditional_steady_state, so that
Dynare computes the steady state conditionally on some predefined levels for the non stationary vari-
ables. In both cases, the idea is to use dummy values for the steady state level of the exogenous non
stationary variables.
Note that the nonstationary variables in the model must be integrated processes (their first difference
or k-difference must be stationary).
heteroskedastic_filter
Runs filter, likelihood, and smoother using heteroskedastic definitions provided in a
heteroskedastic_shocks block.
selected_variables_only
Only run the classical smoother on the variables listed just after the estimation command. This
option is incompatible with requesting classical frequentist forecasts and will be overridden in this
case. When using Bayesian estimation, the smoother is by default only run on the declared endogenous
variables. Default: run the smoother on all the declared endogenous variables.
cova_compute = INTEGER
When 0, the covariance matrix of estimated parameters is not computed after the computation of pos-
terior mode (or maximum likelihood). This increases speed of computation in large models during
development, when this information is not always necessary. Of course, it will break all successive
computations that would require this covariance matrix. Otherwise, if this option is equal to 1, the
covariance matrix is computed and stored in variable hh of MODEL_FILENAME_mode.mat. Default is
1.
solve_algo = INTEGER
See solve_algo.
order = INTEGER
Order of approximation around the deterministic steady state. When greater than 1, the likelihood
is evaluated with a particle or nonlinear filter (see Fernández-Villaverde and Rubio-Ramírez (2005)).
Default is 1, i.e. the likelihood of the linearized model is evaluated using a standard Kalman filter.
irf = INTEGER
See irf . Only used if bayesian_irf is passed.
irf_shocks = ( VARIABLE_NAME [[,] VARIABLE_NAME ...] )
See irf_shocks. Only used if bayesian_irf is passed.
irf_plot_threshold = DOUBLE
See irf_plot_threshold. Only used if bayesian_irf is passed.
aim_solver
See aim_solver.
lyapunov = OPTION
Determines the algorithm used to solve the Lyapunov equation to initialized the variance-covariance
matrix of the Kalman filter using the steady-state value of state variables. Possible values for OPTION
are:
default
Uses the default solver for Lyapunov equations based on Bartels-Stewart algorithm.
fixed_point
Uses a fixed point algorithm to solve the Lyapunov equation. This method is faster
than the default one for large scale models, but it could require a large amount of
iterations.
doubling
Uses a doubling algorithm to solve the Lyapunov equation (disclyap_fast). This
method is faster than the two previous one for large scale models.
square_root_solver
Uses a square-root solver for Lyapunov equations (dlyapchol). This method is fast
for large scale models (available under MATLAB if the Control System Toolbox is in-
stalled; available under Octave if the control package from Octave-Forge is installed)
Default value is default.
lyapunov_fixed_point_tol = DOUBLE
This is the convergence criterion used in the fixed point Lyapunov solver. Its default value is 1e-10.
lyapunov_doubling_tol = DOUBLE
This is the convergence criterion used in the doubling algorithm to solve the Lyapunov equation. Its
default value is 1e-16.
use_penalized_objective_for_hessian
Use the penalized objective instead of the objective function to compute numerically the hessian matrix
at the mode. The penalties decrease the value of the posterior density (or likelihood) when, for some
perturbations, Dynare is not able to solve the model (issues with steady state existence, Blanchard and
Kahn conditions, . . . ). In pratice, the penalized and original objectives will only differ if the posterior
mode is found to be near a region where the model is ill-behaved. By default the original objective
function is used.
analytic_derivation
Triggers estimation with analytic gradient at order=1. The final hessian at the mode is also computed
analytically. Only works for stationary models without missing observations, i.e. for kalman_algo<3.
Optimizers that rely on analytic gradients are mode_compute=1,3,4,5,101.
ar = INTEGER
See ar. Only useful in conjunction with option moments_varendo.
endogenous_prior
Use endogenous priors as in Christiano, Trabandt and Walentin (2011). The procedure is motivated
by sequential Bayesian learning. Starting from independent initial priors on the parameters, specified
in the estimated_params block, the standard deviations observed in a “pre-sample”, taken to be the
actual sample, are used to update the initial priors. Thus, the product of the initial priors and the
pre-sample likelihood of the standard deviations of the observables is used as the new prior (for more
information, see the technical appendix of Christiano, Trabandt and Walentin (2011)). This procedure
helps in cases where the regular posterior estimates, which minimize in-sample forecast errors, result
in a large overprediction of model variable variances (a statistic that is not explicitly targeted, but often
of particular interest to researchers).
use_univariate_filters_if_singularity_is_detected = INTEGER
Decide whether Dynare should automatically switch to univariate filter if a singularity is encountered
in the likelihood computation (this is the behaviour if the option is equal to 1). Alternatively, if the
option is equal to 0, Dynare will not automatically change the filter, but rather use a penalty value for
the likelihood when such a singularity is encountered. Default: 1.
keep_kalman_algo_if_singularity_is_detected
With the default use_univariate_filters_if_singularity_is_detected=1, Dynare will
switch to the univariate Kalman filter when it encounters a singular forecast error variance matrix
during Kalman filtering. Upon encountering such a singularity for the first time, all subsequent pa-
rameter draws and computations will automatically rely on univariate filter, i.e. Dynare will never try
the multivariate filter again. Use the keep_kalman_algo_if_singularity_is_detected option
to have the use_univariate_filters_if_singularity_is_detected only affect the behavior
for the current draw/computation.
rescale_prediction_error_covariance
Rescales the prediction error covariance in the Kalman filter to avoid badly scaled matrix and reduce
the probability of a switch to univariate Kalman filters (which are slower). By default no rescaling is
done.
qz_zero_threshold = DOUBLE
See qz_zero_threshold.
taper_steps = [INTEGER1 INTEGER2 ...]
Percent tapering used for the spectral window in the Geweke (1992,1999) convergence diagnostics
(requires mh_nblocks=1). The tapering is used to take the serial correlation of the posterior draws
into account. Default: [4 8 15].
brooks_gelman_plotrows = INTEGER
Number of parameters to depict along the rows of the figures depicting the Brooks and Gelman (1998)
convergence diagnostics. Default: 3.
filter_algorithm = OPTION
Sets the particle filter algorithm. Possible values for OPTION are:
sis
Sequential importance sampling algorithm, this is the default value.
apf
Auxiliary particle filter.
gf
Gaussian filter.
gmf
Gaussian mixture filter.
cpf
Conditional particle filter.
nlkf
Use a standard (linear) Kalman filter algorithm with the nonlinear measurement and
state equations.
proposal_approximation = OPTION
Sets the method for approximating the proposal distribution. Possible values for OPTION are:
cubature, montecarlo and unscented. Default value is unscented.
distribution_approximation = OPTION
Sets the method for approximating the particle distribution. Possible values for OPTION are:
cubature, montecarlo and unscented. Default value is unscented.
cpf_weights = OPTION
Controls the method used to update the weights in conditional particle filter, possible values are
amisanotristani (Amisano et al. (2010)) or murrayjonesparslow (Murray et al. (2013)). Default
value is amisanotristani.
nonlinear_filter_initialization = INTEGER
Sets the initial condition of the nonlinear filters. By default the nonlinear filters are initialized with
the unconditional covariance matrix of the state variables, computed with the reduced form solu-
tion of the first order approximation of the model. If nonlinear_filter_initialization=2,
the nonlinear filter is instead initialized with a covariance matrix estimated with a stochastic sim-
ulation of the reduced form solution of the second order approximation of the model. Both these
initializations assume that the model is stationary, and cannot be used if the model has unit roots
(which can be seen with the check command prior to estimation). If the model has stochas-
tic trends, user must use nonlinear_filter_initialization=3, the filters are then initial-
ized with an identity matrix for the covariance matrix of the state variables. Default value is
nonlinear_filter_initialization=1 (initialization based on the first order approximation of the
model).
particle_filter_options = (NAME, VALUE, ...)
A list of NAME and VALUE pairs. Can be used to set some fine-grained options for the particle filter
routines. The set of available options depends on the selected filter routine.
More information on particle filter options is available at https://git.dynare.org/Dynare/dynare/-/wikis/
Particle-filters.
Available options are:
'pruning'
Enable pruning for particle filter-related simulations. Default: false.
'liu_west_delta'
Set the value for delta for the Liu/West online filter. Default: 0.99.
'unscented_alpha'
Set the value for alpha for unscented transforms. Default: 1.
'unscented_beta'
Set the value for beta for unscented transforms. Default: 2.
'unscented_kappa'
Set the value for kappa for unscented transforms. Default: 1.
'initial_state_prior_std'
Value of the diagonal elements for the initial covariance of the state variables when
employing nonlinear_filter_initialization=3. Default: 1.
'mixture_state_variables'
Number of mixture components in the Gaussian-mixture filter (gmf) for the state
variables. Default: 5.
'mixture_structural_shocks'
Number of mixture components in the Gaussian-mixture filter (gmf) for the structural
shocks. Default: 1.
'mixture_measurement_shocks'
Number of mixture components in the Gaussian-mixture filter (gmf) for the measure-
ment errors. Default: 1.
Note
If no mh_jscale parameter is used for a parameter in estimated_params, the procedure uses mh_jscale
for all parameters. If mh_jscale option isn’t set, the procedure uses 0.2 for all parameters. Note that if
mode_compute=6 is used or the posterior_sampler_option called scale_file is specified, the values
set in estimated_params will be overwritten.
“Endogenous” prior restrictions
It is also possible to impose implicit “endogenous” priors about IRFs and moments on the model during
estimation. For example, one can specify that all valid parameter draws for the model must generate fiscal
multipliers that are bigger than 1 by specifying how the IRF to a government spending shock must look
like. The prior restrictions can be imposed via irf_calibration and moment_calibration blocks (see
IRF/Moment calibration). The way it works internally is that any parameter draw that is inconsistent with
the “calibration” provided in these blocks is discarded, i.e. assigned a prior density of 0. When specifying
these blocks, it is important to keep in mind that one won’t be able to easily do model_comparison in this
case, because the prior density will not integrate to 1.
Output
After running estimation, the parameters M_.params and the variance matrix M_.Sigma_e of the shocks
are set to the mode for maximum likelihood estimation or posterior mode computation without Metropolis
iterations. After estimation with Metropolis iterations (option mh_replic > 0 or option load_mh_file
set) the parameters M_.params and the variance matrix M_.Sigma_e of the shocks are set to the posterior
mean.
Depending on the options, estimation stores results in various fields of the oo_ structure, described below.
In the following variables, we will adopt the following shortcuts for specific field names:
MOMENT_NAME
This field can take the following values:
HPDinf
4 See options conf_sig and mh_conf_sig to change the size of the HPD interval.
5 See options conf_sig () and mh_conf_sig to change the size of the HPD interval.
oo_.posterior.optimization.OBJECT
oo_.posterior.metropolis.OBJECT
oo_.FilteredVariables.VARIABLE_NAME
oo_.FilteredVariables.MOMENT_NAME.VARIABLE_NAME
oo_.Filtered_Variables_X_step_ahead.VARIABLE_NAME
The n-th entry stores the k-step ahead filtered variable computed at time n for time n+k.
MATLAB/Octave variable: oo_.FilteredVariablesShockDecomposition
Variable set by the estimation command, if it is used with the filter_step_ahead option. The
k-steps are stored along the rows while the columns indicate the respective variables. The third di-
mension corresponds to the shocks in declaration order. The fourth dimension of the array provides
the observation for which the forecast has been made. For example, if filter_step_ahead=[1 2
4] and nobs=200, the element (3,5,2,204) stores the contribution of the second shock to the four pe-
riod ahead filtered value of variable 5 (in deviations from the mean) computed at time t=200 for time
t=204. The periods at the beginning and end of the sample for which no forecasts can be made, e.g.
entries (1,5,1) and (1,5,204) in the example, are set to zero. Padding with zeros and variable ordering
is analogous to oo_.FilteredVariablesKStepAhead.
MATLAB/Octave variable: oo_.PosteriorIRF.dsge
Variable set by the estimation command, if it is used with the bayesian_irf option. Fields are of
the form:
oo_.PosteriorIRF.dsge.MOMENT_NAME.VARIABLE_NAME_SHOCK_NAME
oo_.SmoothedMeasurementErrors.VARIABLE_NAME
oo_.SmoothedShocks.VARIABLE_NAME
oo_.SmoothedShocks.MOMENT_NAME.VARIABLE_NAME
oo_.SmoothedVariables.VARIABLE_NAME
oo_.SmoothedVariables.MOMENT_NAME.VARIABLE_NAME
oo_.UpdatedVariables.VARIABLE_NAME
oo_.UpdatedVariables.MOMENT_NAME.VARIABLE_NAME
oo_.FilterCovariance.MOMENT_NAME
the calib_smoother command. Contains the trend coefficients of the observed variables used in the
smoother in order of declaration of the observed variables.
MATLAB/Octave variable: oo_.Smoother.Trend
Variable set by the estimation command (if used with the smoother option), or by the
calib_smoother command. Contains the trend component of the variables used in the smoother.
Fields are of the form:
oo_.Smoother.Trend.VARIABLE_NAME
oo_.Smoother.Constant.VARIABLE_NAME
oo_.PosteriorTheoreticalMoments.dsge.THEORETICAL_MOMENT.ESTIMATED_OBJECT.
˓→MOMENT_NAME.VARIABLE_NAME
ConditionalVarianceDecompositionME
Only if the conditional_variance_decomposition option has been specified.
Same as ConditionalVarianceDecomposition, but contains the decomposition of the
measured as opposed to the actual variable. The joint contribution of the measure-
ment error will be saved in a field names ME.
MATLAB/Octave variable: oo_.posterior_density
Variable set by the estimation command, if it is used with mh_replic > 0 or load_mh_file op-
tion. Fields are of the form:
oo_.posterior_density.PARAMETER_NAME
oo_.posterior_hpdinf.ESTIMATED_OBJECT.VARIABLE_NAME
oo_.posterior_hpdsup.ESTIMATED_OBJECT.VARIABLE_NAME
oo_.posterior_mean.ESTIMATED_OBJECT.VARIABLE_NAME
oo_.posterior_mode.ESTIMATED_OBJECT.VARIABLE_NAME
oo_.posterior_std_at_mode.ESTIMATED_OBJECT.VARIABLE_NAME
oo_.posterior_std.ESTIMATED_OBJECT.VARIABLE_NAME
oo_.posterior_var.ESTIMATED_OBJECT.VARIABLE_NAME
oo_.posterior_median.ESTIMATED_OBJECT.VARIABLE_NAME
Example
Here are some examples of generated variables:
oo_.posterior_mode.parameters.alp
oo_.posterior_mean.shocks_std.ex
oo_.posterior_hpdsup.measurement_errors_corr.gdp_conso
oo_.RecursiveForecast.FORECAST_OBJECT.VARIABLE_NAME
oo_.convergence.geweke.VARIABLE_NAME.DIAGNOSTIC_OBJECT
Provided that you have observations on some endogenous variables or their dynamic behavior following struc-
tural shocks, Dynare provides a suite of tools for parameter estimation utilizing the method of moments approach.
This includes the Simulated Method of Moments (SMM), the Generalized Method of Moments (GMM), and Im-
pulse Response Function Matching (IRF matching). Each of these methods offers a distinct strategy for estimating
some or all parameters by minimizing the distances between unconditional model objects (moments or impulse
responses) and their empirical counterparts.
GMM and SMM estimation
For SMM Dynare computes model moments via stochastic simulations based on the perturbation approximation
up to any order, whereas for GMM model moments are computed in closed-form based on the pruned state-space
representation of the perturbation solution up to third order. The implementation of SMM is inspired by Born
and Pfeifer (2014) and Ruge-Murcia (2012), whereas the one for GMM is adapted from Andreasen, Fernández-
Villaverde and Rubio-Ramírez (2018) and Mutschler (2018). Successful estimation heavily relies on the accuracy
and efficiency of the perturbation approximation, so it is advised to tune this as much as possible (see Computing
the stochastic solution). The method of moments estimator is consistent and asymptotically normally distributed
given certain regularity conditions (see Duffie and Singleton (1993) for SMM and Hansen (1982) for GMM). For
instance, it is required to have at least as many moment conditions as estimated parameters (over-identified or just
identified). Moreover, the Jacobian of the moments with respect to the estimated parameters needs to have full
rank. Performing identification analysis helps to check this regularity condition.
In the over-identified case of declaring more moment conditions than estimated parameters, the choice of
weighting_matrix matters for the efficiency of the estimation, because the estimated orthogonality conditions
are random variables with unequal variances and usually non-zero cross-moment covariances. A weighting ma-
trix allows to re-weight moments to put more emphasis on moment conditions that are more informative or better
measured (in the sense of having a smaller variance). To achieve asymptotic efficiency, the weighting matrix
needs to be chosen such that, after appropriate scaling, it has a probability limit proportional to the inverse of the
covariance matrix of the limiting distribution of the vector of orthogonality conditions. Dynare uses a Newey-
West-type estimator with a Bartlett kernel to compute an estimate of this so-called optimal weighting matrix.
Note that in this over-identified case, it is advised to perform the estimation in at least two stages by setting e.g.
weighting_matrix=['DIAGONAL','DIAGONAL'] so that the computation of the optimal weighting matrix benefits
from the consistent estimation of the previous stages. The optimal weighting matrix is used to compute standard
errors and the J-test of overidentifying restrictions, which tests whether the model and selection of moment con-
ditions fits the data sufficiently well. If the null hypothesis of a “valid” model is rejected, then something is (most
likely) wrong with either your model or selection of orthogonality conditions.
In case the (presumed) global minimum of the moment distance function is located in a region of the param-
eter space that is typically considered unlikely (dilemma of absurd parameters), you may opt to choose the
penalized_estimator option. Similar to adding priors to the likelihood, this option incorporates prior knowl-
edge (i.e. the prior mean) as additional moment restrictions and weights them by their prior precision to guide the
minimization algorithm to more plausible regions of the parameter space. Ideally, these regions are characterized
by only slightly worse values of the objective function. Note that adding prior information comes at the cost of a
loss in efficiency of the estimator.
IRF matching
Dynare employs a user-specified simulation_method to compute the impulse response function (IRF) for observable
variables with respect to the structural shocks. Currently, only stochastic simulations based on the perturbation
method are supported and it is advised to fine-tune the perturbation approximation as much as possible for optimal
results (see Computing the stochastic solution for guidance).
The core idea of IRF matching is then to treat empirical impulse responses (e.g. given from a SVAR or local
projection estimation) as data and select model parameters that align the model’s IRFs closely with their em-
pirical counterparts. Dynare supports both Frequentist and Bayesian IRF matching approaches, using the same
optimization and sampling techniques as those applied in likelihood-based estimation (sharing many options with
the estimation command). The Frequentist approach to this is inspired by the work of Christiano, Eichenbaum,
and Evans (2005), while the Bayesian method adapts from Christiano, Trabandt, and Walentin (2010). A cru-
cial element in IRF matching is the choice of the weighting matrix, which influences how the distances between
model-generated and empirical IRFs are weighted in the estimation process. It is common practice to employ a
diagonal weighting matrix, with the diagonal elements set to the inverse of the estimated variance of the respective
empirical impulse response, thereby prioritizing more precisely estimated IRFs. While it’s possible to also specify
weights using covariances between different IRF components (possibly with shrinking), this is less common due
to the complex interpretation involved (cross effects of different variables or different shocks or both).
Importantly, it is the user’s responsibility to supply (1) the values of the empirical IRFs intended for matching and
(2) their importance by choosing an appropriate weighting matrix. Dynare does not perform the SVAR or local
projection estimation, it treats the empirical IRFs as given.
VARIABLE_NAME(LEAD/LAG)^POWER*VARIABLE_NAME(LEAD/LAG)^POWER*...*VARIABLE_
˓→NAME(LEAD/LAG)^POWER;
where VARIABLE_NAME is the name of a declared observable variable, LEAD/LAG is either a negative
integer for lags or a positive one for leads, and POWER is a positive integer indicating the exponent on the
variable. You can omit LEAD/LAG equal to 0 or POWER equal to 1.
Example
For 𝐸[𝑐𝑡 ], 𝐸[𝑦𝑡 ], 𝐸[𝑐2𝑡 ], 𝐸[𝑐𝑡 𝑦𝑡 ], 𝐸[𝑦𝑡2 ], 𝐸[𝑐𝑡 𝑐𝑡+3 ], 𝐸[𝑦𝑡+1
2
𝑐3𝑡−4 ], 𝐸[𝑐3𝑡−5 𝑦𝑡2 ] use the following block:
matched_moments;
c;
y;
c*c;
(continues on next page)
Limitations
1. For GMM, Dynare can only compute the theoretical mean, covariance, and autocovariances (i.e. first and
second moments). Higher-order moments are only supported for SMM.
2. By default, the product moments are not demeaned, unless the prefilter option is set to 1. That is, by
default, c*c corresponds to 𝐸[𝑐2𝑡 ] and not to 𝑉 𝑎𝑟[𝑐𝑡 ] = 𝐸[𝑐2𝑡 ] − 𝐸[𝑐𝑡 ]2 .
Output
Dynare translates the matched_moments block into a cell array M_.matched_moments where:
• the first column contains a vector of indices for the chosen variables in declaration order
• the second column contains the corresponding vector of leads and lags
• the third column contains the corresponding vector of powers
During the estimation phase, Dynare will eliminate all redundant or duplicate orthogonality conditions in
M_.matched_moments and display which conditions were removed. In the example above, this would be
the case for the last row, which is the same as the second-to-last one. The original block is saved in M_.
matched_moments_orig.
Block: matched_irfs ;
Block: matched_irfs(overwrite);
This block specifies the values and diagonal weights of the empirical IRFs that are matched in estimation.
The overwrite option replaces the current matched_irfs block with the new one.
Each line inside of the block should be of the form:
var ENDOGENOUS_NAME;
varexo EXOGENOUS_NAME;
periods INTEGER[:INTEGER] [[,] INTEGER[:INTEGER]]...;
values DOUBLE | (EXPRESSION) [[,] DOUBLE | (EXPRESSION) ]...;
weights DOUBLE | (EXPRESSION) [[,] DOUBLE | (EXPRESSION) ]...;
var y; varexo eD; periods 5; values 7; weights 25; var r; varexo eD; periods 1,2; values
17,18; weights 37,38; var c; varexo eA; periods 3:5; values (xx); var y; varexo eA; periods
1:2; values 30; weights (ww);
varexo eR; var w; periods 1, 13:15, 2:12; values 2, (xx), 15; weights 3, (xx), 4; end;
Limitations
Output
Dynare translates the matched_irfs block into a cell array where the rows correspond to the statements in
the block M_.matched_irfs where:
• the first column contains the names of the endogenous variables
• the second column contains the names of the exogenous variables
• the third column contains a nested cell array that contains
the list of horizons, values and weights.
Block: matched_irfs_weights ;
Block: matched_irfs_weights(overwrite) ;
This optional block specifies elements of the weighting matrix used for IRF matching. The overwrite
option replaces the current matched_irfs_weights block with the new one.
The weighting matrix is initialized as a diagonal matrix with ones on the diagonal. Each line inside of the
block should be of the form:
where ENDOGENOUS_NAME_1 and ENDOGENOUS_NAME_2 are the names of declared observable vari-
ables, EXOGENOUS_NAME_1 and EXOGENOUS_NAME_2 are the names of exogenous variables, HORI-
ZON_1 and HORIZON_2 are integers indicating the horizon of the IRFs and WEIGHT is a double value of
the weight one wants to assign to the covariance between the two specified IRFs.
Example You can either enter the values directly or load them from variables in the workspace.
matched_irfs_weights;
c(1), e_A, c(1), e_A, 20;
y(3), e_R, y(2), e_R, (empIRFsCovInv_yR3_yR2);
end;
Limitations
Output
Dynare translates the matched_irfs_weigths block into a cell array M_.matched_irfs_weights where:
• the first column contains the names of the first endogenous variables
• the second column contains the names of the first exogenous variables
• the third column contains the horizons of the IRFs for the first endogneous variable
• the fourth column contains the names of the second endogenous variables
• the fifth column contains the names of the second exogenous variables
• the sixth column contains the horizons of IRFs for the second endogenous variable
• the seventh column contains the vector of weights
All values that are not specified will be either one (if they are on the diagonal) or zero (if they are not on the
diagonal). Symmetry is respected, so one does not need to specify both c(1), e_A, y(3), e_R, WEIGHT
and y(3), e_R, c(1), e_A, WEIGHT. Default: empty cell.
Block: estimated_params ;
Required. This block lists all parameters to be estimated and specifies bounds and priors as necessary. See
estimated_params for details and syntax.
Block: estimated_params_init ;
Optional. This block declares numerical initial values for the optimizer when these ones are different from
the prior mean. See estimated_params_init for details and syntax.
Block: estimated_params_bounds ;
Optional. This block declares lower and upper bounds for parameters in maximum likelihood estimation.
See estimated_params_bounds for details and syntax.
Command: method_of_moments(OPTIONS...);
This command runs the method of moments estimation. The following information will be displayed in the
command window:
• Overview of options chosen by the user
• Estimation results for each stage and iteration
• Value of minimized moment distance objective function
• Result of the J-test (for SMM/GMM)
• Comparison plot of model IRFs and empirical IRFs (for IRF matching)
• Table of data moments/IRFs and estimated model moments/IRFs
mom_method = SMM|GMM|IRF_MATCHING
“Simulated Method of Moments” is triggered by SMM, “Generalized Method of Moments” by
GMM and “Impulse Response Function Matching” by IRF_MATCHING.
datafile = FILENAME
The name of the file containing the data (for GMM and SMM only). See datafile for the
meaning and syntax. For IRF matching, the data is specified in the matched_irfs block.
order = INTEGER
Order of perturbation approximation. For GMM only orders 1|2|3 are supported. For SMM and
IRF matching, you can choose an arbitrary order. Note that the order set in other functions will
not overwrite the default. Default: 1.
pruning
Discard higher order terms when iteratively computing simulations of the solution. See pruning
for more details. Default: not set for SMM and IRF matching, always set for GMM.
verbose
Display and store intermediate estimation results in oo_.mom. Default: not set.
Common options for SMM and GMM
penalized_estimator
This option includes deviations of the estimated parameters from the prior mean as additional
moment restrictions and weights them by their prior precision. Default: not set.
weighting_matrix = ['WM1','WM2',...,'WMn']
Determines the weighting matrix used at each estimation stage. The number of elements
will define the number of stages, i.e. weighting_matrix = ['DIAGONAL','DIAGONAL',
'OPTIMAL'] performs a three-stage estimation. Possible values for WM are:
IDENTITY_MATRIX
Sets the weighting matrix equal to the identity matrix.
OPTIMAL
Uses the optimal weighting matrix computed by a Newey-West-type esti-
mate with a Bartlett kernel. At the first stage, the data-moments are used
as initial estimate of the model moments, whereas at subsequent stages
the previous estimate of model moments will be used when computing
the optimal weighting matrix.
DIAGONAL
Uses the diagonal of the OPTIMAL weighting matrix. This choice puts
weights on the specified moments instead of on their linear combinations.
FILENAME
The name of the MAT-file (extension .mat) containing a user-specified
weighting matrix. The file must include a positive definite square matrix
called weighting_matrix with both dimensions equal to the number of
orthogonality conditions.
Default value is ['DIAGONAL','OPTIMAL'].
weighting_matrix_scaling_factor = DOUBLE
Scaling of weighting matrix in objective function. This value should be chosen to obtain values of
the objective function in a reasonable numerical range to prevent over- and underflows. Default:
1.
bartlett_kernel_lag = INTEGER
Bandwidth of kernel for computing the optimal weighting matrix. Default: 20.
se_tolx = DOUBLE
Step size for numerical differentiation when computing standard errors with a two-sided finite
difference method. Default: 1e-5.
burnin = INTEGER
Number of periods dropped at the beginning of simulation. Default: 500.
bounded_shock_support
Trim shocks in simulations to ±2 standard deviations. Default: not set.
seed = INTEGER
Common seed used in simulations. Default: 24051986.
simulation_multiple = INTEGER
Multiple of data length used for simulation. Default: 7.
analytic_standard_errors
Compute standard errors using analytical derivatives of moments with respect to estimated pa-
rameters. Default: not set, i.e. standard errors are computed using a two-sided finite difference
method, see se_tolx.
simulation_method = METHOD
Method to compute IRFs. Possible values for METHOD are:
STOCH_SIMUL
Simulate the model with stochastic simulations and compute IRFs as the difference
between the simulated and steady state values. See stoch_simul for more details.
irf_matching_file = FILENAME
A MATLAB file containing additional transformations on the model IRFs. This enables more
flexibility in matching the model IRFs to the empirical IRFs, e.g. by adding constants to
model IRFs, multiplying them with factors, taking the cumulative sum, creating ratios etc. See
NK_irf_matching_file.m in the examples directory for an example. Default: empty, i.e.
model IRFs exactly match empirical IRFs.
add_tiny_number_to_cholesky = DOUBLE
In case of a non-positive definite covariance matrix, a tiny number is added to the Cholesky factor
to avoid numerical problems when computing IRFs. Default: 1e-14.
drop = INTEGER
Truncation when computing IRFs with perturbation at orders greater than 1. Default: 100.
relative_irf
Requests the computation of normalized IRFs. See relative_irf for more details. Default:
false.
replic = INTEGER
Number of simulated series used to compute the IRFs. Default: 1 if order=1, and 50 otherwise.
dirname = FILENAME
Directory in which to store estimation output. See dirname for more details. Default:
<mod_file>.
graph_format = FORMAT
Specify the file format(s) for graphs saved to disk. See graph_format for more details. Default:
eps.
nodisplay
See nodisplay. Default: not set.
nograph
See nograph . Default: not set.
noprint
See noprint. Default: not set.
plot_priors = INTEGER
Control the plotting of priors. See plot_priors for more details. Default: 1, i.e. plot priors.
prior_trunc = DOUBLE
See prior_trunc for more details. Default: 1e-10.
tex
See tex. Default: not set.
prefilter = INTEGER
A value of 1 means that the estimation procedure will demean each data series by its empirical
mean and each model moment by its theoretical mean. See prefilter for more details. Default:
0, i.e. no prefiltering.
first_obs = INTEGER
See first_obs. Default: 1.
nobs = INTEGER
See nobs. Default: all observations are considered.
logdata
See logdata. Default: not set.
xls_sheet = QUOTED_STRING
See xls_sheet. Default: 1.
xls_range = RANGE
See xls_range. Default: empty.
mode_file = FILENAME
Name of the file containing previous value for the mode. See mode_file. Default: empty.
mode_compute = INTEGER | FUNCTION_NAME
See mode_compute. Default: 13 for GMM and SMM and 5 for IRF matching.
additional_optimizer_steps = [INTEGER]
additional_optimizer_steps = [INTEGER1:INTEGER2]
additional_optimizer_steps = [INTEGER1 INTEGER2]
Vector of additional minimization algorithms run after mode_compute. If verbose option is
set, then the additional estimation results are saved into the oo_.mom structure prefixed with
verbose_. Default: empty, i.e. no additional optimization iterations.
optim = (NAME, VALUE, ...)
See optim. Default: empty.
analytic_jacobian
Use analytic Jacobian in optimization, only available for GMM and gradient-based optimizers.
Default: not set.
huge_number = DOUBLE
See huge_number. Default: 1e7.
silent_optimizer
See silent_optimizer. Default: not set.
use_penalized_objective_for_hessian
See use_penalized_objective_for_hessian. Default: not set.
General options
posterior_sampling_method = NAME
See posterior_sampling_method. Default: random_walk_metropolis_hastings.
posterior_sampler_options = (NAME, VALUE, ...)
See posterior_sampler_options. Default: not set.
mh_posterior_mode_estimation
See mh_posterior_mode_estimation. Default: not set.
cova_compute = INTEGER
See cova_compute. Default: 1.
mcmc_jumping_covariance = OPTION
See mcmc_jumping_covariance. Default: hessian.
mh_replic = INTEGER
See mh_replic. Default: 0.
mh_nblocks = INTEGER
See mh_nblocks. Default: 2.
mh_jscale = DOUBLE
See mh_jscale. Default: 2.38 divided by the square root of the number of estimated parame-
ters.
mh_tune_jscale [= DOUBLE]
See mh_tune_jscale. Default: 0.33.
mh_tune_guess = DOUBLE
See mh_tune_guess. Default: 2.38 divided by the square root of the number of estimated
parameters.
mh_conf_sig = DOUBLE
See mh_conf_sig. Default: 0.9.
mh_drop = DOUBLE
See mh_drop. Default: 0.5.
mh_init_scale_factor = DOUBLE
See mh_init_scale_factor. Default: 2.
no_posterior_kernel_density
See no_posterior_kernel_density. Default: not set.
posterior_max_subsample_draws = INTEGER
See posterior_max_subsample_draws. Default: 1200.
sub_draws = INTEGER
See sub_draws. Default: min(posterior_max_subsample_draws, (Total number of
draws)*(number of chains) ).
MCMC initialization and recovery
load_mh_file
See load_mh_file. Default: not set.
load_results_after_load_mh
See load_results_after_load_mh . Default: not set.
mh_initialize_from_previous_mcmc
See mh_initialize_from_previous_mcmc. Default: not set.
mh_initialize_from_previous_mcmc_directory = FILENAME
See mh_initialize_from_previous_mcmc_directory. Default: empty.
mh_initialize_from_previous_mcmc_prior = FILENAME
See mh_initialize_from_previous_mcmc_prior. Default: empty.
mh_initialize_from_previous_mcmc_record = FILENAME
See mh_initialize_from_previous_mcmc_record. Default: empty.
mh_recover
See mh_recover. Default: not set.
Convergence diagnostics
nodiagnostic
See nodiagnostic. Default: not set.
brooks_gelman_plotrows = INTEGER
See brooks_gelman_plotrows. Default: 3.
geweke_interval = [DOUBLE DOUBLE]
See geweke_interval. Default: [0.2 0.5].
taper_steps = [INTEGER1 INTEGER2 ...]
See taper_steps. Default: [4 8 15].
raftery_lewis_diagnostics
See raftery_lewis_diagnostics. Default: not set.
raftery_lewis_qrs = [DOUBLE DOUBLE DOUBLE]
See raftery_lewis_qrs. Default: [0.025 0.005 0.95].
aim_solver
See aim_solver. Default: not set.
k_order_solver
See k_order_solver. Default: disabled for order 1 and 2, enabled for order 3 and above.
dr = OPTION
See dr. Default: default, i.e. generalized Schur decomposition.
dr_cycle_reduction_tol = DOUBLE
See dr_cycle_reduction_tol. Default: 1e-7.
dr_logarithmic_reduction_tol = DOUBLE
See dr_logarithmic_reduction_tol. Default: 1e-12.
dr_logarithmic_reduction_maxiter = INTEGER
See dr_logarithmic_reduction_maxiter. Default: 100.
lyapunov = OPTION
See lyapunov. Default: default, i.e. based on Bartlets-Stewart algorithm.
lyapunov_complex_threshold = DOUBLE
See lyapunov_complex_threshold. Default: 1e-15.
lyapunov_fixed_point_tol = DOUBLE
See lyapunov_fixed_point_tol. Default: 1e-10.
lyapunov_doubling_tol = DOUBLE
See lyapunov_doubling_tol. Default: 1e-16.
qz_criterium = DOUBLE
See qz_criterium. For unit roots (only possible at order=1) set e.g. to 1.000001. Default:
0.999999 as it is assumed that the observables are weakly stationary.
qz_zero_threshold = DOUBLE
See qz_zero_threshold. Default: 1e-6.
schur_vec_tol = DOUBLE
Tolerance level used to find nonstationary variables in Schur decomposition of the transition
matrix. Default: 1e-11.
mode_check
Plots univariate slices through the moments distance objective function around the computed
minimum for each estimated parameter. This is helpful to diagnose problems with the optimizer.
Default: not set.
mode_check_neighbourhood_size = DOUBLE
See mode_check_neighbourhood_size. Default: 0.5.
mode_check_symmetric_plots = INTEGER
See mode_check_symmetric_plots. Default: 1.
mode_check_number_of_points = INTEGER
See mode_check_number_of_points. Default: 20.
method_of_moments stores user options in a structure called options_mom_ in the global workspace.
After running the estimation, the parameters M_.params and the covariance matrices of the shocks
M_.Sigma_e and of the measurement errors M_.H are set to the parameters that either minimize the
quadratic moments distance objective function or at the posterior mean in case of Bayesian MCMC
estimation. The estimation results are stored in a subfolder of dirname called method_of_moments.
Moreover, output is stored in the oo_.mom structure with the following fields:
Common outputs
MATLAB/Octave variable: oo_.mom.data_moments
Variable set by the method_of_moments command. Stores the mean of the selected empirical
moments/IRFs of data. NaN values due to leads/lags or missing data are omitted when computing
the mean for moments. Vector of dimension equal to the number of orthogonality conditions or
IRFs.
MATLAB/Octave variable: oo_.mom.model_moments
Variable set by the method_of_moments command. Stores the implied selected model mo-
ments or IRFs given the current parameter guess. Model moments are computed in closed-form
from the pruned state-space system for GMM, whereas for SMM these are based on averages
of simulated data. Model IRFs are computed from the specified simulation_method. Vector of
dimension equal to the number of orthogonality conditions.
MATLAB/Octave variable: oo_.mom.model_moments_params_derivs
Variable set by the method_of_moments command. Stores the analytically computed Jacobian
matrix of the derivatives of the model moments with respect to the estimated parameters. Only
for GMM with analytic_standard_errors. Matrix with dimension equal to the number of
orthogonality conditions times number of estimated parameters.
oo_.mom.prior.OBJECT
Variable set by the method_of_moments command if mode-finding is used. Stores the results
at the mode. Fields are of the form:
oo_.mom.posterior.optimization.OBJECT
oo_.mom.posterior.metropolis.OBJECT
oo_.mom.prior_density.PARAMETER_NAME
oo_.mom.posterior_density.PARAMETER_NAME
oo_.mom.posterior_hpdinf.ESTIMATED_OBJECT.VARIABLE_NAME
oo_.mom.posterior_hpdsup.ESTIMATED_OBJECT.VARIABLE_NAME
oo_.posterior_mean.ESTIMATED_OBJECT.VARIABLE_NAME
oo_.mom.posterior_mode.ESTIMATED_OBJECT.VARIABLE_NAME
oo_.mom.posterior_std_at_mode.ESTIMATED_OBJECT.VARIABLE_NAME
oo_.mom.posterior_std.ESTIMATED_OBJECT.VARIABLE_NAME
oo_.mom.posterior_variance.ESTIMATED_OBJECT.VARIABLE_NAME
oo_.mom.posterior_median.ESTIMATED_OBJECT.VARIABLE_NAME
oo_.mom.posterior_deciles.ESTIMATED_OBJECT.VARIABLE_NAME
This example attributes a 70% prior over my_model and 30% prior over alt_model.
MATLAB/Octave variable: oo_.Model_Comparison
Variable set by the model_comparison command. Fields are of the form:
oo_.Model_Comparison.FILENAME.VARIABLE_NAME
where FILENAME is the file name of the model and VARIABLE_NAME is one of the following:
Prior
diffuse_kalman_tol = DOUBLE
See diffuse_kalman_tol.
diffuse_filter
See diffuse_filter.
xls_sheet = QUOTED_STRING
See xls_sheet.
xls_range = RANGE
See xls_range.
use_shock_groups [= NAME]
Uses shock grouping defined by the string instead of individual shocks in the decomposition. The
groups of shocks are defined in the shock_groups block. If no group name is given, default is
assumed.
colormap = VARIABLE_NAME
Controls the colormap used for the shocks decomposition graphs. VARIABLE_NAME must be the
name of a MATLAB/Octave variable that has been declared beforehand and whose value will be passed
to the MATLAB/Octave colormap function (see the MATLAB/Octave manual for the list of acceptable
values).
nograph
See nograph . Suppresses the display and creation only within the shock_decomposition command,
but does not affect other commands. See plot_shock_decomposition for plotting graphs.
init_state = BOOLEAN
If equal to 0, the shock decomposition is computed conditional on the smoothed state variables in
period 0, i.e. the smoothed shocks starting in period 1 are used. If equal to 1, the shock decomposition
is computed conditional on the smoothed state variables in period 1. Default: 0.
with_epilogue
If set, then also compute the decomposition for variables declared in the epilogue block (see Epilogue
Variables).
Output
MATLAB/Octave variable: oo_.shock_decomposition
The results are stored in the field oo_.shock_decomposition, which is a three dimensional array.
The first dimension contains the M_.endo_nbr endogenous variables. The second dimension stores
in the first M_.exo_nbr columns the contribution of the respective shocks. Column M_.exo_nbr+1
stores the contribution of the initial conditions, while column M_.exo_nbr+2 stores the smoothed
value of the respective endogenous variable in deviations from their steady state, i.e. the mean and
trends are subtracted. The third dimension stores the time periods. Both the variables and shocks are
stored in the order of declaration, i.e. M_.endo_names and M_.exo_names, respectively.
Block: shock_groups ;
Block: shock_groups(OPTIONS...);
Shocks can be regrouped for the purpose of shock decomposition. The composition of the shock groups is
written in a block delimited by shock_groups and end.
Each line defines a group of shocks as a list of exogenous variables:
Options
name = NAME
Specifies a name for the following definition of shock groups. It is possible to use several
shock_groups blocks in a model file, each grouping being identified by a different name. This name
must in turn be used in the shock_decomposition command. If no name is given, default is used.
Example
shock_groups(name=group1);
supply = e_a, e_b;
'aggregate demand' = e_c, e_d;
end;
shock_decomposition(use_shock_groups=group1);
This example defines a shock grouping with the name group1, containing a set of supply and
demand shocks and conducts the shock decomposition for these two groups.
Command: realtime_shock_decomposition [VARIABLE_NAME]...;
Command: realtime_shock_decomposition(OPTIONS...) [VARIABLE_NAME]...;
This command computes the realtime historical shock decomposition for a given sample based on the Kalman
smoother. For each period 𝑇 = [presample, . . . , nobs], it recursively computes three objects:
• Real-time historical shock decomposition 𝑌 (𝑡|𝑇 ) for 𝑡 = [1, . . . , 𝑇 ], i.e. without observing data in
[𝑇 + 1, . . . , nobs]. This results in a standard shock decomposition being computed for each additional
datapoint becoming available after presample.
• Forecast shock decomposition 𝑌 (𝑇 + 𝑘|𝑇 ) for 𝑘 = [1, . . . , 𝑓 𝑜𝑟𝑒𝑐𝑎𝑠𝑡], i.e. the 𝑘-step ahead forecast
made for every 𝑇 is decomposed in its shock contributions.
• Real-time conditional shock decomposition of the difference between the real-time historical shock
decomposition and the forecast shock decomposition. If vintage is equal to 0, it computes the effect
of shocks realizing in period 𝑇 , i.e. decomposes 𝑌 (𝑇 |𝑇 ) − 𝑌 (𝑇 |𝑇 − 1). Put differently, it conducts a
1-period ahead shock decomposition from 𝑇 − 1 to 𝑇 , by decomposing the update step of the Kalman
filter. If vintage>0 and smaller than nobs, the decomposition is conducted of the forecast revision
𝑌 (𝑇 + 𝑘|𝑇 + 𝑘) − 𝑌 (𝑇 + 𝑘|𝑇 ).
Like shock_decomposition it decomposes the historical deviations of the endogenous variables from their
respective steady state values into the contribution coming from the various shocks. The variable_names
provided govern for which variables the decomposition is plotted.
Note that this command must come after either estimation (in case of an estimated model) or
stoch_simul (in case of a calibrated model).
Options
parameter_set = OPTION
See parameter_set for possible values.
datafile = FILENAME
See datafile.
first_obs = INTEGER
See first_obs.
nobs = INTEGER
See nobs.
use_shock_groups [= NAME]
See use_shock_groups.
colormap = VARIABLE_NAME
See colormap.
nograph
See nograph . Only shock decompositions are computed and stored in oo_.
realtime_shock_decomposition, oo_.conditional_shock_decomposition
and oo_.realtime_forecast_shock_decomposition but no plot is made (See
plot_shock_decomposition).
presample = INTEGER
Data point above which recursive realtime shock decompositions are computed, i.e. for 𝑇 =
[presample+1 . . . nobs].
forecast = INTEGER
Compute shock decompositions up to 𝑇 + 𝑘 periods, i.e. get shock contributions to k-step ahead
forecasts.
save_realtime = INTEGER_VECTOR
Choose for which vintages to save the full realtime shock decomposition. Default: 0.
fast_realtime = INTEGER
fast_realtime = [INTEGER1:INTEGER2]
fast_realtime = [INTEGER1 INTEGER2 ...]
Runs the smoother only for the data vintages provided by the specified integer (vector).
with_epilogue
See with_epilogue.
Output
MATLAB/Octave variable: oo_.realtime_shock_decomposition
Structure storing the results of realtime historical decompositions. Fields are three-dimensional arrays
with the first two dimension equal to the ones of oo_.shock_decomposition. The third dimension
stores the time periods and is therefore of size T+forecast. Fields are of the form:
oo_.realtime_shock_decomposition.OBJECT
oo_.realtime_conditional_shock_decomposition.OBJECT
time_*
Store the vintages of 𝑘-step conditional forecast shock decompositions 𝑌 (𝑡|𝑇 + 𝑘),
for 𝑡 = [𝑇 . . . 𝑇 + 𝑘]. See vintage. The third dimension is of size 1+forecast.
MATLAB/Octave variable: oo_.realtime_forecast_shock_decomposition
Structure storing the results of realtime forecast decompositions. Fields are of the form:
oo_.realtime_forecast_shock_decomposition.OBJECT
flip
If passed, plot the decomposition of the opposite of the list of variables. If used in combination with
diff , the diff operator is first applied. Default: not activated
max_nrows
Maximum number of rows in the subplot layout of detailed shock decomposition graphs. Note that
columns are always 3. Default: 6
with_epilogue
See with_epilogue.
init2shocks
init2shocks = NAME
Use the information contained in an init2shocks block, in order to attribute initial conditions to
shocks. The name of the block can be explicitly given, otherwise it defaults to the default block.
Block: init2shocks ;
Block: init2shocks(OPTIONS...);
This blocks gives the possibility of attributing the initial condition of endogenous variables to the contribution
of exogenous variables in the shock decomposition.
For example, in an AR(1) process, the contribution of the initial condition on the process variable can natu-
rally be assigned to the innovation of the process.
Each line of the block should have the syntax:
Where VARIABLE_1 is an endogenous variable whose initial condition will be attributed to the exogenous
VARIABLE_2.
The information contained in this block is used by the plot_shock_decomposition command when given
the init2shocks option.
Options
name = NAME
Specifies a name for the block, that can be referenced from plot_shock_decomposition, so that
several such blocks can coexist in a single model file. If the name is unspecified, it defaults to default.
Example
model;
dq = rho_q*dq(-1)+e_q;
A = rho_A*A(-1)+e_A;
...
end;
...
init2shocks;
dq e_q;
A e_A;
end;
shock_decomposition(nograph);
In this example, the initial conditions of dq and A will be respectively attributed to e_q and e_A.
Command: initial_condition_decomposition [VARIABLE_NAME]...;
Command: initial_condition_decomposition(OPTIONS...) [VARIABLE_NAME]...;
This command computes and plots the decomposition of the effect of smoothed initial conditions of state
variables. The variable_names provided govern which variables the decomposition is plotted for.
Further note that, unlike the majority of Dynare commands, the options specified below are overwritten with
their defaults before every call to initial_condition_decomposition. Hence, if you want to reuse an
option in a subsequent call to initial_condition_decomposition, you must pass it to the command
again.
Options
colormap = VARIABLE_NAME
See colormap.
nodisplay
See nodisplay.
graph_format = FORMAT
graph_format = ( FORMAT, FORMAT... )
See graph_format.
detail_plot
Plots shock contributions using subplots, one per shock (or group of shocks). Default: not activated
steadystate
If passed, the the 𝑦-axis value of the zero line in the shock decomposition plot is translated to the steady
state level. Default: not activated
type = qoq | yoy | aoa
For quarterly data, valid arguments are: qoq for quarter-on-quarter plots, yoy for year-on-year plots
of growth rates, aoa for annualized variables, i.e. the value in the last quarter for each year is plotted.
Default value: empty, i.e. standard period-on-period plots (qoq for quarterly data).
fig_name = STRING
Specifies a user-defined keyword to be appended to the default figure name set by
plot_shock_decomposition. This can avoid to overwrite plots in case of sequential calls to
plot_shock_decomposition.
write_xls
Saves shock decompositions to Excel file in the main directory, named
FILENAME_shock_decomposition_TYPE_FIG_NAME_initval.xls. This option requires your
system to be configured to be able to write Excel files.Page 148, 8
plot_init_date = DATE
If passed, plots decomposition using plot_init_date as initial period. Default: first observation in
estimation
plot_end_date = DATE
If passed, plots decomposition using plot_end_date as last period. Default: last observation in esti-
mation
diff
If passed, plot the decomposition of the first difference of the list of variables. If used in combination
with flip, the diff operator is first applied. Default: not activated
flip
If passed, plot the decomposition of the opposite of the list of variables. If used in combination with
diff , the diff operator is first applied. Default: not activated
diffuse_kalman_tol = DOUBLE
See diffuse_kalman_tol.
xls_sheet = QUOTED_STRING
See xls_sheet.
xls_range = RANGE
See xls_range.
heteroskedastic_filter
See heteroskedastic_filter.
nobs = INTEGER
nobs = [INTEGER1:INTEGER2]
See nobs.
4.20 Forecasting
On a calibrated model, forecasting is done using the forecast command. On an estimated model, use the
forecast option of estimation command.
It is also possible to compute forecasts on a calibrated or estimated model for a given constrained path of
the future endogenous variables. This is done, from the reduced form representation of the DSGE model,
by finding the structural shocks that are needed to match the restricted paths. Use conditional_forecast,
conditional_forecast_paths and plot_conditional_forecast for that purpose.
Finally, it is possible to do forecasting with a Bayesian VAR using the bvar_forecast command.
Command: forecast [VARIABLE_NAME...];
Command: forecast(OPTIONS...) [VARIABLE_NAME...];
This command computes a simulation of a stochastic model from an arbitrary initial point.
When the model also contains deterministic exogenous shocks, the simulation is computed conditionally to
the agents knowing the future values of the deterministic exogenous variables.
forecast must be called after stoch_simul.
forecast plots the trajectory of endogenous variables. When a list of variable names follows the command,
only those variables are plotted. A 90% confidence interval is plotted around the mean trajectory. Use option
conf_sig to change the level of the confidence interval.
Options
periods = INTEGER
Number of periods of the forecast. Default: 5.
conf_sig = DOUBLE
Level of significance for confidence interval. Default: 0.90.
nograph
See nograph .
nodisplay
See nodisplay.
graph_format = FORMAT
graph_format = ( FORMAT, FORMAT... )
See graph_format = FORMAT.
Initial Values
forecast computes the forecast taking as initial values the values specified in histval (see histval).
When no histval block is present, the initial values are the one stated in initval. When initval is
followed by command steady, the initial values are the steady state (see steady).
Output
The results are stored in oo_.forecast, which is described below.
Example
varexo_det tau;
varexo e;
...
shocks;
var e; stderr 0.01;
var tau;
periods 1:9;
values -0.15;
end;
stoch_simul(irf=0);
forecast;
oo_.forecast.FORECAST_MOMENT.VARIABLE_NAME
oo_.PointForecast.MOMENT_NAME.VARIABLE_NAME
oo_.MeanForecast.MOMENT_NAME.VARIABLE_NAME
Command: conditional_forecast(OPTIONS...);
This command computes forecasts on an estimated or calibrated model for a given constrained path of some
future endogenous variables. This is done using the reduced form first order state-space representation of
the DSGE model by finding the structural shocks that are needed to match the restricted paths. Consider the
augmented state space representation that stacks both predetermined and non-predetermined variables into
a vector 𝑦𝑡 :
𝑦𝑡 = 𝑇 𝑦𝑡−1 + 𝑅𝜀𝑡
Both 𝑦𝑡 and 𝜀𝑡 are split up into controlled and uncontrolled ones, and we assume without loss of generality
that the constrained endogenous variables and the controlled shocks come first :
(︂ )︂ (︂ )︂ (︂ )︂ (︂ )︂ (︂ )︂
𝑦𝑐,𝑡 𝑇𝑐,𝑐 𝑇𝑐,𝑢 𝑦𝑐,𝑡−1 𝑅𝑐,𝑐 𝑅𝑐,𝑢 𝜀𝑐,𝑡
= +
𝑦𝑢,𝑡 𝑇𝑢,𝑐 𝑇𝑢,𝑢 𝑦𝑢,𝑡−1 𝑅𝑢,𝑐 𝑅𝑢,𝑢 𝜀𝑢,𝑡
where matrices 𝑇 and 𝑅 are partitioned consistently with the vectors of endogenous variables and innova-
tions. Provided that matrix 𝑅𝑐,𝑐 is square and full rank (a necessary condition is that the number of free
endogenous variables matches the number of free innovations), given 𝑦𝑐,𝑡 , 𝜀𝑢,𝑡 and 𝑦𝑡−1 the first block of
equations can be solved for 𝜀𝑐,𝑡 :
−1
(︀ )︀
𝜀𝑐,𝑡 = 𝑅𝑐,𝑐 𝑦𝑐,𝑡 − 𝑇𝑐,𝑐 𝑦𝑐,𝑡 − 𝑇𝑐,𝑢 𝑦𝑢,𝑡 − 𝑅𝑐,𝑢 𝜀𝑢,𝑡
By iterating over these two blocks of equations, we can build a forecast for all the endogenous variables
in the system conditional on paths for a subset of the endogenous variables. If the distribution of the free
innovations 𝜀𝑢,𝑡 is provided (i.e. some of them have positive variances) this exercise is replicated (the number
of replication is controlled by the option replic described below) by drawing different sequences of free
innovations. The result is a predictive distribution for the uncontrolled endogenous variables, 𝑦𝑢,𝑡 , that
Dynare will use to report confidence bands around the point conditional forecast.
A few things need to be noted. First, the controlled exogenous variables are set to zero for the uncontrolled
periods. This implies that there is no forecast uncertainty arising from these exogenous variables in un-
controlled periods. Second, by making use of the first order state space solution, even if a higher-order
approximation was performed, the conditional forecasts will be based on a first order approximation. Since
the controlled exogenous variables are identified on the basis of the reduced form model (i.e. after solving for
the expectations), they are unforeseen shocks from the perspective of the agents in the model. That is, agents
expect the endogenous variables to return to their respective steady state levels but are surprised in each
period by the realisation of shocks keeping the endogenous variables along a predefined (unexpected) path.
Fourth, if the structural innovations are correlated, because the calibrated or estimated covariance matrix has
non zero off diagonal elements, the results of the conditional forecasts will depend on the ordering of the
innovations (as declared after varexo). As in VAR models, a Cholesky decomposition is used to factorise
the covariance matrix and identify orthogonal impulses. It is preferable to declare the correlations in the
model block (explicitly imposing the identification restrictions), unless you are satisfied with the implicit
identification restrictions implied by the Cholesky decomposition.
This command has to be called after estimation or stoch_simul.
Use conditional_forecast_paths block to give the list of constrained endogenous, and their constrained
future path. Option controlled_varexo is used to specify the structural shocks which will be matched to
generate the constrained path.
Use plot_conditional_forecast to graph the results.
Options
parameter_set = OPTION
See parameter_set for possible values. No default value, mandatory option.
controlled_varexo = (VARIABLE_NAME...)
Specify the exogenous variables to use as control variables. No default value, mandatory option.
periods = INTEGER
Number of periods of the forecast. Default: 40. periods cannot be smaller than the number of con-
strained periods.
replic = INTEGER
Number of simulations used to compute the conditional forecast uncertainty. Default: 5000.
conf_sig = DOUBLE
Level of significance for confidence interval. Default: 0.80.
Output
The results are stored in oo_.conditional_forecast, which is described below.
Example
var y a;
varexo e u;
...
estimation(...);
conditional_forecast_paths;
var y;
periods 1:3, 4:5;
values 2, 5;
var a;
periods 1:5;
values 3;
end;
(continues on next page)
plot_conditional_forecast(periods = 10) a y;
oo_.conditional_forecast.cond.FORECAST_MOMENT.VARIABLE_NAME
oo_.conditional_forecast.uncond.FORECAST_MOMENT.VARIABLE_NAME
oo_.conditional_forecast.controlled_exo_variables.FORECAST_MOMENT.SHOCK_NAME
endogenous variable is controlled for less periods than the first one, the second controlled_varexo isn’t
set for the last periods.
In case of the presence of observation_trends, the specified controlled path for these variables needs to
include the trend component. When using the loglinear option, it is necessary to specify the logarithm of
the controlled variables.
Block: filter_initial_state ;
This block specifies the initial values of the endogenous states at the beginning of the Kalman filter recursions.
That is, if the Kalman filter recursion starts with time t=1 being the first observation, this block provides the
state estimate at time 0 given information at time 0, 𝐸0 (𝑥0 ). If nothing is specified, the initial condition is
assumed to be at the steady state (which is the unconditional mean for a stationary model).
This block is terminated by end;.
Each line inside of the block should be of the form:
VARIABLE_NAME(INTEGER)=EXPRESSION;
EXPRESSION is any valid expression returning a numerical value and can contain parameter values. This
allows specifying relationships that will be honored during estimation. INTEGER refers to the lag with
which a variable appears. By convention in Dynare, period 1 is the first period. Going backwards in
time, the first period before the start of the simulation is period 0, then period -1, and so on. Note that
the filter_initial_state block does not take non-state variables.
Example
filter_initial_state;
k(0)= ((1/bet-(1-del))/alp)^(1/(alp-1))*l_ss;
P(0)=2.5258;
m(0)= mst;
end;
MATLAB/Octave command:
HANDLE = basic_plan(HANDLE, 'VAR_NAME', 'SHOCK_TYPE', DATES, MATLAB VECTOR OF DOUBLE);
Adds to the forecast scenario a shock on the exogenous variable indicated between quotes in the second
argument. The shock type has to be specified in the third argument between quotes: 'surprise' in case
of an unexpected shock or 'perfect_foresight' for a perfectly anticipated shock. The fourth argument
indicates the period of the shock using a dates class (see dates class members). The last argument is the
shock path indicated as a MATLAB vector of double. This function return the handle of the updated forecast
scenario.
The forecast scenario can also contain a constrained path on an endogenous variable. The values of the related
exogenous variable compatible with the constrained path are in this case computed. In other words, a conditional
forecast is performed. This kind of shock is described with the function flip_plan:
MATLAB/Octave command: HANDLE = flip_plan(HANDLE, 'VAR_NAME', 'VAR_NAME',
'SHOCK_TYPE', DATES, MATLAB VECTOR OF DOUBLE);
Adds to the forecast scenario a constrained path on the endogenous variable specified between quotes in
the second argument. The associated exogenous variable provided in the third argument between quotes, is
considered as an endogenous variable and its values compatible with the constrained path on the endogenous
variable will be computed. The nature of the expectation on the constrained path has to be specified in the
fourth argument between quotes: 'surprise' in case of an unexpected path or 'perfect_foresight' for
a perfectly anticipated path. The fifth argument indicates the period where the path of the endogenous vari-
able is constrained using a dates class (see dates class members). The last argument contains the constrained
path as a MATLAB vector of double. This function return the handle of the updated forecast scenario.
Once the forecast scenario if fully described, the forecast is computed with the command det_cond_forecast:
MATLAB/Octave command: DSERIES = det_cond_forecast(HANDLE[, DSERIES [, DATES]]);
Computes the forecast or the conditional forecast using an extended path method for the given forecast sce-
nario (first argument). The past values of the endogenous and exogenous variables provided with a dseries
class (see dseries class members) can be indicated in the second argument. By default, the past values of the
variables are equal to their steady-state values. The initial date of the forecast can be provided in the third
argument. By default, the forecast will start at the first date indicated in the init_plan command. This
function returns a dataset containing the historical and forecast values for the endogenous and exogenous
variables.
Example
var y r;
varexo e u;
...
smoothed = dseries('smoothed_variables.csv');
fplan = init_plan(2013Q4:2029Q4);
fplan = flip_plan(fplan, 'y', 'u', 'surprise', 2013Q4:2014Q4, [1 1.1 1.2 1.
˓→1 ]);
plot(dset_forecast.{'y','u'});
plot(dset_forecast.{'r','e'});
Command: smoother2histval ;
Command: smoother2histval(OPTIONS...);
The purpose of this command is to construct initial conditions (for a subsequent simulation) that are the
smoothed values of a previous estimation.
More precisely, after an estimation run with the smoother option, smoother2histval will extract the
smoothed values (from oo_.SmoothedVariables, and possibly from oo_.SmoothedShocks if there are
lagged exogenous), and will use these values to construct initial conditions (as if they had been manually
entered through histval).
Options
period = INTEGER
Period number to use as the starting point for the subsequent simulation. It should be between 1 and the
number of observations that were used to produce the smoothed values. Default: the last observation.
infile = FILENAME
Load the smoothed values from a _results.mat file created by a previous Dynare run. Default: use
the smoothed values currently in the global workspace.
invars = ( VARIABLE_NAME [VARIABLE_NAME ...] )
A list of variables to read from the smoothed values. It can contain state endogenous variables, and also
exogenous variables having a lag. Default: all the state endogenous variables, and all the exogenous
variables with a lag.
outfile = FILENAME
Write the initial conditions to a file. Default: write the initial conditions in the current workspace, so
that a simulation can be performed.
outvars = ( VARIABLE_NAME [VARIABLE_NAME ...] )
A list of variables which will be given the initial conditions. This list must have the same length than
the list given to invars, and there will be a one-to-one mapping between the two list. Default: same
value as option invars.
Use cases
There are three possible ways of using this command:
• Everything in a single file: run an estimation with a smoother, then run smoother2histval (without
the infile and outfile options), then run a stochastic simulation.
• In two files: in the first file, run the smoother and then run smoother2histval with the outfile
option; in the second file, run histval_file to load the initial conditions, and run a (deterministic or
stochastic) simulation.
• In two files: in the first file, run the smoother; in the second file, run smoother2histval with the
infile option equal to the _results.mat file created by the first file, and then run a (deterministic
or stochastic) simulation.
Dynare has tools to compute optimal policies for various types of objectives. You can either solve for optimal policy
under commitment with ramsey_model, for optimal policy under discretion with discretionary_policy or for
optimal simple rules with osr (also implying commitment).
Command: planner_objective MODEL_EXPRESSION ;
This command declares the policy maker objective, for use with ramsey_model or
discretionary_policy.
You need to give the one-period objective, not the discounted lifetime objective. The discount factor is
given by the planner_discount option of ramsey_model and discretionary_policy. The objective
function can only contain current endogenous variables and no exogenous ones. This limitation is easily
circumvented by defining an appropriate auxiliary variable in the model.
With ramsey_model, you are not limited to quadratic objectives: you can give any arbitrary nonlinear
expression.
With discretionary_policy, the objective function must be quadratic.
Command: evaluate_planner_objective ;
Command: evaluate_planner_objective(OPTIONS...);
This command computes, displays, and stores the value of the planner objective function under Ramsey
policy or discretion in oo_.planner_objective_value. It will provide both unconditional welfare and
welfare conditional on the initial (i.e. period 0) values of the endogenous and exogenous state variables
inherited by the planner. In a deterministic context, the respective initial values are set using initval or
histval (depending on the exact context).
In a stochastic context, if no initial state values have been specified with histval, their values are taken to
be the steady state values. Because conditional welfare is computed conditional on optimal policy by the
planner in the first endogenous period (period 1), it is conditional on the information set in the period 1. This
information set includes both the predetermined states inherited from period 0 (specified via histval for
both endogenous and lagged exogenous states) as well as the period 1 values of the exogenous shocks. The
latter are specified using the perfect foresight syntax of the shocks block.
At the current stage, the stochastic context does not support the pruning option. At order>3, only the com-
putation of conditional welfare with steady state Lagrange multipliers is supported. Note that at order=2,
the output is based on the second-order accurate approximation of the variance stored in oo_.var.
Options
periods = INTEGER
The value of the option specifies the number of periods to use in the simulations in the computation of
unconditional welfare at higher order.
Default: 10000.
drop = INTEGER
The number of burn-in draws out of periods discarded before computing the unconditional welfare
at higher order. Default: 1000.
Example (stochastic context)
var a ...;
varexo u;
model;
a = rho*a(-1)+u+u(-1);
...
end;
histval;
u(0)=1;
a(0)=-1;
end;
shocks;
var u; stderr 0.008;
var u;
periods 1;
values 1;
end;
evaluate_planner_objective;
Scalar storing the value of unconditional welfare. In a perfect foresight context, it corresponds to welfare in
the long-run, approximated as welfare in the terminal simulation period.
MATLAB/Octave variable: oo_.planner_objective_value.conditional
In a perfect foresight context, this field will be a scalar storing the value of welfare conditional on the specified
initial condition and zero initial Lagrange multipliers.
In a stochastic context, it will have two subfields:
MATLAB/Octave variable:
oo_.planner_objective_value.conditional.steady_initial_multiplier
Stores the value of the planner objective when the initial Lagrange multipliers associated with the planner’s
problem are set to their steady state values (see ramsey_policy).
MATLAB/Octave variable:
oo_.planner_objective_value.conditional.zero_initial_multiplier
Stores the value of the planner objective when the initial Lagrange multipliers associated with the planner’s
problem are set to 0, i.e. it is assumed that the planner exploits its ability to surprise private agents in the
first period of implementing Ramsey policy. This value corresponds to the planner implementing optimal
policy for the first time and committing not to re-optimize in the future.
Dynare allows to automatically compute optimal policy choices of a Ramsey planner who takes the specified private
sector equilibrium conditions into account and commits to future policy choices. Doing so requires specifying the
private sector equilibrium conditions in the model block and a planner_objective as well as potentially some
instruments to facilitate computations.
Warning: Be careful when employing forward-looking auxiliary variables in the context of timeless perspec-
tive Ramsey computations. They may alter the problem the Ramsey planner will solve for the first period,
although they seemingly leave the private sector equilibrium unaffected. The reason is the planner optimizes
with respect to variables dated t and takes the value of time 0 variables as given, because they are predeter-
mined. This set of initially predetermined variables will change with forward-looking definitions. Thus, users
are strongly advised to use model-local variables instead.
Example
Consider a perfect foresight example where the Euler equation for the return to capital is given by
1/C=beta*1/C(+1)*(R(+1)+(1-delta))
The job of the Ramsey planner in period 1 is to choose 𝐶1 and 𝑅1 , taking as given 𝐶0 . The above
equation may seemingly equivalently be written as
1/C=beta*1/C(+1)*(R_cap);
R_cap=R(+1)+(1-delta);
due to perfect foresight. However, this changes the problem of the Ramsey planner in the first
period to choosing 𝐶1 and 𝑅1 , taking as given both 𝐶0 and 𝑅0𝑐𝑎𝑝 . Thus, the relevant return to
capital in the Euler equation of the first period is not a choice of the planner anymore due to the
forward-looking nature of the definition in the second line!
A correct specification would be to instead define R_cap as a model-local variable:
1/C=beta*1/C(+1)*(R_cap);
#R_cap=R(+1)+(1-delta);
Command: ramsey_model(OPTIONS...);
This command computes the First Order Conditions for maximizing the policy maker objective function
subject to the constraints provided by the equilibrium path of the private economy.
The planner objective must be declared with the planner_objective command.
This command only creates the expanded model, it doesn’t perform any computations. It needs to be followed
by other instructions to actually perform desired computations. Examples are calls to steady to compute
the steady state of the Ramsey economy, to stoch_simul with various approximation orders to conduct
stochastic simulations based on perturbation solutions, to estimation in order to estimate models under
optimal policy with commitment, and to perfect foresight simulation routines.
See Auxiliary variables, for an explanation of how Lagrange multipliers are automatically created.
Options
This command accepts the following options:
planner_discount = EXPRESSION
Declares or reassigns the discount factor of the central planner optimal_policy_discount_factor.
Default: 1.0.
planner_discount_latex_name = LATEX_NAME
Sets the LaTeX name of the optimal_policy_discount_factor parameter.
instruments = (VARIABLE_NAME,...)
Declares instrument variables for the computation of the steady state under optimal policy. Requires a
steady_state_model block or a _steadystate.m file. See below.
Steady state
Dynare takes advantage of the fact that the Lagrange multipliers appear linearly in the equations of the steady
state of the model under optimal policy. Nevertheless, it is in general very difficult to compute the steady
state with simply a numerical guess in initval for the endogenous variables.
It greatly facilitates the computation, if the user provides an analytical solution for the steady state (in
steady_state_model block or in a _steadystate.m file). In this case, it is necessary to provide a steady
state solution CONDITIONAL on the value of the instruments in the optimal policy problem and declared
with the option instruments. The initial value of the instrument for steady state finding in this case is set
with initval. Note that computing and displaying steady state values using the steady command or calls
to resid must come after the ramsey_model statement and the initval block.
Note that choosing the instruments is partly a matter of interpretation and you can choose instruments that
are handy from a mathematical point of view but different from the instruments you would refer to in the
analysis of the paper. A typical example is choosing inflation or nominal interest rate as an instrument.
Block: ramsey_constraints ;
This block lets you define constraints on the variables in the Ramsey problem. The constraints take the form
of a variable, an inequality operator (> or <) and a constant.
Example
ramsey_constraints;
i > 0;
end;
ramsey_model;
stoch_simul;
evaluate_planner_objective;
It computes an approximation of the policy that maximizes the policy maker’s objective function subject
to the constraints provided by the equilibrium path of the private economy and under commitment to this
optimal policy. The Ramsey policy is computed by approximating the equilibrium system around the pertur-
bation point where the Lagrange multipliers are at their steady state, i.e. where the Ramsey planner acts as if
the initial multipliers had been set to 0 in the distant past, giving them time to converge to their steady state
value. Consequently, the optimal decision rules are computed around this steady state of the endogenous
variables and the Lagrange multipliers.
Note that the variables in the list after the ramsey_policy or stoch_simul command can also contain
multiplier names, but in a case-sensititve way (e.g. MULT_1). In that case, Dynare will for example display
the IRFs of the respective multipliers when irf>0.
The planner objective must be declared with the planner_objective command.
Options
This command accepts all options of stoch_simul, plus:
planner_discount = EXPRESSION
See planner_discount.
instruments = (VARIABLE_NAME,...)
Declares instrument variables for the computation of the steady state under optimal policy. Requires a
steady_state_model block or a _steadystate.m file. See below.
Output
This command generates all the output variables of stoch_simul. For specifying the initial values for the
endogenous state variables (except for the Lagrange multipliers), see above.
Steady state
See Ramsey steady state.
min 𝐸(𝑦𝑡′ 𝑊 𝑦𝑡 )
𝛾
such that:
where:
• 𝐸 denotes the unconditional expectations operator;
• 𝛾 are parameters to be optimized. They must be elements of the matrices 𝐴1 , 𝐴2 , 𝐴3 , i.e. be specified
as parameters in the params command and be entered in the model block;
• 𝑦 are the endogenous variables, specified in the var command, whose (co)-variance enters the loss
function;
• 𝑒 are the exogenous stochastic shocks, specified in the varexo- ommand;
• 𝑊 is the weighting matrix;
The linear quadratic problem consists of choosing a subset of model parameters to minimize the weighted
(co)-variance of a specified subset of endogenous variables, subject to a linear law of motion implied by
the first order conditions of the model. A few things are worth mentioning. First, 𝑦 denotes the selected
endogenous variables’ deviations from their steady state, i.e. in case they are not already mean 0 the vari-
ables entering the loss function are automatically demeaned so that the centered second moments are mini-
mized. Second, osr only solves linear quadratic problems of the type resulting from combining the specified
quadratic loss function with a first order approximation to the model’s equilibrium conditions. The reason
is that the first order state-space representation is used to compute the unconditional (co)-variances. Hence,
osr will automatically select order=1. Third, because the objective involves minimizing a weighted sum
of unconditional second moments, those second moments must be finite. In particular, unit roots in 𝑦 are not
allowed.
The subset of the model parameters over which the optimal simple rule is to be optimized, 𝛾, must be listed
with osr_params.
The weighting matrix 𝑊 used for the quadratic objective function is specified in the optim_weights block.
By attaching weights to endogenous variables, the subset of endogenous variables entering the objective
function, 𝑦, is implicitly specified.
The linear quadratic problem is solved using the numerical optimizer specified with opt_algo.
Options
The osr command will subsequently run stoch_simul and accepts the same options, including restricting
the endogenous variables by listing them after the command, as stoch_simul (see Stochastic solution and
simulation) plus
opt_algo = INTEGER
Specifies the optimizer for minimizing the objective function. The same solvers as for mode_compute
(see mode_compute) are available, except for 5, 6, and 10.
VARIABLE_NAME EXPRESSION;
Example
var y inflation r;
varexo y_ inf_;
parameters delta sigma alpha kappa gammarr gammax0 gammac0 gamma_y_ gamma_
˓→inf_;
delta = 0.44;
(continues on next page)
gammarr = 0;
gammax0 = 0.2;
gammac0 = 1.5;
gamma_y_ = 8;
gamma_inf_ = 3;
model(linear);
y = delta * y(-1) + (1-delta)*y(+1)+sigma *(r - inflation(+1)) + y_;
inflation = alpha * inflation(-1) + (1-alpha) * inflation(+1) + kappa*y␣
˓→+ inf_;
r = gammax0*y(-1)+gammac0*inflation(-1)+gamma_y_*y_+gamma_inf_*inf_;
end;
shocks;
var y_; stderr 0.63;
var inf_; stderr 0.4;
end;
optim_weights;
inflation 1;
y 1;
y, inflation 0.5;
end;
Block: osr_params_bounds ;
This block declares lower and upper bounds for parameters in the optimal simple rule. If not specified the
optimization is unconstrained.
Each line has the following syntax:
Note that the use of this block requires the use of a constrained optimizer, i.e. setting opt_algo to 1, 2, 5
or 9.
Example
osr_params_bounds;
gamma_inf_, 0, 2.5;
end;
osr(opt_algo=9) y;
Dynare provides an interface to the global sensitivity analysis (GSA) toolbox (developed by the Joint Research
Center (JRC) of the European Commission), which is now part of the official Dynare distribution. The GSA
toolbox can be used to answer the following questions:
1. What is the domain of structural coefficients assuring the stability and determinacy of a DSGE model?
2. Which parameters mostly drive the fit of, e.g., GDP and which the fit of inflation? Is there any conflict
between the optimal fit of one observed series versus another?
3. How to represent in a direct, albeit approximated, form the relationship between structural parameters and
the reduced form of a rational expectations model?
The discussion of the methodologies and their application is described in Ratto (2008).
With respect to the previous version of the toolbox, in order to work properly, the GSA toolbox no longer requires
that the Dynare estimation environment is set up.
Command: sensitivity ;
Command: sensitivity(OPTIONS...);
This command triggers sensitivity analysis on a DSGE model.
Sampling Options
Nsam = INTEGER
Size of the Monte-Carlo sample. Default: 2048.
ilptau = INTEGER
If equal to 1, use 𝐿𝑃𝜏 quasi-Monte-Carlo. If equal to 0, use LHS Monte-Carlo. Default: 1.
pprior = INTEGER
If equqal to 1, sample from the prior distributions. If equal to 0, sample from the multivariate normal
¯ Σ), where 𝜃¯ is the posterior mode and Σ = 𝐻 −1 , 𝐻 is the Hessian at the mode. Default: 1.
𝑁 (𝜃,
prior_range = INTEGER
If equal to 1, sample uniformly from prior ranges. If equal to 0, sample from prior distributions.
Default: 1.
morris = INTEGER
If equal to 0, ANOVA mapping (Type I error) If equal to 1, Screening analysis (Type II error). If equal
to 2, Analytic derivatives (similar to Type II error, only valid when identification=1). Default: 1 when
identification=1, 0 otherwise.
morris_nliv = INTEGER
Number of levels in Morris design. Default: 6.
morris_ntra = INTEGER
Number trajectories in Morris design. Default: 20.
ppost = INTEGER
If equal to 1, use Metropolis posterior sample. If equal to 0, do not use Metropolis posterior sample.
Default: 0.
NB: This overrides any other sampling option.
neighborhood_width = DOUBLE
When pprior=0 and ppost=0, allows for the sampling of parameters around the value specified in
the mode_file, in the range xparam1 ± |xparam1 × neighborhood_width|. Default: 0.
Stability Mapping Options
stab = INTEGER
If equal to 1, perform stability mapping. If equal to 0, do not perform stability mapping. Default: 1.
load_stab = INTEGER
If equal to 1, load a previously created sample. If equal to 0, generate a new sample. Default: 0.
alpha2_stab = DOUBLE
Critical value for correlations 𝜌 in filtered samples: plot couples of parmaters with |𝜌| > alpha2_stab.
Default: 0.
pvalue_ks = DOUBLE
The threshold 𝑝𝑣𝑎𝑙𝑢𝑒 for significant Kolmogorov-Smirnov test (i.e. plot parameters with 𝑝𝑣𝑎𝑙𝑢𝑒 <
pvalue_ks). Default: 0.001.
pvalue_corr = DOUBLE
The threshold 𝑝𝑣𝑎𝑙𝑢𝑒 for significant correlation in filtered samples (i.e. plot bivariate samples when
𝑝𝑣𝑎𝑙𝑢𝑒 < pvalue_corr). Default: 1e-5.
Reduced Form Mapping Options
redform = INTEGER
If equal to 1, prepare Monte-Carlo sample of reduced form matrices. If equal to 0, do not prepare
Monte-Carlo sample of reduced form matrices. Default: 0.
load_redform = INTEGER
If equal to 1, load previously estimated mapping. If equal to 0, estimate the mapping of the reduced
form model. Default: 0.
logtrans_redform = INTEGER
If equal to 1, use log-transformed entries. If equal to 0, use raw entries. Default: 0.
threshold_redform = [DOUBLE DOUBLE]
The range over which the filtered Monte-Carlo entries of the reduced form coefficients should be an-
alyzed. The first number is the lower bound and the second is the upper bound. An empty vector
indicates that these entries will not be filtered. Default: empty.
ksstat_redform = DOUBLE
Critical value for Smirnov statistics 𝑑 when reduced form entries are filtered. Default: 0.001.
alpha2_redform = DOUBLE
Critical value for correlations 𝜌 when reduced form entries are filtered. Default: 1e-5.
namendo = (VARIABLE_NAME...)
List of endogenous variables. ‘:’ indicates all endogenous variables. Default: empty.
namlagendo = (VARIABLE_NAME...)
List of lagged endogenous variables. ‘:’ indicates all lagged endogenous variables. Analyze entries
[namendo × namlagendo] Default: empty.
namexo = (VARIABLE_NAME...)
List of exogenous variables. ‘:’ indicates all exogenous variables. Analyze entries [namendo ×
namexo]. Default: empty.
RMSE Options
rmse = INTEGER
If equal to 1, perform RMSE analysis. If equal to 0, do not perform RMSE analysis. Default: 0.
load_rmse = INTEGER
If equal to 1, load previous RMSE analysis. If equal to 0, make a new RMSE analysis. Default: 0.
lik_only = INTEGER
If equal to 1, compute only likelihood and posterior. If equal to 0, compute RMSE’s for all observed
series. Default: 0.
var_rmse = (VARIABLE_NAME...)
List of observed series to be considered. ‘:’ indicates all observed variables. Default: varobs.
pfilt_rmse = DOUBLE
Filtering threshold for RMSE’s. Default: 0.1.
istart_rmse = INTEGER
Value at which to start computing RMSE’s (use 2 to avoid big intitial error). Default: presample+1.
alpha_rmse = DOUBLE
Critical value for Smirnov statistics 𝑑: plot parameters with 𝑑 > alpha_rmse. Default: 0.001.
alpha2_rmse = DOUBLE
Critical value for correlation 𝜌: plot couples of parmaters with |𝜌| = alpha2_rmse. Default: 1e-5.
datafile = FILENAME
See datafile.
nobs = INTEGER
nobs = [INTEGER1:INTEGER2]
See nobs.
first_obs = INTEGER
See first_obs.
prefilter = INTEGER
See prefilter.
presample = INTEGER
See presample.
nograph
See nograph .
nodisplay
See nodisplay.
graph_format = FORMAT
The irf_calibration and moment_calibration blocks allow imposing implicit “endogenous” priors about
IRFs and moments on the model. The way it works internally is that any parameter draw that is inconsistent
with the “calibration” provided in these blocks is discarded, i.e. assigned a prior density of 0. In the context of
dynare_sensitivity, these restrictions allow tracing out which parameters are driving the model to satisfy or
violate the given restrictions.
IRF and moment calibration can be defined in irf_calibration and moment_calibration blocks:
Block: irf_calibration ;
Block: irf_calibration(OPTIONS...);
This block allows defining IRF calibration criteria and is terminated by end;. To set IRF sign restrictions,
the following syntax is used:
VARIABLE_NAME(INTEGER), EXOGENOUS_NAME, -;
VARIABLE_NAME(INTEGER:INTEGER), EXOGENOUS_NAME, +;
To set IRF restrictions with specific intervals, the following syntax is used:
When (INTEGER:INTEGER) is used, the restriction is considered to be fulfilled by a logical OR. A list of
restrictions must always be fulfilled with logical AND.
Options
relative_irf
See relative_irf .
Example
irf_calibration;
y(1:4), e_ys, [-50, 50]; //[first year response with logical OR]
@#for ilag in 21:40
R_obs(@{ilag}), e_ys, [0, 6]; //[response from 5th to 10th years with␣
˓→logical AND]
@#endfor
end;
Block: moment_calibration ;
Block: moment_calibration(OPTIONS...);
This block allows defining moment calibration criteria. This block is terminated by end;, and contains lines
of the form:
When (INTEGER:INTEGER) is used, the restriction is considered to be fulfilled by a logical OR. A list of
restrictions must always be fulfilled with logical AND. The moment restrictions generally apply to auto- and
cross-correlations between variables. The only exception is a restriction on the unconditional variance of an
endogenous variable, specified as shown in the example below.
Example
moment_calibration;
y_obs,y_obs, [0.5, 1.5]; //[unconditional variance]
y_obs,y_obs(-(1:4)), +; //[sign restriction for first year␣
˓→autocorrelation with logical OR]
Command: identification ;
Command: identification(OPTIONS...);
This command triggers:
1. Theoretical identification analysis based on
• moments as in Iskrev (2010)
• spectral density as in Qu and Tkachenko (2012)
• minimal system as in Komunjer and Ng (2011)
• reduced-form solution and linear rational expectation model as in Ratto and Iskrev (2011)
Note that for orders 2 and 3, all identification checks are based on the pruned state space system as in
Mutschler (2015). That is, theoretical moments and spectrum are computed from the pruned ABCD-
system, whereas the minimal system criteria is based on the first-order system, but augmented by the
theoretical (pruned) mean at order 2 or 3.
2. Identification strength analysis based on (theoretical or simulated) curvature of moment information
matrix as in Ratto and Iskrev (2011)
3. Parameter checks based on nullspace and multicorrelation coefficients to determine which (combina-
tions of) parameters are involved
General Options
order = 1|2|3
Order of approximation. At orders 2 and 3 identification is based on the pruned state space
system. Note that the order set in other functions does not overwrite the default. Default: 1.
parameter_set = OPTION
See parameter_set for possible values. Default: prior_mean.
prior_mc = INTEGER
Size of Monte-Carlo sample. Default: 1.
prior_range = INTEGER
Triggers uniform sample within the range implied by the prior specifications (when
prior_mc>1). Default: 0.
advanced = INTEGER
If set to 1, shows a more detailed analysis, comprised of an analysis for the linearized rational
expectation model as well as the associated reduced form solution. Further performs a bruteforce
search of the groups of parameters best reproducing the behavior of each single parameter. The
maximum dimension of the group searched is triggered by max_dim_cova_group. Default: 0.
max_dim_cova_group = INTEGER
In the brute force search (performed when advanced=1) this option sets the maximum dimension
of groups of parameters that best reproduce the behavior of each single model parameter. Default:
2.
gsa_sample_file = INTEGER|FILENAME
If equal to 0, do not use sample file. If equal to 1, triggers gsa prior sample. If equal to 2, triggers
gsa Monte-Carlo sample (i.e. loads a sample corresponding to pprior=0 and ppost=0 in the
dynare_sensitivity options). If equal to FILENAME uses the provided path to a specific user
defined sample file. Default: 0.
diffuse_filter
Deals with non-stationary cases. See diffuse_filter.
Numerical Options
analytic_derivation_mode = INTEGER
Different ways to compute derivatives either analytically or numerically. Possible values are:
• 0: efficient sylvester equation method to compute analytical derivatives
• 1: kronecker products method to compute analytical derivatives (only at order=1)
• -1: numerical two-sided finite difference method to compute all identification Jacobians
(numerical tolerance level is equal to options_.dynatol.x)
• -2: numerical two-sided finite difference method to compute derivatives of steady state
and dynamic model numerically, the identification Jacobians are then computed analytically
(numerical tolerance level is equal to options_.dynatol.x)
Default: 0.
normalize_jacobians = INTEGER
If set to 1: Normalize Jacobian matrices by rescaling each row by its largest element in abso-
lute value. Normalize Gram (or Hessian-type) matrices by transforming into correlation-type
matrices. Default: 1
tol_rank = DOUBLE
Tolerance level used for rank computations. Default: 1.e-10.
tol_deriv = DOUBLE
Tolerance level for selecting non-zero columns in Jacobians. Default: 1.e-8.
tol_sv = DOUBLE
Tolerance level for selecting non-zero singular values. Default: 1.e-3.
schur_vec_tol = DOUBLE
See schur_vec_tol.
Identification Strength Options
no_identification_strength
Disables computations of identification strength analysis based on sample information matrix.
periods = INTEGER
When the analytic Hessian is not available (i.e. with missing values or diffuse Kalman filter or
univariate Kalman filter), this triggers the length of stochastic simulation to compute Simulated
Moments Uncertainty. Default: 300.
replic = INTEGER
When the analytic Hessian is not available, this triggers the number of replicas to compute Sim-
ulated Moments Uncertainty. Default: 100.
Moments Options
no_identification_moments
Disables computations of identification check based on Iskrev (2010)’s J, i.e. derivative of first
two moments.
ar = INTEGER
Number of lags of computed autocovariances/autocorrelations (theoretical moments) in Iskrev
(2010)’s J criteria. Default: 1.
useautocorr = INTEGER
If equal to 1, compute derivatives of autocorrelation. If equal to 0, compute derivatives of auto-
covariances. Default: 0.
Spectrum Options
no_identification_spectrum
Disables computations of identification check based on Qu and Tkachenko (2012)’s G, i.e. Gram
matrix of derivatives of first moment plus outer product of derivatives of spectral density.
grid_nbr = INTEGER
Number of grid points in [-pi;pi] to approximate the integral to compute Qu and Tkachenko
(2012)’s G criteria. Default: 5000.
Minimal State Space System Options
no_identification_minimal
Disables computations of identification check based on Komunjer and Ng (2011)’s D, i.e. mini-
mal state space system and observational equivalent spectral density transformations.
Misc Options
nograph
See nograph .
nodisplay
See nodisplay.
graph_format = FORMAT
graph_format = ( FORMAT, FORMAT... )
See graph_format.
tex
See tex.
Debug Options
load_ident_files = INTEGER
If equal to 1, allow Dynare to load previously computed analyzes. Default: 0.
lik_init = INTEGER
See lik_init.
kalman_algo = INTEGER
See kalman_algo.
no_identification_reducedform
Disables computations of identification check based on steady state and reduced-form solution.
checks_via_subsets = INTEGER
If equal to 1: finds problematic parameters in a bruteforce fashion: It computes the rank of the
Jacobians for all possible parameter combinations. If the rank condition is not fullfilled, these
parameter sets are flagged as non-identifiable. The maximum dimension of the group searched
is triggered by max_dim_subsets_groups. Default: 0.
max_dim_subsets_groups = INTEGER
Sets the maximum dimension of groups of parameters for which the above bruteforce search is
performed. Default: 4.
The sensitivity analysis toolbox includes several types of analyses. Sensitivity analysis results are saved locally in
<mod_file>/gsa, where <mod_file>.mod is the name of the Dynare model file.
4.22.4.1 Sampling
Figure files produced are of the form <mod_file>_prior_*.fig and store results for stability mapping from
prior Monte-Carlo samples:
• <mod_file>_prior_stable.fig: plots of the Smirnov test and the correlation analyses confronting the
cdf of the sample fulfilling Blanchard-Kahn conditions (blue color) with the cdf of the rest of the sample
(red color), i.e. either instability or indeterminacy or the solution could not be found (e.g. the steady state
solution could not be found by the solver);
• <mod_file>_prior_indeterm.fig: plots of the Smirnov test and the correlation analyses confronting
the cdf of the sample producing indeterminacy (red color) with the cdf of the rest of the sample (blue color);
• <mod_file>_prior_unstable.fig: plots of the Smirnov test and the correlation analyses confronting
the cdf of the sample producing explosive roots (red color) with the cdf of the rest of the sample (blue color);
• <mod_file>_prior_wrong.fig: plots of the Smirnov test and the correlation analyses confronting the cdf
of the sample where the solution could not be found (e.g. the steady state solution could not be found by the
solver - red color) with the cdf of the rest of the sample (blue color);
• <mod_file>_prior_calib.fig: plots of the Smirnov test and the correlation analyses splitting the sample
fulfilling Blanchard-Kahn conditions, by confronting the cdf of the sample where IRF/moment restrictions
are matched (blue color) with the cdf where IRF/moment restrictions are NOT matched (red color);
Similar conventions apply for <mod_file>_mc_*.fig files, obtained when samples from multivariate normal are
used.
When the option threshold_redform is not set, or it is empty (the default), this analysis estimates a multivariate
smoothing spline ANOVA model (the ’mapping’) for the selected entries in the transition matrix of the shock
matrix of the reduce form first order solution of the model. This mapping is done either with prior samples or with
MC samples with neighborhood_width. Unless neighborhood_width is set with MC samples, the mapping
of the reduced form solution forces the use of samples from prior ranges or prior distributions, i.e.: pprior=1 and
ppost=0. It uses 250 samples to optimize smoothing parameters and 1000 samples to compute the fit. The rest
of the sample is used for out-of-sample validation. One can also load a previously estimated mapping with a new
Monte-Carlo sample, to look at the forecast for the new Monte-Carlo sample.
The following synthetic figures are produced:
• <mod_file>_redform_<endo name>_vs_lags_*.fig: shows bar charts of the sensitivity indices for
the ten most important parameters driving the reduced form coefficients of the selected endogenous vari-
ables (namendo) versus lagged endogenous variables (namlagendo); suffix log indicates the results for
log-transformed entries;
• <mod_file>_redform_<endo name>_vs_shocks_*.fig: shows bar charts of the sensitivity indices for
the ten most important parameters driving the reduced form coefficients of the selected endogenous variables
(namendo) versus exogenous variables (namexo); suffix log indicates the results for log-transformed entries;
• <mod_file>_redform_gsa(_log).fig: shows bar chart of all sensitivity indices for each parameter: this
allows one to notice parameters that have a minor effect for any of the reduced form coefficients.
Detailed results of the analyses are shown in the subfolder <mod_file>/gsa/redform_prior for prior samples
and in <mod_file>/gsa/redform_mc for MC samples with option neighborhood_width, where the detailed
results of the estimation of the single functional relationships between parameters 𝜃 and reduced form coefficient
(denoted as 𝑦 hereafter) are stored in separate directories named as:
• <namendo>_vs_<namlagendo>, for the entries of the transition matrix;
• <namendo>_vs_<namexo>, for entries of the matrix of the shocks.
The following files are stored in each directory (we stick with prior sample but similar conventions are used for
MC samples):
• <mod_file>_prior_<namendo>_vs_<namexo>.fig: histogram and CDF plot of the MC sample of the
individual entry of the shock matrix, in sample and out of sample fit of the ANOVA model;
• <mod_file>_prior_<namendo>_vs_<namexo>_map_SE.fig: for entries of the shock matrix it shows
graphs of the estimated first order ANOVA terms 𝑦 = 𝑓 (𝜃𝑖 ) for each deep parameter 𝜃𝑖 ;
• <mod_file>_prior_<namendo>_vs_<namlagendo>.fig: histogram and CDF plot of the MC sample of
the individual entry of the transition matrix, in sample and out of sample fit of the ANOVA model;
• <mod_file>_prior_<namendo>_vs_<namlagendo>_map_SE.fig: for entries of the transition matrix it
shows graphs of the estimated first order ANOVA terms 𝑦 = 𝑓 (𝜃𝑖 ) for each deep parameter 𝜃𝑖 ;
• <mod_file>_prior_<namendo>_vs_<namexo>_map.mat, <mod_file>_<namendo>_vs_<namlagendo>_map.
mat: these files store info in the estimation;
When option logtrans_redform is set, the ANOVA estimation is performed using a log-transformation of each
y. The ANOVA mapping is then transformed back onto the original scale, to allow comparability with the baseline
estimation. Graphs for this log-transformed case, are stored in the same folder in files denoted with the _log suffix.
When the option threshold_redform is set, the analysis is performed via Monte Carlo filtering, by displaying
parameters that drive the individual entry y inside the range specified in threshold_redform. If no entry is
found (or all entries are in the range), the MCF algorithm ignores the range specified in threshold_redform
and performs the analysis splitting the MC sample of y into deciles. Setting threshold_redform=[-inf inf]
triggers this approach for all y’s.
Results are stored in subdirectories of <mod_file>/gsa/redform_prior named
• <mod_file>_prior_<namendo>_vs_<namlagendo>_threshold, for the entries of the transition matrix;
• <mod_file>_prior_<namendo>_vs_<namexo>_threshold, for entries of the matrix of the shocks.
The files saved are named:
• <mod_file>_prior_<namendo>_vs_<namexo>_threshold.fig, <mod_file>_<namendo>_vs_<namlagendo>_thresh
fig: graphical outputs;
• <mod_file>_prior_<namendo>_vs_<namexo>_threshold.mat, <mod_file>_<namendo>_vs_<namlagendo>_thresh
mat: info on the analysis;
4.22.4.5 RMSE
The RMSE analysis can be performed with different types of sampling options:
1. When pprior=1 and ppost=0, the toolbox analyzes the RMSEs for the Monte-Carlo sample obtained by
sampling parameters from their prior distributions (or prior ranges): this analysis provides some hints about
what parameter drives the fit of which observed series, prior to the full estimation;
2. When pprior=0 and ppost=0, the toolbox analyzes the RMSEs for a multivariate normal Monte-Carlo
sample, with covariance matrix based on the inverse Hessian at the optimum: this analysis is useful when
maximum likelihood estimation is done (i.e. no Bayesian estimation);
3. When ppost=1 the toolbox analyzes the RMSEs for the posterior sample obtained by Dynare’s Metropolis
procedure.
The use of cases 2 and 3 requires an estimation step beforehand. To facilitate the sensitivity analysis after estimation,
the dynare_sensitivity command also allows you to indicate some options of the estimation command.
These are:
• datafile
• nobs
• first_obs
• prefilter
• presample
• nograph
• nodisplay
• graph_format
• conf_sig
• loglinear
• mode_file
Binary files produced my RMSE analysis are:
• <mod_file>_prior_*.mat: these files store the filtered and smoothed variables for the prior Monte-Carlo
sample, generated when doing RMSE analysis (pprior=1 and ppost=0);
• <mode_file>_mc_*.mat: these files store the filtered and smoothed variables for the multivariate normal
Monte-Carlo sample, generated when doing RMSE analysis (pprior=0 and ppost=0).
Figure files <mod_file>_rmse_*.fig store results for the RMSE analysis.
• <mod_file>_rmse_prior*.fig: save results for the analysis using prior Monte-Carlo samples;
• <mod_file>_rmse_mc*.fig: save results for the analysis using multivariate normal Monte-Carlo samples;
• <mod_file>_rmse_post*.fig: save results for the analysis using Metropolis posterior samples.
The following types of figures are saved (we show prior sample to fix ideas, but the same conventions are used for
multivariate normal and posterior):
• <mod_file>_rmse_prior_params_*.fig: for each parameter, plots the cdfs corresponding to the best
10% RMSEs of each observed series (only those cdfs below the significance threshold alpha_rmse);
• <mod_file>_rmse_prior_<var_obs>_*.fig: if a parameter significantly affects the fit of var_obs, all
possible trade-off’s with other observables for same parameter are plotted;
• <mod_file>_rmse_prior_<var_obs>_map.fig: plots the MCF analysis of parameters significantly driv-
ing the fit the observed series var_obs;
• <mod_file>_rmse_prior_lnlik*.fig: for each observed series, plots in BLUE the cdf of the log-
likelihood corresponding to the best 10% RMSEs, in RED the cdf of the rest of the sample and in BLACK
the cdf of the full sample; this allows one to see the presence of some idiosyncratic behavior;
• <mod_file>_rmse_prior_lnpost*.fig: for each observed series, plots in BLUE the cdf of the log-
posterior corresponding to the best 10% RMSEs, in RED the cdf of the rest of the sample and in BLACK
the cdf of the full sample; this allows one to see idiosyncratic behavior;
• <mod_file>_rmse_prior_lnprior*.fig: for each observed series, plots in BLUE the cdf of the log-
prior corresponding to the best 10% RMSEs, in RED the cdf of the rest of the sample and in BLACK the
cdf of the full sample; this allows one to see idiosyncratic behavior;
• <mod_file>_rmse_prior_lik.fig: when lik_only=1, this shows the MCF tests for the filtering of the
best 10% log-likelihood values;
• <mod_file>_rmse_prior_post.fig: when lik_only=1, this shows the MCF tests for the filtering of
the best 10% log-posterior values.
Screening analysis does not require any additional options with respect to those listed in Sampling Options. The
toolbox performs all the analyses required and displays results.
The results of the screening analysis with Morris sampling design are stored in the subfolder <mod_file>/gsa/
screen. The data file <mod_file>_prior stores all the information of the analysis (Morris sample, reduced form
coefficients, etc.).
Screening analysis merely concerns reduced form coefficients. Similar synthetic bar charts as for the reduced form
analysis with Monte-Carlo samples are saved:
• <mod_file>_redform_<endo name>_vs_lags_*.fig: shows bar charts of the elementary effect tests for
the ten most important parameters driving the reduced form coefficients of the selected endogenous variables
(namendo) versus lagged endogenous variables (namlagendo);
• <mod_file>_redform_<endo name>_vs_shocks_*.fig: shows bar charts of the elementary effect tests
for the ten most important parameters driving the reduced form coefficients of the selected endogenous
variables (namendo) versus exogenous variables (namexo);
• <mod_file>_redform_screen.fig: shows bar chart of all elementary effect tests for each parameter: this
allows one to identify parameters that have a minor effect for any of the reduced form coefficients.
Setting the option identification=1, an identification analysis based on theoretical moments is performed.
Sensitivity plots are provided that allow to infer which parameters are most likely to be less identifiable.
Prerequisite for properly running all the identification routines, is the keyword identification; in the Dynare
model file. This keyword triggers the computation of analytic derivatives of the model with respect to estimated
parameters and shocks. This is required for option morris=2, which implements Iskrev (2010) identification
analysis.
For example, the placing:
identification;
dynare_sensitivity(identification=1, morris=2);
in the Dynare model file triggers identification analysis using analytic derivatives as in Iskrev (2010), jointly with
the mapping of the acceptable region.
The identification analysis with derivatives can also be triggered by the single command:
identification;
This does not do the mapping of acceptable regions for the model and uses the standard random sampler of
Dynare. Additionally, using only identification; adds two additional identification checks: namely, of Qu
and Tkachenko (2012) based on the spectral density and of Komunjer and Ng (2011) based on the minimal state
space system. It completely offsets any use of the sensitivity analysis toolbox.
Given a list of variables, observed variables and a data file, Dynare can be used to solve a Markov-switching SBVAR
model according to Sims, Waggoner and Zha (2008).11 Having done this, you can create forecasts and compute
the marginal data density, regime probabilities, IRFs, and variance decomposition of the model.
The commands have been modularized, allowing for multiple calls to the same command within a <mod_file>.
mod file. The default is to use <mod_file> to tag the input (output) files used (produced) by the program. Thus,
11 If you want to align the paper with the description herein, please note that 𝐴 is 𝐴0 and 𝐹 is 𝐴+ .
to call any command more than once within a <mod_file>.mod file, you must use the *_tag options described
below.
Command: markov_switching(OPTIONS...);
Declares the Markov state variable information of a Markov-switching SBVAR model.
Options
chain = INTEGER
The Markov chain considered. Default: none.
number_of_regimes = INTEGER
Specifies the total number of regimes in the Markov Chain. This is a required option.
duration = DOUBLE | [ROW VECTOR OF DOUBLES]
The duration of the regimes or regimes. This is a required option. When passed a scalar
real number, it specifies the average duration for all regimes in this chain. When passed a
vector of size equal number_of_regimes, it specifies the average duration of the associated
regimes (1:number_of_regimes) in this chain. An absorbing state can be specified through the
restrictions option.
restrictions = [[ROW VECTOR OF 3 DOUBLES],[ROW VECTOR OF 3 DOUBLES],...]
Provides restrictions on this chain’s regime transition matrix. Its vector argument takes three inputs of
the form: [current_period_regime, next_period_regime, transition_probability].
The first two entries are positive integers, and the third is a non-negative real in the set [0,1]. If restric-
tions are specified for every transition for a regime, the sum of the probabilities must be 1. Otherwise,
if restrictions are not provided for every transition for a given regime the sum of the provided transition
probabilities msut be <1. Regardless of the number of lags, the restrictions are specified for parameters
at time t since the transition probability for a parameter at t is equal to that of the parameter at t-1.
In case of estimating a MS-DSGE model,12 in addition the following options are allowed:
parameters = [LIST OF PARAMETERS]
This option specifies which parameters are controlled by this Markov Chain.
number_of_lags = DOUBLE
Provides the number of lags that each parameter can take within each regime in this chain.
Example
Specifies a Markov-switching BVAR with a first chain with 3 regimes that all have a duration of
2.5 periods. The probability of directly going from regime 1 to regime 3 and vice versa is 0.
Example
Specifies a Markov-switching DSGE model with a second chain with 3 regimes that have dura-
tions of 0.5, 2.5, and 2.5 periods, respectively. The switching parameters are alpha and rho.
The probability of directly going from regime 1 to regime 3 is 0, while regime 3 is an absorbing
state.
Command: svar(OPTIONS...);
Each Markov chain can control the switching of a set of parameters. We allow the parameters to be divided
equation by equation and by variance or slope and intercept.
Options
coefficients
Specifies that only the slope and intercept in the given equations are controlled by the given chain. One,
but not both, of coefficients or variances must appear. Default: none.
variances
Specifies that only variances in the given equations are controlled by the given chain. One, but not
both, of coefficients or variances must appear. Default: none.
equations
Defines the equation controlled by the given chain. If not specified, then all equations are controlled
by chain. Default: none.
chain = INTEGER
Specifies a Markov chain defined by markov_switching. Default: none.
Command: sbvar(OPTIONS...);
To be documented. For now, see the wiki: https://archives.dynare.org/DynareWiki/SbvarOptions
Options
datafile, freq, initial_year, initial_subperiod, final_year, final_subperiod, data, vlist,
vlistlog, vlistper, restriction_fname, nlags, cross_restrictions, contemp_reduced_form,
real_pseudo_forecast, no_bayesian_prior, dummy_obs, nstates, indxscalesstates, alpha,
beta, gsig2_lmdm, q_diag, flat_prior, ncsk, nstd, ninv, indxparr, indxovr, aband, indxap,
apband, indximf, indxfore, foreband, indxgforhat, indxgimfhat, indxestima, indxgdls, eq_ms,
cms, ncms, eq_cms, tlindx, tlnumber, cnum, forecast, coefficients_prior_hyperparameters
Block: svar_identification ;
This block is terminated by end; and contains lines of the form:
UPPER_CHOLESKY;
LOWER_CHOLESKY;
EXCLUSION CONSTANTS;
EXCLUSION LAG INTEGER; EQUATION INTEGER, VARIABLE_NAME [[,] VARIABLE_NAME...];
RESTRICTION EQUATION INTEGER, EXPRESSION = EXPRESSION;
Initialization Options
coefficients_prior_hyperparameters = [DOUBLE1 DOUBLE2 ... DOUBLE6]
Sets the hyper parameters for the model. The six elements of the argument vector have the following
interpretations:
1
Overall tightness for 𝐴0 and 𝐴+ .
2
Relative tightness for 𝐴+ .
3
Relative tightness for the constant term.
4
Tightness on lag decay (range: 1.2 - 1.5); a faster decay produces better inflation process.
5
Weight on nvar sums of coeffs dummy observations (unit roots).
6
Weight on single dummy initial observation including constant.
Default: [1.0 1.0 0.1 1.2 1.0 1.0]
freq = INTEGER | monthly | quarterly | yearly
Frequency of the data (e.g. monthly, 12). Default: 4.
initial_year = INTEGER
The first year of data. Default: none.
initial_subperiod = INTEGER
The first period of data (i.e. for quarterly data, an integer in [1,4]). Default: 1.
final_year = INTEGER
The last year of data. Default: Set to encompass entire dataset.
final_subperiod = INTEGER
The final period of data (i.e. for monthly data, an integer in [1,12]. Default: When final_year is also
missing, set to encompass entire dataset; when final_year is indicated, set to the maximum number
of subperiods given the frequency (i.e. 4 for quarterly data, 12 for monthly,. . . ).
datafile = FILENAME
See datafile.
xls_sheet = QUOTED_STRING
See xls_sheet.
xls_range = RANGE
See xls_range.
nlags = INTEGER
The number of lags in the model. Default: 1.
cross_restrictions
Use cross 𝐴0 and 𝐴+ restrictions. Default: off.
contemp_reduced_form
Use contemporaneous recursive reduced form. Default: off.
no_bayesian_prior
Do not use Bayesian prior. Default: off (i.e. use Bayesian prior).
alpha = INTEGER
Alpha value for squared time-varying structural shock lambda. Default: 1.
beta = INTEGER
Beta value for squared time-varying structural shock lambda. Default: 1.
gsig2_lmdm = INTEGER
The variance for each independent 𝜆 parameter under SimsZha restrictions. Default: 50^2.
specification = sims_zha | none
This controls how restrictions are imposed to reduce the number of parameters. Default: Random
Walk.
Estimation Options
convergence_starting_value = DOUBLE
This is the tolerance criterion for convergence and refers to changes in the objective function value. It
should be rather loose since it will gradually be tightened during estimation. Default: 1e-3.
convergence_ending_value = DOUBLE
The convergence criterion ending value. Values much smaller than square root machine epsilon are
probably overkill. Default: 1e-6.
convergence_increment_value = DOUBLE
Determines how quickly the convergence criterion moves from the starting value to the ending value.
Default: 0.1.
max_iterations_starting_value = INTEGER
This is the maximum number of iterations allowed in the hill-climbing optimization routine and should
be rather small since it will gradually be increased during estimation. Default: 50.
max_iterations_increment_value = DOUBLE
Determines how quickly the maximum number of iterations is increased. Default: 2.
max_block_iterations = INTEGER
The parameters are divided into blocks and optimization proceeds over each block. After a set of
blockwise optimizations are performed, the convergence criterion is checked and the blockwise opti-
mizations are repeated if the criterion is violated. This controls the maximum number of times the
blockwise optimization can be performed. Note that after the blockwise optimizations have converged,
a single optimization over all the parameters is performed before updating the convergence value and
maximum number of iterations. Default: 100.
max_repeated_optimization_runs = INTEGER
The entire process described by max_block_iterations is repeated until improvement has stopped.
This is the maximum number of times the process is allowed to repeat. Set this to 0 to not allow
repetitions. Default: 10.
function_convergence_criterion = DOUBLE
The convergence criterion for the objective function when max_repeated_optimizations_runs is
positive. Default: 0.1.
parameter_convergence_criterion = DOUBLE
The convergence criterion for parameter values when max_repeated_optimizations_runs is pos-
itive. Default: 0.1.
number_of_large_perturbations = INTEGER
The entire process described by max_block_iterations is repeated with random starting values
drawn from the posterior. This specifies the number of random starting values used. Set this to 0 to
not use random starting values. A larger number should be specified to ensure that the entire parameter
space has been covered. Default: 5.
number_of_small_perturbations = INTEGER
The number of small perturbations to make after the large perturbations have stopped improving. Set-
ting this number much above 10 is probably overkill. Default: 5.
number_of_posterior_draws_after_perturbation = INTEGER
The number of consecutive posterior draws to make when producing a small perturbation. Because the
posterior draws are serially correlated, a small number will result in a small perturbation. Default: 1.
max_number_of_stages = INTEGER
The small and large perturbation are repeated until improvement has stopped. This specifies the maxi-
mum number of stages allowed. Default: 20.
random_function_convergence_criterion = DOUBLE
The convergence criterion for the objective function when number_of_large_perturbations is
positive. Default: 0.1.
random_parameter_convergence_criterion = DOUBLE
The convergence criterion for parameter values when number_of_large_perturbations is positive.
Default: 0.1.
Example
ms_estimation(file_tag=second_run, output_file_tag=third_run,
no_create_init, max_repeated_optimization_runs=5,
number_of_large_perturbations=10);
Command: ms_simulation ;
Command: ms_simulation(OPTIONS...);
Simulates a Markov-switching SBVAR model.
Options
file_tag = FILENAME
The portion of the filename associated with the ms_estimation run. Default: <mod_file>.
output_file_tag = FILENAME
The portion of the output filename that will be assigned to this run. Default: <file_tag>.
mh_replic = INTEGER
The number of draws to save. Default: 10,000.
drop = INTEGER
The number of burn-in draws. Default: 0.1*mh_replic*thinning_factor.
thinning_factor = INTEGER
The total number of draws is equal to thinning_factor*mh_replic+drop. Default: 1.
adaptive_mh_draws = INTEGER
Tuning period for Metropolis-Hastings draws. Default: 30,000.
save_draws
Save all elements of 𝐴0 , 𝐴+ , 𝑄, and 𝜁, to a file named draws_<<file_tag>>.out with each
draw on a separate line. A file that describes how these matrices are laid out is contained in
ms_simulation(file_tag=second_run);
ms_simulation(file_tag=third_run, mh_replic=5000, thinning_factor=3);
Command: ms_compute_mdd ;
Command: ms_compute_mdd(OPTIONS...);
Computes the marginal data density of a Markov-switching SBVAR model from the posterior draws. At the
end of the run, the Muller and Bridged log marginal densities are contained in the oo_.ms structure.
Options
file_tag = FILENAME
See file_tag.
output_file_tag = FILENAME
See output_file_tag.
simulation_file_tag = FILENAME
The portion of the filename associated with the simulation run. Default: <file_tag>.
proposal_type = INTEGER
The proposal type:
1
Gaussian.
2
Power.
3
Truncated Power.
4
Step.
5
Truncated Gaussian.
Default: 3
proposal_lower_bound = DOUBLE
The lower cutoff in terms of probability. Not used for proposal_type in [1,2]. Required for all
other proposal types. Default: 0.1.
proposal_upper_bound = DOUBLE
The upper cutoff in terms of probability. Not used for proposal_type equal to 1. Required for all
other proposal types. Default: 0.9.
mdd_proposal_draws = INTEGER
The number of proposal draws. Default: 100,000.
mdd_use_mean_center
Use the posterior mean as center. Default: off.
Command: ms_compute_probabilities ;
Command: ms_compute_probabilities(OPTIONS...);
Computes smoothed regime probabilities of a Markov-switching SBVAR model. Output .eps files are
contained in <output_file_tag/Output/Probabilities>.
Options
file_tag = FILENAME
See file_tag.
output_file_tag = FILENAME
See output_file_tag.
filtered_probabilities
Filtered probabilities are computed instead of smoothed. Default: off.
real_time_smoothed
Smoothed probabilities are computed based on time t information for 0 ≤ 𝑡 ≤ 𝑛𝑜𝑏𝑠. Default: off
Command: ms_irf ;
Command: ms_irf(OPTIONS...);
Computes impulse response functions for a Markov-switching SBVAR model. Output .eps files are con-
tained in <output_file_tag/Output/IRF>, while data files are contained in <output_file_tag/IRF>.
Options
file_tag = FILENAME
See file_tag.
output_file_tag = FILENAME
See output_file_tag.
simulation_file_tag = FILENAME
See simulation_file_tag.
horizon = INTEGER
The forecast horizon. Default: 12.
filtered_probabilities
Uses filtered probabilities at the end of the sample as initial conditions for regime probabilities. Only
one of filtered_probabilities, regime and regimes may be passed. Default: off.
error_band_percentiles = [DOUBLE1 ...]
The percentiles to compute. Default: [0.16 0.50 0.84]. If median is passed, the default is [0.5].
shock_draws = INTEGER
The number of regime paths to draw. Default: 10,000.
shocks_per_parameter = INTEGER
The number of regime paths to draw under parameter uncertainty. Default: 10.
thinning_factor = INTEGER
Only 1/thinning_factor of the draws in posterior draws file are used. Default: 1.
free_parameters = NUMERICAL_VECTOR
A vector of free parameters to initialize theta of the model. Default: use estimated parameters
parameter_uncertainty
Calculate IRFs under parameter uncertainty. Requires that ms_simulation has been run. Default:
off.
regime = INTEGER
Given the data and model parameters, what is the ergodic probability of being in the specified regime.
Only one of filtered_probabilities, regime and regimes may be passed. Default: off.
regimes
Describes the evolution of regimes. Only one of filtered_probabilities, regime and regimes
may be passed. Default: off.
median
A shortcut to setting error_band_percentiles=[0.5]. Default: off.
Command: ms_forecast ;
Command: ms_forecast(OPTIONS...);
Generates forecasts for a Markov-switching SBVAR model. Output .eps files are contained in
<output_file_tag/Output/Forecast>, while data files are contained in <output_file_tag/
Forecast>.
Options
file_tag = FILENAME
See file_tag.
output_file_tag = FILENAME
See output_file_tag.
simulation_file_tag = FILENAME
See simulation_file_tag.
data_obs_nbr = INTEGER
The number of data points included in the output. Default: 0.
error_band_percentiles = [DOUBLE1 ...]
See error_band_percentiles.
shock_draws = INTEGER
See shock_draws.
shocks_per_parameter = INTEGER
See shocks_per_parameter.
thinning_factor = INTEGER
See thinning_factor.
free_parameters = NUMERICAL_VECTOR
See free_parameters.
parameter_uncertainty
See parameter_uncertainty.
regime = INTEGER
See regime.
regimes
See regimes.
median
See median.
horizon = INTEGER
See horizon.
Command: ms_variance_decomposition ;
Command: ms_variance_decomposition(OPTIONS...);
Computes the variance decomposition for a Markov-switching SBVAR model. Output .eps files are con-
tained in <output_file_tag/Output/Variance_Decomposition>, while data files are contained in
<output_file_tag/Variance_Decomposition>.
Options
file_tag = FILENAME
See file_tag.
output_file_tag = FILENAME
See output_file_tag.
simulation_file_tag = FILENAME
See simulation_file_tag.
horizon = INTEGER
See horizon.
filtered_probabilities
See filtered_probabilities.
no_error_bands
Do not output percentile error bands (i.e. compute mean). Default: off (i.e. output error bands)
error_band_percentiles = [DOUBLE1 ...]
See error_band_percentiles.
shock_draws = INTEGER
See shock_draws.
shocks_per_parameter = INTEGER
See shocks_per_parameter.
thinning_factor = INTEGER
See thinning_factor.
free_parameters = NUMERICAL_VECTOR
See free_parameters.
parameter_uncertainty
See parameter_uncertainty.
regime = INTEGER
See regime.
regimes
See regimes.
Block: epilogue ;
The epilogue block is useful for computing output variables of interest that may not be necessarily defined in
the model (e.g. various kinds of real/nominal shares or relative prices, or annualized variables out of a quarterly
model).
It can also provide several advantages in terms of computational efficiency and flexibility:
• You can calculate variables in the epilogue block after smoothers/simulations have already been run without
adding the new definitions and equations and rerunning smoothers/simulations. Even posterior smoother
subdraws can be recycled for computing epilogue variables without rerunning subdraws with the new defi-
nitions and equations.
• You can also reduce the state space dimension in data filtering/smoothing. Assume, for example, you want
annualized variables as outputs. If you define an annual growth rate in a quarterly model, you need lags up
to order 7 of the associated quarterly variable; in a medium/large scale model this would just blow up the
state dimension and increase by a huge amount the computing time of a smoother.
The epilogue block is terminated by end; and contains lines of the form:
NAME = EXPRESSION;
Example
epilogue;
// annualized level of y
ya = exp(y)+exp(y(-1))+exp(y(-2))+exp(y(-3));
// annualized growth rate of y
gya = ya/ya(-4)-1;
end;
Dynare provides tools for semi-structural models, in the vain of the FRB/US model (see Brayton and Tinsley
(1996)), where expectations are not necessarily model consistent but based on a VAR auxiliary model. In the fol-
lowing, it is assumed that each equation is written as VARIABLE = EXPRESSION or T(VARIABLE) = EXPRESSION
where T(VARIABLE) stands for a transformation of an endogenous variable (log or diff). This representation,
where each equation determines the endogenous variable on the LHS, can be exploited when simulating the model
(see algorithms 12 and 14 in solve_algo) and is mandatory to define auxiliary models used for computing expec-
tations (see below).
The two auxiliary models defined in this section are linear backward-looking models used to form expectations.
Both models can be recast as VAR(1)-processes and therefore offer isomorphic ways of specifying the expectations
process, but differ in their convenience of specifying features like cointegration and error correction. var_model
directly specifies a VAR, while trend_component_model allows to define a trend target to which the endogenous
variables may be attracted in the long-run (i.e. an error correction model).
Command: var_model(OPTIONS...);
Picks equations in the model block to form a VAR model. This model can be used as an auxiliary model in
var_expectation_model or pac_model. It must be of the following form:
𝑝
∑︁
𝑌𝑡 = c + 𝐴𝑖 𝑌𝑡−𝑖 + 𝜀𝑡
𝑖=1
or
𝑝
∑︁
𝐴0 𝑌𝑡 = c + 𝐴𝑖 𝑌𝑡−𝑖 + 𝜀𝑡
𝑖=1
if the VAR is structural (see below), where 𝑌𝑡 and 𝜀𝑡 are 𝑛 × 1 vectors, c is a 𝑛 × 1 vector of parameters,
𝐴𝑖 (𝑖 = 0, . . . , 𝑝) are 𝑛 × 𝑛 matrices of parameters, and 𝐴0 is non singular square matrix. Vector c and
matrices 𝐴𝑖 (𝑖 = 0, . . . , 𝑝) are set by parsing the equations in the model block. Then, Dynare builds a
VAR(1)-companion form model for 𝒴𝑡 = (1, 𝑌𝑡 , . . . , 𝑌𝑡−𝑝+1 )′ as:
⎛ ⎞ ⎛ ⎞⎛ 1 ⎞ ⎛ 0 ⎞
1 1 0′𝑛 ... ... . . . 0′𝑛
⎜ 𝑌𝑡 ⎟ ⎜ ⎜𝑌𝑡−1 ⎟ ⎜ 𝜀𝑡 ⎟
⎜ ⎟ ⎜c 𝐴1 𝐴2 ... . . . 𝐴𝑝 ⎟⎟⎜ ⎟ ⎜ ⎟
⎜ 𝑌𝑡−1 ⎟ ⎜ ⎜𝑌𝑡−2 ⎟ ⎜0𝑛 ⎟
0𝑛 𝐼𝑛 𝑂𝑛 ... . . . 𝑂𝑛 ⎟
⎜ .. ⎟ = ⎜ ⎟⎜ . ⎟ ⎟ + ⎜ .. ⎟
⎜ ⎟ ⎜ ⎜ ⎟
⎜ . ⎟ ⎜ 0 𝑂𝑛 𝐼𝑛 𝑂𝑛 . . . 𝑂𝑛 ⎟ .
. ⎟ ⎜ ⎜.⎟
𝑛 ⎜ ⎟ ⎟
⎟ ⎜. .. .. .. .. ⎟ ⎜
⎟
⎜ . ⎟ ⎜
⎝ .. ⎠ ⎝ .. . ⎠ ⎝ ... ⎠ ⎝ ... ⎠
⎜
𝑂𝑛 . . . ⎜ ⎟ ⎜ ⎟
assuming that we are dealing with a reduced form VAR (otherwise, the right-hand side would additionally
be premultiplied by 𝐴−10 . to obtain the reduced for representation). If the VAR does not have a constant, we
remove the first line of the system and the first column of the companion matrix 𝒞. Dynare only saves the
companion matrix, since that is the only information required to compute the expectations.
MATLAB/Octave variable: oo_.var.MODEL_NAME.CompanionMatrix
Reduced form companion matrix of the var_model.
Options
model_name = STRING
List of equations in the model block (referenced using the equation tag name) used to build the
VAR model.
structural
By default the VAR model is not structural, i.e. each equation must contain exactly one contem-
poraneous variable (on the LHS). If the structural option is provided then any variable defined
in the system can appear at time 𝑡 in each equation. Internally Dynare will rewrite this model as
a reduced form VAR (by inverting the implied matrix 𝐴0 ).
Example
model;
[ name = 'X' ]
x = a*x(-1) + b*x(-2) + c*z(-2) + e_x;
[ name = 'Z' ]
z = f*z(-1) + e_z;
[ name = 'Y' ]
y = d*y(-2) + e*z(-1) + e_y;
end;
Command: trend_component_model(OPTIONS...);
Picks equations in the model block to form a trend component model. This model can be used as an auxiliary
model in var_expectation_model or pac_model. It must be of the following form:
{︃ ∑︀𝑝
∆𝑋𝑡 = 𝐴0 (𝑋𝑡−1 − 𝐶0 𝑍𝑡−1 ) + 𝑖=1 𝐴𝑖 ∆𝑋𝑡−𝑖 + 𝜀𝑡
𝑍𝑡 = 𝑍𝑡−1 + 𝜂𝑡
where 𝑋𝑡 and 𝑍𝑡 are 𝑛 × 1 and 𝑚 × 1 vectors of endogenous variables. 𝑍𝑡 defines the trend target to
whose linear combination 𝐶0 𝑍𝑡 the endogenous variables 𝑋𝑡 will be attracted, provided the implied error
correction matrix 𝐴0 is negative definite. 𝜀𝑡 and 𝜂𝑡 are 𝑛 × 1 and 𝑚 × 1 vectors of exogenous variables, 𝐴𝑖
(𝑖 = 0, . . . , 𝑝) are 𝑛 × 𝑛 matrices of parameters, and 𝐶0 is a 𝑛 × 𝑚 matrix. This model can also be cast into
a VAR(1) model by first rewriting it in levels. Let 𝑌𝑡 = (𝑋𝑡′ , 𝑍𝑡′ )′ and 𝜁𝑡 = (𝜀′𝑡 , 𝜂𝑡′ )′ . Then we have:
𝑝+1
∑︁
𝑌𝑡 = 𝐵𝑖 𝑌𝑡−𝑖 + 𝜁𝑡
𝑖=1
with
(︂ )︂
𝐼𝑛 + 𝐴0 + 𝐴1 −Λ
𝐵1 =
𝑂𝑚,𝑛 𝐼𝑚
where Λ = 𝐴0 𝐶0 ,
(︂ )︂
𝐴𝑖 − 𝐴𝑖−1 𝑂𝑛,𝑚
𝐵𝑖 =
𝑂𝑚,𝑛 𝑂𝑚
for 𝑖 = 2, . . . , 𝑝, and
(︂ )︂
−𝐴𝑝 𝑂𝑛,𝑚
𝐵𝑝+1 =
𝑂𝑚,𝑛 𝑂𝑚
List of equations in the model block (referenced using the equation tag name) used to build the
trend component model.
targets = [QUOTED_STRING[, QUOTED_STRING[, ...]]]
List of targets, corresponding to the variables in vector 𝑍𝑡 , referenced using the equation tag
name) of the associated equation in the model block. target must be a subset of eqtags.
Example
model;
[name='eq:x1']
diff(x1) = a_x1_0*(x1(-1)-x1bar(-1))+a_x1_0_*(x2(-1)-x2bar(-1)) + a_x1_
(continues on next page)
[name='eq:x2']
diff(x2) = a_x2_0*(x2(-1)-x2bar(-1)) + a_x2_1*diff(x1(-1)) + a_x2_
˓→2*diff(x1(-2)) + a_x2_x1_1*diff(x2(-1)) + a_x2_x1_2*diff(x2(-2)) + ex2;
[name='eq:x1bar']
x1bar = x1bar(-1) + ex1bar;
[name='eq:x2bar']
x2bar = x2bar(-1) + ex2bar;
end;
Suppose we wish to forecast a variable 𝑦𝑡 and that 𝑦𝑡 is an element of vector of variables 𝒴𝑡 whose law of motion
is described by a VAR(1) model 𝒴𝑡 = 𝒞𝒴𝑡−1 + 𝜖𝑡 . More generally, 𝑦𝑡 may be a linear combination of the scalar
variables in 𝒴𝑡 . Let the vector 𝛼 be such that 𝑦𝑡 = 𝛼′ 𝒴𝑡 (𝛼 is a selection vector if 𝑦𝑡 is a variable in 𝒴𝑡 , i.e. a
column of an identity matrix, or an arbitrary vector defining the weights of a linear combination). Then the best
prediction, in the sense of the minimisation of the RMSE, for 𝑦𝑡+ℎ given the information set at 𝑡 − 𝜏 (which we
assume to include all observables up to time 𝑡 − 𝜏 , 𝒴𝑡−𝜏 ) is:
In a semi-structural model, variables appearing in 𝑡 + ℎ (e.g. the expected output gap in a dynamic IS curve or
expected inflation in a New Keynesian Phillips curve) will be replaced by the expectation implied by an auxiliary
VAR model. Another use case is for the computation of permanent incomes. Typically, consumption will depend
on something like:
∞
∑︁
𝛽 ℎ 𝑦𝑡+ℎ|𝑡−𝜏
ℎ=0
Assuming that 0 < 𝛽 < 1 and knowing the limit of geometric series, the conditional expectation of this variable
can be evaluated based on the same auxiliary model:
[︃ ∞
⃒ ]︃
∑︁ ⃒
𝛽 𝑦𝑡+ℎ ⃒𝒴𝑡−𝜏 = 𝛼𝒞 𝜏 (𝐼 − 𝛽𝒞)−1 𝒴𝑡−𝜏
ℎ ⃒
E
⃒
ℎ=0
where (𝑎, 𝑏) ∈ N2 with 𝑎 < 𝑏, 𝛽 ∈ (0, 1] is a discount factor, and 𝜏 is a finite positive integer.
Options
model_name = STRING
Name of the VAR based expectation model, which will be referenced in the model block.
auxiliary_model = STRING
The upper limit 𝑏 of the horizon ℎ (in which case 𝑎 = 0), or range of periods 𝑎 : 𝑏 over which the
discounted sum is computed (the upper bound can be Inf).
time_shift = INTEGER
This operator is used instead of a leaded variable, e.g. X(1), in the model block to substitute a
model-consistent forecast with a forecast based on a VAR model.
Example
model;
[name='X']
x = a*x(-1) + b*x(-2) + c*z(-2) + e_x;
[name='Z']
z = f*z(-1) + e_z;
[name='Y']
y = d*y(-2) + e*z(-1) + e_y;
end;
In this example var_expectation(varexp) stands for the one step ahead expectation of x, as
a replacement for x(1).
MATLAB/Octave command: var_expectation.initialize(NAME_OF_VAR_EXPECTATION_MODEL);
Initialise the var_expectation_model by building the companion matrix of the associated auxiliary
var_model. Needs to be executed before attempts to simulate or estimate the model.
Example (continued)
var_expectation.initialize('varexp');
var_expectation.update('varexp');
Warning: Changes to the parameters of the underlying auxiliary var_model require calls to
var_expectation.initialize and var_expectation.update to become effective. Changes to the
var_expectation_model or its associated parameters require a call to var_expectation.update.
In its simplest form, a PAC equation breaks down changes in a variable of interest 𝑦 into three contributions: (i)
the lagged deviation from a target 𝑦 ⋆ , (ii) the lagged changes in the variable 𝑦, and (iii) the expected changes in the
target 𝑦 ⋆ :
𝑚−1
∑︁ ∞
∑︁
⋆ ⋆
∆𝑦𝑡 = 𝑎0 (𝑦𝑡−1 − 𝑦𝑡−1 ) + 𝑎𝑖 ∆𝑦𝑡−𝑖 + 𝑑𝑖 ∆𝑦𝑡+𝑖 + 𝜀𝑡
𝑖=1 𝑖=0
Brayton et alii (2000) shows how such an equation can be derived from the minimisation of a quadratic cost function
penalising expected deviations from the target and non-smoothness of 𝑦, where future costs are discounted (with
discount factor 𝛽). They also show that the parameters (𝑑𝑖 )𝑖∈N are non-linear functions of the 𝑚 parameters 𝑎𝑖 and
the discount factor 𝛽. To simulate or estimate this equation we need to figure out how to determine the expected
changes of the target. This can be done as in the previous section using VAR based expectations, or considering
model consistent expectations (MCE).
To ensure that the endogenous variable 𝑦 is equal to its target 𝑦 ⋆ in the (deterministic) long run, i.e. that the
error correction term is zero in the long run, we can optionally add a growth neutrality correction to this equation.
Suppose that 𝑔 is the long run growth rate, for 𝑦 and 𝑦 ⋆ , then in the long run (assuming that the data are in logs)
we must have:
𝑚−1
∑︁ ∞
∑︁
⋆
𝑔 = 𝑎0 (𝑦∞ − 𝑦∞ ) + 𝑔 𝑎𝑖 + 𝑔 𝑑𝑖
𝑖=1 𝑖=0
∞
(︃ 𝑚−1
)︃
∑︁ ∑︁
⋆
⇔ 𝑎0 (𝑦∞ − 𝑦∞ ) = 1− 𝑎𝑖 − 𝑑𝑖 𝑔
𝑖=1 𝑖=0
∞
(︃ 𝑚−1
)︃
∑︁ ∑︁
∆𝑦𝑡 = 𝜆 ⋆
𝑎0 (𝑦𝑡−1 − 𝑦𝑡−1 ) + 𝑎𝑖 ∆𝑦𝑡−𝑖 + ⋆
𝑑𝑖 ∆𝑦𝑡+𝑖 + (1 − 𝜆)𝛾 ′ 𝑋𝑡 + 𝜀𝑡
𝑖=1 𝑖=0
where 𝜆 ∈ [0, 1] is the weight of the pure PAC equation, 𝛾 is a 𝑘 × 1 vector of parameters, and 𝑋𝑡 a 𝑘 × 1 vector
of variables in the rule of thumb part. Or we can simply add the exogenous variables to the PAC equation (without
the weight 𝜆):
𝑚−1
∑︁ ∞
∑︁
⋆
∆𝑦𝑡 = 𝑎0 (𝑦𝑡−1 − 𝑦𝑡−1 ) + 𝑎𝑖 ∆𝑦𝑡−𝑖 + ⋆
𝑑𝑖 ∆𝑦𝑡+𝑖 + 𝛾 ′ 𝑋𝑡 + 𝜀𝑡
𝑖=1 𝑖=0
Command: pac_model(OPTIONS...);
Declares a PAC model. A .mod file can have more than one PAC model or PAC equation, but each PAC
equation must be associated to a different PAC model.
Options
model_name = STRING
vector ℎ, of the variables involved in the companion representation of the auxiliary model. The
weights defining the linear combination are nonlinear functions of the (𝑎𝑖 )𝑚−1
𝑖=0 coefficients in
the PAC equation. This option is not mandatory, if absent Dynare understands that the expected
changes of the target have to be computed under the MCE assumption. This is done by rewriting
recursively the infinite sum as shown in equation 10 of Brayton et alii (2000).
discount = PARAMETER_NAME | DOUBLE
Discount factor (𝛽) for future expected costs appearing in the definition of the cost function.
growth = PARAMETER_NAME | VARIABLE_NAME | EXPRESSION | DOUBLE
If present a growth neutrality correction is added to the PAC equation. The user must ensure that
the provided value (or long term level if a variable or expression is given) is consistent with the
asymptotic growth rate of the endogenous variable.
kind = dd | dl
Instructs Dynare how to compute the vector ℎ, the weights defining the linear combination of
the companion VAR variables. The default value dd must be used if the target appears in first
difference in the auxiliary model, see equation (A.79) in Brayton et alii (2000), while value dl
must be used if the target shows up in level in the auxiliary model, equation (A.74) in Brayton et
alii (2000).
Operator: pac_expectation (NAME_OF_PAC_MODEL);
∑︀∞
This operator is used instead of the infinite sum, 𝑖=0 𝑑𝑖 ∆𝑦𝑡+𝑖
⋆
, in a PAC equation defined in the model
block. Depending on the assumption regarding the formation of expectations, it will be replaced by a lin-
ear combination of the variables involved in the companion representation of the auxiliary model or by a
recursive forward equation.
The PAC equation target can be composite and defined as a weighted sum of stationary and non stationary com-
ponents. Such a target requires an additional equation in the model block, with the target variable on the left
hand-side and the components in the right hand-side. Each component must be an endogenous variable in the aux-
iliary model. The characteristics of each component must be described in the pac_target_info block, see below,
and the pac_target_nonstationary operator must be used in the error correction term of the PAC equation to
link the target to the provided description. Note that composite targets make only sense if the auxiliary model is
not a trend component model (where all the variables are non stationary).
Block: pac_target_info(NAME_OF_PAC_MODEL);
This block enables the user to provide the properties of each component of a target in PAC models with
a composite target. The NAME_OF_PAC_MODEL argument refers to a PAC model (must match the value of
option model_name in the declaration of a PAC model).
On the first line of the block, the name of the composite target variable must be provided using the following
syntax:
target VARIABLE_NAME ;
where VARIABLE_NAME is a declared endogenous variable, its associated equation is not part of the auxiliary
model but all the components (the variables on the right hand-side) must be defined in the auxiliary model.
Next, the following line declares the name of the auxilary variable that will appear in the error correction
term, this variable contains only the non stationary components of the target:
auxname_target_nonstationary NAME ;
The block should contain the following group of lines for each stationary component:
component STATIONARY_VARIABLE_NAME ;
kind ll ;
auxname AUX_VAR_NAME ;
where STATIONARY_VARIABLE_NAME is the name of a stationary variable appearing in the right hand-
side of the equation defining the target VARIABLE_NAME. The second line instructs Dynare that the com-
ponent appears in levels in the auxiliary model and in the PAC expectations. The third line specifies the
name of the auxiliary variable created by Dynare for the component of the PAC expectation related to
STATIONARY_VARIABLE_NAME.
The block should contain the following group of lines for each nonstationary component:
component NONSTATIONARY_VARIABLE_NAME ;
kind dd | dl ;
auxname AUX_VAR_NAME ;
growth PARAMETER_NAME | VARIABLE_NAME | EXPRESSION | DOUBLE ;
model;
[name='eq:y']
y = (1-rho_1-rho_2)*diff(x2(-1)) + rho_1*y(-1) + rho_2*y(-2) + ey;
[name='eq:x1']
diff(x1) = a_x1_0*(x1(-1)-x1bar(-1)) + a_x1_1*diff(x1(-1)) + a_x1_
˓→2*diff(x1(-2)) + a_x1_x2_1*diff(x2(-1)) + a_x1_x2_2*diff(x2(-2)) + ex1;
[name='eq:x2']
diff(x2) = a_x2_0*(x2(-1)-x2bar(-1)) + a_x2_1*diff(x1(-1)) + a_x2_
˓→2*diff(x1(-2)) + a_x2_x1_1*diff(x2(-1)) + a_x2_x1_2*diff(x2(-2)) + ex2;
[name='eq:x1bar']
x1bar = x1bar(-1) + ex1bar;
[name='eq:x2bar']
x2bar = x2bar(-1) + ex2bar;
[name='zpac']
diff(z) = e_c_m*(x1(-1)-z(-1)) + c_z_1*diff(z(-1)) + c_z_2*diff(z(-2)) +␣
˓→pac_expectation(pacman) + ez;
end;
pac.initialize('pacman');
pac.update.expectation('pacman');
pac_target_info(pacman);
target v;
auxname_target_nonstationary vns;
component y;
auxname pv_y_;
kind ll;
component x;
growth diff(x(-1));
auxname pv_dx_;
kind dd;
end;
model;
(continues on next page)
[name='eq:y']
y = a_y_1*y(-1) + a_y_2*diff(x(-1)) + b_y_1*y(-2) + b_y_2*diff(x(-2)) +␣
˓→ey ;
[name='eq:x']
diff(x) = b_x_1*y(-2) + b_x_2*diff(x(-1)) + ex ;
[name='eq:v']
v = x + d_y*y ; // Composite PAC target, no residuals here only␣
˓→variables defined in the auxiliary model.
[name='zpac']
diff(z) = e_c_m*(pac_target_nonstationary(pacman)-z(-1)) + c_z_1*diff(z(-
˓→1)) + c_z_2*diff(z(-2)) + pac_expectation(pacman) + ez;
end;
pac.initialize('pacman');
pac.update.expectation('pacman');
The PAC equation, introduced in the previous section, can be estimated. This equation is nonlinear with respect
to the estimated parameters (𝑎𝑖 )𝑚−1
𝑖=0 , since the reduced form parameters (in the computation of the infinite sum)
are nonlinear functions of the autoregressive parameters and the error correction parameter. Brayton et alii (2000)
shows how to estimate the PAC equation by iterative OLS. Although this approach is implemented in Dynare,
mainly for comparison purposes, we also propose NLS estimation, which is much preferable (asymptotic properties
of NLS being more solidly grounded).
Note that it is currently not feasible to estimate the PAC equation jointly with the remaining parameters of the
model using e.g. Bayesian techniques. Thus, estimation of the PAC equation can only be conducted conditional
on the values of the parameters of the auxiliary model.
Warning: The estimation routines described below require the option json=compute be passed to the pre-
processor (via the command line or at the top of the .mod file, see Dynare invocation).
structure containing the initial guess values for the estimated parameters. Each field is the name of a param-
eter in the PAC equation and holds the initial guess for this parameter. If some parameters are calibrated,
then they should not be members of the GUESS structure (and values have to be provided in the .mod file
before the call to the estimation routine).
For the NLS routine the estimation results are displayed in a table after the estimation. For both the NLS
and iterative OLS routines, the results are saved in oo_ (under the fields nls or iterative_ols). Also, the
values of the parameters are updated in M_.params.
Example (continued)
Warning: The specification of GUESS and DATA involves the use of structures. As such, their subfields will
not be cleared across Dynare runs as the structures stay in the workspace. Be careful to clear these structures
from the memory (e.g. within the .mod file) when e.g. changing which parameters are calibrated.
Dynare has comments to plot the results of a simulation and to save the results.
Command: rplot VARIABLE_NAME...;
Plots the simulated path of one or several variables, as stored in oo_.endo_simul by either
perfect_foresight_solver, simul (see Deterministic simulation) or stoch_simul with option
periods (see Stochastic solution and simulation). The variables are plotted in levels.
Command: dynatype(FILENAME) [VARIABLE_NAME...];
This command prints the listed endogenous or exogenous variables in a text file named FILENAME. If no
VARIABLE_NAME is listed, all endogenous variables are printed.
Command: dynasave(FILENAME) [VARIABLE_NAME...];
This command saves the listed endogenous or exogenous variables in a binary file named FILENAME. If no
VARIABLE_NAME is listed, all endogenous variables are saved.
In MATLAB or Octave, variables saved with the dynasave command can be retrieved by the command:
load(FILENAME,'-mat')
It is possible to use “macro” commands in the .mod file for performing tasks such as: including modular source
files, replicating blocks of equations through loops, conditionally executing some code, writing indexed sums or
products inside equations. . .
The Dynare macro-language provides a new set of macro-commands which can be used in .mod files. It features:
• File inclusion
• Loops (for structure)
• Conditional inclusion (if/then/else structures)
• Expression substitution
This macro-language is totally independent of the basic Dynare language, and is processed by a separate component
of the Dynare pre-processor. The macro processor transforms a .mod file with macros into a .mod file without
macros (doing expansions/inclusions), and then feeds it to the Dynare parser. The key point to understand is that
the macro processor only does text substitution (like the C preprocessor or the PHP language). Note that it is
possible to see the output of the macro processor by using the savemacro option of the dynare command (see
Dynare invocation).
The macro processor is invoked by placing macro directives in the .mod file. Directives begin with an at-sign
followed by a pound sign (@#). They produce no output, but give instructions to the macro processor. In most
cases, directives occupy exactly one line of text. If needed, two backslashes (\\) at the end of the line indicate
that the directive is continued on the next line. Macro directives following // are not interpreted by the macro
processor. For historical reasons, directives in commented blocks, ie surrounded by /* and */, are interpreted by
the macro processor. The user should not rely on this behavior. The main directives are:
• @#includepath, paths to search for files that are to be included,
• @#include, for file inclusion,
• @#define, for defining a macro processor variable,
• @#if, @#ifdef, @#ifndef, @#elseif, @#else, @#endif for conditional statements,
• @#for, @#endfor for constructing loops.
The macro processor maintains its own list of variables (distinct from model variables and MATLAB/Octave vari-
ables). These macro-variables are assigned using the @#define directive and can be of the following basic types:
boolean, real, string, tuple, function, and array (of any of the previous types).
Boolean
Real
String
Tuple
Tuples are enclosed by parentheses and elements are separated by commas (like (a,b,c) or (1,2,3)).
The following operators can be used on tuples:
• Comparison operators: ==, !=
• Functions: empty, length
Array
Arrays are enclosed by brackets, and their elements are separated by commas (like [1,[2,3],4] or ["US",
"FR"]).
The following operators can be used on arrays:
• Comparison operators: ==, !=
• Dereferencing: if v is an array, then v[2] is its 2nd element
• Concatenation of two arrays: +
• Set union of two arrays: |
• Set intersection of two arrays: &
• Difference -: returns the first operand from which the elements of the second operand have been removed.
• Cartesian product of two arrays: *
• Cartesian product of one array N times: ^N
• Extraction of sub-arrays: e.g. v[4:6]
• Testing membership of an array: in operator (for example: "b" in ["a", "b", "c"] returns 1)
• Functions: empty, sum, length
Comprehension
Comprehension syntax is a shorthand way to make arrays from other arrays. There are three different ways the
comprehension syntax can be employed: filtering, mapping, and filtering and mapping.
Filtering
Filtering allows one to choose those elements from an array for which a certain condition hold.
Example
Create a new array, choosing the even numbers from the array 1:5:
[2, 4]
Mapping
Mapping allows you to apply a transformation to every element of an array.
Example
Create a new array, squaring all elements of the array 1:5:
Example
Create a new array, squaring all even elements of the array 1:5:
[4, 16]
Further Examples
Function
Functions can be defined in the macro processor using the @#define directive (see below). A function is evalu-
ated at the time it is invoked during the macroprocessing stage, not at define time. Functions can be included in
expressions and the operators that can be combined with them depend on their return type.
Given a variable name or literal, you can check the type it evaluates to using the following functions: isboolean,
isreal, isstring, istuple, and isarray.
Examples
Code Output
isboolean(0) false
isboolean(true) true
isreal("str") false
Variables and literals of one type can be cast into another type. Some type changes are straightforward (e.g.
changing a real to a string) whereas others have certain requirements (e.g. to cast an array to a real it must be a
one element array containing a type that can be cast to real).
Examples
Code Output
(bool) -1.1 true
(bool) 0 false
(real) "2.2" 2.2
(tuple) [3.3] (3.3)
(array) 4.4 [4.4]
(real) [5.5] 5.5
(real) [6.6, 7.7] error
(real) "8.8 in a string" error
Examples
Code Output
(bool) 0 && true false
(real) "1" + 2 3
(string) (3 + 4) "7"
(array) 5 + (array) 6 [5, 6]
@#includepath "/path/to/folder/containing/modfiles"
@#includepath folders_containing_mod_files
@#include "modelcomponent.mod"
@#include location_of_modfile
Example
@#define x = 1
@#define y = [ "B", "C" ]
(continues on next page)
model;
A = @{y[i] + f("D")};
end;
model;
A = BD + B;
end;
...
model;
i = i(-1)^w * i_ss^(1-w) * (pie/piestar)^w2;
...
end;
Example
Choose between two alternative monetary policy rules using a macro-variable. The only differ-
ence between this example and the previous one is the use of @#ifdef instead of @#if:
Although linear_mon_pol contains the value false because @#ifdef only checks that the
variable has been defined, the linear monetary policy is output::This would result in:
...
model;
i = w*i(-1) + (1-w)*i_ss + w2*(pie-piestar);
...
end;
model;
@#for country in [ "home", "foreign" ]
GDP_@{country} = A * K_@{country}^a * L_@{country}^(1-a);
@#endfor
end;
model;
GDP_home = A * K_home^a * L_home^(1-a);
GDP_foreign = A * K_foreign^a * L_foreign^(1-a);
end;
Example
model;
@#for (i, j) in ["GDP"] * ["home", "foreign"]
(continues on next page)
model;
GDP_home = A * K_home^a * L_home^(1-a);
GDP_foreign = A * K_foreign^a * L_foreign^(1-a);
end;
Example
model;
(1+i_FR) = (1+i_US) * E_FR(+1) / E_FR;
(1+i_JA) = (1+i_US) * E_JA(+1) / E_JA;
E_US = 1;
end;
@#define A = 1
@#define B = 2
@#define C(x) = x*2
@#echomacrovars A C D
Macro Variables:
A = 1
Macro Functions:
C(x) = (x * 2)
4.27.3.1 Modularization
The @#include directive can be used to split .mod files into several modular components.
Example setup:
modeldesc.mod
Contains variable declarations, model equations, and shocks declarations.
simul.mod
Includes modeldesc.mod, calibrates parameter,s and runs stochastic simulations.
estim.mod
Includes modeldesc.mod, declares priors on parameters, and runs Bayesian estimation.
Dynare can be called on simul.mod and estim.mod, but it makes no sense to run it on modeldesc.mod.
The main advantage is that you don’t have to copy/paste the whole model (during initial development) or changes
to the model (during development).
@#define window = 2
var x MA_x;
...
model;
...
MA_x = @{1/(2*window+1)}*(
@#for i in -window:window
+x(@{i})
@#endfor
);
...
end;
var x MA_x;
...
model;
...
MA_x = 0.2*(
+x(-2)
+x(-1)
+x(0)
+x(1)
+x(2)
);
...
end;
@#for co in countries
var Y_@{co} K_@{co} L_@{co} i_@{co} E_@{co} ...;
parameters a_@{co} ...;
varexo ...;
@#endfor
model;
@#for co in countries
Y_@{co} = K_@{co}^a_@{co} * L_@{co}^(1-a_@{co});
...
@#if co != nth_co
(1+i_@{co}) = (1+i_@{nth_co}) * E_@{co}(+1) / E_@{co}; // UIP relation
@#else
E_@{co} = 1;
@#endif
@#endfor
end;
When calibrating the model, it may be useful to pin down parameters by targeting endogenous objects.
For example, suppose production is defined by a CES function:
(︁ )︁𝜉/(𝜉−1)
1−1/𝜉 1−1/𝜉
𝑦𝑡 = 𝛼1/𝜉 ℓ𝑡 + (1 − 𝛼)1/𝜉 𝑘𝑡
@#if steady
var alpha;
parameter lab_rat;
@#else
parameter alpha;
var lab_rat;
@#endif
steadystate.mod
This file computes the steady state. It begins with:
@#define steady = 1
@#include "modeqs.mod"
Then it initializes parameters (including lab_rat, excluding 𝛼), computes the steady state (using
guess values for endogenous, including 𝛼), then saves values of parameters and variables at steady
state in a file, using the save_params_and_steady_state command.
simulate.mod
This file computes the simulation. It begins with:
@#define steady = 0
@#include "modeqs.mod"
Then it loads values of parameters and variables at steady state from file, using the
load_params_and_steady_state command, and computes the simulations.
Suppose you have a model with a parameter 𝜌 and you want to run simulations for three values: 𝜌 = 0.8, 0.9, 1.
There are several ways of doing this:
With a MATLAB/Octave loop
Here the loop is not unrolled, MATLAB/Octave manages the iterations. This is interesting when there
are a lot of iterations. It is strongly advised to always check whether the error flag info(1)==0 to
prevent erroneously relying on stale results from previous iterations.
With a macro processor loop (case 1)
This is very similar to the previous example, except that the loop is unrolled. The macro processor
manages the loop index but not the data array (rhos).
With a macro processor loop (case 2)
The advantage of this method is that it uses a shorter syntax, since the list of values is directly given in
the loop construct. The inconvenience is that you can not reuse the macro array in MATLAB/Octave.
Pass everything contained within the verbatim block to the <mod_file>.m file.
Block: verbatim ;
By default, whenever Dynare encounters code that is not understood by the parser, it is directly passed to the
preprocessor output.
In order to force this behavior you can use the verbatim block. This is useful when the code you want
passed to the driver file contains tokens recognized by the Dynare preprocessor.
Example
verbatim;
% Anything contained in this block will be passed
% directly to the driver file, including comments
var = 1;
end;
Command: set_dynare_seed(INTEGER)
Command: set_dynare_seed('default')
Command: set_dynare_seed('clock')
Command: set_dynare_seed('reset')
Command: set_dynare_seed('ALGORITHM', INTEGER)
Sets the seed used for random number generation. It is possible to set a given integer value, to use a default
value, or to use the clock (by using the latter, one will therefore get different results across different Dynare
runs). The reset option serves to reset the seed to the value set by the last set_dynare_seed command.
On MATLAB 7.8 or above, it is also possible to choose a specific algorithm for random number genera-
tion; accepted values are mcg16807, mlfg6331_64, mrg32k3a, mt19937ar (the default), shr3cong and
swb2712.
Command: save_params_and_steady_state(FILENAME);
For all parameters, endogenous and exogenous variables, stores their value in a text file, using a simple
name/value associative table.
• for parameters, the value is taken from the last parameter initialization.
• for exogenous, the value is taken from the last initval block.
• for endogenous, the value is taken from the last steady state computation (or, if no steady state has been
computed, from the last initval block).
Note that no variable type is stored in the file, so that the values can be reloaded with
load_params_and_steady_state in a setup where the variable types are different.
The typical usage of this function is to compute the steady-state of a model by calibrating the steady-state
value of some endogenous variables (which implies that some parameters must be endogeneized during the
steady-state computation).
You would then write a first .mod file which computes the steady state and saves the result of the computation
at the end of the file, using save_params_and_steady_state.
In a second file designed to perform the actual simulations, you would use
load_params_and_steady_state just after your variable declarations, in order to load the steady
state previously computed (including the parameters which had been endogeneized during the steady state
computation).
The need for two separate .mod files arises from the fact that the variable declarations differ between the
files for steady state calibration and for simulation (the set of endogenous and parameters differ between the
two); this leads to different var and parameters statements.
Also note that you can take advantage of the @#include directive to share the model equations between the
two files (see Macro processing language).
Command: load_params_and_steady_state(FILENAME);
For all parameters, endogenous and exogenous variables, loads their value from a file created with
save_params_and_steady_state.
• for parameters, their value will be initialized as if they had been calibrated in the .mod file.
• for endogenous and exogenous variables, their value will be initialized as they would have been from
an initval block .
This function is used in conjunction with save_params_and_steady_state; see the documentation of
that function for more information.
Command: compilation_setup(OPTIONS);
When the use_dll option is present, Dynare uses the GCC compiler that was distributed with it to compile
the static and dynamic C files produced by the preprocessor. You can use this option to change the compiler,
flags, and libraries used.
Options
compiler = FILENAME
The path to the compiler.
substitute_flags = QUOTED_STRING
The flags to use instead of the default flags.
add_flags = QUOTED_STRING
The flags to use in addition to the default flags. If substitute_flags is passed, these flags
are added to the flags specified there.
substitute_libs = QUOTED_STRING
The libraries to link against instead of the default libraries.
add_libs = QUOTED_STRING
The libraries to link against in addition to the default libraries. If substitute_libs is
passed, these libraries are added to the libraries specified there.
MATLAB/Octave command: dynare_version ;
Output the version of Dynare that is currently being used (i.e. the one that is highest on the MATLAB/Octave
path).
FIVE
The configuration file is used to provide Dynare with information not related to the model (and hence not placed
in the model file). At the moment, it is only used when using Dynare to run parallel computations.
On Linux and macOS, the configuration file is searched by default under dynare/dynare.ini in the configura-
tion directories defined by the XDG specification (typically $HOME/.config/dynare/dynare.ini for the user-
specific configuration and /etc/xdg/dynare/dynare.ini for the system-wide configuration, the former having
precedence over the latter). Under Windows, the configuration file is searched by default in %APPDATA%\dynare\
dynare.ini (typically c:\Users\USERNAME\AppData\Roaming\dynare\dynare.ini). You can specify a
non standard location using the conffile option of the dynare command (see Dynare invocation).
The parsing of the configuration file is case-sensitive and it should take the following form, with each option/choice
pair placed on a newline:
[command0]
option0 = choice0
option1 = choice1
[command1]
option0 = choice0
option1 = choice1
The configuration file follows a few conventions (self-explanatory conventions such as USER_NAME have been ex-
cluded for concision):
COMPUTER_NAME
Indicates the valid name of a server (e.g. localhost, server.cepremap.org) or an IP address.
DRIVE_NAME
Indicates a valid drive name in Windows, without the trailing colon (e.g. C).
PATH
Indicates a valid path in the underlying operating system (e.g. /home/user/dynare/matlab/).
PATH_AND_FILE
Indicates a valid path to a file in the underlying operating system (e.g. /usr/local/MATLAB/R2023b/
bin/matlab).
BOOLEAN
Is true or false.
215
Dynare Reference Manual, Release 6.0
This section explains how to configure Dynare for general processing. Currently, there is only one option available.
[hooks]
GlobalInitFile = /home/usern/dynare/myInitFile.m
[paths]
Include = /path/to/folder/containing/modfiles:/path/to/another/folder
This section explains how to configure Dynare for parallelizing some tasks which require very little inter-process
communication.
The parallelization is done by running several MATLAB or Octave processes, either on local or on remote ma-
chines. Communication between leader and follower processes are done through SMB on Windows and SSH on
UNIX. Input and output data, and also some short status messages, are exchanged through network filesystems.
Currently the system works only with homogenous grids: only Windows or only Unix machines.
The following routines are currently parallelized:
• the posterior sampling algorithms when using multiple chains;
• the Metropolis-Hastings diagnostics;
• the posterior IRFs;
• the prior and posterior statistics;
• some plotting routines.
Note that creating the configuration file is not enough in order to trigger parallelization of the computations: you
also need to specify the parallel option to the dynare command. For more details, and for other options related
to the parallelization engine, see Dynare invocation.
You also need to verify that the following requirements are met by your cluster (which is composed of a leader and
of one or more followers):
For a Windows grid:
• a standard Windows network (SMB) must be in place;
• the PsTools suite must be installed in the path of the leader Windows machine;
• the Windows user on the leader machine has to be user of any other follower machine in the cluster, and that
user will be used for the remote computations.
• detailed step-by-step setup instructions can be found in Windows Step-by-Step Guide.
For a UNIX grid:
• SSH must be installed on the leader and on the follower machines;
• SSH keys must be installed so that the SSH connection from the leader to the follower can be done without
passwords, or using an SSH agent.
We now turn to the description of the configuration directives. Note that comments in the configuration file can be
provided by separate lines starting with a hashtag (#).
Configuration block: [cluster]
When working in parallel, [cluster] is required to specify the group of computers that will be used. It is
required even if you are only invoking multiple processes on one computer.
Options
Name = CLUSTER_NAME
The reference name of this cluster.
Members = NODE_NAME[(WEIGHT)] NODE_NAME[(WEIGHT)] ...
A list of nodes that comprise the cluster with an optional computing weight specified for that node.
The computing weight indicates how much more powerful one node is with respect to the others (e.g.
n1(2) n2(1) n3(3) means that n1 is two times more powerful than n2 whereas n3 is three times
more powerful than n2). Each node is separated by at least one space and the weights are in parenthesis
with no spaces separating them from their node.
Example
[cluster]
Name = c1
Members = n1 n2 n3
[cluster]
Name = c2
Members = n1(4) n2 n3
Name = NODE_NAME
The reference name of this node.
CPUnbr = INTEGER | [INTEGER:INTEGER]
If just one integer is passed, the number of processors to use. If a range of integers is passed, the specific
processors to use (processor counting is defined to begin at one as opposed to zero). Note that using
specific processors is only possible under Windows; under Linux and macOS, if a range is passed the
same number of processors will be used but the range will be adjusted to begin at one.
ComputerName = COMPUTER_NAME
The name or IP address of the node. If you want to run locally, use localhost (case-sensitive).
Port = INTEGER
The port number to connect to on the node. The default is empty, meaning that the connection will be
made to the default SSH port (22).
UserName = USER_NAME
The username used to log into a remote system. Required for remote runs on all platforms.
Password = PASSWORD
The password used to log into the remote system. Required for remote runs originating from Windows.
RemoteDrive = DRIVE_NAME
The drive to be used for remote computation. Required for remote runs originating from Windows.
RemoteDirectory = PATH
The directory to be used for remote computation. Required for remote runs on all platforms.
DynarePath = PATH
The path to the matlab subdirectory within the Dynare installation directory. The default is the empty
string.
MatlabOctavePath = PATH_AND_FILE
The path to the MATLAB or Octave executable. The default value is matlab as MATLAB’s executable
is typically in the %PATH% environment variable. When using full paths on Windows, you may
need to enclose the path in quoted strings, e.g. MatlabOctavePath="C:\Program Files\MATLAB\
R2023b\bin\matlab.exe"
NumberOfThreadsPerJob = INTEGER
This option controls the distribution of jobs (e.g. MCMC chains) across additional MATLAB instances
that are run in parallel. Needs to be an exact divisor of the number of cores. The formula CPUnbr
divided by NumberOfThreadsPerJob calculates the number of MATLAB/Octave instances that will
be launched in parallel, where each instance will then execute a certain number of jobs sequentially.
For example, if you run a MCMC estimation with 24 chains on a 12 core machine, setting CPUnbr =
12 and NumberOfThreadsPerJob = 4 will launch 3 MATLAB instances in parallel, each of which
will compute 8 chains sequentially. Note that this option does not dictate the number of maximum
threads utilized by each MATLAB/Octave instance, see related option SingleCompThread for this.
Particularly for very large models, setting this option to 2 might distribute the workload in a more
efficient manner, depending on your hardware and task specifics. It’s advisable to experiment with
different values to achieve optimal performance. The default value is 1.
SingleCompThread = BOOLEAN
This option allows you to enable or disable MATLAB’s native multithreading capability. When
set to true, the additional MATLAB instances are initiated in single thread mode utilizing the
-singleCompThread startup option, thereby disabling MATLAB’s native multithreading. When set
to false, MATLAB’s native multithreading is enabled, e.g. the actual number of threads utilized by
each MATLAB instance is usually determined by the number of CPU cores (you can check this by
running maxNumCompThreads in MATLAB’s command window). Note: While MATLAB aims to
accelerate calculations by distributing them across your computer’s threads, certain tasks, like MCMC
estimations, may exhibit slowdowns with MATLAB’s multitasking especially when Dynare’s parallel
computing is turned on as we do not use MATLAB’s parallel toolbox. So in many cases it is advisable
to set this setting to true. If you want to have more control, you can manually add the MATLAB
command maxNumCompThreads(N) at the beginning of fParallel.m. The default value is false. This
option is ineffective under Octave.
OperatingSystem = OPERATING_SYSTEM
The operating system associated with a node. Only necessary when creating a cluster with nodes from
different operating systems. Possible values are unix or windows. There is no default value.
Example
[node]
Name = n1
ComputerName = localhost
CPUnbr = 1
[node]
Name = n2
ComputerName = dynserv.cepremap.org
CPUnbr = 5
UserName = usern
RemoteDirectory = /home/usern/Remote
DynarePath = /home/usern/dynare/matlab
MatlabOctavePath = matlab
[node]
Name = n3
ComputerName = dynserv.dynare.org
Port = 3333
CPUnbr = [2:4]
UserName = usern
RemoteDirectory = /home/usern/Remote
DynarePath = /home/usern/dynare/matlab
MatlabOctavePath = matlab
This section outlines the steps necessary on most Windows systems to set up Dynare for parallel execu-
tion. Note that the steps 3 to 6 are required unless parallel execution is confined to a local pool with the
parallel_use_psexec=false option.
1. Write a configuration file containing the options you want. A mimimum working example setting
up a cluster consisting of two local CPU cores that allows for e.g. running two Monte Carlo
Markov Chains in parallel is shown below.
2. Save the configuration file somwhere. The name and file ending do not matter if you are providing
it with the conffile command line option. The only restrictions are that the path must be a valid
filename, not contain non-alpha-numeric characters, and not contain any whitespaces. For the
configuration file to be accessible without providing an explicit path at the command line, you
must save it under the name dynare.ini into your user account’s Application Data folder.
3. Install PSTools to your system, e.g. into C:\PSTools.
4. Set the Windows System Path to the PSTools folder (e.g. using something along the line of
pressing Windows Key+Pause to open the System Configuration, then go to Advanced -> Envi-
ronment Variables -> Path).
5. Restart your computer to make the path change effective.
6. Open MATLAB and type into the command window:
!psexec
This executes the psexec.exe from PSTools on your system and shows whether Dynare will be
able to locate it. If MATLAB complains at this stage, you did not correctly set your Windows
system path for the PSTools folder.
7. If psexec.exe was located in the previous step, a popup will show up, asking for confirmation
of the license agreement. Confirm this copyright notice of psexec (this needs to be done only
once). After this, Dynare should be ready for parallel execution.
8. Call Dynare on your mod-file invoking the parallel option and providing the path to your
configuration file with the conffile option (if you did not save it as %APPDATA%\dynare.ini
in step 2 where it should be detected automatically):
Please keep in mind that no white spaces or names longer than 8 characters are allowed in the
conffile path. The 8-character restriction can be circumvented by using the tilde Windows path
notation as in the above example.
Example:
SIX
TIME SERIES
Dynare provides a MATLAB/Octave class for handling time series data, which is based on a class for handling
dates. Dynare also provides a new type for dates, so that the user does not have to worry about class and methods
for dates. Below, you will first find the class and methods used for creating and dealing with dates and then the
class used for using time series. Dynare also provides an interface to the X-13 ARIMA-SEATS seasonal adjustment
program produced, distributed, and maintained by the U.S. Census Bureau (2020).
6.1 Dates
Dynare understands dates in a mod file. Users can declare annual, bi-annual, quarterly, or monthly dates using the
following syntax:
1990Y
1990S2
1990Q4
1990M11
Behind the scene, Dynare’s preprocessor translates these expressions into instantiations of the MATLAB/Octave’s
class dates described below. Basic operations can be performed on dates:
plus binary operator (+)
An integer scalar, interpreted as a number of periods, can be added to a date. For instance, if a =
1950Q1 then b = 1951Q2 and b = a + 5 are identical.
plus unary operator (+)
Increments a date by one period. +1950Q1 is identical to 1950Q2, ++++1950Q1 is identical to 1951Q1.
minus binary operator (-)
Has two functions: difference and subtraction. If the second argument is a date, calculates the differ-
ence between the first date and the secmond date (e.g. 1951Q2-1950Q1 is equal to 5). If the second
argument is an integer X, subtracts X periods from the date (e.g. 1951Q2-2 is equal to 1950Q4).
minus unary operator (-)
Subtracts one period to a date. -1950Q1 is identical to 1949Q4. The unary minus operator is the
reciprocal of the unary plus operator, +-1950Q1 is identical to 1950Q1.
colon operator (:)
Can be used to create a range of dates. For instance, r = 1950Q1:1951Q1 creates a dates object
with five elements: 1950Q1, 1950Q2, 1950Q3, 1950Q4 and 1951Q1. By default the increment
between each element is one period. This default can be changed using, for instance, the following
instruction: 1950Q1:2:1951Q1 which will instantiate a dates object with three elements: 1950Q1,
1950Q3 and 1951Q1.
221
Dynare Reference Manual, Release 6.0
which will lead to a crash because this expression is illegal in MATLAB. For this situation, Dynare provides the $
escape parameter. The following expression:
Members
• freq – equal to 1, 2, 4, 12 or 365 (resp. for annual, bi-annual, quarterly, monthly, or
daily dates).
• time – a n*1 array of integers, the number of periods since year 0 ().
Each member is private, one can display the content of a member but cannot change its value directly.
Note also that it is not possible to mix frequencies in a dates object: all the elements must have common
frequency.
The dates class has the following constructors:
Constructor: dates()
Constructor: dates(FREQ)
Returns an empty dates object with a given frequency (if the constructor is called with one input
argument). FREQ is a character equal to ’Y’ or ’A’ for annual dates, ’S’ or ’H’ for bi-annual dates, ’Q’
for quarterly dates, ’M’ for monthly dates, or ’D’ for daily dates. Note that FREQ is not case sensitive, so
that, for instance, ’q’ is also allowed for quarterly dates. The frequency can also be set with an integer
scalar equal to 1 (annual), 2 (bi-annual), 4 (quarterly), 12 (monthly), or 365 (daily). The instantiation
of empty objects can be used to rename the dates class. For instance, if one only works with quarterly
dates, object qq can be created as:
qq = dates('Q')
d0 = qq(2009,2);
which is much simpler if dates objects have to be defined programmatically. For daily dates, we would
instantiate an empty daily dates object as:
dd = dates('D')
d1 = dd(2020,12,31);
Constructor: dates(STRING)
Constructor: dates(STRING, STRING, ...)
Returns a dates object that represents a date as given by the string STRING. This string has to be
interpretable as a date (only strings of the following forms are admitted: '1990Y', '1990A', 1990S1,
1990H1, '1990Q1', '1990M2', or '2020-12-31'), the routine isdate can be used to test if a string
is interpretable as a date. If more than one argument is provided, they should all be dates represented
as strings, the resulting dates object contains as many elements as arguments to the constructor. For
the daily dates, the string must be of the form yyyy-mm-dd with two digits for the months (mm) and
days (dd), even if the number of days or months is smaller than ten (in this case a leading 0 is required).
Constructor: dates(DATES)
do1 = dates('1950Q1');
do2 = dates('1950Q2','1950Q3');
do3 = dates(do1,do2);
do4 = dates('Q',1950, 1);
do5 = dates('D',1973, 1, 25);
A list of the available methods, by alphabetical order, is given below. Note that by default the methods do
not allow in place modifications: when a method is applied to an object a new object is instantiated. For
instance, to apply the method multiplybytwo to an object X we write:
>> X = 2;
>> Y = X.multiplybytwo();
>> X
>> Y
or equivalently:
>> Y = multiplybytwo(X);
the object X is left unchanged, and the object Y is a modified copy of X (multiplied by two). This behaviour
is altered if the name of the method is postfixed with an underscore. In this case the creation of a copy is
avoided. For instance, following the previous example, we would have:
>> X = 2;
>> X.multiplybytwo_();
>> X
Modifying the objects in place, with underscore methods, is particularly useful if the methods are called in
loops, since this saves the object instantiation overhead.
Method: C = append(A, B)
Method: C = append_(A, B)
Appends dates object B, or a string that can be interpreted as a date, to the dates object A. If B is a
dates object it is assumed that it has no more than one element.
Example
>> D = dates('1950Q1','1950Q2');
>> d = dates('1950Q3');
>> E = D.append(d);
>> F = D.append('1950Q3');
>> isequal(E,F)
ans =
1
>> F
>> D
>> D.append_('1950Q3')
Method: B = char(A)
Overloads the MATLAB/Octave char function. Converts a dates object into a character array.
Example
>> A = dates('1950Q1');
> A.char()
ans =
'1950Q1'
Method: C = colon(A, B)
Method: C = colon(A, i, B)
Overloads the MATLAB/Octave colon (:) operator. A and B are dates objects. The optional incre-
ment i is a scalar integer (default value is i=1). This method returns a dates object and can be used
to create ranges of dates.
Example
>> A = dates('1950Q1');
>> B = dates('1951Q2');
>> C = A:B
>> D = A:2:B
Method: B = copy(A)
Returns a copy of a dates object.
Method: disp(A)
Overloads the MATLAB/Octave disp function for dates object.
Method: display(A)
Overloads the MATLAB/Octave display function for dates object.
Example
>> disp(B)
>> display(B)
Method: B = double(A)
Overloads the MATLAB/Octave double function. A is a dates object. The method returns a floating
point representation of a dates object, the integer and fractional parts respectively corresponding to
the year and the subperiod. The fractional part is the subperiod number minus one divided by the
frequency (1, 4, or 12).
Example:
>> a = dates('1950Q1'):dates('1950Q4');
>> a.double()
ans =
1950.00
1950.25
1950.50
1950.75
Method: C = eq(A, B)
Overloads the MATLAB/Octave eq (equal, ==) operator. dates objects A and B must have the same
number of elements (say, n). The returned argument is a n by 1 vector of logicals. The i-th element of
C is equal to true if and only if the dates A(i) and B(i) are the same.
Example
>> A = dates('1950Q1','1951Q2');
>> B = dates('1950Q1','1950Q2');
>> A==B
ans =
1
0
Method: C = ge(A, B)
Overloads the MATLAB/Octave ge (greater or equal, >=) operator. dates objects A and B must have
the same number of elements (say, n). The returned argument is a n by 1 vector of logicals. The i-th
element of C is equal to true if and only if the date A(i) is posterior or equal to the date B(i).
Example
>> A = dates('1950Q1','1951Q2');
>> B = dates('1950Q1','1950Q2');
>> A>=B
1
1
Method: C = gt(A, B)
Overloads the MATLAB/Octave gt (greater than, >) operator. dates objects A and B must have the
same number of elements (say, n). The returned argument is a n by 1 vector of logicals. The i-th
element of C is equal to 1 if and only if the date A(i) is posterior to the date B(i).
Example
>> A = dates('1950Q1','1951Q2');
>> B = dates('1950Q1','1950Q2');
>> A>B
ans =
0
1
>> A = dates('1950Q1');
>> B = dates('1950Q2');
>> C = [A, B];
>> C
Method: C = intersect(A, B)
Overloads the MATLAB/Octave intersect function. All the input arguments must be dates objects.
The returned argument is a dates object gathering all the common dates given in the input arguments.
If A and B are disjoint dates objects, the function returns an empty dates object. Returned dates in
dates object C are sorted by increasing order.
Example
>> A = dates('1950Q1'):dates('1951Q4');
>> B = dates('1951Q1'):dates('1951Q4');
>> C = intersect(A, B);
>> C
Method: B = isempty(A)
Overloads the MATLAB/Octave isempty function.
Example
>> A = dates('1950Q1');
>> A.isempty()
ans =
logical
>> B = dates();
>> B.isempty()
ans =
logical
Method: C = isequal(A, B)
Overloads the MATLAB/Octave isequal function.
Example
>> A = dates('1950Q1');
>> B = dates('1950Q2');
>> isequal(A, B)
ans =
logical
Method: C = le(A, B)
Overloads the MATLAB/Octave le (less or equal, <=) operator. dates objects A and B must have
the same number of elements (say, n). The returned argument is a n by 1 vector of logicals. The i-th
element of C is equal to true if and only if the date A(i) is anterior or equal to the date B(i).
Example
>> A = dates('1950Q1','1951Q2');
>> B = dates('1950Q1','1950Q2');
>> A<=B
ans =
1
0
Method: B = length(A)
Overloads the MATLAB/Octave length function. Returns the number of elements in a dates object.
Example
>> A = dates('1950Q1'):dates(2000Q3);
>> A.length()
(continues on next page)
ans =
203
Method: C = lt(A, B)
Overloads the MATLAB/Octave lt (less than, <) operator. dates objects A and B must have the same
number of elements (say, n). The returned argument is a n by 1 vector of logicals. The i-th element of
C is equal to true if and only if the date A(i) is anterior or equal to the date B(i).
Example
>> A = dates('1950Q1','1951Q2');
>> B = dates('1950Q1','1950Q2');
>> A<B
ans =
0
0
Method: C = minus(A, B)
Overloads the MATLAB/Octave minus operator (-). If both input arguments are dates objects, then
number of periods between A and B is returned (so that A+C=B). If B is a vector of integers, the minus
operator shifts the dates object by B periods backward.
Example
>> d1 = dates('1950Q1','1950Q2','1960Q1');
>> d2 = dates('1950Q3','1950Q4','1960Q1');
>> ee = d2-d1
ee =
>> d1-(-ee)
Method: C = mtimes(A, B)
Overloads the MATLAB/Octave mtimes operator (*). A and B are respectively expected to be a dates
object and a scalar integer. Returns dates object A replicated B times.
Example
>> d = dates('1950Q1');
>> d*2
Method: C = ne(A, B)
Overloads the MATLAB/Octave ne (not equal, ~=) operator. dates objects A and B must have the
same number of elements (say, n) or one of the inputs must be a single element dates object. The
returned argument is a n by 1 vector of logicals. The i-th element of C is equal to true if and only if
the dates A(i) and B(i) are different.
Example
>> A = dates('1950Q1','1951Q2');
>> B = dates('1950Q1','1950Q2');
>> A~=B
ans =
0
1
Method: C = plus(A, B)
Overloads the MATLAB/Octave plus operator (+). If both input arguments are dates objects, then the
method combines A and B without removing repetitions. If B is a vector of integers, the plus operator
shifts the dates object by B periods forward.
Example
>> d1 = dates('1950Q1','1950Q2')+dates('1960Q1');
>> d2 = (dates('1950Q1','1950Q2')+2)+dates('1960Q1');
>> ee = d2-d1;
ee =
2
2
0
>> d1+ee
ans = <dates: 1950Q3, 1950Q4, 1960Q1>
Method: C = pop(A)
Method: C = pop(A, B)
Method: C = pop_(A)
Method: C = pop_(A, B)
Pop method for dates class. If only one input is provided, the method removes the last element of a
dates object. If a second input argument is provided, a scalar integer between 1 and A.length(), the
method removes element number B from dates object A.
Example
>> d = dates('1950Q1','1950Q2');
>> d.pop()
>> d.pop_(1)
Method: C = remove(A, B)
Method: C = remove_(A, B)
Remove method for dates class. Both inputs have to be dates objects, removes dates in B from A.
Example
>> d = dates('1950Q1','1950Q2');
>> d.remove(dates('1950Q2'))
Method: C = setdiff(A, B)
Overloads the MATLAB/Octave setdiff function. All the input arguments must be dates objects.
The returned argument is a dates object all dates present in A but not in B. If A and B are disjoint
dates objects, the function returns A. Returned dates in dates object C are sorted by increasing order.
Example
>> A = dates('1950Q1'):dates('1969Q4');
>> B = dates('1960Q1'):dates('1969Q4');
>> C = dates('1970Q1'):dates('1979Q4');
>> setdiff(A, B)
>> setdiff(A, C)
Method: B = sort(A)
Method: B = sort_(A)
Sort method for dates objects. Returns a dates object with elements sorted by increasing order.
Example
>> dd = dates('1945Q3','1938Q4','1789Q3');
>> dd.sort()
Method: B = strings(A)
Converts a dates object into a cell of char arrays.
Example
>> A = dates('1950Q1');
>> A = A:A+1;
>> A.strings()
ans =
{'1950Q1'} {'1950Q2'}
Method: B = subperiod(A)
Returns the subperiod of a date (an integer scalar between 1 and A.freq). This method is not imple-
mented for daily dates.
Example
>> A = dates('1950Q2');
>> A.subperiod()
ans =
Method: B = uminus(A)
Overloads the MATLAB/Octave unary minus operator. Returns a dates object with elements shifted
one period backward.
Example
>> dd = dates('1945Q3','1938Q4','1973Q1');
>> -dd
>> d1 = dates('1945Q3','1973Q1','1938Q4');
>> d2 = dates('1973Q1','1976Q1');
>> union(d1,d2)
Method: B = unique(A)
Method: B = unique_(A)
Overloads the MATLAB/Octave unique function. Returns a dates object with repetitions removed
(only the last occurence of a date is kept).
Example
>> d1 = dates('1945Q3','1973Q1','1945Q3');
>> d1.unique()
Method: B = uplus(A)
Overloads the MATLAB/Octave unary plus operator. Returns a dates object with elements shifted
one period ahead.
Example
>> dd = dates('1945Q3','1938Q4','1973Q1');
>> +dd
>> A = dates('1950Q2');
>> A.subperiod()
ans =
1950
FREQ__ = 4;
INIT__ = '1994Q3';
NAMES__ = {'azert';'yuiop'};
TEX__ = {'azert';'yuiop'};
azert = randn(100,1);
yuiop = randn(100,1);
If a .mat file is used instead, it should provide the same informations, except that the data should not
be given as a set of vectors, but as a single matrix of doubles named DATA__. This array should have
as many columns as elements in NAMES__ (the number of variables). Note that the INIT__ variable
can be either a dates object or a string which could be used to instantiate the same dates object. If
INIT__ is not provided in the .mat or .m file, the initial is by default set equal to dates('1Y'). If
a second input argument is passed to the constructor, dates object INITIAL_DATE, the initial date
defined in FILENAME is reset to INITIAL_DATE. This is typically usefull if INIT__ is not provided
in the data file.
If an .xlsx file is used, the first row should be a header containing the variable names. The first column
may contain date information that must correspond to a valid date format recognized by Dynare. If such
date information is specified in the first column, its header name must be left empty.
Constructor: dseries(DATA_MATRIX[,INITIAL_DATE[,LIST_OF_NAMES[,TEX_NAMES]]])
Constructor: dseries(DATA_MATRIX[,RANGE_OF_DATES[,LIST_OF_NAMES[,TEX_NAMES]]])
If the data is not read from a file, it can be provided via a 𝑇 ×𝑁 matrix as the first argument to dseries
’ constructor, with 𝑇 representing the number of observations on 𝑁 variables. The optional second
argument, INITIAL_DATE, can be either a dates object representing the period of the first observation
or a string which would be used to instantiate a dates object. Its default value is dates('1Y'). The
optional third argument, LIST_OF_NAMES, is a 𝑁 × 1 cell of strings with one entry for each variable
name. The default name associated with column i of DATA_MATRIX is Variable_i. The final
argument, TEX_NAMES, is a 𝑁 × 1 cell of strings composed of the LaTeX names associated with the
variables. The default LaTeX name associated with column i of DATA_MATRIX is Variable\_i. If
the optional second input argument is a range of dates, dates object RANGE_OF_DATES, the number
of rows in the first argument must match the number of elements RANGE_OF_DATES or be equal to
one (in which case the single observation is replicated).
Constructor: dseries(TABLE)
Creates a dseries object given the MATLAB Table provided as the sole argument. It is assumed that
the first column of the table contains the dates of the dseries and the first row contains the names.
This feature is not available under Octave or MATLAB R2013a or earlier.
Example
Various ways to create a dseries object:
do1 = dseries(1999Q3);
do2 = dseries('filename.csv');
do3 = dseries([1; 2; 3], 1999Q3, {'var123'}, {'var_{123}'});
One can easily create subsamples from a dseries object using the overloaded parenthesis operator. If ds
is a dseries object with 𝑇 observations and d is a dates object with 𝑆 < 𝑇 elements, such that min(𝑑)
is not smaller than the date associated to the first observation in ds and max(𝑑) is not greater than the date
associated to the last observation, then ds(d) instantiates a new dseries object containing the subsample
defined by d.
A list of the available methods, by alphabetical order, is given below. As in the previous section the in place
modifications versions of the methods are postfixed with an underscore.
Method: A = abs(B)
Method: abs_(B)
Overloads the abs() function for dseries objects. Returns the absolute value of the variables in
dseries object B.
Example
| A1 | A2
1973Q1 | -0.67284 | 1.4367
1973Q2 | -0.51222 | -0.4948
1973Q3 | 0.99791 | 0.22677
>> ts1
| abs(A1) | abs(A2)
1973Q1 | 0.67284 | 1.4367
1973Q2 | 0.51222 | 0.4948
1973Q3 | 0.99791 | 0.22677
| Variable_1
2000Q1 | 0.81472
2000Q2 | 0.90579
2000Q3 | 0.12699
2000Q4 | 0.91338
2001Q1 | 0.63236
2001Q2 | NaN
| Variable_1
2000Q1 | NaN
2000Q2 | NaN
2000Q3 | NaN
2000Q4 | 0.66653
2001Q1 | 0.17813
2001Q2 | 0.12801
| Variable_1
2000Q1 | NaN
2000Q2 | NaN
2000Q3 | NaN
2000Q4 | 0.66653
2001Q1 | 0.17813
2001Q2 | 0.12801
ts is a dseries object:
| Variable_1
1950Q1 | 1
1950Q2 | 2
1950Q3 | 3
1950Q4 | 4
us is a dseries object:
| Variable_1
1950Q3 | 3
1950Q4 | 4
1951Q1 | 5
1951Q2 | 6
| Variable_1
1950Q1 | 1
1950Q2 | 2
1950Q3 | 3
(continues on next page)
>> a = dseries(randn(5,1))
a is a dseries object:
| Variable_1
1Y | -0.16936
2Y | -1.1451
3Y | -0.034331
4Y | -0.089042
5Y | -0.66997
>> b = copy(a);
>> c = a;
>> a.abs();
>> a.abs_();
>> a
a is a dseries object:
| Variable_1
1Y | 0.16936
2Y | 1.1451
3Y | 0.034331
4Y | 0.089042
5Y | 0.66997
>> b
b is a dseries object:
| Variable_1
1Y | -0.16936
2Y | -1.1451
3Y | -0.034331
4Y | -0.089042
5Y | -0.66997
>> c
c is a dseries object:
| Variable_1
(continues on next page)
| cumprod(Variable_1)
1Y | 2
2Y | 4
3Y | 8
4Y | 16
5Y | 32
6Y | 64
7Y | 128
| cumprod(Variable_1)
1Y | 0.25
2Y | 0.5
3Y | 1
4Y | 2
5Y | 4
6Y | 8
7Y | 16
| cumprod(Variable_1)
1Y | 0.7854
2Y | 1.5708
3Y | 3.1416
4Y | 6.2832
(continues on next page)
| cumsum(Variable_1)
1Y | 1
2Y | 2
3Y | 3
4Y | 4
5Y | 5
6Y | 6
7Y | 7
8Y | 8
9Y | 9
10Y | 10
| cumsum(Variable_1)
1Y | -2
2Y | -1
3Y | 0
4Y | 1
5Y | 2
6Y | 3
7Y | 4
8Y | 5
9Y | 6
10Y | 7
| cumsum(Variable_1)
(continues on next page)
Method: B = detrend(A, m)
Method: detrend_(A, m)
Detrends dseries object A with a fitted polynomial of order m. Note that each variable is detrended
with a different polynomial.
Method: B = dgrowth(A)
Method: dgrowth_(A)
Computes daily growth rates.
Method: B = diff(A)
Method: diff_(A)
Returns the first difference of dseries object A.
Method: disp(A)
Overloads the MATLAB/Octave disp function for dseries object.
Method: display(A)
Overloads the MATLAB/Octave display function for dseries object. display is the function called
by MATLAB to print the content of an object if a semicolon is missing at the end of a MATLAB
statement. If the dseries object is defined over a too large time span, only the first and last periods
will be printed. If the dseries object contains too many variables, only the first and last variables will
be printed. If all the periods and variables are required, the disp method should be used instead.
Method: C = eq(A, B)
Overloads the MATLAB/Octave eq (equal, ==) operator. dseries objects A and B must have the same
number of observations (say, 𝑇 ) and variables (𝑁 ). The returned argument is a 𝑇 × 𝑁 matrix of
logicals. Element (𝑖, 𝑗) of C is equal to true if and only if observation 𝑖 for variable 𝑗 in A and B are
the same.
Example
ans =
1
0
1
>> ts = dseries(randn(100,1));
>> ts.exist('Variable_1')
ans =
logical
>> ts.exist('Variable_2')
ans =
logical
Method: B = exp(A)
Method: exp_(A)
Overloads the MATLAB/Octave exp function for dseries objects.
Example
ans =
logical
Method: f = firstdate(A)
Returns the first period in dseries object A.
Method: f = firstobservedperiod(A)
Returns the first period where all the variables in dseries object A are observed (non NaN).
Method: B = flip(A)
Method: flip_(A)
Flips the rows in the data member (without changing the periods order).
Method: f = frequency(B)
Returns the frequency of the variables in dseries object B.
Example
>> ts = dseries(randn(3,2),'1973Q1');
>> ts.frequency
ans =
Method: C = insert(A, B, I)
Inserts variables contained in dseries object B in dseries object A at positions specified by integer
scalars in vector I, returns augmented dseries object C. The integer scalars in I must take values
between `` and A.length()+1 and refers to A ’s column numbers. The dseries objects A and B need
not be defined over the same time ranges, but it is assumed that they have common frequency.
Example
Method: B = isempty(A)
Overloads the MATLAB/octave’s isempty function. Returns true if dseries object A is empty.
Method: C = isequal(A, B)
Overloads the MATLAB/octave’s isequal function. Returns true if dseries objects A and B are
identical.
Method: C = isinf(A)
Overloads the MATLAB/octave’s isinf function. Returns a logical array, with element (i,j) equal
to true if and only if variable j is finite in period A.dates(i).
Method: C = isnan(A)
Overloads the MATLAB/octave’s isnan function. Returns a logical array, with element (i,j) equal
to true if and only if variable j isn’t NaN in period A.dates(i).
Method: C = isreal(A)
Overloads the MATLAB/octave’s isreal function. Returns a logical array, with element (i,j) equal
to true if and only if variable j is real in period A.dates(i).
Method: B = lag(A[, p])
| Variable_1
1950Q1 | 1
1950Q2 | 2
1950Q3 | 3
1950Q4 | 4
| Variable_1
1950Q1 | NaN
1950Q2 | 1
1950Q3 | 2
1950Q4 | 3
| Variable_1
1950Q1 | NaN
1950Q2 | NaN
1950Q3 | 1
1950Q4 | 2
>> ts0.lag(1)
| Variable_1
1950Q1 | NaN
1950Q2 | 1
1950Q3 | 2
1950Q4 | 3
or alternatively:
>> ts0(-1)
| Variable_1
1950Q1 | NaN
1950Q2 | 1
(continues on next page)
Method: l = lastdate(B)
Returns the last period in dseries object B.
Example
>> ts = dseries(randn(3,2),'1973Q1');
>> ts.lastdate()
Method: f = lastobservedperiod(A)
Returns the last period where all the variables in dseries object A are observed (non NaN).
Method: f = lastobservedperiods(A)
Returns for each variable the last period without missing observations in dseries object A. Output
argument f is a structure, each field name is the name of a variable in A, each field content is a singleton
date object.
Method: B = lead(A[, p])
Method: lead_(A[, p])
Returns lead time series. Default value of integer scalar p, the number of leads, is 1. As in the lag
method, the dseries class overloads the parenthesis so that ts.lead(p) is equivalent to ts(p).
Example
| Variable_1
1950Q1 | 2
1950Q2 | 3
1950Q3 | 4
1950Q4 | NaN
| Variable_1
1950Q1 | 3
1950Q2 | 4
1950Q3 | NaN
1950Q4 | NaN
Remark
The overloading of the parenthesis for dseries objects, allows to easily create new dseries objects
by copying/pasting equations declared in the model block. For instance, if an Euler equation is defined
in the model block:
model;
...
1/C - beta/C(1)*(exp(A(1))*K^(alpha-1)+1-delta) ;
(continues on next page)
and if variables , ``A and K are defined as dseries objects, then by writing:
outside of the model block, we create a new dseries object, called Residuals, for the residuals of
the Euler equation (the conditional expectation of the equation defined in the model block is zero, but
the residuals are non zero).
Method: B = lineartrend(A)
Returns a linear trend centered on 0, the length of the trend is given by the size of dseries object A
(the number of periods).
Example
>> ts = dseries(ones(3,1));
>> ts.lineartrend()
ans =
-1
0
1
Method: B = log(A)
Method: log_(A)
Overloads the MATLAB/Octave log function for dseries objects.
Example
Method: B = mdiff(A)
Method: mdiff_(A)
Method: B = mgrowth(A)
Method: mgrowth_(A)
Computes monthly differences or growth rates of variables in dseries object A.
Method: B = mean(A[, geometric])
Overloads the MATLAB/Octave mean function for dseries objects. Returns the mean of each variable
in dseries object A. If the second argument is true the geometric mean is computed, otherwise
(default) the arithmetic mean is reported.
Method: C = merge(A, B[, legacy])
Merges two dseries objects A and B in dseries object C. Objects A and B need to have common
frequency but can be defined on different time ranges. If a variable, say x, is defined both in dseries
objects A and B, then the merge will select the variable x as defined in the second input argument, B,
except for the NaN elements in B if corresponding elements in A (ie same periods) are well defined
numbers. This behaviour can be changed by setting the optional argument legacy equal to true, in
which case the second variable overwrites the first one even if the second variable has NaNs.
Example
| A1 | A2
1950Q1 | 0.96284 | 0.5363
1950Q2 | 0.25145 | 0.31866
1950Q3 | 0.34447 | 0.4355
| A1
1950Q2 | 0.40161
1950Q3 | 0.81763
1950Q4 | 0.97769
>> merge(ts0,ts1)
| A1 | A2
1950Q1 | 0.96284 | 0.5363
1950Q2 | 0.40161 | 0.31866
1950Q3 | 0.81763 | 0.4355
1950Q4 | 0.97769 | NaN
>> merge(ts1,ts0)
| A1 | A2
1950Q1 | 0.96284 | 0.5363
1950Q2 | 0.25145 | 0.31866
1950Q3 | 0.34447 | 0.4355
1950Q4 | 0.97769 | NaN
Method: C = minus(A, B)
Overloads the MATLAB/Octave minus (-) operator for dseries objects, element by element subtrac-
tion. If both A and B are dseries objects, they do not need to be defined over the same time ranges. If
A and B are dseries objects with 𝑇𝐴 and 𝑇𝐵 observations and 𝑁𝐴 and 𝑁𝐵 variables, then 𝑁𝐴 must be
equal to 𝑁𝐵 or 1 and 𝑁𝐵 must be equal to 𝑁𝐴 or 1. If 𝑇𝐴 = 𝑇𝐵 , isequal(A.init,B.init) returns
1 and 𝑁𝐴 = 𝑁𝐵 , then the minus operator will compute for each couple (𝑡, 𝑛), with 1 ≤ 𝑡 ≤ 𝑇𝐴 and
1 ≤ 𝑛 ≤ 𝑁𝐴 , C.data(t,n)=A.data(t,n)-B.data(t,n). If 𝑁𝐵 is equal to 1 and 𝑁𝐴 > 1, the
smaller dseries object (B) is “broadcast” across the larger dseries (A) so that they have compatible
shapes, the minus operator will subtract the variable defined in B from each variable in A. If B is a
double scalar, then the method minus will subtract B from all the observations/variables in A. If B is
a row vector of length 𝑁𝐴 , then the minus method will subtract B(i) from all the observations of
variable i, for 𝑖 = 1, ..., 𝑁𝐴 . If B is a column vector of length 𝑇𝐴 , then the minus method will subtract
B from all the variables.
Example
| Variable_1 | Variable_2
1Y | -0.48853 | 0
2Y | -0.50535 | 0
3Y | -0.32063 | 0
>> ts1
| Variable_2
1Y | 0.703
2Y | 0.75415
3Y | 0.54729
>> ts1-ts1.data(1)
| Variable_2
1Y | 0
2Y | 0.051148
3Y | -0.15572
>> ts1.data(1)-ts1
| Variable_2
1Y | 0
2Y | -0.051148
3Y | 0.15572
Method: C = mpower(A, B)
Overloads the MATLAB/Octave mpower (^) operator for dseries objects and computes element-by-
element power. A is a dseries object with N variables and T observations. If B is a real scalar, then
mpower(A,B) returns a dseries object C with C.data(t,n)=A.data(t,n)^C. If B is a dseries
object with N variables and T observations then mpower(A,B) returns a dseries object C with C.
data(t,n)=A.data(t,n)^C.data(t,n).
Example
>> ts0 = dseries(transpose(1:3));
>> ts1 = ts0^2
| Variable_1
1Y | 1
2Y | 4
3Y | 9
| Variable_1
1Y | 1
2Y | 4
3Y | 27
Method: C = mrdivide(A, B)
Overloads the MATLAB/Octave mrdivide (/) operator for dseries objects, element by element
division (like the ./ MATLAB/Octave operator). If both A and B are dseries objects, they do not need
to be defined over the same time ranges. If A and B are dseries objects with 𝑇𝐴 and 𝑇𝐵 observations
and 𝑁𝐴 and 𝑁𝐵 variables, then 𝑁𝐴 must be equal to 𝑁𝐵 or 1 and 𝑁𝐵 must be equal to 𝑁𝐴 or 1. If
𝑇𝐴 = 𝑇𝐵 , isequal(A.init,B.init) returns 1 and 𝑁𝐴 = 𝑁𝐵 , then the mrdivide operator will
compute for each couple (𝑡, 𝑛), with 1 ≤ 𝑡 ≤ 𝑇𝐴 and 1 ≤ 𝑛 ≤ 𝑁𝐴 , C.data(t,n)=A.data(t,n)/
B.data(t,n). If 𝑁𝐵 is equal to 1 and 𝑁𝐴 > 1, the smaller dseries object (B) is “broadcast” across
the larger dseries (A) so that they have compatible shapes. In this case the mrdivide operator will
divide each variable defined in A by the variable in B, observation per observation. If B is a double
scalar, then mrdivide will divide all the observations/variables in A by B. If B is a row vector of length
𝑁𝐴 , then mrdivide will divide all the observations of variable i by B(i), for 𝑖 = 1, ..., 𝑁𝐴 . If B is a
column vector of length 𝑇𝐴 , then mrdivide will perform a division of all the variables by B, element
by element.
Example
| Variable_1 | Variable_2
1Y | 0.72918 | 0.90307
2Y | 0.93756 | 0.21819
3Y | 0.51725 | 0.87322
| Variable_1 | Variable_2
1Y | 0.80745 | 1
2Y | 4.2969 | 1
3Y | 0.59235 | 1
Method: C = mtimes(A, B)
Overloads the MATLAB/Octave mtimes (*) operator for dseries objects and the Hadammard product
(the .* MATLAB/Octave operator). If both A and B are dseries objects, they do not need to be defined
over the same time ranges. If A and B are dseries objects with 𝑇𝐴 and 𝐵 observations and 𝑁𝐴 and
𝑁𝐵 variables, then 𝑁𝐴 must be equal to 𝑁𝐵 or 1 and 𝑁𝐵 must be equal to 𝑁𝐴 or 1. If 𝑇𝐴 = 𝑇𝐵 ,
isequal(A.init,B.init) returns 1 and 𝑁𝐴 = 𝑁𝐵 , then the mtimes operator will compute for each
couple (𝑡, 𝑛), with 1 ≤ 𝑡 ≤ 𝑇𝐴 and 1 ≤ 𝑛 ≤ 𝑁𝐴 , C.data(t,n)=A.data(t,n)*B.data(t,n). If
𝑁𝐵 is equal to 1 and 𝑁𝐴 > 1, the smaller dseries object (B) is “broadcast” across the larger dseries
(A) so that they have compatible shapes, mtimes operator will multiply each variable defined in A by
the variable in B, observation per observation. If B is a double scalar, then the method mtimes will
multiply all the observations/variables in A by B. If B is a row vector of length 𝑁𝐴 , then the mtimes
method will multiply all the observations of variable i by B(i), for 𝑖 = 1, ..., 𝑁𝐴 . If B is a column
vector of length 𝑇𝐴 , then the mtimes method will perform a multiplication of all the variables by B,
element by element.
ans =
0
1
0
Method: B = nobs(A)
Returns the number of observations in dseries object A.
Example
ans =
10
>> ts = dseries(randn(100,2),'1950Q1');
>> plot(ts{'Variable_1'},'-k','linewidth',2);
The next command will draw all the variables in ts on the same figure:
>> h = plot(ts);
If one wants to modify the properties of the plotted time series (line style, colours, . . . ), the
set function can be used (see MATLAB’s documentation):
>> set(h(1),'-k','linewidth',2);
>> set(h(2),'--r');
>> plot(ts{'Variable_1'},ts{'Variable_1'}.exp(),'ok');
Again, the properties can also be modified using the returned plot handle and the set function:
Method: C = plus(A, B)
Overloads the MATLAB/Octave plus (+) operator for dseries objects, element by element addition.
If both A and B are dseries objects, they do not need to be defined over the same time ranges. If A
and B are dseries objects with 𝑇𝐴 and 𝑇𝐵 observations and 𝑁𝐴 and 𝑁𝐵 variables, then 𝑁𝐴 must be
equal to 𝑁𝐵 or 1 and 𝑁𝐵 must be equal to 𝑁𝐴 or 1. If 𝑇𝐴 = 𝑇𝐵 , isequal(A.init,B.init) returns
1 and 𝑁𝐴 = 𝑁𝐵 , then the plus operator will compute for each couple (𝑡, 𝑛), with 1 ≤ 𝑡 ≤ 𝑇𝐴 and
1 ≤ 𝑛 ≤ 𝑁𝐴 , C.data(t,n)=A.data(t,n)+B.data(t,n). If 𝑁𝐵 is equal to 1 and 𝑁𝐴 > 1, the
smaller dseries object (B) is “broadcast” across the larger dseries (A) so that they have compatible
shapes, the plus operator will add the variable defined in B to each variable in A. If B is a double scalar,
then the method plus will add B to all the observations/variables in A. If B is a row vector of length
𝑁𝐴 , then the plus method will add B(i) to all the observations of variable i, for 𝑖 = 1, ..., 𝑁𝐴 . If B
is a column vector of length 𝑇𝐴 , then the plus method will add B to all the variables.
Method: C = pop(A[, B])
| Variable_1 | Variable_3
1Y | 1 | 1
2Y | 1 | 1
3Y | 1 | 1
Method: B = qdiff(A)
Method: B = qgrowth(A)
Method: qdiff_(A)
Method: qgrowth_(A)
Computes quarterly differences or growth rates.
Example
| Variable_1
1950Q1 | NaN
1950Q2 | 1
1950Q3 | 1
1950Q4 | 1
| Variable_1
1950M1 | NaN
1950M2 | NaN
1950M3 | NaN
1950M4 | 3
1950M5 | 3
1950M6 | 3
Method: C = remove(A, B)
Method: remove_(A, B)
If B is a row char array, the name of a variable, these methods are aliases for pop and pop_ methods with
two arguments. They remove variable B from dseries object A. To remove more than one variable,
one can pass a cell of row char arrays for B.
Example
| Variable_1 | Variable_3
1Y | 1 | 1
2Y | 1 | 1
3Y | 1 | 1
ts{'Variable_@2,3,4@'} = [];
will remove Variable_2, Variable_3 and Variable_4 from dseries object ts (if these
variables exist). Regular expressions cannot be used but implicit loops can.
Method: B = rename(A, oldname, newname)
Method: rename_(A, oldname, newname)
Rename variable oldname to newname in dseries object A. Returns a dseries object. If more than
one variable needs to be renamed, it is possible to pass cells of char arrays as second and third argu-
ments.
Example
| Stinkly | Variable_2
1Y | 1 | 1
2Y | 1 | 1
>> ts = dseries(pi)
ts is a dseries object:
| Variable_1
1Y | 3.1416
>> ts.round_();
>> ts
ts is a dseries object:
| Variable_1
1Y | 3
The last command will create a file ts0.csv with the following content:
,Variable_1,Variable_2
1Y, 1, 1
2Y, 1, 1
>> ts0.save('ts0','m');
FREQ__ = 1;
INIT__ = ' 1Y';
Variable_1 = [
1
1];
Variable_2 = [
1
1];
The generated (csv, m, or mat) files can be loaded when instantiating a dseries object as
explained above.
Method: B = set_names(A, s1, s2, ...)
Renames variables in dseries object A and returns a dseries object B with new names s1, s2, . . .
The number of input arguments after the first one (dseries object A) must be equal to A.vobs (the
number of variables in A). s1 will be the name of the first variable in B, s2 the name of the second
variable in B, and so on.
Example
ans =
1 3
each variable in dseries object A. If the second argument is true the geometric standard deviation is
computed (default value of the second argument is false).
Method: B = subsample(A, d1, d2)
Returns a subsample, for periods between dates d1 and d2. The same can be achieved by indexing a
dseries object with a dates object, but the subsample method is easier to use programmatically.
Example
>> o = dseries(transpose(1:5));
>> o.subsample(dates('2y'),dates('4y'))
| Variable_1
2Y | 2
3Y | 3
4Y | 4
| Variable_1
1Y | 1
| Variable_1
1Y | -1
| nifnif | noufnouf
1950Q1 | 0.82558 | 0.31852
1950Q2 | 0.78996 | 0.53406
1950Q3 | 0.089951 | 0.13629
1950Q4 | 0.11171 | 0.67865
Method: B = vobs(A)
Returns the number of variables in dseries object A.
Example
ans =
Method: B = ydiff(A)
Method: B = ygrowth(A)
Method: ydiff_(A)
Method: ygrowth_(A)
Computes yearly differences or growth rates.
Method: clean(A)
Removes the temporary files created by an x13 run that store the intermediate results. This method
allows keeping the main folder clean but will also delete potentially important debugging information.
Example
>> ts = dseries(rand(100,1),'1999M1');
>> o = x13(ts);
>> o.x11('save','(d11)');
>> o.automdl('savelog','amd','mixed','no');
>> o.outlier('types','all','save','(fts)');
>> o.check('maxlag',24,'save','(acf pcf)');
>> o.estimate('save','(mdl est)');
>> o.forecast('maxlead',18,'probability',0.95,'save','(fct fvr)');
>> o.run();
The above example shows a run of X13 with various commands an options specified.
Example
% 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960
y = [112 115 145 171 196 204 242 284 315 340 360 417 ..
˓→. % Jan
118 126 150 180 196 188 233 277 301 318 342 391 ..
˓→. % Feb
132 141 178 193 236 235 267 317 356 362 406 419 ..
˓→. % Mar
129 135 163 181 235 227 269 313 348 348 396 461 ..
˓→. % Apr
121 125 172 183 229 234 270 318 355 363 420 472 ..
˓→. % May
135 149 178 218 243 264 315 374 422 435 472 535 ..
˓→. % Jun
148 170 199 230 264 302 364 413 465 491 548 622 ..
˓→. % Jul
148 170 199 242 272 293 347 405 467 505 559 606 ..
˓→. % Aug
136 158 184 209 237 259 312 355 404 404 463 508 ..
˓→. % Sep
119 133 162 191 211 229 274 306 347 359 407 461 ..
˓→. % Oct
104 114 146 172 180 203 237 271 305 310 362 390 ..
˓→. % Nov
118 140 166 194 201 229 278 306 336 337 405 432 ]
˓→'; % Dec
ts = dseries(y,'1949M1');
o = x13(ts);
o.transform('function','auto','savelog','atr');
o.automdl('savelog','all');
o.x11('save','(d11 d10)');
o.run();
o.clean();
y_SA=o.results.d11;
y_seasonal_pattern=o.results.d10;
The above example shows how to remove a seasonal pattern from a time series. o.
transform('function','auto','savelog','atr') instructs the subsequent o.
automdl() command to check whether an additional or a multiplicative pattern fits the
data better and to save the result. The result is saved in o.results.autotransform, which in the
present example indicates that a log transformation, i.e. a multiplicative model was preferred.
The o.automdl('savelog','all') automatically selects a fitting ARIMA model and saves
all relevant output to the .log-file. The o.x11('save','(d11, d10)') instructs x11 to save
both the final seasonally adjusted series d11 and the final seasonal factor d10 into dseries with
the respective names in the output structure o.results. o.clean() removes the temporary
files created by o.run(). Among these are the .log-file storing summary information, the
.err-file storing information on problems encountered, the .out-file storing the raw output, and
the .spc-file storing the specification for the x11 run. There may be further files depending on
the output requested. The last part of the example reads out the results and plots a comparison of
the logged raw data and its log-additive decomposition into a seasonal pattern and the seasonally
adjusted series.
6.4 Miscellaneous
>> ts = dseries(rand(12,1),'2000M1')
ts is a dseries object:
| Variable_1
2000M1 | 0.55293
2000M2 | 0.14228
2000M3 | 0.38036
2000M4 | 0.39657
(continues on next page)
ds is a dseries object:
| Variable_1
2000Y | 0.60889
It is possible to expand a dseries object recursively with the from command. For instance to create
a dseries object containing the simulation of an ARMA(1,1) model:
y is a dseries object:
| y
2000Q1 | 0
2000Q2 | -0.95221
2000Q3 | -0.6294
2000Q4 | -1.8935
2001Q1 | -1.1536
2001Q2 | -1.5905
2001Q3 | 0.97056
2001Q4 | 1.1409
2002Q1 | -1.9255
2002Q2 | -0.29287
|
2022Q2 | -1.4683
2022Q3 | -1.3758
2022Q4 | -1.2218
2023Q1 | -0.98145
2023Q2 | -0.96542
2023Q3 | -0.23203
2023Q4 | -0.34404
2024Q1 | 1.4606
2024Q2 | 0.901
2024Q3 | 2.4906
2024Q4 | 0.79661
The expression following the do keyword can be any univariate equation, the only constraint is that the
model cannot have leads. It can be a static equation, or a very nonlinear backward equation with an
arbitrary number of lags. The from command must be followed by a range, which is separated from
the (recursive) expression to be evaluated by the do command.
SEVEN
REPORTING
Dynare provides a simple interface for creating LATEX reports, comprised of LATEX tables and PGFPLOTS/TikZ
graphs. You can use the report as created through Dynare or pick out the pieces (tables and graphs) you want for in-
clusion in your own paper. Though Dynare provides a subset of options available through PGFPLOTS/TikZ, you can
easily modify the graphs created by Dynare using the options available in the PGFPLOTS/TikZ manual. You can ei-
ther do this manually or by passing the options to miscTikzAxisOptions or graphMiscTikzAddPlotOptions.
Reports are created and modified by calling methods on class objects. The objects are hierarchical, with the follow-
ing order (from highest to lowest): Report, Page, Section, Graph/Table/Vspace, Series. For simplicity of
syntax, we abstract away from these classes, allowing you to operate directly on a Report object, while maintaining
the names of these classes in the Report class methods you will use.
The report is created sequentially, command by command, hence the order of the commands matters. When an
object of a certain hierarchy is inserted, all methods will function on that object until an object of equal or greater
hierarchy is added. Hence, once you add a Page to the report, every time you add a Section object, it will be
added to this Page until another Page is added to the report (via addPage). This will become more clear with the
example at the end of the section.
Options to methods are passed differently than those to Dynare commands. They take the form of named op-
tions to MATLAB functions where the arguments come in pairs (e.g. function_name(`option_1_name',
`option_1_value', `option_2_name', `option_2_value', ...), where option_X_name is the name
of the option while option_X_value is the value assigned to that option). The ordering of the option pairs mat-
ters only in the unusual case when an option is provided twice (probably erroneously). In this case, the last value
passed is the one that is used.
Below, you will see a list of methods available for the Report class and a clarifying example.
Constructor: report
Instantiates a Report object.
Options
compiler, FILENAME
The full path to the LATEX compiler on your system. If this option is not provided, Dynare will try to
find the appropriate program to compile LATEX on your system. Default is system dependent:
• Windows: the result of findtexmf --file-type=exe pdflatex.
• macOS and Linux: the result of which pdflatex.
directory, FILENAME
The path to the directory you want the report created in. Default: current directory.
showDate, BOOLEAN
Display the date and time when the report was compiled. Default: true.
fileName, FILENAME
The file name to use when saving this report. Default: report.tex.
header, STRING
The valid LATEX code to be included in the report before \begin{document}. Default: empty.
265
Dynare Reference Manual, Release 6.0
maketoc, BOOLEAN
Whether or not to make the table of contents. One entry is made per page containing a title. Default:
false.
margin, DOUBLE
The margin size. Default: 2.5.
marginUnit, `cm' | `in'
Units associated with the margin. Default: `cm'.
orientation, `landscape' | `portrait'
Paper orientation: Default: `portrait'.
paper, `a4' | `letter'
Paper size. Default: `a4'.
reportDirName, FILENAME
The name of the folder in which to store the component parts of the report (preamble, document, end).
Default: tmpRepDir.
showDate, BOOLEAN
Display the date and time when the report was compiled. Default: true.
showOutput, BOOLEAN
Print report creation progress to screen. Shows you the page number as it is created and as it is written.
This is useful to see where a potential error occurs in report creation. Default: true.
title, STRING
Report Title. Default: none.
Method: addPage
Adds a Page to the Report.
Options
footnote, STRING
A footnote to be included at the bottom of this page. Default: none.
latex, STRING
The valid LATEX code to be used for this page. Alows the user to create a page to be included in the
report by passing LATEX code directly. If this option is passed, the page itself will be saved in the
pageDirName directory in the form page_X.tex where X refers to the page number. Default: empty.
orientation, `landscape' | `portrait'
See orientation.
pageDirName, FILENAME
The name of the folder in which to store this page. Directory given is relative to the directory option
of the report class. Only used when the latex command is passed. Default: tmpRepDir.
paper, `a4' | `letter'
See paper.
title, STRING | CELL_ARRAY_STRINGS
With one entry (a STRING), the title of the page. With more than one entry (a
CELL_ARRAY_STRINGS), the title and subtitle(s) of the page. Values passed must be valid
LATEX code (e.g., % must be \%). Default: none.
titleFormat, STRING | CELL_ARRAY_STRINGS
A string representing the valid LATEX markup to use on title. The number of cell array entries must be
equal to that of the title option if you do not want to use the default value for the title (and subtitles).
Default: \large\bfseries.
titleTruncate, INTEGER
Useful when automatically generating page titles that may become too long, titleTruncate can be
used to truncate a title (and subsequent subtitles) when they pass the specified number of characters.
Default: .off.
Method: addSection
Adds a Section to a Page.
Options
cols, INTEGER
The number of columns in the section. Default: 1.
height, STRING
A string to be used with the \sectionheight LATEX command. Default: '!'
Method: addGraph
Adds a Graph to a Section.
Options
data, dseries
The dseries that provides the data for the graph. Default: none.
axisShape, `box' | `L'
The shape the axis should have. `box' means that there is an axis line to the left, right, bottom, and
top of the graphed line(s). ‘L’`` means that there is an axis to the left and bottom of the graphed line(s).
Default: `box'.
graphDirName, FILENAME
The name of the folder in which to store this figure. Directory given is relative to the directory option
of the report class. Default: tmpRepDir.
graphName, STRING
The name to use when saving this figure. Default: something of the form
graph_pg1_sec2_row1_col3.tex.
height, DOUBLE
The height of the graph, in inches. Default: 4.5.
showGrid, BOOLEAN
Whether or not to display the major grid on the graph. Default: true.
showLegend, BOOLEAN
Whether or not to display the legend.
Unless you use the graphLegendName option, the name displayed in the legend is the tex name asso-
ciated with the dseries. You can modify this tex name by using tex_rename. Default: false.
legendAt, NUMERICAL_VECTOR
The coordinates for the legend location. If this option is passed, it overrides the legendLocation
option. Must be of size 2. Default: empty.
showLegendBox, BOOLEAN
Whether or not to display a box around the legend. Default: false.
legendLocation, OPTION
Where to place the legend in the graph. Possible values for OPTION are:
`south west' | `south east' | `north west' | `north east' | `outer north east
˓→'
267
Dynare Reference Manual, Release 6.0
Default: tiny.
miscTikzAxisOptions, STRING
If you are comfortable with PGFPLOTS/TikZ, you can use this option to pass arguments directly to
the PGFPLOTS/TikZ axis environment command. Specifically to be used for desired PGFPLOTS/TikZ
options that have not been incorporated into Dynare Reporting. Default: empty.
miscTikzPictureOptions, STRING
If you are comfortable with PGFPLOTS/TikZ, you can use this option to pass arguments directly to
the PGFPLOTS/TikZ tikzpicture environment command. (e.g., to scale the graph in the x and y di-
mensions, you can pass following to this option: ‘xscale=2.5, yscale=0.5’). Specifically to be
used for desired ``PGFPLOTS/TikZ options that have not been incorporated into Dynare Report-
ing. Default: empty.
seriesToUse, CELL_ARRAY_STRINGS
The names of the series contained in the dseries provided to the data option. If empty, use all series
provided to data option. Default: empty.
shade, dates
The date range showing the portion of the graph that should be shaded. Default: none.
shadeColor, STRING
The color to use in the shaded portion of the graph. All valid color strings defined for use by PGFPLOTS/
TikZ are valid. A list of defined colors is:
Furthermore, You can use combinations of these colors. For example, if you wanted a color that is
20% green and 80% purple, you could pass the string 'green!20!purple'. You can also use RGB
colors, following the syntax: `rgb,255:red,231;green,84;blue,121' which corresponds to the
RGB color (231;84;121). More examples are available in the section 4.7.5 of the PGFPLOTS/TikZ
manual, revision 1.10. Default: `green'
shadeOpacity, DOUBLE
The opacity of the shaded area, must be in [0,100]. Default: 20.
tickFontSize, OPTION
The font size for x- and y-axis tick labels. Possible values for OPTION are:
Default: normalsize.
title, STRING | CELL_ARRAY_STRINGS
Same as title, just for graphs.
titleFontSize, OPTION
The font size for title. Possible values for OPTION are:
Default: normalsize.
titleFormat, STRING
The format to use for the graph title. Unlike titleFormat, due to a constraint of TikZ, this format
applies to the title and subtitles. Default: TikZ default.
width, DOUBLE
The width of the graph, in inches. Default: 6.0.
writeCSV, BOOLEAN
Whether or not to write a CSV file with only the plotted data. The file will be saved in the directory
specified by graphDirName with the same base name as specified by graphName with the ending
.csv. Default: false.
xlabel, STRING
The x-axis label. Default: none.
ylabel, STRING
The y-axis label. Default: none.
xAxisTight, BOOLEAN
Use a tight x axis. If false, uses PGFPLOTS/TikZ enlarge x limits to choose appropriate axis size.
Default: true.
xrange, dates
The boundary on the x-axis to display in the graph. Default: all.
xTicks, NUMERICAL_VECTOR
Used only in conjunction with xTickLabels, this option denotes the numerical position of the label
along the x-axis. The positions begin at 1. Default: the indices associated with the first and last dates
of the dseries and, if passed, the index associated with the first date of the shade option.
xTickLabels, CELL_ARRAY_STRINGS | `ALL'
The labels to be mapped to the ticks provided by xTicks. Default: the first and last dates of the
dseries and, if passed, the date first date of the shade option.
xTickLabelAnchor, STRING
Where to anchor the x tick label. Default: `east'.
xTickLabelRotation, DOUBLE
The amount to rotate the x tick labels by. Default: 0.
yAxisTight, BOOLEAN
Use a tight y axis. If false, uses PGFPLOTS/TikZ enlarge y limits to choose appropriate axis size.
Default: false.
yrange, NUMERICAL_VECTOR
The boundary on the y-axis to display in the graph, represented as a NUMERICAL_VECTOR of size 2,
with the first entry less than the second entry. Default: all.
yTickLabelFixed, BOOLEAN
Round the y tick labels to a fixed number of decimal places, given by yTickLabelPrecision. Default:
true.
yTickLabelPrecision, INTEGER
The precision with which to report the yTickLabel. Default: 0.
269
Dynare Reference Manual, Release 6.0
yTickLabelScaled, BOOLEAN
Determines whether or not there is a common scaling factor for the y axis. Default: true.
yTickLabelZeroFill, BOOLEAN
Whether or not to fill missing precision spots with zeros. Default: true.
showZeroline, BOOLEAN
Display a solid black line at 𝑦 = 0. Default: false.
zeroLineColor, STRING
The color to use for the zero line. Only used if showZeroLine is true. See the explanation in
shadeColor for how to use colors with reports. Default: `black'.
Method: addTable
Adds a Table to a Section.
Options
data, dseries
See data.
highlightRows, CELL_ARRAY_STRINGS
A cell array containing the colors to use for row highlighting. See shadeColor for how to use colors
with reports. Highlighting for a specific row can be overridden by using the tableRowColor option
to addSeries. Default: empty.
showHlines, BOOLEAN
Whether or not to show horizontal lines separating the rows. Default: false.
precision, INTEGER
The number of decimal places to report in the table data (rounding done via the round half away from
zero method). Default: 1.
range, dates
The date range of the data to be displayed. Default: all.
seriesToUse, CELL_ARRAY_STRINGS
See seriesToUse.
tableDirName, FILENAME
The name of the folder in which to store this table. Directory given is relative to the directory option
of the report class. Default: tmpRepDir.
tableName, STRING
The name to use when saving this table. Default: something of the form
table_pg1_sec2_row1_col3.tex.
title, STRING
Same as title, just for tables.
titleFormat, STRING
Same as titleFormat, just for tables. Default: \large.
vlineAfter, dates | CELL_ARRAY_DATES
Show a vertical line after the specified date (or dates if a cell array of dates is passed). Default: empty.
vlineAfterEndOfPeriod, BOOLEAN
Show a vertical line after the end of every period (i.e. after every year, after the fourth quarter, etc.).
Default: false.
showVlines, BOOLEAN
Whether or not to show vertical lines separating the columns. Default: false.
writeCSV, BOOLEAN
Whether or not to write a CSV file containing the data displayed in the table. The file will be saved in
the directory specified by tableDirName with the same base name as specified by tableName with
the ending .csv. Default: false.
Method: addSeries
Adds a Series to a Graph or a Table.
Options specific to graphs begin with `graph' while options specific to tables begin with `table'.
Options
data, dseries
See data.
graphBar, BOOLEAN
Whether or not to display this series as a bar graph as oppsed to the default of displaying it as a line
graph. Default: false.
graphFanShadeColor, STRING
The shading color to use between a series and the previously-added series in a graph. Useful for making
fan charts. Default: empty.
graphFanShadeOpacity, INTEGER
The opacity of the color passed in graphFanShadeColor. Default: 50.
graphBarColor, STRING
The outline color of each bar in the bar graph. Only active if graphBar is passed. Default: `black'.
graphBarFillColor, STRING
The fill color of each bar in the bar graph. Only active if graphBar is passed. Default: `black'.
graphBarWidth, DOUBLE
The width of each bar in the bar graph. Only active if graphBar is passed. Default: 2.
graphHline, DOUBLE
Use this option to draw a horizontal line at the given value. Default: empty.
graphLegendName, STRING
The name to display in the legend for this series, passed as valid LATEX (e.g., GDP_{US}, $\alpha$,
\color{red}GDP\color{black}). Will be displayed only if the data and showLegend options have
been passed. Default: the tex name of the series.
graphLineColor, STRING
Color to use for the series in a graph. See the explanation in shadeColor for how to use colors with
reports. Default: `black'
graphLineStyle, OPTION
Line style for this series in a graph. Possible values for OPTION are:
Default: `solid'.
graphLineWidth DOUBLE
Line width for this series in a graph. Default: 0.5.
271
Dynare Reference Manual, Release 6.0
graphMarker, OPTION
The Marker to use on this series in a graph. Possible values for OPTION are:
Default: none.
graphMarkerEdgeColor, STRING
The edge color of the graph marker. See the explanation in shadeColor for how to use colors with
reports. Default: graphLineColor.
graphMarkerFaceColor, STRING
The face color of the graph marker. See the explanation in shadeColor for how to use colors with
reports. Default: graphLineColor.
graphMarkerSize, DOUBLE
The size of the graph marker. Default: 1.
graphMiscTikzAddPlotOptions, STRING
If you are comfortable with PGFPLOTS/TikZ, you can use this option to pass arguments directly to the
PGFPLOTS/TikZ addPlots command. (e.g., Instead of passing the marker options above, you can pass
a string such as the following to this option: `mark=halfcircle*,mark options={rotate=90,
scale=3}'). Specifically to be used for desired PGFPLOTS/TikZ options that have not been incorpo-
rated into Dynare Reproting. Default: empty.
graphShowInLegend, BOOLEAN
Whether or not to show this series in the legend, given that the showLegend option was passed to
addGraph . Default: true.
graphVline, dates
Use this option to draw a vertical line at a given date. Default: empty.
tableDataRhs, dseries
A series to be added to the right of the current series. Usefull for displaying aggregate data for a series.
e.g if the series is quarterly tableDataRhs could point to the yearly averages of the quarterly series.
This would cause quarterly data to be displayed followed by annual data. Default: empty.
tableRowColor, STRING
The color that you want the row to be. Predefined values include LightCyan and Gray. Default:
white.
tableRowIndent, INTEGER
The number of times to indent the name of the series in the table. Used to create subgroups of series.
Default: 0.
tableShowMarkers, BOOLEAN
In a Table, if true, surround each cell with brackets and color it according to tableNegColor and
tablePosColor. No effect for graphs. Default: false.
tableAlignRight, BOOLEAN
Whether or not to align the series name to the right of the cell. Default: false.
tableMarkerLimit, DOUBLE
For values less than −1 * tableMarkerLimit, mark the cell with the color denoted by tableNegColor.
For those greater than tableMarkerLimit, mark the cell with the color denoted by tablePosColor.
Default: 1e-4.
tableNaNSymb, STRING
Replace NaN values with the text in this option. Default: NaN.
tableNegColor, LATEX_COLOR
The color to use when marking Table data that is less than zero. Default: `red'
tablePrecision, INTEGER
The number of decimal places to report in the table data. Default: the value set by precision.
tablePosColor, LATEX_COLOR
The color to use when marking Table data that is greater than zero. Default: `blue'
tableSubSectionHeader, STRING
A header for a subsection of the table. No data will be associated with it. It is equivalent to adding an
empty series with a name. Default: ''
zeroTol, DOUBLE
The zero tolerance. Anything smaller than zeroTol and larger than -zeroTol will be set to zero
before being graphed or written to the table. Default: 1e-6.
Method: addParagraph
Adds a Paragraph to a Section.
The Section can only be comprised of Paragraphs and must only have 1 column.
Options
balancedCols, BOOLEAN
Determines whether the text is spread out evenly across the columns when the Paragraph has more
than one column. Default: true.
cols, INTEGER
The number of columns for the Paragraph. Default: 1.
heading, STRING
The heading for the Paragraph (like a section heading). The string must be valid LATEX code. Default:
empty.
indent, BOOLEAN
Whether or not to indent the paragraph. Default: true.
text, STRING
The paragraph itself. The string must be valid LATEX code. Default: empty.
Method: addVspace
Adds a Vspace (vertical space) to a Section.
Options
hline, INTEGER
The number of horizontal lines to be inserted. Default: 0.
number, INTEGER
The number of new lines to be inserted. Default: 1.
Method: write
Writes the LATEX representation of this Report, saving it to the file specified by filename.
Method: compile
Compiles the report written by write into a pdf file. If the report has not already been written (determined
by the existence of the file specified by filename, write is called.
Options
273
Dynare Reference Manual, Release 6.0
compiler, FILENAME
Like compiler, except will not overwrite the value of compiler contained in the report object. Hence,
passing the value here is useful for using different LATEX compilers or just for passing the value at the
last minute.
showOutput, BOOLEAN
Print the compiler output to the screen. Useful for debugging your code as the LATEX compiler hangs
if there is a problem. Default: the value of showOutput.
showReport, BOOLEAN
Open the compiled report (works on Windows and macOS on MATLAB). Default: true.
Example
The following code creates a one page report. The first part of the page contains two graphs displayed across two
columns and one row. The bottom of the page displays a centered table:
%% Create dseries
dsq = dseries(`quarterly.csv');
dsa = dseries(`annual.csv');
dsca = dseries(`annual_control.csv');
%% Report
rep = report();
%% Page 1
rep.addPage('title', {'My Page Title', 'My Page Subtitle'}, ...
'titleFormat', {'\large\bfseries', '\large'});
% Section 1
rep.addSection('cols', 2);
% Section 2
rep.addVspace('number', 15);
rep.addSection();
rep.addTable('title', 'Table 1', 'range', dates('2012Y'):dates('2014Y'));
shortNames = {'US', 'EU'};
longNames = {'United States', 'Euro Area'};
for i=1:length(shortNames)
rep.addSeries('data', dsa{['GROWTH_' shortNames{i}]});
delta = dsa{['GROWTH_' shortNames{i}]}-dsca{['GROWTH_' shortNames{i}]};
delta.tex_rename_('$\Delta$');
rep.addSeries('data', delta, ...
(continues on next page)
275
Dynare Reference Manual, Release 6.0
EIGHT
EXAMPLES
Dynare comes with a database of example .mod files, which are designed to show a broad range of Dynare features,
and are taken from academic papers for most of them. You should have these files in the examples subdirectory
of your distribution.
Here is a short list of the examples included. For a more complete description, please refer to the comments inside
the files themselves.
ramst.mod
An elementary real business cycle (RBC) model, simulated in a deterministic setup.
example1.mod example2.mod
Two examples of a small RBC model in a stochastic setup, presented in Collard (2001) (see the file
guide.pdf which comes with Dynare).
example3.mod
A small RBC model in a stochastic setup, presented in Collard (2001). The steady state is solved
analytically using the steady_state_model block (see steady_state_model).
fs2000.mod
A cash in advance model, estimated by Schorfheide (2000). The file shows how to use Dynare for
estimation.
fs2000_nonstationary.mod
The same model than fs2000.mod, but written in non-stationary form. Detrending of the equations
is done by Dynare.
bkk.mod
Multi-country RBC model with time to build, presented in Backus, Kehoe and Kydland (1992). The
file shows how to use Dynare’s macro processor.
agtrend.mod
Small open economy RBC model with shocks to the growth trend, presented in Aguiar and Gopinath
(2004).
Gali_2015.mod
Basic New Keynesian model of Galí (2015), Chapter 3 showing how to i) use “system prior”-type
prior restrictions as in Andrle and Plašil (2018) and ii) run prior/posterior-functions.
NK_baseline.mod
Baseline New Keynesian Model estimated in Fernández-Villaverde (2010). It demonstrates how to
use an explicit steady state file to update parameters and call a numerical solver.
Occbin_example.mod
RBC model with two occasionally binding constraints. Demonstrates how to set up Occbin.
Ramsey_Example.mod
277
Dynare Reference Manual, Release 6.0
File demonstrating how to conduct optimal policy experiments in a simple New Keynesian model
either under commitment (Ramsey) or using optimal simple rules (OSR)
Ramsey_steady_file.mod
File demonstrating how to conduct optimal policy experiments in a simple New Keynesian model
under commitment (Ramsey) with a user-defined conditional steady state file
NINE
Command: posterior_function(OPTIONS);
Same as the prior_function command but for the posterior distribution. Results returned in oo_.
posterior_function_results.
Options
function = FUNCTION_NAME
See prior_function_function.
sampling_draws = INTEGER
See prior_function_sampling_draws.
Command: generate_trace_plots(CHAIN_NUMBER);
Generates trace plots of the MCMC draws for all estimated parameters and the posterior density for the
specified Markov Chain(s) CHAIN_NUMBER. If CHAIN_NUMBER is a vector of integers, the trace plots will
plot contains separate lines for each chain.
279
Dynare Reference Manual, Release 6.0
if routine.m is not in the current directory, the full path has to be given:
--display-mh-history
Displays information about the previously saved MCMC draws generated by a .mod file named
MODFILENAME. This file must be in the current directory.
Example
--load-mh-history
Loads into the MATLAB/Octave’s workspace informations about the previously saved MCMC
draws generated by a .mod file named MODFILENAME.
Example
This will create a structure called mcmc_informations (in the workspace) with the following
fields:
Nblck
The number of MCMC chains.
InitialParameters
A Nblck*n, where n is the number of estimated parameters, array of doubles. Initial
state of the MCMC.
LastParameters
A Nblck*n, where n is the number of estimated parameters, array of doubles. Current
state of the MCMC.
InitialLogPost
A Nblck*1 array of doubles. Initial value of the posterior kernel.
LastLogPost
A Nblck*1 array of doubles. Current value of the posterior kernel.
InitialSeeds
A 1*Nblck structure array. Initial state of the random number generator.
LastSeeds
A 1*Nblck structure array. Current state of the random number generator.
AcceptanceRatio
A 1*Nblck array of doubles. Current acceptance ratios.
>> search X
Y = alpha*X/(1-X)+e;
281
Dynare Reference Manual, Release 6.0
Y = 1.254634*X/(1-X)+e;
will produce plots for 2/b*cumsum(x/y(-1)-1), where x and y are variables in dseries objects
toto and noddy, in the same figure.
TEN
BIBLIOGRAPHY
• Abramowitz, Milton and Irene A. Stegun (1964): “Handbook of Mathematical Functions”, Courier Dover
Publications.
• Adjemian, Stéphane, Matthieu Darracq Parriès and Stéphane Moyen (2008): “Towards a monetary policy
evaluation framework”, European Central Bank Working Paper, 942.
• Aguiar, Mark and Gopinath, Gita (2004): “Emerging Market Business Cycles: The Cycle is the Trend,”
NBER Working Paper, 10734.
• Amisano, Gianni and Tristani, Oreste (2010): “Euro area inflation persistence in an estimated nonlinear
DSGE model”, Journal of Economic Dynamics and Control, 34(10), 1837–1858.
• Andreasen, Martin M., Jesús Fernández-Villaverde, and Juan Rubio-Ramírez (2018): “The Pruned State-
Space System for Non-Linear DSGE Models: Theory and Empirical Applications,” Review of Economic
Studies, 85(1), 1-49.
• Andrle, Michal and Miroslav Plašil (2018): “Econometrics with system priors,” Economics Letters, 172,
134-137.
• Andrews, Donald W.K (1991): “Heteroskedasticity and autocorrelation consistent covariance matrix esti-
mation”, Econometrica, 59(3), 817–858.
• Backus, David K., Patrick J. Kehoe, and Finn E. Kydland (1992): “International Real Business Cycles,”
Journal of Political Economy, 100(4), 745–775.
• Baxter, Marianne and Robert G. King (1999): “Measuring Business Cycles: Approximate Band-pass Filters
for Economic Time Series,” Review of Economics and Statistics, 81(4), 575–593.
• Bini, Dario A., Guy Latouche, and Beatrice Meini (2002): “Solving matrix polynomial equations arising in
queueing problems,” Linear Algebra and its Applications, 340, 225–244.
• Born, Benjamin and Johannes Pfeifer (2014): “Policy risk and the business cycle”, Journal of Monetary
Economics, 68, 68-85.
• Boucekkine, Raouf (1995): “An alternative methodology for solving nonlinear forward-looking models,”
Journal of Economic Dynamics and Control, 19, 711–734.
• Brayton, Flint and Peter Tinsley (1996): “A Guide to FRB/US: A Macroeconomic Model of the United
States”, Finance and Economics Discussion Series, 1996-42.
• Brayton, Flint, Morris Davis and Peter Tulip (2000): “Polynomial Adjustment Costs in FRB/US”, Unpub-
lished manuscript.
• Brooks, Stephen P., and Andrew Gelman (1998): “General methods for monitoring convergence of iterative
simulations,” Journal of Computational and Graphical Statistics, 7, pp. 434–455.
• Cardoso, Margarida F., R. L. Salcedo and S. Feyo de Azevedo (1996): “The simplex simulated annealing
approach to continuous non-linear optimization,” Computers & Chemical Engineering, 20(9), 1065-1080.
• Chib, Siddhartha and Srikanth Ramamurthy (2010): “Tailored randomized block MCMC methods with
application to DSGE models,” Journal of Econometrics, 155, 19–38.
• Christiano, Lawrence J., Martin Eichenbaum and Charles L. Evans (2005): “Nominal Rigidities and the
Dynamic Effects of a Shock to Monetary Policy,” Journal of Political Economy, 113(1), 1–45.
283
Dynare Reference Manual, Release 6.0
• Christiano, Lawrence J., Mathias Trabandt, and Karl Walentin (2010): “DSGE Models for Monetary Policy
Analysis,” In: Handbook of Monetary Economics 3, 285–367.
• Christiano, Lawrence J., Mathias Trabandt and Karl Walentin (2011): “Introducing financial frictions and
unemployment into a small open economy model,” Journal of Economic Dynamics and Control, 35(12),
1999–2041.
• Christoffel, Kai, Günter Coenen and Anders Warne (2010): “Forecasting with DSGE models,” ECB Working
Paper Series, 1185.
• Collard, Fabrice (2001): “Stochastic simulations with Dynare: A practical guide”.
• Collard, Fabrice and Michel Juillard (2001a): “Accuracy of stochastic perturbation methods: The case of
asset pricing models,” Journal of Economic Dynamics and Control, 25, 979–999.
• Collard, Fabrice and Michel Juillard (2001b): “A Higher-Order Taylor Expansion Approach to Simulation of
Stochastic Forward-Looking Models with an Application to a Non-Linear Phillips Curve,” Computational
Economics, 17, 125–139.
• Corana, Angelo, M. Marchesi, Claudio Martini, and Sandro Ridella (1987): “Minimizing multimodal func-
tions of continuous variables with the “simulated annealing” algorithm”, ACM Transactions on Mathematical
Software, 13(3), 262–280.
• Cuba-Borda, Pablo, Luca Guerrieri, Matteo Iacoviello, and Molin Zhong (2019): “Likelihood evaluation of
models with occasionally binding constraints”, Journal of Applied Econometrics, 34(7), 1073-1085
• Del Negro, Marco and Frank Schorfheide (2004): “Priors from General Equilibrium Models for VARs”,
International Economic Review, 45(2), 643–673.
• Dennis, Richard (2007): “Optimal Policy In Rational Expectations Models: New Solution Algorithms”,
Macroeconomic Dynamics, 11(1), 31–55.
• Duffie, Darrel and Kenneth J. Singleton (1993): “Simulated Moments Estimation of Markov Models of Asset
Prices”, Econometrica, 61(4), 929-952.
• Durbin, J. and S. J. Koopman (2012), Time Series Analysis by State Space Methods, Second Revised Edition,
Oxford University Press.
• Fair, Ray and John Taylor (1983): “Solution and Maximum Likelihood Estimation of Dynamic Nonlinear
Rational Expectation Models,” Econometrica, 51, 1169–1185.
• Fernández-Villaverde, Jesús (2010): “The econometrics of DSGE models,” SERIEs, 1, 3–49.
• Fernández-Villaverde, Jesús and Juan Rubio-Ramírez (2004): “Comparing Dynamic Equilibrium
Economies to Data: A Bayesian Approach,” Journal of Econometrics, 123, 153–187.
• Fernández-Villaverde, Jesús and Juan Rubio-Ramírez (2005): “Estimating Dynamic Equilibrium
Economies: Linear versus Nonlinear Likelihood,” Journal of Applied Econometrics, 20, 891–910.
• Ferris, Michael C. and Todd S. Munson (1999): “Interfaces to PATH 3.0: Design, Implementation and
Usage”, Computational Optimization and Applications, 12(1), 207–227.
• Galí, Jordi (2015): “Monetary Policy, Inflation, and the Business Cycle,” 2nd Edition, Princeton University
Press, Princeton.
• Geweke, John (1992): “Evaluating the accuracy of sampling-based approaches to the calculation of posterior
moments,” in J.O. Berger, J.M. Bernardo, A.P. Dawid, and A.F.M. Smith (eds.) Proceedings of the Fourth
Valencia International Meeting on Bayesian Statistics, pp. 169–194, Oxford University Press.
• Geweke, John (1999): “Using simulation methods for Bayesian econometric models: Inference, development
and communication,” Econometric Reviews, 18(1), 1–73.
• Giovannini, Massimo, Philipp Pfeiffer, and Marco Ratto (2021), “Efficient and robust inference of models
with occasionally binding constraints,” Working Papers 2021-03, Joint Research Centre, European Commis-
sion
• Giordani, Paolo, Michael Pitt, and Robert Kohn (2011): “Bayesian Inference for Time Series State Space
Models” in: The Oxford Handbook of Bayesian Econometrics, ed. by John Geweke, Gary Koop, and Herman
van Dijk, Oxford University Press, 61–124.
• Guerrieri, Luca and Matteo Iacoviello (2015): “OccBin: A toolkit for solving dynamic models with occa-
sionally binding constraints easily,” Journal of Monetary Economics, 70, 22–38.
• Goffe, William L., Gary D. Ferrier, and John Rogers (1994): “Global Optimization of Statistical Functions
with Simulated Annealing,” Journal of Econometrics, 60(1/2), 65–100.
• Hansen, Lars P. (1982): “Large sample properties of generalized method of moments estimators,” Econo-
metrica, 50(4), 1029–1054.
• Hansen, Nikolaus and Stefan Kern (2004): “Evaluating the CMA Evolution Strategy on Multimodal Test
Functions”. In: Eighth International Conference on Parallel Problem Solving from Nature PPSN VIII, Pro-
ceedings, Berlin: Springer, 282–291.
• Harvey, Andrew C. and Garry D.A. Phillips (1979): “Maximum likelihood estimation of regression models
with autoregressive-moving average disturbances,” Biometrika, 66(1), 49–58.
• Herbst, Edward and Schorfheide, Frank (2014): “Sequential Monte Carlo Sampling for DSGE Models,”
Journal of Applied Econometrics, 29, 1073-1098.
• Herbst, Edward (2015): “Using the “Chandrasekhar Recursions” for Likelihood Evaluation of DSGE Mod-
els,” Computational Economics, 45(4), 693–705.
• Ireland, Peter (2004): “A Method for Taking Models to the Data,” Journal of Economic Dynamics and
Control, 28, 1205–26.
• Iskrev, Nikolay (2010): “Local identification in DSGE models,” Journal of Monetary Economics, 57(2),
189–202.
• Judd, Kenneth (1996): “Approximation, Perturbation, and Projection Methods in Economic Analysis”, in
Handbook of Computational Economics, ed. by Hans Amman, David Kendrick, and John Rust, North Hol-
land Press, 511–585.
• Juillard, Michel (1996): “Dynare: A program for the resolution and simulation of dynamic models with
forward variables through the use of a relaxation algorithm,” CEPREMAP, Couverture Orange, 9602.
• Kanzow, Christian and Stefania Petra (2004): “On a semismooth least squares formulation of complemen-
tarity problems with gap reduction,” Optimization Methods and Software, 19, 507–525.
• Kim, Jinill and Sunghyun Kim (2003): “Spurious welfare reversals in international business cycle models,”
Journal of International Economics, 60, 471–500.
• Kim, Jinill, Sunghyun Kim, Ernst Schaumburg, and Christopher A. Sims (2008): “Calculating and using
second-order accurate solutions of discrete time dynamic equilibrium models,” Journal of Economic Dy-
namics and Control, 32(11), 3397–3414.
• Komunjer, Ivana and Ng, Serena (2011): ”Dynamic identification of dynamic stochastic general equilibrium
models”, Econometrica, 79, 1995–2032.
• Koop, Gary (2003), Bayesian Econometrics, John Wiley & Sons.
• Koopman, S. J. and J. Durbin (2000): “Fast Filtering and Smoothing for Multivariate State Space Models,”
Journal of Time Series Analysis, 21(3), 281–296.
• Koopman, S. J. and J. Durbin (2003): “Filtering and Smoothing of State Vector for Diffuse State Space
Models,” Journal of Time Series Analysis, 24(1), 85–98.
• Kuntsevich, Alexei V. and Franz Kappel (1997): “SolvOpt - The solver for local nonlinear optimization
problems (version 1.1, Matlab, C, FORTRAN)”, University of Graz, Graz, Austria.
• Laffargue, Jean-Pierre (1990): “Résolution d’un modèle macroéconomique avec anticipations rationnelles”,
Annales d’Économie et Statistique, 17, 97–119.
• Liu, Jane and Mike West (2001): “Combined parameter and state estimation in simulation-based filtering”,
in Sequential Monte Carlo Methods in Practice, Eds. Doucet, Freitas and Gordon, Springer Verlag.
• Murray, Lawrence M., Emlyn M. Jones and John Parslow (2013): “On Disturbance State-Space Models and
the Particle Marginal Metropolis-Hastings Sampler”, SIAM/ASA Journal on Uncertainty Quantification, 1,
494–521.
285
Dynare Reference Manual, Release 6.0
• Mutschler, Willi (2015): “Identification of DSGE models - The effect of higher-order approximation and
pruning“, Journal of Economic Dynamics & Control, 56, 34-54.
• Mutschler, Willi (2018): “Higher-order statistics for DSGE models”, Econometrics and Statistics, 6(C), 44-
56.
• Pearlman, Joseph, David Currie, and Paul Levine (1986): “Rational expectations models with partial infor-
mation,” Economic Modelling, 3(2), 90–105.
• Planas, Christophe, Marco Ratto and Alessandro Rossi (2015): “Slice sampling in Bayesian estimation of
DSGE models”.
• Pfeifer, Johannes (2013): “A Guide to Specifying Observation Equations for the Estimation of DSGE Mod-
els”.
• Pfeifer, Johannes (2014): “An Introduction to Graphs in Dynare”.
• Qu, Zhongjun and Tkachenko, Denis (2012): “Identification and frequency domain quasi-maximum likeli-
hood estimation of linearized dynamic stochastic general equilibrium models“, Quantitative Economics, 3,
95–132.
• Rabanal, Pau and Juan Rubio-Ramírez (2003): “Comparing New Keynesian Models of the Business Cycle:
A Bayesian Approach,” Federal Reserve of Atlanta, Working Paper Series, 2003-30.
• Raftery, Adrian E. and Steven Lewis (1992): “How many iterations in the Gibbs sampler?,” in Bayesian
Statistics, Vol. 4, ed. J.O. Berger, J.M. Bernardo, A.P. * Dawid, and A.F.M. Smith, Clarendon Press: Oxford,
pp. 763-773.
• Ratto, Marco (2008): “Analysing DSGE models with global sensitivity analysis”, Computational Economics,
31, 115–139.
• Ratto, Marco and Iskrev, Nikolay (2011): “Identification Analysis of DSGE Models with DYNARE.“, MON-
FISPOL 225149.
• Ruge-Murcia, Francisco J. (2012): “Estimating nonlinear DSGE models by the simulated method of mo-
ments: With an application to business cycles“, Journal of Economic Dynamics and Control, 36, 914-938.
• Schmitt-Grohé, Stephanie and Martin Uríbe (2004): “Solving Dynamic General Equilibrium Models Using
a Second-Order Approximation to the Policy Function,” Journal of Economic Dynamics and Control, 28(4),
755–775.
• Schnabel, Robert B. and Elizabeth Eskow (1990): “A new modified Cholesky algorithm,” SIAM Journal of
Scientific and Statistical Computing, 11, 1136–1158.
• Schorfheide, Frank (2000): “Loss Function-based evaluation of DSGE models,” Journal of Applied Econo-
metrics, 15(6), 645–670.
• Sims, Christopher A., Daniel F. Waggoner and Tao Zha (2008): “Methods for inference in large multiple-
equation Markov-switching models,” Journal of Econometrics, 146, 255–274.
• Skoeld, Martin and Gareth O. Roberts (2003): “Density Estimation for the Metropolis-Hastings Algorithm,”
Scandinavian Journal of Statistics, 30, 699–718.
• Smets, Frank and Rafael Wouters (2003): “An Estimated Dynamic Stochastic General Equilibrium Model
of the Euro Area,” Journal of the European Economic Association, 1(5), 1123–1175.
• Stock, James H. and Mark W. Watson (1999). “Forecasting Inflation,”, Journal of Monetary Economics,
44(2), 293–335.
• Uhlig, Harald (2001): “A Toolkit for Analysing Nonlinear Dynamic Stochastic Models Easily,” in Compu-
tational Methods for the Study of Dynamic Economies, Eds. Ramon Marimon and Andrew Scott, Oxford
University Press, 30–61.
• U.S. Census Bureau (2020): “X-13 ARIMA-SEATS Reference Manual, Version 1.1”, Center for Statistical
Research and Methodology, U.S. Census Bureau, https://www.census.gov/data/software/x13as.html
• Villemot, Sébastien (2011): “Solving rational expectations models at first order: what Dynare does,” Dynare
Working Papers, 2, CEPREMAP.
287
Dynare Reference Manual, Release 6.0
288 Index
Dynare Reference Manual, Release 6.0
Index 289
Dynare Reference Manual, Release 6.0
290 Index
Dynare Reference Manual, Release 6.0
oo_.trend_component.MODEL_NAME.CompanionMatrix Q
(MATLAB variable), 191 qdiff (dseries method), 254
oo_.UpdatedVariables (MATLAB variable), 123 qdiff_ (dseries method), 254
oo_.var (MATLAB variable), 79 qgrowth (dseries method), 254
oo_.var.MODEL_NAME.CompanionMatrix (MAT- qgrowth_ (dseries method), 254
LAB variable), 190
oo_.var_list (MATLAB variable), 80 R
oo_.variance_decomposition (MATLAB variable),
ramsey_constraints (block), 162
80
ramsey_model (command), 161
oo_.variance_decomposition_ME (MATLAB vari-
ramsey_policy (command), 162
able), 81
realtime_shock_decomposition (command), 145
oo_recursive_ (MATLAB variable), 17
regression (x13 method), 260
optim_weights (block), 165
remove (dates method), 231
options_ (MATLAB variable), 17
remove (dseries method), 255
osr (command), 164
remove_ (dates method), 231
osr_params (command), 165
remove_ (dseries method), 255
osr_params_bounds (block), 166
rename (dseries method), 255
outlier (x13 method), 260
rename_ (dseries method), 255
resetags (dseries method), 256
P resetops (dseries method), 256
pac.estimate.iterative_ols (MATLAB com- resid (command), 42
mand), 198 round (dseries method), 256
pac.estimate.nls (MATLAB command), 198 round_ (dseries method), 256
pac.initialize (MATLAB command), 196 rplot (command), 199
pac.update (MATLAB command), 196 run (x13 method), 261
pac_expectation (operator), 195
pac_model (command), 195 S
pac_target_info (block), 196 save (dseries method), 256
pac_target_nonstationary (operator), 196 save_params_and_steady_state (command), 211
parameters (command), 22 sbvar (command), 181
paths (config block), 216 search (MATLAB command), 281
perfect_foresight_setup (command), 64 seats (x13 method), 261
perfect_foresight_solver (command), 64 send_endogenous_variables_to_workspace
perfect_foresight_with_expectation_errors_setup (MATLAB command), 279
(command), 72 send_exogenous_variables_to_workspace
perfect_foresight_with_expectation_errors_solver (MATLAB command), 279
(command), 73 send_irfs_to_workspace (MATLAB command),
pickmdl (x13 method), 261 279
planner_objective (command), 159 sensitivity (command), 167
plot (dseries method), 252 set_dynare_seed (command), 211
plot_conditional_forecast (command), 157 set_names (dseries method), 257
plot_shock_decomposition (command), 147 set_param_value (MATLAB command), 30
plus (dates method), 230 set_shock_stderr_value (MATLAB command), 54
plus (dseries method), 253 setdiff (dates method), 231
pop (dates method), 230 shock_decomposition (command), 143
pop (dseries method), 253 shock_groups (block), 144
pop_ (dates method), 230 shocks (block), 51, 69, 87
pop_ (dseries method), 253 sign (function), 27
posterior_function (command), 279 simul (command), 68
predetermined_variables (command), 23 sin (function), 27
print (x13 method), 261 sinh (function), 28
print_bytecode_dynamic_model (command), 63 size (dseries method), 257
print_bytecode_static_model (command), 63 slidingspans (x13 method), 261
prior (MATLAB command), 281 smoother2histval (command), 158
prior_function (command), 279 sort (dates method), 231
projection (dseries method), 254 sort_ (dates method), 231
spectrum (x13 method), 261
sqrt (function), 27
Index 291
Dynare Reference Manual, Release 6.0
U
uminus (dates method), 232
uminus (dseries method), 258
union (dates method), 232
unique (dates method), 232
unique_ (dates method), 232
unit_root_vars (command), 128
uplus (dates method), 233
V
var (command), 20
var_expectation (operator), 193
var_expectation.initialize (MATLAB com-
mand), 193
var_expectation.update (MATLAB command),
193
var_expectation_model (command), 192
var_model (command), 189
var_remove (command), 23
varexo (command), 21
varexo_det (command), 22
varobs (command), 91, 129
verbatim (block), 211
vertcat (dates method), 233
vertcat (dseries method), 258
vobs (dseries method), 259
W
write (reporting method), 273
write_latex_definitions (MATLAB command),
212
write_latex_dynamic_model (command), 35
write_latex_original_model (command), 34
write_latex_parameter_table (MATLAB com-
mand), 213
292 Index