%% Code to calibrate parameters for aggregate economy model

clear; 
clc;
addpath('\Model\Tables\CompEcon2017\CEtools')

format short g

% Import data
pre_data=xlsread('\Inputs for model.xlsx','pre_main','d2:i13');
post_data=xlsread('\Inputs for model.xlsx','post_main','d2:i13');

% Create parametr saving object
params = zeros(2,12,2);

% Loop over pre and post period
for pre = 1:2

if pre == 1 
data = pre_data;
else
data=post_data;
end

% Loop over the various specficiations 1,2 are main versions in paper. 9 and 10 are superalsticity sample in Appendix B. 11 and 12 are time-varying model in Appendix B
for option = 1:12



% Put parameters into relevant places
   selast = data(option,1);
   concen =data(option,2); 
   Markuptarget = data(option,3);                      % our target for aggregate markup
   p.xi         = 3;          % Pareto tail productivity - starting point
   p.sigma      = 8.0084;          % demand elasticity: match level of markups  - starting point
    l_share = data(option,4);
    k_share = data(option,5);
m_share= data(option,6);

x            = [p.xi;   p.sigma];
 
lb           = [2;       4];  
ub           = [20;       20];
% OPtimise objective function with the relevant inputs
ftarget      = @(x) objective(x, Markuptarget, selast, concen ,l_share, k_share, m_share  );



options             = optimset('fminsearch');
options.Display     = 'iter';
options.TolX        = 1e-5;
options.MaxFunEvals = 200;
% OPtimise objective function with the relevant inputs
x                   = fminsearchbnd(ftarget, x, lb, ub, options);
 
% SAave outputs
params(:,option,pre) = x;
end
end

% export
writematrix(params(:,:,1), 'G:\Research\JonathanH\EMX 2022 Replication Package\out_full_pre.xlsx')
writematrix(params(:,:,2), 'G:\Research\JonathanH\EMX 2022 Replication Package\out_full_post.xlsx')
  