
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   This file solves the reserve wars model of Fanelli Straub (2021)  %
%     " A Theory of Foreign Exchange Interventions "                  %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

clear all
close all

% header
width = '3in';
height = '2in';
scale  = 0.8; % slides: 0.65. Paper: 0.8
suffix = '_paper'; % change to '' for slides!
globalstyle = 'very thick';

% paths
H.root_path = '';
H.path_tikz = [H.root_path 'tikz/'];
H.compile_pdf_folder     = 'tikz_pdfs/';
H.compile_pdf_tikzfolder = 'tikz/';
H.pdflatexpath = '/usr/local/texlive/2018/bin/x86_64-darwin'; % location of pdflatex
fprintf(['\n\n *** NOTE *** \n Location of pdflatex set to: ' H.pdflatexpath '\n If this location is incorrect the tikz and pdf production will fail.\n Please set write_tikz and compile_pdf to 0 or adjust pdflatexpath.\n'])

% Set these two options to 1 to produce tikz files and pdfs
%  NOTE: this *only* works if above path 'pdflatexpath' was set to the
%  location of pdflatex! Otherwise, choose these to be 0
compile_pdf = 1;
write_tikz  = 1;


%% Parameters

%%% General Parameters
P.beta_EME = 0.90;
P.beta_AE  = 0.90;
P.mass_EME = 0.99999;  % no advanced economies. symmetric EMEs!
P.mass_AE  = 1-P.mass_EME;
P.nfa0     = 0;        % average nfa of EMEs (per EME)

% AE specifics [NOT USED, AEs are assumed away]
P.Y0       = 1;
P.Y1       = 1;
P.Sigma    = 1; % inverse EIS

% EME specifics
P.alpha    = 0.051148; % share of tradables in consumption ( 1-home bias )
P.mu       = 0.2;   % share hand to mouth
chi        = 0.078; % share of T and NT endowments owned by the poor
P.gamma_T  = chi;   % share of T income earned by poor
P.gamma_NT = chi;   % share of NT income earned by poor
P.yT       = 0.234;  % total T endowment
P.yNT      = 1;     % total NT endowment (only important for the price)
P.yT_decline = 1;   % factor at which yT declines from first to second period
P.c_lbar   = 0.19271;  % per capita subsistence consumption
P.sigma    = 1;     % inverse EIS

% intermediaries
P.Gamma = 9; P.Gamma_H = 3; P.mass = 0; P.mass_H = 0.02;


%% Compute everything
PP = P;

% vary these parameters / shocks
PP.yT_decline = 0.93; PP.Y1 = PP.yT_decline;  % shock
parlist = linspace(0.1,200,100); parfields ={'Gamma'};  % vary Gamma

% plot properties
field_options = struct(...
            'rstar',struct('title','World interest rate',...
                           'stepsize',1,...
                           'yaxis_percent',1),...
            'tau',struct('title','Interest rate spread',...
                           'stepsize',1,...
                           'yaxis_percent',1),...
            'V_EME',struct('title','Average welfare of countries',...
                           'stepsize',10,...
                           'yaxis_percent',0,...
                           'normalize','bla',...% normalizes data w.r.t to first number (just difference) in tikz. Important for tikz
                           'scale',1e5),...  % scale the data for tikz
            'V_AE',struct('title','Intermediary welfare',...
                           'stepsize',1,...
                           'yaxis_percent',0),...
            'reserves_GDP',struct('title','World reserves / world GDP',...
                           'stepsize',1,...
                           'yaxis_percent',1),...
            'priv_flows_GDP',struct('title','Private capital inflows',...
                           'stepsize',1,...
                           'yaxis_percent',1) ...
            );
xaxis = {0, 200}; xtick = {0,100,200};
plot_fields= fields(field_options);
n_plots     = length(plot_fields);

RAWDATA  = cell(1,length(plot_fields));
DATA  = cell(1,length(plot_fields));
data_tikz = cell(1,length(plot_fields));

i = 0;
for par = parlist
    i = i+1;
    for k = 1:length(parfields)
        PP.(parfields{k}) = par;
        P.Gamma_H = 0.2*par;
    end
    
    % 1. exog tau
    PP.mode = 'exog_tau';
    PP.tau  = 0;
    PP_list{1} = compute_reserve_wars(PP);
    
    % 2. Nash
    PP.mode = 'Nash';
    PP_list{2} = compute_reserve_wars(PP);

    % Store
    no_lines = length(PP_list);
    for f = 1:n_plots
        cur_field = plot_fields{f};
        for j=1:no_lines
            value = PP_list{j}.(cur_field);
            RAWDATA{f}(j,i) = value;
            
            % possibly normalize:
            if isfield(field_options.(plot_fields{f}),'normalize') && i == 1
                value = 0;
            elseif isfield(field_options.(plot_fields{f}),'normalize') && i > 1
                value = value - RAWDATA{f}(j,1);
            end
            
            % and scale
            if isfield(field_options.(plot_fields{f}),'scale')
                value = value * field_options.(plot_fields{f}).scale;
            end
            
            % write into data
            DATA{f}(j,i) = value;
            data_tikz{f}{j}(i,1) = parlist(i); %= {data_tikz{f}{:},[parlist',DATA{f}(j,:)']};
            data_tikz{f}{j}(i,2) = value*(1+99*field_options.(plot_fields{f}).yaxis_percent);
        end
    end
    
end


% plot
figure(1)
n = ceil(sqrt(n_plots));
m = ceil(n_plots/n);
for f = 1:length(plot_fields)
    subplot(n,m,f)
    plot(parlist,DATA{f})
    title(plot_fields{f});
    
    % read out stuff from the plot
    % 1: Y ticks
    cur_ytick = get(gca,'YTick');
    if field_options.(plot_fields{f}).stepsize == 0
        field_options.(plot_fields{f}).stepsize = (cur_ytick(2) - cur_ytick(1))*(1+99*field_options.(plot_fields{f}).yaxis_percent);
    end
    % 2: YLim
    field_options.(plot_fields{f}).yaxis = get(gca,'YLim')*(1+99*field_options.(plot_fields{f}).yaxis_percent);
end
legend('tau_0','Nash','Coord')


% write to tikz
if write_tikz == 1
                    
    for f = 1:length(plot_fields)
        field = plot_fields{f};
  
        O        = struct;
        O.scale  = scale;
        O.data   = data_tikz{f};
        O.plot_name = ['world' suffix '_' field];
        O.xaxis  = xaxis;
        O.yaxis  = num2cell(field_options.(field).yaxis(:)');
        O.title  = field_options.(field).title;
        O.colors = {'red','green'};
        O.styles = {'',''};
        O.legend = {'No interventions','Individually optimal interventions'};
        O.legend_cols = 2; % max 2 legend columns
        O.xlabel = 'financial friction $\\Gamma$';
        O.globalstyle = 'line width = 1pt';
        O.width  = width;
        O.height = height;
        % O.width_off  = 1;
        % O.height_off = 1;
        O.yaxis_percent = field_options.(field).yaxis_percent;
        O.xtick = xtick;
        O.ytick = create_ticks(O.yaxis{1},O.yaxis{2},field_options.(field).stepsize,true);
        O.compile_pdf    = compile_pdf; 
        O.compile_pdf_folder = H.compile_pdf_folder;
        O.compile_pdf_paperpath = H.root_path;
        O.compile_pdf_tikzfolder = H.compile_pdf_tikzfolder;

        write_tikz_file(O, H.path_tikz);
    end
end

