% CAPITAL CONTROL PROJECT
% Author: Muratori Umberto
% Modified: Javier Caicedo
% Date: June, 22nd 2015
%PURPOSE: CALCULATE CORRELATION BETWEEN GDP GROWTH RATES AND FIRST
%DIFFERENCE OVERALL INDEX

format long g

%data path from where to import data and find functions
BasePath=pwd;

global num_c vect_adv num_adv vect_mid num_mid vect_poor num_poor schindler_years Countries Years

switch variable
    
    case 1

%% DEFINITION OF PARAMETERS

%# of years of the Schindler Index
schindler_years=17;

%# of gdp series
num_grate=1;

%# num index series
num_index=3;

% Definition of country groups and # of member in each group (no less than 25 data points in GDP and no less than 17 in Schindler)
% The Definition comes from WEO 2013 which catergorized into 3 groups: Advanced/Emerging/Low-Income
vect_adv=[3 4 6 11 17 22 23 24 26 29 32 34 36 46 47 49 56 61 64 65 73 74];
num_adv=size(vect_adv,2);
vect_mid=[2 8 9 12 13 14 16 18 19 21 27 28 30 33 35 38 39 40 41 42 43 44 50 52 54 57 58 59 60 63 67 69 70 72 75 77];
num_mid=size(vect_mid,2);
vect_poor=[1 5 7 10 15 20 25 31 37 45 48 51 53 55 62 66 68 71 76 78];
num_poor=size(vect_poor,2);


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%IMPORT AND MANIPULATE GROWTH RATE DATA AND SCHINDLER INDEX%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%% Import data on GDP growth rate
if mac_user==1
[vardat,textdata, raw]=xlsread(strcat(BasePath, '\WDI_gdp.xls') ,char('wdi_growth')); 
else
[vardat,textdata, raw]=xlsread(strcat(BasePath, '/WDI_gdp.xls') ,char('wdi_growth'));     
end

%Definition of the time span
Years = raw(1,2:end);
num_years=size(Years,2);
%Names of countries in full sample
Countries = raw(2:end,1);

%# of countries in the full sample
Full_sample=size(vardat,1); 

%Creates a index with teh position of the first non NaN value for each cuntry
for i = 1:Full_sample;
idx_first(i,1) = find(sum(~isnan(vardat(i,:)),1) > 0, 1 ,'first');
end

%Eliminate from the sample the countries that have less than 25 yeasr observation
 period_cutoff=num_years-24;
 count=1;                                % Brief Description of the command:
 for i=1:Full_sample                     % for each country, if the nn NaN value
    if idx_first(i,1)<=period_cutoff     % starts before period 25, I keep the country
    vardat_1(count,:)=vardat(i,:);       % series and name and the # of NaN Observations.
    Countries_1(count,1)=Countries(i,1); % Rearrange all in matrices with new dimensions
    idx_first_1(count,1)=idx_first(i,1); % Finally, substitute the old vectors with
    count=count+1;                       % the new ones    
    end
 end
 clear vardat Countries idx_first
 vardat=vardat_1;
 Countries=Countries_1;
 idx_first=idx_first_1;
 clear vardat_1 Countries_1 idx_first_1

% %CHANGE MANUALLY!!!!!!!!!
% %ELIMINATE BAHRAIN because there are missing observation for the Schindler Index in 2007
vardat=[vardat(1:4,:); vardat(6:end,:)]; 
Countries=[Countries(1:4,:); Countries(6:end,:)];
idx_first=[idx_first(1:4,:); idx_first(6:end,:)];

%# of countries used in the research (full sample minus countries with less than 25 years)
num_c=size(vardat,1);

%Compute the growth rates only for the Schindler period
grate=vardat(:,end-16:end);

%Create vectors for growth rates divided by country groups
[grate_adv, grate_mid, grate_poor] = country_groups(num_grate, grate);

%Eliminate the first observations because we take the first difference in
%the index
grate=grate(:,2:end);
grate_adv=grate_adv(:,2:end);
grate_mid=grate_mid(:,2:end);
grate_poor=grate_poor(:,2:end);

%% Import data on Schindler Index
if mac_user==1
[vardat_2,textdata_2, raw_2]=xlsread(strcat(BasePath, '\FRU_dataset') ,char('index_paper'));
else
[vardat_2,textdata_2, raw_2]=xlsread(strcat(BasePath, '/FRU_dataset') ,char('index_paper'));    
end

%Import Schindler index data
index_data= vardat_2;

%Create matrix only with cumulative indexes (ka,kai, kao) and reshape the
%matrix
for i=1:Full_sample
     for j=1:schindler_years
         for k=1:num_index
             index_matrix(i,j,k) = vardat_2(j+(17*(i-1)), 1+k);
         end
     end
end

%CHANGE MANUALLY!!!!!!!!!
%ELIMINATE 12 COUNTRIES WITH LESS THAN 25 YEAR OBSERVATIONS FOR GDP AND THE BAHRAIN THAT HAS LESS THAN 17 OBSERVATION FOR INDEX
index_matrix=[index_matrix(1:4,:,:); index_matrix(6:10,:,:); index_matrix(12:18,:,:); index_matrix(20:26,:,:);index_matrix(28:32,:,:);index_matrix(34:41,:,:);index_matrix(43:45,:,:);
     index_matrix(48:52,:,:);index_matrix(54:66,:,:);index_matrix(69:70,:,:);index_matrix(72:89,:,:);index_matrix(91,:,:)];

%Calculate index first difference
for j=1:schindler_years-1
    index_diff(:,j,:)=index_matrix(:,j+1,:)-index_matrix(:,j,:);
end

%Create matrices for the first difference in the index divided by country groups
[index_diff_adv, index_diff_mid, index_diff_poor] = country_groups(num_index, index_diff);


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%IDENTIFY BOOM AND BUST AND DESCRIPITVE STATISTICS%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%Calculate standard deviations for each country
for i=1:num_c
    country_std(i,1)=nanstd(grate(i,:),0,2);
end

%Calculate mean for each country
for i=1:num_c
    country_mean(i,1)=nanmean(grate(i,:),2);
end

%Calculate the interval for each country
for i=1:num_c
    country_int(i,:)=[country_mean(i,1)-1.3*country_std(i,1), country_mean(i,1)+1.3*country_std(i,1)];
end

%Select boom/bust episodes for the growth rate (when growth rate is
%larger/smaller than 1.3 standard deviation
%BOOM
count_boom=1;
for i=1:num_c
    for j=1:schindler_years-1
        if grate(i,j)>country_int(i,2)
            boom_matrix(count_boom,:)=[i, j, nan, grate(i,j)];
            count_boom=count_boom+1;
        end
    end
end

num_boom=size(boom_matrix,1);

%BUST
count_bust=1;
for i=1:num_c
    for j=1:schindler_years-1
        if grate(i,j)<country_int(i,1)
            bust_matrix(count_bust,:)=[i, j, nan, grate(i,j)];
            count_bust=count_bust+1;
        end
    end
end

num_bust=size(bust_matrix,1);

%Eliminate episodes that are in consecutive years picking up ONLY the
%maximum of this time range
%BOOM
count_boom=1;
for i=1:num_boom-1
    %Case 1: Two consecutive years in same country
    if and(boom_matrix(i,1)==boom_matrix(i+1,1), boom_matrix(i,2)+1==boom_matrix(i+1,2))
       %Identify the maximum in the interval and the position of this value
       max_1 = max(boom_matrix(i:i+1,4));
           %Create new boom matrix
           if max_1==boom_matrix(i,1)
               boom_matrix_grate(count_boom,:)=boom_matrix(i,:);
               count_boom=count_boom+1;           
           elseif max_1==boom_matrix(i+1,1)
               boom_matrix_grate(count_boom,:)=boom_matrix(i+1,:);
               count_boom=count_boom+1;
           end
    %Case 2: No consecutive years in same country
    elseif and(boom_matrix(i,1)==boom_matrix(i+1,1), boom_matrix(i+1,2)>boom_matrix(i,2)+1)
       %Create new boom matrix
       boom_matrix_grate(count_boom,:)=boom_matrix(i,:);
       count_boom=count_boom+1;    
    %Case 3: No same country
    elseif boom_matrix(i,1)~=boom_matrix(i+1,1)
       %Create new boom matrix
       boom_matrix_grate(count_boom,:)=boom_matrix(i,:);
       count_boom=count_boom+1;
    end
end

num_boom_grate=size(boom_matrix_grate,1);

%BUST
count_bust=1;
for i=1:num_bust-1
    %Case 1: Two consecutive years in same country
    if and(bust_matrix(i,1)==bust_matrix(i+1,1), bust_matrix(i,2)+1==bust_matrix(i+1,2))
       %Identify the maximum in the interval and the position of this value
       max_2 = max(bust_matrix(i:i+1,4));
           %Create new bust matrix
           if max_2==bust_matrix(i,1)
               bust_matrix_grate(count_bust,:)=bust_matrix(i,:);
               count_bust=count_bust+1;           
           elseif max_2==bust_matrix(i+1,1)
               bust_matrix_grate(count_bust,:)=bust_matrix(i+1,:);
               count_bust=count_bust+1;
           end
    %Case 2: No consecutive years in same country
    elseif and(bust_matrix(i,1)==bust_matrix(i+1,1), bust_matrix(i+1,2)>bust_matrix(i,2)+1)
       %Create new bust matrix
       bust_matrix_grate(count_bust,:)=bust_matrix(i,:);
       count_bust=count_bust+1;    
    %Case 3: No same country
    elseif bust_matrix(i,1)~=bust_matrix(i+1,1)
       %Create new bust matrix
       bust_matrix_grate(count_bust,:)=bust_matrix(i,:);
       count_bust=count_bust+1;
    end
end

num_bust_grate=size(bust_matrix_grate,1);

%% Create average boom and bust values for t=-2/-1/0/+1/+2 (reference point the boom/bust)

%BOOM
%Calculate average, standard deviation and confidence interval
[average_boom_values_grate,~,~,~, boom_values_grate] = average_boom_bust_grate(num_grate, num_boom_grate, boom_matrix_grate, grate);

%BUST
%Calculate average, standard deviation and confidence interval
[average_bust_values_grate,~,~,~, bust_values_grate] = average_boom_bust_grate(num_grate, num_bust_grate, bust_matrix_grate, grate);

%% Create average detrended index and confidence interval for t=-2/-1/0/+1/+2 (refrence point the boom/bust)

%BOOM
%Calculate average, standard deviation and confidence interval
[average_index_diff_boom_grate, std_index_diff_boom_grate, upper_bound_boom_grate, lower_bound_boom_grate, index_diff_boom_grate] = average_boom_bust_grate(num_index, num_boom_grate, boom_matrix_grate, index_diff);

%BUST
%Calculate average, standard deviation and confidence interval
[average_index_diff_bust_grate, std_index_diff_bust_grate, upper_bound_bust_grate, lower_bound_bust_grate, large_index_diff_bust_grate] = average_boom_bust_grate(num_index, num_bust_grate, bust_matrix_grate, index_diff);

save case_GROWTH average_index_diff_boom_grate std_index_diff_boom_grate upper_bound_boom_grate lower_bound_boom_grate index_diff_boom_grate...
    average_index_diff_bust_grate std_index_diff_bust_grate upper_bound_bust_grate lower_bound_bust_grate large_index_diff_bust_grate...
    average_boom_values_grate boom_values_grate average_bust_values_grate bust_values_grate

    case 2
%% Make plots

load case_GROWTH

x=[-2 -1 0 1 2];
label_x=[-2 -1 0 +1 +2];
label_y = [-1 0 1];

figure(1)
% Inflows-Boom
subplot(2,2,1)
[haxes,hline1,hline2] = plotyy(average_index_diff_boom_grate(1,:,2), 'b', 100*average_boom_values_grate ,'r-*','plot');
set(haxes, 'xTickLabel','')
set(gca, 'XTick', 1:5, 'XTickLabel', label_x,'FontSize',10);
set(hline1,'LineWidth',2)
set(hline2,'LineWidth',2)
xlabel('Years');
set(haxes(1), 'yTickLabel','')
set(haxes(1), 'yLim',[roundTo(1.75*min(lower_bound_boom_grate(1,:,2)),2) roundTo(1.75*max(upper_bound_boom_grate(1,:,2)),2)])
set(haxes(1),'YTick',[roundTo(1.75*min(lower_bound_boom_grate(1,:,2)),2) 0 roundTo(1.75*max(upper_bound_boom_grate(1,:,2)),2)], 'YTickLabel',[roundTo(1.75*min(lower_bound_boom_grate(1,:,2)),2) 0 roundTo(1.75*max(upper_bound_boom_grate(1,:,2)),2)],'FontSize',10);
t=title('Inflows','FontWeight','bold');
set(t,'FontSize',10);
hold on
set(haxes(1),'Nextplot','add');
hline3=plot(lower_bound_boom_grate(1,:,2),'k-.');
hold on
set(haxes(1),'Nextplot','add');
plot(upper_bound_boom_grate(1,:,2),'k-.');
box off
hold off
%Inflow-Bust
subplot(2,2,3)
[haxes,hline1,hline2] = plotyy(average_index_diff_bust_grate(1,:,2), 'b', 100*average_bust_values_grate ,'r-*','plot');
set(haxes, 'xTickLabel','')
set(gca, 'XTick', 1:5, 'XTickLabel', label_x,'FontSize',10);
set(hline1,'LineWidth',2)
set(hline2,'LineWidth',2)
xlabel('Years');
set(haxes(1), 'yTickLabel','')
set(haxes(1), 'yLim',[roundTo(1.75*min(lower_bound_bust_grate(1,:,2)),2) roundTo(1.75*max(upper_bound_bust_grate(1,:,2)),2)])
set(haxes(1),'YTick',[roundTo(1.75*min(lower_bound_bust_grate(1,:,2)),2) 0 roundTo(1.75*max(upper_bound_bust_grate(1,:,2)),2)], 'YTickLabel', [roundTo(1.75*min(lower_bound_bust_grate(1,:,2)),2) 0 roundTo(1.75*max(upper_bound_bust_grate(1,:,2)),2)],'FontSize',10);
t=title('Inflows','FontWeight','bold');
set(t,'FontSize',10);
hold on
set(haxes(1),'Nextplot','add');
hline3=plot(lower_bound_bust_grate(1,:,2),'k-.');
hold on
set(haxes(1),'Nextplot','add');
plot(upper_bound_bust_grate(1,:,2),'k-.');
box off
hold off
% outflows-Boom
subplot(2,2,2)
[haxes,hline1,hline2] = plotyy(average_index_diff_boom_grate(1,:,3), 'b', 100*average_boom_values_grate ,'r-*','plot');
set(haxes, 'xTickLabel','')
set(gca, 'XTick', 1:5, 'XTickLabel', label_x,'FontSize',10);
set(hline1,'LineWidth',2)
set(hline2,'LineWidth',2)
xlabel('Years');
set(haxes(1), 'yTickLabel','')
set(haxes(1), 'yLim',[roundTo(1.75*min(lower_bound_boom_grate(1,:,3)),2) roundTo(1.75*max(upper_bound_boom_grate(1,:,3)),2)])
set(haxes(1),'YTick',[roundTo(1.75*min(lower_bound_boom_grate(1,:,3)),2) 0 roundTo(1.75*max(upper_bound_boom_grate(1,:,3)),2)], 'YTickLabel',[roundTo(1.75*min(lower_bound_boom_grate(1,:,3)),2) 0 roundTo(1.75*max(upper_bound_boom_grate(1,:,3)),2)],'FontSize',10);
t=title('Outflows','FontWeight','bold');
set(t,'FontSize',10);
hold on
set(haxes(1),'Nextplot','add');
hline3=plot(lower_bound_boom_grate(1,:,3),'k-.');
hold on
set(haxes(1),'Nextplot','add');
plot(upper_bound_boom_grate(1,:,3),'k-.');
box off
hold off
%Outflow-Bust
subplot(2,2,4)
[haxes,hline1,hline2] = plotyy(average_index_diff_bust_grate(1,:,3), 'b', 100*average_bust_values_grate ,'r-*','plot');
set(haxes, 'xTickLabel','')
set(gca, 'XTick', 1:5, 'XTickLabel', label_x,'FontSize',10);
set(hline1,'LineWidth',2)
set(hline2,'LineWidth',2)
xlabel('Years');
set(haxes(1), 'yTickLabel','')
set(haxes(1), 'yLim',[roundTo(1.75*min(lower_bound_bust_grate(1,:,3)),2) roundTo(1.75*max(upper_bound_bust_grate(1,:,3)),2)])
set(haxes(1),'YTick',[roundTo(1.75*min(lower_bound_bust_grate(1,:,3)),2) 0 roundTo(1.75*max(upper_bound_bust_grate(1,:,3)),2)], 'YTickLabel', [roundTo(1.75*min(lower_bound_bust_grate(1,:,3)),2) 0 roundTo(1.75*max(upper_bound_bust_grate(1,:,3)),2)],'FontSize',10);
t=title('Outflows','FontWeight','bold');
set(t,'FontSize',10);
hold on
set(haxes(1),'Nextplot','add');
hline3=plot(lower_bound_bust_grate(1,:,3),'k-.');
hold on
set(haxes(1),'Nextplot','add');
plot(upper_bound_bust_grate(1,:,3),'k-.');
box off
hold off
h=legend([hline1 hline2 hline3],'Average Index Difference (lhs)','Average Output Growth Rate (rhs)','Two Standard Deviation for the Index (lhs)');
set(h,'FontSize',8,'Position',[0.265494791666667 0.015 0.505729166666667 0.0285343709468223], 'Orientation', 'horizontal', 'Box','off');
ha = axes('Position',[0 0 1 1],'Xlim',[0 1],'Ylim',[0.1 1],'Box','off','Visible','off','Units','normalized', 'clipping' , 'off');
text(0.5, 1,'\bf Figure A.3. Boom-Bust Episodes and Capital Controls: Differences','Position',[0.508203125 0.978604294478528 9.16025403784439],'HorizontalAlignment','center')
sub_ha1 = axes('Visible','off','Position',[0 0 1 1]);
text('Parent',sub_ha1,'String','\bf (a) Boom','Position',[0.514453125 0.954180064308682 9.16025403784439],'HorizontalAlignment','center');
sub_ha2 = axes('Visible','off','Position',[0 0 1 1]);
text('Parent',sub_ha2,'String','\bf (b) Bust','Position',[0.516796875 0.526069518716578 9.16025403784439],'HorizontalAlignment','center');

end