Linking Dynare to Matlab code

Hey Johannes,

Is it possible to link Dynare to matlab code in the following way? Suppose I want to do simulated method of moments and use Dynare to compute the stochastic simulated time series under a different set of parameters – in other words, I want to find the parameters that match the data, which involves solving Dynare under each parametric guess.

How would I want to go about coding this – do you have some pseudocode in mind? I think the main stumbling block for me is that dynare erases whatever is in matlab memory. With that aside, my general structure is:
a) solve the dynamic model with dynare
b) call the data and compute actual moments
3) take the difference between actual and simulated moments
4) send that objective function to fminsearch

On a related note, if I just want to pass a numerical steady state computed in one function file onto dynare, would I do that?

You can call Dynare with the noclearall option:

For implementing a SMM-approach see e.g. the replication material to Born/Pfeifer (2014): “Risk Matters: The Real Effects of Volatility Shocks: Comment” at [Born/Pfeifer (2014): “Risk Matters: A comment”](Born/Pfeifer (2014): “Risk Matters: A comment”)

Wow, that’s great, thank you!

It’s definitely amazing how flexible Dynare is and all that can be done with it. Just to follow up on your suggestion with “noclearall”:

My SMM code looks a little different than your AER comment code. I have one matlab file that computes moments and then calls fminsearch to optimize over a separate file; in that file, I create the GMM objective function and, to do that, I call Dynare to get the simulated moments.

The problem is that I call Dynare .mod file in the matlab function file and the results of the file don’t show up. It’s super odd because after I get the error, all the relevant Dynare created variables appear. In other words, in my function file that computes the simulated moments, I call Dynare:

dynare benchmark.mod noclearall %addpath C:\dynare\4.4.2\matlab
load dynarerocks

and then I want to use variables created from Dynare, call it X, to created moments F(X) that go into the objective function. And yet, none of the content shows up after calling the .mod file.

(The “load dynarerocks” also doesn’t work for me – I spent a while searching and it looked like some files use that.)

Again, really appreciate your always being available to give suggestions – reminds me to check the forum to learn more! I’m sure my question here has a simple answer.

The bottom part of the mod-file in our replication files does exactly what you describe. We added essentially Matlab code to a mod-file, but you can put that part just in a Matlab file.

Please don’t use the Den Haan dynarerocks. It is hugely inefficient.

From what you describe, the problem is the scope of variables. Try defining

before calling Dynare the first time and use the same statement within your objective function (or alternatively, pass these three variables as function arguments to the objective function)

Dear Johannes,

I am trying to implement a SMM procedure and I’m using the aforementioned 2014 AER code as guidance. When I try to run your code setting @#define estimation = 1 (this being the only change made to the code posted on your website), I get the following error:

Index exceeds matrix dimensions. Error in Born_Pfeifer_RM_Comment (line 455) [fhat,xhat] = csminwel(@smm_diff_function,x_start,H0,],crit,nit,target,estimation_replications,shock_mat(:,:,1:estimation_replications)); Error in dynare (line 180) evalin('base',fname) ;

Do you know what might be the reason for this? (I’m using Dynare 4.4.3 and Matlab R2014b).

I also wanted to ask you how the shocks enter the csminwel function. In the code they enter as: shock_mat(:,:,1:estimation_replications))however, in the code the matrix shock_mat is defined as a 2-dimensional matrix (npts x M_.exo_nbr).

Finally, how does the simult_FV differ from the simult_ function? I didn’t find the definition.

Thank you!

Hi Martin,
this seems to be a path conflict. The csminwel-function we used was the original one of Chris Sims. But Dynare has its own one with the same name, but a somewhat different syntax. It is best if you download the original one to the same folder, rename it and then call this function.

There should not be a simult_FV but only a simult_FGRU. The difference to the Dynare one is that it uses the FGRU pruning, not the Andreasen et al one of Dynare. Always use the latter (for differences, see the Appendix to our comment)

Dear Johannes,

thank you. I tried downloading and renaming the original csminwel (and the functions it calls), but I get exactly the same error message. As I mentioned before, I think it might be related to the dimensions of the shock_mat matrix, but I might be overlooking something else…

As for the “simult_FV”, I was asking because, if I get it correctly, this function shows up in the “smm_diff_function.m” file of the replication files posted on your website.

Thanks for pointing this out. There seem to have happened a few copy and paste mistakes when we prepared the codes for the AER. I will post an updated version soon.

Hi Johannes,

I spent some additional time looking at this, but I might still be misunderstanding; I added:
global moments_model oo_ M_ options_

in both matlab files. What do you mean “use the same statement within your objective function” – what statement, the global? My objective function is:
gmm=(moments_data - moments_model)'weight(moments_data - moments_model)

which is assembled after calling dynare to get the simulated moments.

Just to make sure we both are talking about the same problem – feel free to skip this if you know we’re talking about the same thing – the issue that I was running into was that I had computed all my empirical moments with the code for doing smm, and then call the dynare file; but, after I call the file and introduce the objective function (moments_data - moments_simulated), the dynare simulations dont show up. It’s odd to explain – the dynare simulations show up after I let it run, but while it’s running the dynare produced simulations dont show, and thus the program doesnt work since the simulations dont show up “in time”.

I was hoping to get this working in my original format since I don’t understand yours entirely in your paper – although you did nice job documenting it, excellent compared the the vast majority of paper documentation! Just to better understand your lines of code, maybe I could clarify a few additional things:

The line below feeds in the simulated data and computes the relevant moments?
What’s the difference with the below (is it that there are only a subset of moments here?)
// moments_short(9,:)=[nx_y_share nx_y_share];
[moments_long, row_names, column_names, std_nx]=get_quarterly_moments(out_withshock,ergodicmean_no_shocks,M_,oo_);

Related to mharding’s point:

Are sigma_x, phipar,D_bar,exp(phi) the only parameters you are trying to calibrate? This code below is where you’re actually calling the optimizer to do smm? (in my case, I have a separate matlab file.)
@#if estimation == 1
x_start=[sigma_x,phipar,D_bar,exp(Phi)]; //use calibration as starting point
target=[moments_emp(1:3);moments_emp(8)]’; //define target moments
//optimizer options
H0 = 1e-2*eye(length(x_start)); //Initial Hessian
crit = 1e-7; //Tolerance
nit = 1000; //Number of iterations
//make sure Dynare does not print out stuff during runs

//options_.qz_criterium = 1+1e-6; //required because it is empty by default, leading to a crash in k_order_pert
[fhat,xhat] = csminwel(@smm_diff_function,x_start,H0,],crit,nit,target,estimation_replications,shock_mat(:,:,1:estimation_replications));

@# endif

Again, excellent advice and appreciate your sharing all your expertise!

@mharding: the updated files are now available at my homepage. Please try them out. Thanks again for pointing this out. The two mistakes were:
*] In smm_diff_function.m the simult_FV should be simult_FGRU throughout
*] The Born_Pfeifer_RM_Comment.mod is missing the line

before the call to csminwel.


Please provide me with the files to replicate the issue.

Hey Johannes – I was able to get the issue I mentioned above to work – a very simple thing, I just needed to save variables X via X=oo_.endog_ etc. The moment matching isn’t working, but that’s a separate and non-Dynare issue-- will keep working on that!

Thanks again for your time and energy in answering all these questions, and posting the correction to your prior code!

Thank you for the update Johannes! I tried the files and everything works fine.

Great. The AER has also updated the files.

Sorry to bump the thread again, but it’s somewhat related to the initial question.

After some time, I got the SMM working no problem – what is a slight issue, however, is that there are some moments I want to match that are long run growth rates of some variables. However, as you know better than anyone else, dynare focuses more on cyclical fluctuations. My initial understanding that long run growth was built in merely by doing:

z_t = rho*z_t-1 + (1-rho)*growth + eps

where growth = .03, for example. However, taking the average across the variables is still zero (over the simulated series). I looked for previous threads on this and the only related one, I think, was [Growth of variables and unit root), however, it didn’t have a response.

One way to deal with this, of course, is to “add in” the long run growth component afterwards, but that would change the dynamic choices I’d think. Is there a simple way to do this I’m overlooking? Note that the issue isn’t solved by detrending since I want the model to be able to produce some long run growth.

Theory imposes that in your model the growth rate of any variable is just

(or a transformation of this like (1-capitalshare)*growth)). Thus, what you should match is the average z. Alternatively, you can define the model-implied growth rate of any variable and match this mean growth rate to the one in the data. This is a simple matter of defining the correct observation equation in undemeaned first differences.

Thanks for the reply (again)! I don’t follow entirely though? Indeed, the model implies a growth rate – for example, two separate shock processes to X and Z in the production function
Y= F((AxX),(AzZ))

where F is a CES. But when you compute the growth rate of the variables, e.g.,
Z_grow = (Z_t - Z_t-1)/Z_t-1
you end up getting an average of zero when averaging over the time series.

Is there an example you could point to that would make it more concrete? All the examples in Dynare I’ve seen just focus on business cycle fluctuations, not long run growth.

Take a look at section 5 of my Guide to Observation Equations. There you can see how to transform a growing model into a detrended one that can be entered into Dynare.

Short outline: Write e.g. actual output Y as detrended output y times the trending TFP X:

Enter the model in detrended form. That will include a process for the growth rate of X:

The growth rate of Y is then given by

The mean of d_Y is the mean of mu_x, which is non-zero.

Hey Johannes,

I thought it would be worth posting here for some recurring issues that might be relevant for others too. Just FYI for readers, the “simul_” command is key here – feed in the long run growth after recovering the decision rules in a model without long run growth.

The main problem is that dynare continues to either not find a steady state or violate rank condition when iterating over different parameters. Other than adjusting the bounds when using fmincon to conduct the SMM, I’m not sure what other alternatives there are? Every time dynare stops due to lack of a steady state or violations to the rank condition, the moment conditions arent necessarily satisfied, so it’s NOT as if it stops at a location that’s almost ideal.

Looking forward to your tips!

What do you mean with the first part? It sounds as if your rational expectations model solved under no growth is fed with a shock process that is inconsistent with rational expectations.

REgarding the problem you describe, you need to filter these cases out where no unique and bounded solution is found (for whatever reason that happens). In this case, Dynare, or more precise resol.m or stoch_simul.m will return an error code that allows assigning a penalty for these parameter values to steer the optimizer to a different parameter value.