%To run in parallel:
%   dynare test_small_base.mod conffile='/Applications/Dynare/4.4.2/dynare_parallel.txt' parallel
%To test parallel configuration
%   dynare test_small_base.mod conffile='/Applications/Dynare/4.4.2/dynare_parallel.txt' parallel_test

% Model in real terms: investment and capital-asset ratio adjustment cost, 
%                      consumption habits, sticky prices  via Rotemberg 
%                      with indexation to both past and steady state inflation
% Equation Blocks 1) households  2) capital producers     
%                 3) entrepreneurs    4) banks     5) retailers      
%                 6) aggregation     7) monetary policy  

%Version: January 5th, 2015

global I_SS;

var 
%Households
c_h d l_h lam_h w
%Retailers
J_R x       
%Capital Producers   
I q_k       
%Entrepreneurs
c_e k b y lam_e s_e r_k            
%Banks
r_d r_b r_ib K_b J_B leverage  eps_r_cb
%Aggregation         
C                 
%Monetary Policy                      
r_cb     
%Shocks   
A_e
%Measurement
data_I data_rCB
%Prices
pie pie_w
;

varexo e_A_e e_r_cb; %e_sig e_q_e;

parameters  
%Households and Entrepreneurs
beta_p beta_e m_e alpha eps_l gamma phi
%Banks                        
eps_d eps_b delta_kb vi kappa_kb z M sig
%Retailers                           
kappa_p ind_p delta_e eps_y                             
%Capital Producers            
kappa_i deltak 
%Prices
piss
%Aggregation
S
%Shocks                               
rho_A_e rho_r_cb
sig_ss  r_cb_ss
%Monetary Policy
rho_ib phi_pie phi_y
%Measurement
I_SS                                   
;


% *********************			
% Calibrated Parameters
% *********************

%Discount factors 
beta_p       = 0.9943;                      
beta_e       = 0.975;                                                                              
%Loan-to-value ratio entrepreneurs                                                                      
m_e       = 0.35 ;
%Capital share in the production function                          
alpha        = 0.250;                       
%Elast. of subst. of deposits and loans 
eps_d        = -1.1402; %-1.46025;                    
eps_b        = 2.2987; %2.932806;                     
%Elast. of subst. of goods and labor                                                               
eps_y     = 6;                                                                              
%Depreciation rate for physical capital                                                     
deltak    = 0.025;
%Steady state gross inflation rate                          
piss      = 1;
%Steady state gross nominal interest rate                               
r_cb_ss   = (piss/beta_p-1)* (eps_d-1)/eps_d ;                    							                    
%Capital-asset ratio (Basel II)
vi           = 0.09;                                                      
%Depreciation rate of bank capital
delta_kb 	=	 0.153661;

%Estimated Parameters
%Inverse Frisch elasticity of labor supply       
%phi          = 0.9167; 
%Cofficient of Relative Risk Aversioin
%gamma       = 1.3589;
%Adjustment cost parameter for prices, investment, and capital-asset ratio                                                   
%kappa_p      = 20.2155;                   
%kappa_i      =  2.6804;                    
%kappa_kb     = 23.8727;                    
%Monetary policy response to lagged interest rate, inflation, output
%rho_ib       = 0.8305;                 
%phi_pie      = 2.2018;                  
%phi_y        = -0.0664;   
%Indexation to lagged and steady state inflation                
%ind_p        = 0.4414; 
%AR(1) coefficients on shocks                   
%rho_A_e      = 0.5855;      
%rho_r_cb     = 0.8094;            
%Steady States for Measurement Variables
I_SS = -1.75257;

%------------------------------------------------------------
% Model equations
%------------------------------------------------------------

model;

%1) Houshold ********************************************************6

exp(c_h)^(-gamma) = exp(lam_h); // CON rescaling
exp(lam_h)  = beta_p * exp(lam_h(+1)) * (1+exp(r_d))/exp(pie(+1)); // 
exp(l_h)^phi = exp(lam_h)*exp(w);
exp(pie_w) = exp(w) / exp(w(-1)) * exp(pie);
exp(c_h) + exp(d) = exp(w) * exp(l_h)+ (1+exp(r_d(-1)))*exp(d(-1))/exp(pie) ;  //

%2) Capital Producers *****************************************************

exp(k) = (1-deltak) * exp(k(-1)) + ( 1 - kappa_i/2 * (exp(I)/exp(I(-1)) - 1)^2 ) * exp(I) ;   
1 = exp(q_k) * ( 1 -  kappa_i/2 * (exp(I)/exp(I(-1)) - 1)^2  - kappa_i * (exp(I)/exp(I(-1)) - 1) * exp(I)/exp(I(-1)) ) 
  + beta_e * exp(lam_e(+1)) / exp(lam_e) * exp(q_k(+1)) *   kappa_i * (exp(I(+1))/exp(I) - 1) * (exp(I(+1))/exp(I))^2 ; //   13                              //   15

%3) Entrepreneurs *********************************************************

exp(c_e)^(-gamma) = exp(lam_e);         // CON rescaling
exp(s_e)  * m_e * exp(q_k(+1)) * exp(pie(+1)) * (1-deltak) 
     + beta_e * exp(lam_e(+1)) * ( exp(q_k(+1))*(1-deltak) + exp(r_k(+1)))   = exp(lam_e) * exp(q_k) ;  //
exp(w) =  (1-alpha) * exp(y) / ( exp(l_h)*exp(x) );
exp(lam_e) - exp(s_e)  * (1+exp(r_b)) = beta_e * exp(lam_e(+1)) * (1+exp(r_b)) / exp(pie(+1));  //
exp(c_e) + ((1+exp(r_b(-1))) * exp(b(-1)) / exp(pie) ) +  (exp(w)*exp(l_h)) + exp(q_k) * exp(k) 
   = exp(y) / exp(x) + exp(b) + exp(q_k) * (1-deltak) * exp(k(-1)) + exp(J_R) ;   
exp(y) = exp(A_e) * (exp(k(-1)))^(alpha) * ( exp(l_h) ) ^ (1-alpha);
(1+exp(r_b)) * exp(b) = m_e * exp(q_k(+1))  *exp(pie(+1)) * exp(k) * (1-deltak); 
exp(r_k) = alpha * exp(A_e) * exp(k(-1))^(alpha-1) * ( exp(l_h)) ^ (1-alpha)/exp(x);  

%4) Banks ****************************************************************

exp(r_ib) = - kappa_kb * (exp(K_b)/(exp(b)) - vi ) * (exp(K_b)/(exp(b))) ^2  + exp(r_cb) ; 
exp(K_b) = (1-delta_kb) * exp(K_b(-1)) + exp(J_B(-1)) ;
%exp(K_b)/(exp(b))=vi;
exp(b) =  exp(d) + exp(K_b);

- 1 + eps_d  - eps_d  * exp(r_cb)/exp(r_d);
+ 1 - eps_b  +  eps_b  * exp(r_ib)/exp(r_b);

exp(J_B) = + exp(r_b)  *  exp(b) 
           - exp(r_d)   *  exp(d)
           - kappa_kb/2 * ( (exp(K_b) / (exp(b))  - vi ) ^2) * exp(K_b); 

exp(leverage)=(exp(b))/exp(K_b);

%5) Retailers **************************************************************

exp(J_R)  = exp(y)*(1 - 1/exp(x)    - (kappa_p/2) * (exp(pie) -  exp(pie(-1)) ^ ind_p * piss ^ (1-ind_p) )^2 ) ;
1 - eps_y + eps_y/exp(x) -    kappa_p * (exp(pie)    -  exp(pie(-1)) ^ ind_p * piss ^ (1-ind_p) ) * exp(pie) 
    + beta_p*(exp(lam_e(+1))/exp(lam_e))* kappa_p * (exp(pie(+1)) -  exp(pie)     ^ ind_p * piss ^ (1-ind_p) ) * exp(pie(+1)) * (exp(y(+1))/exp(y)) = 0;  

%6) Aggregation  ************************************************

exp(C)              = exp(c_h) + exp(c_e);

%7) Monetary Policy *****************************************************                                                  

(1+exp(r_cb)) = (1+r_cb_ss)^(1 - rho_ib ) * (1+exp(r_cb(-1)))^rho_ib * (( exp(pie) / piss ) ^phi_pie *  
             (exp(y)/exp(y(-1)))^phi_y  ) ^ ( 1 - rho_ib ) * exp(eps_r_cb) ;

%8) Shocks ****************************************************12

exp(A_e)      = (1 - rho_A_e)    *    1          + rho_A_e    * exp(A_e(-1))     + e_A_e;
exp(eps_r_cb)      = (1 - rho_r_cb)    *    1          + rho_r_cb    * exp(eps_r_cb(-1))     + e_r_cb;

%9) Measurement Equations ******************************12

data_I       =  I-I_SS;
data_rCB     = exp(r_cb) - r_cb_ss;

end;  

%------------------------------------------------------------
% Initial Values
%------------------------------------------------------------

initval;

c_h      =		 0.0192946;
d        =		 0.747995;
l_h      =		 -0.00897527;
lam_h    =		 -0.0268194;
w        =		 0.0163184;
J_R      =		 -1.31441;
x        =		 0.182322;
I        =		 -1.75257;
q_k      =		 0;
c_e      =		 -0.949657;
k        =		 1.93631;
b        =		 0.842306;
y        =		 0.477347;
lam_e    =		 1.32002;
s_e      =		 -3.74563;
r_k      =		 -3.02758;
r_d      =		 -5.16157;
r_b      =		 -3.96089;
r_ib     =		 -4.53188;
K_b      =		 -1.56564;
J_B      =		 -3.43865;
leverage =		 2.40795;
eps_r_cb =		 0;
C        =		 0.341002;
r_cb     =		 -4.53188;
A_e      =		 0;
data_I   =		 0;
data_rCB =		 0;
pie      =		 0;
pie_w    =		 0;

end;

%------------------------------------------------------------
% Bayesian Estimation
%------------------------------------------------------------

%Defining which dataseries are used in estimation
varobs data_I data_rCB;

%load Model.txt; % load dataseries from file

filename = 'Model.txt';
delimiter = '\t';
startRow = 2;

%% Format string for each line of text:
%   column1: double (%f)
%	column2: double (%f)
%   column3: double (%f)
%	column4: double (%f)
%   column5: double (%f)
%	column6: double (%f)
%   column7: double (%f)
%	column8: double (%f)
%   column9: double (%f)
%	column10: double (%f)
%   column11: double (%f)
%	column12: double (%f)
%   column13: double (%f)
%	column14: double (%f)
%   column15: double (%f)
%	column16: double (%f)
% For more information, see the TEXTSCAN documentation.
formatSpec = '%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%f%[^\n\r]';

%% Open the text file.
fileID = fopen(filename,'r');

%% Read columns of data according to format string.
% This call is based on the structure of the file used to generate this
% code. If an error occurs for a different file, try regenerating the code
% from the Import Tool.
dataArray = textscan(fileID, formatSpec, 'Delimiter', delimiter, 'HeaderLines' ,startRow-1, 'ReturnOnError', false);

%% Close the text file.
fclose(fileID);

%% Post processing for unimportable data.
% No unimportable data rules were applied during the import, so no post
% processing code is included. To generate code which works for
% unimportable data, select unimportable cells in a file and regenerate the
% script.

%% Allocate imported array to column variable names
Year = dataArray{:, 1};
Quarter = dataArray{:, 2};
Investment = dataArray{:, 4};
FedFundsRate = dataArray{:, 9};

%% Clear temporary variables
clearvars filename delimiter startRow formatSpec fileID dataArray ans;

Dates=horzcat(Year, Quarter);
save('Model_small.mat', 'Dates', 'FedFundsRate', 'Investment')

BEG_OBS          = 1;                          % 1997:Q2
END_OBS          = length(Dates);              % 2007:Q4    43 quarterly observations
DATES            = Dates(BEG_OBS:END_OBS,:);
datadescr.DATES  = DATES;
datadescr.MODEL  = M_.fname;

% give the dataseries the names listed in the 'varobs' command ...

dataseries.data_I    = Investment (BEG_OBS:END_OBS);
datadescr.data_I     = 'Real Investment';

dataseries.data_rCB  = FedFundsRate (BEG_OBS:END_OBS) - mean(FedFundsRate (BEG_OBS:END_OBS));
datadescr.data_rCB   = 'Short-term dinterest rate';

%Saving the renamed series for Dynare
save ('DYNARE_estimdata','-STRUCT','dataseries')

estimated_params ;
%Variable       Prior Shape     Mean      Std. Dev.
stderr e_A_e,   inv_gamma_pdf,	0.0100,     0.05;  
stderr e_r_cb,  inv_gamma_pdf,  0.0100,     0.05;  
rho_A_e,        beta_pdf,       0.80,       0.10;                   
rho_r_cb,     beta_pdf,       0.80,       0.10;
kappa_p,        gamma_pdf,      50,         20;   					
kappa_i,        gamma_pdf,      2.5,        1.0;			
kappa_kb,       gamma_pdf,      10.0,       5.0;
phi_pie,        gamma_pdf,      2.0,        0.5; 
rho_ib,         beta_pdf,       0.75,       0.10;   
phi_y,          normal_pdf,     0.10,       0.15;     
ind_p,          beta_pdf,       0.50,       0.15;
gamma,          gamma_pdf,      1.0,        0.5; 
phi,            gamma_pdf,      1.0,        0.5; 
end;

%options_.parallel = struct('Local', 1, 'PcName','', 'CPUnbr', [0:3], 'user','','passwd','','RemoteDrive', '', 'RemoteFolder','');

estimation(datafile=DYNARE_estimdata
                ,mode_compute = 6
                ,mh_jscale    = 0.30            
               ,presample    = 0
                ,prefilter    = 0
                ,prior_trunc  = 1e-14
                ,mh_replic    = 100000
                ,mh_nblocks   = 10
                ,mode_check
               ,lik_init     = 1
                ,order        = 1
                )                
                C I y r_cb r_b r_d pie b d J_B K_b;
              
              