% Loop for different levels of H (eta in the paper): a PERMANENT credit shock
% 
% PLEASE, SET PRODUCTIVITY SHOCK TO 1 and CREDIT SHOCK TO 0 IN dyn_main.mod

    % When you invoke the solver, I suggest you set irf=0 and specify

% options_.nomoments=0;
% options_.nofunctions=1;
% options_.nograph=1;
% options_.verbosity=0;
% options_.noprint=1;
% options_.TeX=0; 

% Declare model name.

model_name='dyn_main';

% Call model.

eval(['dynare ',model_name])

% Shock of interest (make shock name as character type)

shock={'H'};  param_name=char(shock);

% Find position in declaration of parameters.

H_pos=strmatch(param_name,M_.param_names,'exact');
% enF_pos=strmatch('enF',M_.exo_names,'exact');


% get variable positions in variable list.

exH_pos=strmatch('exH',M_.endo_names,'exact'); %Home exports

exF_pos=strmatch('exF',M_.endo_names,'exact'); %Home imports

cH_pos=strmatch('cH',M_.endo_names,'exact'); % Consumption

gdpH_pos=strmatch('gdpH',M_.endo_names,'exact'); %GDP

iH_pos=strmatch('iH',M_.endo_names,'exact'); %Investment

% Grid.
ini=0.20; %var=stderr^2
fin=0.90;

H_grid = ini:0.005:fin; % Level of H.

% Pre-allocate.

variance.exH=zeros(length(H_grid),1);

variance.exF=zeros(length(H_grid),1);

variance.cH=zeros(length(H_grid),1);

variance.gdpH=zeros(length(H_grid),1);

variance.iH=zeros(length(H_grid),1);

% Storage matrix.

mat_loopH=zeros(6,length(H_grid));

% Start counter.

n=0;

% Start loop.

  for ii = 1:length(H_grid)

          % Assign value

          H = H_grid(ii); 
     
          info=stoch_simul(var_list_); % loop over stoch_simul.

 

      if info == 0

        %read out variances.    

        variance.exH(ii)=oo_.var(exH_pos,exH_pos); %finding domestic exports variance

        variance.exF(ii)=oo_.var(exF_pos,exF_pos); %finding domestic imports variance
        
        variance.cH(ii)=oo_.var(cH_pos,cH_pos);

        variance.gdpH(ii)=oo_.var(gdpH_pos,gdpH_pos);

        variance.iH(ii)=oo_.var(iH_pos,iH_pos);

      else

        variance.exH(ii)=NaN;
        variance.exF(ii)=NaN;
        variance.cH(ii)=NaN;
        variance.gdpH(ii)=NaN;
        variance.iH(ii)=NaN;

     end

% Next iteration.   

n=n+1
H

% Store.

mat_loopH(:,n)=[H_grid(ii);sqrt(variance.exH(ii));sqrt(variance.exF(ii));sqrt(variance.cH(ii));sqrt(variance.gdpH(ii));sqrt(variance.iH(ii))];

  end
 
  figure
  plot(mat_loopH(1,:),mat_loopH(2,:),mat_loopH(1,:),mat_loopH(3,:))
  title('Exports and Imports variance over \eta')
    xlabel('levels of \eta')
    ylabel('trade variance')
    legend({'X','M'})
    
  figure
  plot(mat_loopH(1,:),(mat_loopH(4,:)),mat_loopH(1,:),(mat_loopH(5,:)))
  title('Consumption and GDP variance')
    xlabel('levels of \eta')
    ylabel('C and GDP variance')
    legend({'C','GDP'})
    
 figure
  plot(mat_loopH(1,:),mat_loopH(6,:))
  title('Investment variance')
    xlabel('levels of \eta')
    ylabel('I variance')   