%**************************************************************************
% Farms, Fertiliser, and Financial Frictions: Yields from a DSGE Model    * 
% Sébastien E.J. Walker (2014)                                            *
%**************************************************************************

%-----------------------------------------------------
% 0. Housekeeping
%-----------------------------------------------------

%This version is written for MATLAB 2013b and Dynare 4.4.2
%close all;
%digits(100)
%format long;

%-----------------------------------------------------
% 1. Define variables
% Endogenous (var) and exogenous (varexo)
%-----------------------------------------------------

var

A,a,B,Bf,Bh,C,Cf,Ch,Ch_star,e,i,
k,L,Lambda,lambda_cons,Gamma,geta_g,M,
m,m_star,N,
omega,P,Prh,pi,
r,rm,r_star,S,s,T,W,Y,Yh,z;
%TEST,D,Df,Dh,Omega_f,

varexo

eta_A,eta_a,eta_m_star,eta_r_star;

%-----------------------------------------------------
% 2. Define parameters and assign parameter values 
%-----------------------------------------------------

% *******************
% *Define parameters*
% *******************

parameters 

% Behavioural parameters 
beta,epsilon,
gamma,mu,mu_f,nu,phi,rho,
Sigma,S_M,tau,theta,varsigma,zeta,

% Constants
pi_,

% Fiscal and monetary parameters
gamma_pi,gamma_S,gamma_y,kappa,pi_Theta,S_Theta,Y_Theta,

% Initialisation values
A0,a0,Cf0,e0,L0,M0,m0,m_star0,N0,
P0,Prh0,pi0,W0,Y0,Yh0,

% Parameters/initialisation values for the financial accelerator
fail_Y,fail_Q,omega0,sigmasq_l,sigmasq,mean_n,sigma_omega,k0,Lambda0,Gamma0,
geta_g0,s0,z0,

% Derived Parameters
alpha_L,alpha_M,B0,Bf0,Bh0,C0,Ch0,Ch_star0,delta,i0,lambda_cons0,lambda_p,
Pwh0,r0,rm0,r_star0,T0,Y_star,

check1, check2, C_phi,

% Autoregressive parameters for structure of shocks
rho_A,rho_a,rho_m_star,rho_r_star,S0

;

% *************************
% *Assign parameter values*
% *************************

% Behavioural parameters 

beta    = 0.91;  % Discount factor, 0.91 from Adam et al. (2008) (discount rate = 0.1)
epsilon = 1.00;  % Relative-price sensitivity of foreign demand for domestic retail goods, 1 from GGN
gamma   = 0.75;  % Share of domestic retail goods in domestic consumption, 0.8 from below (Cf =0.2)
mu      = 1.20;  % Retailers' desired (actual in steady state) mark-up over wholesale prices, 1.2 from GGN
mu_f    = mu;    % Foreign retailers' desired mark-up over wholesale prices, 1.2 from GGN
nu      = 2.00;  % Inverse of intertemporal elasticity of substitution, 1/0.50 from Adam et al. (2008)
rho     = 0.50;  % Elasticity of substitution between domestic and foreign retail goods, 0.50 from Adam et al. (2008)
Sigma   = 0.50;  % Fertiliser/labour elasticity of substitution with 0 < Sigma < 1 [cf. agriculture]
tau     = 0.8;  % 'Monitoring cost' paid in case of farm bankruptcy, 0.12 from GGN [certainly higher in Kenya]
theta   = 0.25;  % Quarterly probability of price NOT changing (domestic firms), 0.75 from GGN [ANNUALISE?]
zeta    = 0.25;  % (1-zeta)= degree of inertia in export demand, with zeta in (0,1), 0.25 from GGN

% Constants

pi_     = 3.14159265358979;   % Pi

%  Fiscal and monetary policy parameters

gamma_pi = 1;  % Inflation weight in interest rate rule, 2.00 in GGN
gamma_y  = 1;  % Output weight in interest rate rule, 0.75 in GGN
gamma_S  = -1;  % Nominal exchange rate weight in interest rate rule
kappa    = 0.8;% Proportion of fertiliser cost NOT subsidised, so (1-kappa)=subsidy rate
pi_Theta = 0;  % Inflation target
S_Theta  = 1;  % Nominal exchange rate target

% Initialisation values

Cf0       = 0.20;     % SS consumption of foreign retail goods, [0.20 from Lozev - cf. Kenya data]
e0        = 1;        % Real exchange rate normalisation
L0        = 1/3;      % SS labour used
M0        = 2/3;      % SS fertiliser used
m0        = 1;        % Normalisation of domestic real fertiliser price
m_star0   = 1;        % Normalisation of foreign real fertiliser price
pi0       = pi_Theta; % SS inflation = inflation target
r_star0   = 0.04;     % SS foreign real interest rate, 0.04 from Buffie et al. (2012)
S0        = S_Theta;  % SS nominal exchange rate = exchange rate target
Y0        = 1;        % SS domestic real wholesale output
Yh0       = 1;        % SS domestic real retail output
C0        = 0.8*Y0;   % SS consumption 80% of initial real wholesale output [80% of GDP from data.worldbank.org]
Y_Theta   = Y0;       % Output target, [SS output in Lozev, but GGN target flex-price output - equivalent?]

%Parameters/initialisation values for the financial accelerator

%[I still need to check where some of these come from]

%fail_Y    = 0.086427384216111;  % Annual 'failure' rate [= NPL close to 8.6?]
fail_Y    = 0.144;               % Annual 'failure' rate (Kenya NPL 4.4% in 2011, WB website (higher before))
fail_Q    = 1-(1-fail_Y)^(1/4);  % Quarterly 'failure' rate [NOT NECESSARY IF PERIODS ARE YEARS] = normcdf(z0)
%sigmasq_l = 0.42432634083021^2; % [Lozev trying to calibrate this close to 0.39? (Bulg. thesis p. 28)]
sigmasq_l = 2.9^2;
sigmasq   = log(sigmasq_l+1);
mean_n    = -0.5*sigmasq;
sigma_omega = sqrt(sigmasq);
omega0    = logninv(fail_Q,mean_n,sigma_omega);
z0        = (log(omega0)+0.5*sigma_omega^2)/sigma_omega;
geta_g0   = (1-tau)*normcdf(z0-sigma_omega)+omega0*(1-normcdf(z0));
Gamma0    = normcdf(z0-sigma_omega)+omega0*(1-normcdf(z0));
Lambda0   = 1/(1-tau*omega0*lognpdf(omega0,mean_n,sigma_omega)/(1-fail_Q));
s0        = Lambda0/(1-Gamma0+Lambda0*geta_g0);
k0        = 1 + Lambda0*geta_g0/(1-Gamma0);

% Derived Parameters

Pwh0      = S0;
Prh0      = mu*Pwh0;                               % SS ... (desired mark-up achieved)
P0        = (gamma*Prh0^(1-rho)+(1-gamma)*(mu_f*S0)^(1-rho))^(1/(1-rho)); % SS domestic CPI
lambda_p  = (1-theta)*(1-beta*theta)/theta;        % Sensitivity of price of domestic retail goods to MC of production
r0        = 1/beta - 1;                            % SS domestic real interest rate
i0        = (1+pi0)/beta - 1;                      % SS domestic nominal interest rate
delta     = (Sigma-1)/Sigma;                       % Parameter related to fertiliser/labour elasticity of substitution 
rm0       = (1+i0)/(1+pi0)*s0 - 1;                 % SS `return on fertiliser'
syms x y;
[x, y]    = solve(x*((Y0/M0)^delta) == ((1/(kappa*m0))*(Pwh0/P0)*((y)^Sigma)*((Y0/M0)^(1/Sigma))/(1+rm0))^(-1), y == Y0/((x*((Y0/M0)^delta)*(M0^delta)+(1-x)*((Y0/L0)^delta)*(L0^delta))^(1/delta)) , x, y,'Real',true);
S_M       = x;                                     % Fertiliser share of national income
A0        = y;                                     % SS TFP
alpha_M   = S_M*((Y0/M0)^delta);                   % Fertiliser distribution parameter
alpha_L   = (1-S_M)*((Y0/L0)^delta);               % Labour distribution parameter
W0        = alpha_L*Pwh0*(A0^Sigma)*(Y0^(1/Sigma))*(L0^(-1/Sigma));  % SS real wage
varsigma  = ((1/C0)*(W0/P0))/((1/(1-L0)+(1/C0)*(W0/P0)));            % Preference for leisure vs. consumption
lambda_cons0 = (1-varsigma)*((C0^((nu-1)*(varsigma-1)-1)))*((1-L0)^(varsigma*(1-nu))); % Lagrange mult.: HH BC
N0        = (kappa*m0*M0)/k0;     % SS farm net worth
B0        = (kappa*m0*M0-N0)*P0;  % SS farmers' nominal borrowings/`bonds' sold
Bh0       = 0.5*B0;               % SS farmers' nominal bonds held by foreign investors (arbitrary assumption)
Bf0       = 0.5*B0;               % SS farmers' nominal bonds held by domestic investors (arbitrary assumption)
phi       = ((1+i0)/(1+pi0))/(1+r_star0)*(P0/Bf0)*Yh0; % Domestic country risk premium parameter
Ch0       = (P0*C0-(mu_f*S0)*Cf0)/Prh0;                % SS domestic consumption of domestic retail goods
%a0        =(e0*m_star0*M0+i0*Bf0/P0-Yh0+Ch0+Cf0)/e0;   % SS real net budgetary aid in foreign currency
a0=0.05;
T0        = (1-kappa)*e0*m_star0*M0 - e0*a0;           % Constant real lump-sum taxes
Ch_star0  = Yh0-Ch0-tau*normcdf(z0-sigma_omega)*(1+rm0)*m0*M0; % Foreign demand: dom. retail goods
Y_star    = Ch_star0;                                              % SS real foreign output
check1    = (kappa*m0*M0)/k0;
check2    = (1+rm0)*kappa*m0*M0-(1+i0)*B0/P0-tau*normcdf(z0-sigma_omega)*(1+rm0)*kappa*m0*M0;
C_phi     = check1-check2;        % Balancing term (farmers' consumption)

% Autoregressive parameters for structure of shocks

rho_A      = 0.95;                % Persistence of total factor productivity (weather), 0.95 from Lozev [cf. lit.]
rho_a      = 0.95;                % Persitence of real net budgetary aid in foreign currency, [cf. lit.]
rho_m_star = 0.95;                % Persistence of foreign real fertiliser price, [cf. lit.]
rho_r_star = 0.95;                % Persistence of foreign real interest rate, [cf. lit.]


%-----------------------------------------------------
% 3. Defining the model
%-----------------------------------------------------

model;

% Demand side

Yh = Y;                                                                             %(1) Output: retail = wholesale
Yh = Ch+Ch_star+tau*normcdf(z-sigma_omega)*(1+rm)*m(-1)*M(-1);                  %(2) Domestic resource constraint 
lambda_cons= (1-varsigma)*((C^((nu-1)*(varsigma-1)-1)))*((1-L)^(varsigma*(1-nu)));  %(3) Lagrange mult. on HH BC
lambda_cons= beta*lambda_cons(+1)*(1+i)*P/P(+1);                                    %(4) Euler equation
C       = ((gamma*Ch^(rho-1))^(1/rho)+((1-gamma)*Cf^(rho-1))^(1/rho))^(rho/(rho-1));%(5) Domestic consumption index
Ch/Cf   = (gamma/(1-gamma))*((Prh/(mu_f*S))^(-rho));                                %(6) FOC dom. goods vs. imports
P       = (gamma*Prh^(1-rho)+(1-gamma)*(mu_f*S)^(1-rho))^(1/(1-rho));               %(7) Domestic price level
Ch_star = (((((Prh/S)/mu_f)^(-epsilon)*Y_star))^zeta)*(((Ch_star(-1))^(1-zeta)));   %(8) Foreign demand: dom. retail goods
L       = (((alpha_L*S)/W)^Sigma)*(A^(Sigma^2))*Y;                                  %(9) Labour demand
(1+rm(+1))=(1/(kappa*m))*(S(+1)/P(+1))*alpha_M*(A(+1)^Sigma)*((Y(+1)/M)^(1/Sigma)); %(10)Fertiliser demand
%(1+rm)  = (1/(kappa*m(-1)))*(S/P)*alpha_M*(A^Sigma)*((Y/M(-1))^(1/Sigma));                                                             

% Supply side

Y                        = A*((alpha_M*((M(-1))^delta)+alpha_L*(L^delta))^(1/delta));%(11) Production function
(1-varsigma)*(1/C)*(W/P) = varsigma*(1/(1-L));                                       %(12) FOC labour supply
(1+rm(+1))               = s*(1+i)*P/P(+1);                                          %(13) Supply: external finance
%(1+rm)               = s(-1)*(1+i(-1))*P(-1)/P;

% Pricing, interest rates, and exchange rates

Prh/Prh(-1) = ((mu*S/Prh)^lambda_p)*((Prh(+1)/Prh)^beta); %(14) Domestic retail goods 'inflation'
e           = S*mu_f/Prh;                                 %(15) Real exchange rate (increase = domestic depreciation)

% Budget constraints and other identities
       
B/P = kappa*m*M-N;                                        %(16) Farmers' real borrowing
N       = (1+rm)*kappa*m(-1)*M(-1)-(1+i(-1))*B(-1)/P-tau*normcdf(z-sigma_omega)*(1+rm)*kappa*m(-1)*M(-1)+C_phi; %(17) Farm net worth
B       = Bh+Bf;                                          %(18) Nominal farm 'bonds'
%1+pi    = P/P(-1);                                        %(19) Definition: inflation
1+pi(+1)= P(+1)/P;                   
m       = e*m_star;                                       %(20) Domestic real fertiliser price
1+r     = (1+i(-1))*P(-1)/P;                              %(21) Definition: real interest rate
%1+r(+1)     = (1+i)*P/P(+1);

% Interest rate premium

z      = (log(omega)+0.5*sigma_omega^2)/sigma_omega;           %(22) `Standardised' idiosyncratic shock threshold
Lambda = 1/(1-tau*((exp((-(log(omega)-mean_n)^2)/(2*sigma_omega^2))/sqrt(2*pi_*sigma_omega^2))/(1-normcdf(z))));
           %(23) Lagrange mult. on lenders' constraint: expected return = opportunity cost
Gamma  = normcdf(z-sigma_omega)+omega*(1-normcdf(z));         %(24) Gross share of profits to lender [Lozev's `geta']
geta_g = (1-tau)*normcdf(z-sigma_omega)+omega*(1-normcdf(z)); %(25) Net share of profits to lender [Gamma-tau*G in GGN]
s      = Lambda/(1-Gamma+Lambda*geta_g);                      %(26) External finance premium
%s=s0;
k      = 1+Lambda*geta_g/(1-Gamma); %(27) Fertiliser expenditure per unit net worth [GGN'S k(omega bar), Lozev's psi]
k      = (kappa*m*M)/N;             %(28) Fertiliser expenditure per unit net worth [GGN'S k(omega bar), Lozev's psi]

% Government budget constraint

(1-kappa)*e*m_star*M = T+e*a;                                           %(29)

% Interest parity condition

(1+i)*P/P(+1)= (1+r_star(+1))*((e(+1)/e)^(gamma))*phi*((Bf(-1)/P)/Yh); %(30)

% Shocks

log(1+A)-log(1+A0)          = rho_A*(log(1+A(-1))-log(1+A0))-eta_A;         %(31) TFP (weather)
log(1+a)-log(1+a0)          = rho_a*(log(1+a(-1))-log(1+a0))+eta_a;         %(32) Real net budgetary aid, foreign currency
log(1+m_star)-log(1+m_star0)= rho_m_star*(log(1+m_star(-1))-log(1+m_star0))+eta_m_star;%(33) Foreign real fertiliser price
log(1+r_star)-log(1+r_star0)= rho_r_star*(log(1+r_star(-1))-log(1+r_star0))+eta_r_star;%(34) Foreign real interest rate 

% Policy rules

1+i = ((1+i0)/(1+pi0))*(((1+pi)/(1+pi_Theta))^gamma_pi)*((Yh/Y_Theta)^gamma_y)*((S/S_Theta)^gamma_S);%(35) 'Taylor' rule 

end;

%kappa = ...;                                                      % Fertiliser subsidy rule (if endog.)


%-----------------------------------------------------
% 4. Initialisation of endogenous variables
% - steady - allows approximate values to be included 
%-----------------------------------------------------

initval;

A           =  A0;
a           =  a0;
B           =  B0;
Bf          =  Bf0;
Bh          =  Bh0;
C           =  C0;
Cf          =  Cf0;
Ch          =  Ch0;
Ch_star     =  Ch_star0;
e           =  e0;
i           =  i0;  
k           =  k0;
L           =  L0;
Lambda      =  Lambda0;
lambda_cons	=  lambda_cons0;
Gamma       =  Gamma0;
geta_g      =  geta_g0;
M           =  M0;
m           =  m0;
m_star      =  m_star0;
N           =  N0;
omega       =  omega0;
P           =  P0;
Prh         =  Prh0;
pi          =  pi0;
r           =  r0;
rm          =  rm0;
r_star      =  r_star0;
S           =  S0;
s           =  s0;
T           =  T0;
W           =  W0;
Y           =  Y0;
Yh          =  Yh0;
z           =  z0;

end;

resid(1);
steady;
check;
%check(qz_zero_threshold =1e-15);
model_diagnostics;

%-----------------------------------------------------
% 5. Calibration of Shocks
%-----------------------------------------------------

shocks;
%var eta_A;      stderr 0.000000001;   %[Autocorrelated shock = drought? Trend = climate change?]
var eta_A;      stderr 0.01;

var eta_a;      stderr 0.000000001;
%var eta_a;      stderr 0.01;

var eta_m_star; stderr 0.000000001;
%var eta_m_star; stderr 0.01;

var eta_r_star; stderr 0.000000001;
%var eta_r_star; stderr 0.01;
end;

%-----------------------------------------------------
% 6. Simulation
% For stoch_simul:...
%-----------------------------------------------------

%resid(2);
set_dynare_seed(500);
stoch_simul(periods=1000, order=1,irf=16)
A Y pi P Prh S e m_star m M L
k N B Bf i r rm s r_star  
%a lambda_cons geta_g T Yh z Bh omega  W C Lambda Gamma omega
;

%stoch_simul(periods=1000, order=1,irf=16)
%A a B Bf Bh C Cf Ch Ch_star e i 
%k L Lambda lambda_cons Gamma geta_g M 
%m m_star N 
%omega P Prh pi 
%r rm r_star S s T W Y Yh z;




%close all;
//dynasave results_oibg2;