Loop over parameters

Hi,

I know that this problem was broached on this forum many times since I found some topics connected with it but I didn’t find any solution for my problem.

I want to look at some statistics of variables in the model when some parameters change. The steady state is calculated by hand and included in ‘initval’. For creating the loop over parameters, I used simple syntax like this:

rhos = 0.8:0.05:1.05;
for i=1:length(rhos);
rho = rhos(i);
stoch_simul(order=1);
if info;
disp('Computation fails for rho = ' num2str(rho)]);
end;
// results can be saved here
end;

This code with the loop above included is only working when I am looping over parameters that are not used for calculating steady state in the ‘initval’ part. Otherwise it gives me following error (though I included ‘initval’ part in the loop):

dynare:k_order_perturbation: Caught Kord exception: NaN or Inf asserted in first order derivatives in FirstOrder::solve
Error using mexErrCheck (line 41)
Error encountered in: k_order_perturbation.

Error in k_order_pert (line 40)
    mexErrCheck('k_order_perturbation', err);

Error in stochastic_solvers (line 65)
        [dr,info] = k_order_pert(dr,M_,options_,oo_);

Error in resol (line 118)
    [dr,info] = stochastic_solvers(dr,check_flag,M,options,oo);

Error in stoch_simul (line 76)
    [oo_.dr,info,M_,options_,oo_] = resol(0,M_,options_,oo_);

Error in b120813_1703_equity_premium_grid_search (line 407)
info = stoch_simul(var_list_);

Error in dynare (line 120)
evalin('base',fname) ;

I would be thankful for any help.
Regards

Looping over parameter value/entering value from matlab
"how to "loop" over paramterizations" for dummies?
Loop over parameters - program
Incorporating matlab function into dynare
Minimizing negative welfare
Parameters
Plots
How to store the constant term in policy and transition func
Running loops and error message
MODEL SIMULATION for several values of a parameter
Looping over deep parameter
Replication of sensitivity check
Automate the Iteration of a Parameter Value
Simulate data using the model
Multiple parameter values
Looping Over Parameters - Problem in Steady State File
Obtaining optimal values for policy function
Setting parameter and initial values frome matlab
How to edit the mod file via m file in MatLab?
Calibration with Dynare
Grid search for parameter values
Converging to steady state
Loop over parameters inside the mod file
Is there a way to suppress *all* Dynare output in Matlab?
Error "Reference to non-existent field 'exo_nbr"
Error "Reference to non-existent field 'exo_nbr"
Comparative static analysis
Looping in deterministic simulation
Which subroutine generates ghx and ghu?
Howtoloops page
Continue dynare loop even when B/K condition violated (or
Posterior predictive checks
Second order approximation and the IRF explosive
Question about IRF for a loop
Where does Dynare store impulse response after looping over certain parameter
Using Dynare as a Matlab function
Overloop estimation in .mod takes more than due
Optimal Monetary Policy with nonlinear loss function
Loop over parameters to find maximized welfare
Dynare loop for - help
Loop over correlation coefficient of shocks
Occasional Freezing While Configuring Dynare
Macroprocessor question
Getting errors from matlab after running dynare
How xxx.m, xxx_dynamic.m,xxx_static.m files are related?
Output dynare results into excel
Creating Graphs through a static model
Loop crashes
Prevent dynare from storing results
Using dynare for a solver for OSR and calibration

You are not actually setting the parameter. What you should do is use the the set_param_value command. Moreover, if you have an analytic steady state, use a steady_state_model block instead of initval. You can find an example for such a loop here: [Need help to check Matlab compatibility). Basically, you need to write a Matlab m-file with the following parts:

rhos = 0.8:0.05:1.05;
first_time = 1;
for i=1:length(rhos)
    if first_time
        set_param_value('rho',rhos(i));
        dynare your_mod_file_here noclearall;
        first_time = 0;
    else
        set_param_value('rho',rhos(i));
        info = stoch_simul(var_list_);
        if info;
          disp('Computation fails for rho = ' num2str(rho)]);
        end;
    end
end

Inside your mod-file you still need to use the steady_state_model block.

Addendum:

The set_param_value command only refers to structural parameters. You cannot set standard deviations or measurement error defined in the shocks-block this way. You either have to set M_.Sigma_e directly, or calibrate the shock variances to 1 and use in the model

+sigma_eps*eps_z

instead of

+eps_z

The structural parameter sigma_eps now contains the standard deviation and can be set using the set_param_value command. Similarly, correlated shocks can be entered by specifying a joint shock.

Sorry for late response but I was on vacations.

Thank you for your helpful advice. I tried to implement all your hints and it paid off. I used set_param_value command and calculated steady state in the external file. Then it all worked so that I could performed loop.

Thank you one more time!

I am implementing a poor man’s version of the method of moments using this procedure: I have three AR(1) shocks, set up a grid for each of the shocks’ autocorrelation and variance, and evaluate the model at each point in the grid, from where I take the moments of some variables and pick the parameter point that does the best.
My problem is that even if I pick a grid of size 4 for each parameter, this corresponds to 4^6 = 4096 evaluations of the stoch_simul function. Any way you think that I could speed up the process? Especially considering that the procedure may have to be repeated many times.

I am afraid there isn’t. You should just make sure that Dynare does not print or plot or compute stuff you don’t need within stoch_simul.

Hi,

If you are willing to estimate a DSGE model with a simulation based method you should not call Dynare in a loop. This is very inefficient, because there is no need to parse the model at each iteration. We do not provide any interface for SMM, I hope to release this in Dynare 4.5, so you need to write a routine that computes an objective (based on the moment conditions) that calls Dynare’s simult or simult_ routines, and minimize this objective usig the provided optimization routines…

More generally it is always simpler and more efficient to perform the loops in the mod file (where the Matlab statements are legal) rather than around calls to Dynare.

Best,
Stéphane.

Either Stéphane or I misunderstood you. To clarify: my original post shows how to do exactly what Stéphane proposes. Dynare is only called once to parse the model. Subsequently, only the Matlab routines are called. In your case, you are trying to run an SMM. This requires setting the parameters, computing the steady state, solving the model, and then simulating it. This is the sequence you get when repeatedly calling stoch_simul from a Matlab file (as opposed to running full Dynare everytime). My second post recommends that when calling stoch_simul several times, you shut off all things there that you do not need (alternatively, the fastest way is just calling the routines from stoch_simul you need (basically resol(0,M_,options_,oo_); and simult), but that is more advanced).

Ok, so what I am using is pretty much a poor man’s version of SMM as you pointed out. I run

dynare modelname

once, before the loop, and then call stoch_simul for each point in the parameter grid. Keep the moments I need from the simulations and then use a simple criterion function to pick the best point in the parameter space.

I was reading the function description for simult but am not totally sure if I understood exactly what it does: the description says that I can feed exogenous shocks and decision rules, and it gives me the path for endogenous variables. I might be wrong, but I have the impression that decision rules may change for different parameter values, and I have little hope of getting closed forms for anything since this is a 2nd order approximation.

I am going to check resol out as well. And I didn’t know you could write loops inside a mod file!! How would that work? Would I need a modle block for each grid point? Can a loop-inside-mod be used for what I am trying to implement? Sorry for all these questions, and thank you very much for your time.

Since I am only changing parameters that govern the persistence and variance of the shocks, the steady state should be unaffected and there is no need to recompute it every time. So from what I gathered, the fastest way with external loops would be

dynare mymodel

for i = 1:N

set_param_value('paramx',paramxgrid(i))

[dr,~,M,~,oo] = resol(0,M_,options_,oo_);
y_            = simult_(oo_.steady_state,dr,oo_.exo_simul,2);

storey(i) = y_
end

Any problem with this approach? I am just not sure at what stage I should use the set_param_value ! Thanks in advance!

I just tried what I described above and it seems to work. Furthermore, I have just collapsed a 9-hour job to 10 minutes. If you can offer me confirmation that the above pseudo-code is doing the right stuff, you, sirs, have just saved my life :slight_smile:

The basic structure looks correct. However, as noted above, the set_param_value-command only works for standard deviations if they enter the model as an explicit parameter (and not in the shocks-block). Without seeing the mod-file and what paramx is it is hard to tell.

Moreover, I you are not correctly feeding in the shocks for your simulation. oo_.exo_simul is typically not a shock series that you are trying to simulate.

Rather, if you have all your standard deviations as explicit model parameters, you should be providing a standard normal shock matrix like

shock_mat=randn(M_.exo_nbr,1000)

for 1000 periods of random numbers. As you are doing SMM, you should always use the same random number. Thus, move the generation of shock_mat outside of the loop. For an example on how to use simult_, see the AguiarGopinath2007.mod on my homepage.

Last comment: calling resol will also update the steady state, so your procedure is even valid when the steady stM_ate changes.

Thank you for your swift reply. I am writing standard deviations as explicit parameters due to the issue you discuss, and indeed I was feeding the wrong shock sequence. Thank you so much, it is so so faster that I am considering just writing a function and feeding it to a numerical optimizer instead of doing it over a grid.

Hi, all.
It seems you are discussing sth advance. I am wondering what’s the purpose to loop over parameter in such a way? I mean, if we want to compare model results with different parameters, can we just simply run the different codes separately? and then combine the IRF figures together with plot code by hand. I am just new to DYNARE and am now confused by how to combine figures. I don’t know what’s the advantage of doing loop over parameters. Will it just produce combined figures with different parameters automatically?
Many thanks indeed.
GOODLUCK

No, it does not help you with plotting.
Looping over parameters is useful if you want to embedd Dynare in more complicated settings like using for a simulated method of moments or impulse response function matching approach.

Got it . It just has some programming edge.Many thanks for your explanation, jpfeifer.

Suppose that we want to estimate the parameters using GMM. In particular, we would like to match the theoretical moments implied by the linearized model to the sample moments based on the data. Also assume that we have a separate toolbox for GMM estimation in which we just need to code the moment conditions in a separate m file. In this case, we need to pass the information obtained from first run of the Dynare to parse the code to the moment function in GMM and the objective function. Can we do this as follows:

  1. In a Matlab script file define the parameters and all other necessary stuff along with

global var_list_ oo_ M_ ex0_ options_ estimation_info info
save parameters gamma1 alpha1 delta1 rho1 beta1 sigma1
dynare stochgrowth_dyna noclearall

  1. In the mod file define

parameters gamma alpha delta rho beta sigma;

load parameters;

set_param_value(‘gamma’,gamma1) % utility parameter
set_param_value(‘alpha’,alpha1) % production elasticity
set_param_value(‘delta’,delta1) % depreciation rate
set_param_value(‘rho’,rho1) % production shock autocorrelation
set_param_value(‘beta’,beta1 ) % discount factor
set_param_value(‘sigma’,sigma1) % production shock volatility

at the beginning, the rest of the mode file is standard.

  1. In the GMM moment function matlab m file:

function mom = GMMmoments(theta,X,avg)

global var_list_ oo_ M_ ex0_ options_ estimation_info info

gamma1 = theta(1);
alpha1 = theta(2);
delta1 = theta(3);
rho1 = theta(4);
beta1 = theta(5);
sigma1 = theta(6);

yobs = X(:,1);
cobs = X(:,2);
kobs = X(:,3);
iobs = X(:,4);

set_param_value(‘gamma’,gamma1)
set_param_value(‘alpha’,alpha1)
set_param_value(‘delta’,delta1)
set_param_value(‘rho’,rho1)
set_param_value(‘beta’,beta1 )
set_param_value(‘sigma’,sigma1)

info = stoch_simul(var_list_);
if info
disp(‘Stochastic Simulation failed’);
end

xmean = oo_.mean;
xvar = diag(oo_.var);

Basically, what I did here is to define Dynare solution variables as GLOBAL variables in the main file and the moment file. I am not a big fan of using global variables but I could not use local variables. Is this procedure OK? Is there any other ways?

(By the way I did not post the full codes but they seem to work OK)

Looks correct to me. There are ways to get around using global variables in the main file, but they are typically not worth the hassle. The only global variables you should need are

oo_ M_  options_ 

One important comment: if you are using simulated moments, make sure you use the same random numbers for every parameter draw.

Exactly. The same set of shocks has to be used in the SMM or indirect inference. One can easily code this using Dynare with second or third order linearization.
Better way is of course to solve the nonlinear eq’m conditions using residual based methods, e.g. collocation, and then to embed it into the indirect inference framework. That would be a very nice extension to the Dynare.

By the way I think we also need

var_list_

as a global variable in addition to the ones you mentioned.
Thanks for your reply,

Cheers

If you did not specify variables for var_list_, you can just use

var_list_=]; info = stoch_simul(var_list_);

If you did, you can either make var_list_ global or use something along the lines of

var_list_=]; var_list_ = 'yobs '; var_list_ = char(var_list_, 'cobs'); var_list_ = char(var_list_, 'kobs'); var_list_ = char(var_list_, 'iobs'); info = stoch_simul(var_list_);

Hi all,

I am trying to evaluate the conditional welfare and I am getting the following error

??? Reference to non-existent field ‘eigval’.

Error in ==> check at 80
eigenvalues_ = dr.eigval;

Error in ==> openeconomy_loop_det at 626
oo_.dr.eigval = check(M_,options_,oo_);

Error in ==> dynare at 120
evalin(‘base’,fname) ;

Error in ==> max_cond_welfare2 at 31
dynare openeconomy_loop_det noclearall nolog

How can I solve the problem?

Thanks Boniface
Boniface2.zip (9.09 KB)