% CAPITAL CONTROL PROJECT
% Author: Muratori Umberto
% Date: August, 17th 2013
% Email: umbertom@iadb.org

%PURPOSE: CALCULATE BOOM AND BUST AND CONSTRUCT CHARTS AND TABLES FOR THE
%CHINN-ITO INDEX

format long g

%list of tasks made in the code:
% TASK 1= IMPORT AND MANIPULATE GDP DATA
% TASK 2= QUADRATIC DETREND, PLOTS AND DESCRIPTIVE STATISTICS FOR GDP
% TASK 3= IMPORT, MANIPULATE AND LINEAR DETREND AND BAR PLOT FOR CHINN-ITO INDEX
% TASK 4= CALCULATE CORRELATION BETWEEN OUTPUT GAP AND INDEX, METHOD 1: STACKED MATRIX
% TASK 5= IDENTIFY BOOM/BUST EPISODES
% TASK 6= BOOM/BUST AND DETRENDED INDEX
% TASK 7= ONLINE APPENDIX FIGURE 9.A.1, 9.A.2
% TASK 8= ONLINE APPENDIX FIGURE A.7


%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

%% DEFINITION OF PARAMETERS

%# of years of the Schindler Index and Chinn-Ito Index
schindler_years=17;

%# of main indexes
num_index=1;

%# of gdp series
num_gdp=1;

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

switch variable
    
    case 1

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%IMPORT AND MANIPULATE GDP DATA%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%% Import data on GDP
if mac_user==1
[vardat,textdata, raw]=xlsread(strcat(BasePath, '\WDI_gdp.xls') ,char('Sheet1')); 
else
[vardat,textdata, raw]=xlsread(strcat(BasePath, '/WDI_gdp.xls') ,char('Sheet1'));     
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 idx_first Countries
 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 and SWITZERLAND and BRUNEI because it doesn't have data on
% Chinn for 1995-2011
vardat=[vardat(1:4,:); vardat(6:9,:); vardat(11:65,:); vardat(67:76,:); vardat(78:end,:)]; 
Countries=[Countries(1:4,:); Countries(6:9,:); Countries(11:65,:); Countries(67:76,:); Countries(78:end,:)];
idx_first=[idx_first(1:4,:); idx_first(6:9,:); idx_first(11:65,:); idx_first(67:76,:); idx_first(78:end,:)];

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

%Effective # of valid observations for each country
for i = 1:num_c;
    lenght(i,1) = size((vardat(2,:)),2)- idx_first(i,1) +1;
end

%Calculate Log of GDP
log_GDP = log(vardat);

save  case_CHINN1 log_GDP lenght Countries idx_first num_c Years Full_sample

    case 2
        
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%QUADRATIC TREND FOR GDP AND PLOTS%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
load case_CHINN1

%% Quadratic Trend and Plot output gap and quadratic trend

% To make the plots unocmment the part of script in the function
% quadratic_trend
ylabel={'Log of GDP (thousand of lcu)'};

[xt] = quadratic_trend(lenght, idx_first, log_GDP, ylabel);

%Create matrices for the output gap divided by country groups
[xt_adv, xt_mid, xt_poor] = country_groups(num_gdp, xt);

save case_CHINN2 xt xt_adv xt_mid xt_poor

    case 3

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%IMPORT AND MANIPULATE SCHINDLER INDEX%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
load case_CHINN1
load case_CHINN2
load Result_QUINN3
load case_aux_QUINN3

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

%Import Schindler index data
index_matrix= vardat_2(2:end,:);

%Define years for the Chinn-Ito index
chinn_years_list=(1995:1:2011);

%CHANGE MANUALLY!!!!!!!!!
%ELIMINATE COUNTRIES WITH LESS THAN 25 YEAR OBSERVATIONS FOR GDP AND THE
%BAHRAIN THAT HAS LESS THAN 17 OBSERVATION FOR INDEX AND SWITZERLAND
index_matrix=[index_matrix(1:4,:,:); index_matrix(6:9,:,:); 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:76,:,:);index_matrix(78:87,:,:);index_matrix(89,:,:);index_matrix(91,:,:)];

%Create matrices for the index divided by country groups
[index_adv, index_mid, index_poor] = country_groups(num_index, index_matrix);

%Create auxiliary matrices for the plots
index_matrix_aux=index_matrix(:,end-16:end);
index_adv_aux=index_adv(:,end-16:end);
index_mid_aux=index_mid(:,end-16:end);
index_poor_aux=index_poor(:,end-16:end);

%Calculate the average index for each year over all countries
for i=1:schindler_years
    year_chinn_mean(i,1)= nanmean(index_matrix_aux(1:num_c,i)); 
    year_chinn_adv_mean(i,1)=nanmean(index_adv_aux(1:num_adv,i));
    year_chinn_mid_mean(i,1)=nanmean(index_mid_aux(1:num_mid,i));
    year_chinn_poor_mean(i,1)=nanmean(index_poor_aux(1:num_poor,i));
end

%Calculate the average index for each country over all years
for i=1:num_c
    country_mean_index(i,1) = nanmean(index_matrix_aux(i,:,1));

end

%Calculate the standard deviation across countries in each year
std_chinn_country = nanstd(index_matrix_aux(:,:),0,1)';

%Compute interval for the standard deviation around the average of the overall index
interval_std_chinn=[year_chinn_mean(:,1)-std_chinn_country, year_chinn_mean(:,1)+std_chinn_country];

%Add nan to the quinn averages and interval
year_quinn_mean=[year_quinn_mean; nan; nan; nan; nan];
year_quinn_adv_mean=[year_quinn_adv_mean; nan; nan; nan; nan];
year_quinn_mid_mean=[year_quinn_mid_mean; nan; nan; nan; nan];
year_quinn_poor_mean=[year_quinn_poor_mean; nan; nan; nan; nan];
interval_std_quinn=[interval_std_quinn(:,1) interval_std_quinn(:,2); nan nan; nan nan; nan nan; nan nan];

%Plot the time serie of the average over all countries for the chinn-ito
%and quinn index and the standard deviation interval
figure(1)
subplot(2,1,1)
plot(year_chinn_mean(:,1),'-*r');
set(gca, 'XTick', 1:schindler_years, 'XTickLabel', chinn_years_list,'FontSize',8);
xlabel('Years');
t=title('(a) Chinn-Ito Index: 1995-2011','FontWeight','bold');
set(t,'FontSize',10);
hold on
plot(interval_std_chinn(:,1),'--b');
hold on
plot(interval_std_chinn(:,2),'--b');
box off
hold off
subplot(2,1,2)
plot(year_quinn_mean(:,1),'-*r');
set(gca, 'XTick', 1:schindler_years, 'XTickLabel', chinn_years_list,'FontSize',8);
xlabel('Years');
t=title('(b) Quinn Index: 1995-2007','FontWeight','bold');
set(t,'FontSize',10);
hold on
plot(interval_std_quinn(:,1),'--b');
hold on
plot(interval_std_quinn(:,2),'--b');
box off
hold on
hold off
legend1 = legend('Average Index', 'Confidence Interval, one standard deviation');
set(legend1,'Orientation','horizontal','Position',[0.360807291666667 0.0177845528455285 0.336979166666667 0.0274390243902439],'FontSize',8, '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.18. Alternative Indexes','Position',[0.508203125 0.978604294478528 9.16025403784439],'HorizontalAlignment','center','FontSize',10)


%Plot the time serie of the average by countriy groups for the chinn-ito
%and quinn index and the standard deviation interval
figure(2)
subplot(2,1,1)
plot(year_chinn_adv_mean(:,1),'r')
set(gca, 'XTick', 1:schindler_years, 'XTickLabel', chinn_years_list,'FontSize',8);
xlabel('Years');
t=title('(a) Chinn-Ito Index: 1995-2011','FontWeight','bold');
set(t,'FontSize',10);
hold on
plot(year_chinn_mid_mean(:,1),'b')
hold on
plot(year_chinn_poor_mean(:,1),'c')
box off
hold off
subplot(2,1,2)
plot(year_quinn_adv_mean(:,1),'r')
set(gca, 'XTick', 1:schindler_years, 'XTickLabel', chinn_years_list,'FontSize',8);
xlabel('Years');
t=title('(b) Quinn Index: 1995-2007','FontWeight','bold');
set(t,'FontSize',10);
hold on
plot(year_quinn_mid_mean(:,1),'b')
hold on
plot(year_quinn_poor_mean(:,1),'c')
box off
hold off
legend1 = legend('Advanced Economies', 'Emerging Markets', 'Low-Income Countries');
set(legend1,'Orientation','horizontal','Position',[0.360807291666667 0.0177845528455285 0.336979166666667 0.0274390243902439],'FontSize',8,'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.19. Alternative Indexes by Country Group','Position',[0.508203125 0.978604294478528 9.16025403784439],'HorizontalAlignment','center','FontSize',10)


%% Linear Detrend Chinn-Ito Index

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

%Effective # of valid observations for each country
for i = 1:num_c
    lenght_ind(i,1) = size((index_matrix(2,:)),2)- idx_first_ind(i,1) +1;
end

%Linear Detrend of the Chinn-Ito Index
for i=1:num_c

    %Construct a Matrix Counter with # of valid observations
     for j=1:lenght_ind(i,1);
         t(i,j) = j; 
     end

    %Construct matrix of independent regressors
        %First column: vector of ones
        %Second column: corresponding vector of t
    X= [ones(lenght_ind(i,1),1) t(i,1:lenght_ind(i,1))'];

    %Calculate the beta coefficient
    B = X\index_matrix(i,idx_first_ind(i,1):end)';


    %Calculate Quadratic trend
    Th= X*B;

    %Calculate the deviations from the quadratic trend over last 17
    %observations
    indext(i,:) = index_matrix(i,end-16:end) - Th(end-16:end,1)';
end

%Create vector with detrended index for the different inocme groups
[indext_adv, indext_mid, indext_poor] = country_groups(num_index, indext);

%% Calculate descriptive statistics for the Chinn-Ito index

%Calculate volatility(standard deviation) and persistency(correlation between t and t-1)of the index
%for each country over the period of study
[stats_index_std, stats_index_corr] = des_statistics(num_c, num_index, indext);

%Create vector with standard deviation for the different inocme groups
[stats_index_std_adv, stats_index_std_mid, stats_index_std_poor] = country_groups(1, stats_index_std);

%Create vector with autocorrelation for the different income groups
[stats_index_corr_adv, stats_index_corr_mid, stats_index_corr_poor] = country_groups(1, stats_index_corr);

%Create matrix with descriptive statistics for detrended chinn-ito index
    %First column: Stadard deviation
    %Second Column: Autocorrelation
index_chinn_des_stats=[nanmean(stats_index_std(:,1)) nanmean(stats_index_corr(:,1))
    nanmean(stats_index_std_adv(:,1)) nanmean(stats_index_corr_adv(:,1))
    nanmean(stats_index_std_mid(:,1)) nanmean(stats_index_corr_mid(:,1))
    nanmean(stats_index_std_poor(:,1)) nanmean(stats_index_corr_poor(:,1))]';

%Report only two decimals
index_chinn_des_stats=roundTo(index_chinn_des_stats,2);

%% Make tables for the descriptive statistics of the indexes

%Define labels for descriptive statistics table
Labels_v = {'Standard Deviation'; 'Autocorrelation'};
Labels_h = {'','Total', 'Advanced Economies', 'Emerging Markets', 'Low-Income Countries'};
empty_vector={'','','','',''};

%Create subtitle vectors
title_chinn_quinn_des={'Table A.10. Alternative Indexes: Descriptive Statistics','','','',''};
subtitle_chinn_des_stats={'(b) Chinn-Ito Index', '','','',''};

%Create tables for descriptive statistics of the overall index
index_chinn_des_stats1 = num2cell(index_chinn_des_stats);
table_index_chinn_des_stats = [subtitle_chinn_des_stats; Labels_v, index_chinn_des_stats1];

Table_chinn_quinn_des_stats=[title_chinn_quinn_des;Labels_h; table_index_chinn_des_stats; empty_vector; table_index_quinn_des_stats];

%% Calculate correlations between output gap and index for t=0 and make plots

%Calculate correlation and pvalues when output gap t=0 and index t=0
[r, p] = country_correlation(num_index, xt, indext);

%Sort them and associate stars to the country name
[corr_matrix_sort, legend_matrix_star, star_matrix, legend_matrix] = star_zero(num_index, r, p);

%Create vector for chinn Index correlation
corr_chinn_sort=corr_matrix_sort(:,:);
legend_chinn_star= legend_matrix_star(:,:);

%Create a bar chart for the CHINN CORRELATIONS with bars with different colors
%for different significance levels
figure(3)
b_ov=barh(corr_chinn_sort(:,2));
set(gca, 'YDir', 'reverse')
set(gca, 'YTick', 1:num_c, 'YTickLabel', legend_chinn_star,'FontSize',6,'FontWeight','bold');
set(gca,'XLim',[-1 1])
t=title('Figure A.20. Country Correlations: Output and the Chinn-Ito Index','FontWeight','bold');
set(t, 'Visible', 'on','Fontsize', 10);
bar_child_chinn=get(b_ov,'Children');
set(bar_child_chinn,'CData', corr_chinn_sort(:,2));
%Vector of colors for bars: ***blue, **green, white
mycolor=[0 0 1; 0 1 0; 1 1 1];
for iCount_chinn=1:num_c
    if (corr_chinn_sort(iCount_chinn,3)<.01)
        index_chinn(iCount_chinn)=1;
    elseif and(corr_chinn_sort(iCount_chinn,3)>.01, corr_chinn_sort(iCount_chinn,3)<.05)
        index_chinn(iCount_chinn)=2;
    else
        index_chinn(iCount_chinn)=3;
    end
end
set(bar_child_chinn, 'CData',index_chinn);
colormap(mycolor);
box off


save case_CHINN3 indext indext_adv indext_mid indext_poor index_matrix index_adv index_mid index_poor
save Result_CHINN3 Table_chinn_quinn_des_stats

    case 4

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%CALCULATE CORRELATION BETWEEN OUTPUT GAP AND INDEX, METHOD 1: STACKED MATRIX%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
load case_CHINN1
load case_CHINN2
load case_CHINN3    
load Result_QUINN4

%Create a vector of aggregated index (overall, inflow and outflow)
for k=1:num_index
    for j=1:schindler_years
        for i=1:num_c
            aggregate_indext_matrix(j+schindler_years*(i-1),k)=indext(i,j,k);
        end
    end
end

%Create a vector of aggregated ouput gap
for j=1:schindler_years
    for i=1:num_c
        aggregate_xt(j+schindler_years*(i-1),1)=xt(i,j,1);
    end
end

%Calculate correlation for aggregated matrices   
[r_agg_matrix, p_agg_matrix, star_agg_matrix] = aggregate_correlation(num_index, aggregate_xt, aggregate_indext_matrix);

%Concatenate values and stars
r_agg_chinn=num2str(r_agg_matrix(:,1));
r_agg_chinn=strcat(r_agg_chinn,star_agg_matrix(:,1));

%% Aggregate data for income groups at time t=0

%Create country groups for detrended index
[aggregate_indext_matrix_adv, aggregate_indext_matrix_mid, aggregate_indext_matrix_poor]=aggregate_group(num_index, indext_adv, indext_mid, indext_poor);

%Create country groups for output gap
[aggregate_xt_adv, aggregate_xt_mid, aggregate_xt_poor]=aggregate_group(num_gdp, xt_adv, xt_mid, xt_poor);

%% Calculate correlations divided by income groups at time t=0

%Calculate correlation for aggregated matrices: ADVANCED COUNTRIES
[r_agg_matrix_adv, p_agg_matrix_adv, star_agg_matrix_adv] = aggregate_correlation(num_index, aggregate_xt_adv, aggregate_indext_matrix_adv);

%Concatenate values and stars
r_agg_chinn_adv=num2str(r_agg_matrix_adv(:,1));
r_agg_chinn_adv=strcat(r_agg_chinn_adv,star_agg_matrix_adv(:,1));

%Calculate correlation for aggregated matrices: MIDDLE INCOME COUNTRIES
[r_agg_matrix_mid, p_agg_matrix_mid, star_agg_matrix_mid] = aggregate_correlation(num_index, aggregate_xt_mid, aggregate_indext_matrix_mid);
 
%Concatenate values and stars
r_agg_chinn_mid=num2str(r_agg_matrix_mid(:,1));
r_agg_chinn_mid=strcat(r_agg_chinn_mid,star_agg_matrix_mid(:,1));

%Calculate correlation for aggregated matrices: POOR COUNTRIES
[r_agg_matrix_poor, p_agg_matrix_poor, star_agg_matrix_poor] = aggregate_correlation(num_index, aggregate_xt_poor, aggregate_indext_matrix_poor);

%Concatenate values and stars
r_agg_chinn_poor=num2str(r_agg_matrix_poor(:,1));
r_agg_chinn_poor=strcat(r_agg_chinn_poor,star_agg_matrix_poor(:,1));

%% Aggregate data for output gap and index for calculating the lag and lead correlations

%LAG INDEX
%Create a vector of aggregated index (overall, inflow and outflow) with
%index t=-1
for k=1:num_index
    for j=1:schindler_years-1
        for i=1:num_c
            aggregate_indext_aux1(j+(schindler_years-1)*(i-1),k)=indext(i,j,k);
        end
    end
end

%Create a vector of aggregated ouput gap for index t=-1
for j=2:schindler_years
    for i=1:num_c
        aggregate_xt_aux1(j-1+(schindler_years-1)*(i-1),1)=xt(i,j);
    end
end

%LEAD INDEX
%Create a vector of aggregated index (overall, inflow and outflow) with
%index t=-1
for k=1:num_index
    for j=2:schindler_years
        for i=1:num_c
            aggregate_indext_aux2(j-1+(schindler_years-1)*(i-1),k)=indext(i,j,k);
        end
    end
end

%Create a vector of aggregated ouput gap for index t=-1
for j=1:schindler_years-1
    for i=1:num_c
        aggregate_xt_aux2(j+(schindler_years-1)*(i-1),1)=xt(i,j);
    end
end

%% Calculate correlations for index t=-1

%Calculate correlation for aggregated matrices
[r_agg_minus1_matrix, p_agg_minus1_matrix, star_agg_minus1_matrix] = aggregate_correlation(num_index, aggregate_xt_aux1, aggregate_indext_aux1);

%Concatenate values and stars
r_agg_minus1_chinn=num2str(r_agg_minus1_matrix(:,1));
r_agg_minus1_chinn=strcat(r_agg_minus1_chinn,star_agg_minus1_matrix(:,1));

%% Calculate correlations for index t=+1

%Calculate correlation for aggregated matrices
[r_agg_plus1_matrix, p_agg_plus1_matrix, star_agg_plus1_matrix] = aggregate_correlation(num_index, aggregate_xt_aux2, aggregate_indext_aux2);
 
%Concatenate values and stars
r_agg_plus1_chinn=num2str(r_agg_plus1_matrix(:,1));
r_agg_plus1_chinn=strcat(r_agg_plus1_chinn,star_agg_plus1_matrix(:,1));

%% Aggregate data for output gap and index for calculating the lag and lead correlations divided by groups

%LAG INDEX
%Create country groups for detrended index and output gap
[aggregate_indext_aux1_adv, aggregate_indext_aux1_mid, aggregate_indext_aux1_poor, aggregate_xt_aux1_adv, aggregate_xt_aux1_mid, aggregate_xt_aux1_poor] = aggregate_group_one(num_index, num_gdp, indext_adv, indext_mid, indext_poor, xt_adv, xt_mid, xt_poor);

%LEAD INDEX
%Create country groups for detrended index and output gap
[aggregate_xt_aux2_adv, aggregate_xt_aux2_mid, aggregate_xt_aux2_poor, aggregate_indext_aux2_adv, aggregate_indext_aux2_mid, aggregate_indext_aux2_poor] = aggregate_group_one(num_gdp, num_index, xt_adv, xt_mid, xt_poor, indext_adv, indext_mid, indext_poor);

%% Calculate correlations for index t=-1 divided by income group

%Calculate correlation for aggregated matrices: ADVANCED COUNTRIES
[r_agg_minus1_matrix_adv, p_agg_minus1_matrix_adv, star_agg_minus1_matrix_adv] = aggregate_correlation(num_index, aggregate_xt_aux1_adv, aggregate_indext_aux1_adv);

%Concatenate values and stars
r_agg_minus1_adv_chinn=num2str(r_agg_minus1_matrix_adv(:,1));
r_agg_minus1_adv_chinn=strcat(r_agg_minus1_adv_chinn,star_agg_minus1_matrix_adv(:,1));

%Calculate correlation for aggregated matrices: MIDDLE COUNTRIES
[r_agg_minus1_matrix_mid, p_agg_minus1_matrix_mid, star_agg_minus1_matrix_mid] = aggregate_correlation(num_index, aggregate_xt_aux1_mid, aggregate_indext_aux1_mid);
 
%Concatenate values and stars
r_agg_minus1_mid_chinn=num2str(r_agg_minus1_matrix_mid(:,1));
r_agg_minus1_mid_chinn=strcat(r_agg_minus1_mid_chinn,star_agg_minus1_matrix_mid(:,1));

%Calculate correlation for aggregated matrices: POOR COUNTRIES
[r_agg_minus1_matrix_poor, p_agg_minus1_matrix_poor, star_agg_minus1_matrix_poor] = aggregate_correlation(num_index, aggregate_xt_aux1_poor, aggregate_indext_aux1_poor);
 
%Concatenate values and stars
r_agg_minus1_poor_chinn=num2str(r_agg_minus1_matrix_poor(:,1));
r_agg_minus1_poor_chinn=strcat(r_agg_minus1_poor_chinn,star_agg_minus1_matrix_poor(:,1));

%% Calculate correlations for index t=1 divided by income group
 
%Calculate correlation for aggregated matrices: ADVANCED COUNTRIES
[r_agg_plus1_matrix_adv, p_agg_plus1_matrix_adv, star_agg_plus1_matrix_adv] = aggregate_correlation(num_index, aggregate_xt_aux2_adv, aggregate_indext_aux2_adv);
 
%Concatenate values and stars
r_agg_plus1_adv_chinn=num2str(r_agg_plus1_matrix_adv(:,1));
r_agg_plus1_adv_chinn=strcat(r_agg_plus1_adv_chinn,star_agg_plus1_matrix_adv(:,1));

%Calculate correlation for aggregated matrices: MIDDLE COUNTRIES
[r_agg_plus1_matrix_mid, p_agg_plus1_matrix_mid, star_agg_plus1_matrix_mid] = aggregate_correlation(num_index, aggregate_xt_aux2_mid, aggregate_indext_aux2_mid);
 
%Concatenate values and stars
r_agg_plus1_mid_chinn=num2str(r_agg_plus1_matrix_mid(:,1));
r_agg_plus1_mid_chinn=strcat(r_agg_plus1_mid_chinn,star_agg_plus1_matrix_mid(:,1));

%Calculate correlation for aggregated matrices: POOR COUNTRIES
[r_agg_plus1_matrix_poor, p_agg_plus1_matrix_poor, star_agg_plus1_matrix_poor] = aggregate_correlation(num_index, aggregate_xt_aux2_poor, aggregate_indext_aux2_poor);
 
%Concatenate values and stars
r_agg_plus1_poor_chinn=num2str(r_agg_plus1_matrix_poor(:,1));
r_agg_plus1_poor_chinn=strcat(r_agg_plus1_poor_chinn,star_agg_plus1_matrix_poor(:,1));


%% Make tables for all correlations

%Define labels for the table
Labels_h = { '' , 'j=-1', 'j=0', 'j=+1'};
Labels_v = {'Total'; 'Advanced Economies'; 'Emerging Markets'; 'Low-Income Countries'};
empty_vector={'','','',''};

%Create tables for chinn index
correlation_chinn_table=[ r_agg_minus1_chinn r_agg_chinn r_agg_plus1_chinn
    r_agg_minus1_adv_chinn r_agg_chinn_adv r_agg_plus1_adv_chinn
    r_agg_minus1_mid_chinn r_agg_chinn_mid r_agg_plus1_mid_chinn
    r_agg_minus1_poor_chinn r_agg_chinn_poor r_agg_plus1_poor_chinn];

title_average_corr_chinn_quinn={'Table A.11. Correlations between Output and alternative Indexes','','',''};
subtitle_average_corr_chinn={'(a) Chinn-Ito Index', '', '', ''};
table_average_corr_chinn = [subtitle_average_corr_chinn; Labels_v correlation_chinn_table];
Table_average_corr_chinn_quinn=[title_average_corr_chinn_quinn; Labels_h; table_average_corr_chinn; empty_vector; table_average_corr_quinn];

save case_CHINN4 aggregate_xt aggregate_xt_adv aggregate_xt_mid aggregate_xt_poor
save Result_CHINN4 Table_average_corr_chinn_quinn
    
    case 5

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%IDENTIFY BOOM/BUST EPISODES%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
load case_CHINN1
load case_CHINN2

%% Identify Boom and Bust

%Create the matrices for booms and bustes
[boom_matrix, bust_matrix, jump] = identify_boom_bust(xt);

% Calculate the descriptive statistics for booms and bustes
[num_boom, num_bust, duration_boom, duration_bust, amplitude_average_boom, amplitude_average_bust, average_boom, average_bust] = des_stats_boom_bust(num_c,boom_matrix, bust_matrix);

%% Boom and bust episodes divided by income groups

%Divide booms in country groups 
[boom_adv, boom_mid, boom_poor] = country_groups_boom_bust(num_gdp, num_boom, boom_matrix, boom_matrix);

%Divide bustes in country groups
[bust_adv, bust_mid, bust_poor] = country_groups_boom_bust(num_gdp,num_bust, bust_matrix, bust_matrix);

%% Calculate number, diration and amplitude for boom and bust divided by country groups

%ADVANCED
% Calculate the descriptive statistics for booms and bustes
[num_boom_adv, num_bust_adv,~,~,~,~,~,~] = des_stats_boom_bust(num_adv, boom_adv, bust_adv);

%MIDDLE
% Calculate the descriptive statistics for booms and bustes
[num_boom_mid, num_bust_mid,~,~,~,~,~,~] = des_stats_boom_bust(num_mid, boom_mid, bust_mid);

%POOR
% Calculate the descriptive statistics for booms and bustes
[num_boom_poor, num_bust_poor,~,~,~,~,~,~] = des_stats_boom_bust(num_poor, boom_poor, bust_poor);

save case_CHINN5 boom_matrix bust_matrix boom_adv boom_mid boom_poor bust_adv bust_mid bust_poor num_boom num_bust

    case 6

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%BOOM/BUST AND DETRENDED CHINN-ITO INDEX%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
load case_CHINN1
load case_CHINN2
load case_CHINN3
load case_CHINN5
load case_aux_QUINN6
load case_KLEIN

%% 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
[chinn_average_boom_values,~,~,~,boom_values] = average_boom_bust(num_gdp, num_boom, boom_matrix, xt);

%BUST
%Calculate average, standard deviation and confidence interval
[chinn_average_bust_values,~,~,~,bust_values] = average_boom_bust(num_gdp, num_bust, bust_matrix, xt);

%% 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_chinn_values_boom, std_chinn_values_boom, chinn_upper_bound_boom, chinn_lower_bound_boom, indext_values_boom] = average_boom_bust(num_index, num_boom, boom_matrix, indext);

%BUST
%Calculate average, standard deviation and confidence interval
[average_chinn_values_bust, std_chinn_values_bust, chinn_upper_bound_bust, chinn_lower_bound_bust, indext_values_bust] = average_boom_bust(num_index, num_bust, bust_matrix, indext);

%% Make plots with average detrended index and average output gap (reference point boom/bust)

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

figure(1)
% QUINN INDEX
% Boom
subplot(3,2,1)
[haxes,hline1,hline2] = plotyy(average_quinn_values_boom, 'b', 100*quinn_average_boom_values ,'r-*','plot');
set(haxes,'Xlim',[1 5])
set(hline1,'LineWidth',2)
set(hline2,'LineWidth',2)
set(haxes, 'xTickLabel','')
set(gca, 'XTick', 1:5, 'XTickLabel', label_x,'FontSize',8);
% xlabel('Years');
set(haxes(1), 'yTickLabel','')
set(haxes(1), 'yLim',[roundTo(1.75*min(quinn_lower_bound_boom(1,:)),2) roundTo(1.75*max(quinn_upper_bound_boom(1,:)),2)])
set(haxes(1),'YTick',[roundTo(1.75*min(quinn_lower_bound_boom(1,:)),2) 0 roundTo(1.75*max(quinn_upper_bound_boom(1,:)),2)], 'YTickLabel',[roundTo(1.75*min(quinn_lower_bound_boom(1,:)),2) 0 roundTo(1.75*max(quinn_upper_bound_boom(1,:)),2)],'FontSize',10);
t=title('Boom','FontWeight','bold');
set(t,'FontSize',8);
hold on
set(haxes(1),'Nextplot','add');
hline3=plot(quinn_lower_bound_boom(1,:),'k-.');
hold on
set(haxes(1),'Nextplot','add');
plot(quinn_upper_bound_boom(1,:),'k-.');
box off
hold off
%Bust
subplot(3,2,2)
[haxes,hline1,hline2] = plotyy(average_quinn_values_bust, 'b', 100*quinn_average_bust_values ,'r-*','plot');
set(haxes,'Xlim',[1 5])
set(hline1,'LineWidth',2)
set(hline2,'LineWidth',2)
set(haxes, 'xTickLabel','')
set(gca, 'XTick', 1:5, 'XTickLabel', label_x,'FontSize',8);
% xlabel('Years');
set(haxes(1), 'yTickLabel','')
set(haxes(1), 'yLim',[roundTo(1.75*min(quinn_lower_bound_bust(1,:)),2) roundTo(1.75*max(quinn_upper_bound_bust(1,:)),2)])
set(haxes(1),'YTick',[roundTo(1.75*min(quinn_lower_bound_bust(1,:)),2) 0 roundTo(1.75*max(quinn_upper_bound_bust(1,:)),2)], 'YTickLabel',[roundTo(1.75*min(quinn_lower_bound_bust(1,:)),2) 0 roundTo(1.75*max(quinn_upper_bound_bust(1,:)),2)],'FontSize',10);
t=title('Bust','FontWeight','bold');
set(t,'FontSize',8);
hold on
set(haxes(1),'Nextplot','add');
hline3=plot(quinn_lower_bound_bust(1,:),'k-.');
hold on
set(haxes(1),'Nextplot','add');
plot(quinn_upper_bound_bust(1,:),'k-.');
box off
hold off
% CHINN INDEX
% Boom
subplot(3,2,3)
[haxes,hline1,hline2] = plotyy(average_chinn_values_boom, 'b', 100*chinn_average_boom_values ,'r-*','plot');
set(haxes,'Xlim',[1 5])
set(hline1,'LineWidth',2)
set(hline2,'LineWidth',2)
set(haxes, 'xTickLabel','')
set(gca, 'XTick', 1:5, 'XTickLabel', label_x,'FontSize',8);
% xlabel('Years');
set(haxes(1), 'yTickLabel','')
set(haxes(1), 'yLim',[roundTo(1.75*min(chinn_lower_bound_boom(1,:)),2) roundTo(1.75*max(chinn_upper_bound_boom(1,:)),2)])
set(haxes(1),'YTick',[roundTo(1.75*min(chinn_lower_bound_boom(1,:)),2) 0 roundTo(1.75*max(chinn_upper_bound_boom(1,:)),2)], 'YTickLabel',[roundTo(1.75*min(chinn_lower_bound_boom(1,:)),2) 0 roundTo(1.75*max(chinn_upper_bound_boom(1,:)),2)],'FontSize',10);
t=title('Boom','FontWeight','bold');
set(t,'FontSize',8);
hold on
set(haxes(1),'Nextplot','add');
hline3=plot(chinn_lower_bound_boom(1,:),'k-.');
hold on
set(haxes(1),'Nextplot','add');
plot(chinn_upper_bound_boom(1,:),'k-.');
box off
hold off
%Bust
subplot(3,2,4)
[haxes,hline1,hline2] = plotyy(average_chinn_values_bust, 'b', 100*chinn_average_bust_values ,'r-*','plot');
set(haxes,'Xlim',[1 5])
set(hline1,'LineWidth',2)
set(hline2,'LineWidth',2)
set(haxes, 'xTickLabel','')
set(gca, 'XTick', 1:5, 'XTickLabel', label_x,'FontSize',8);
% xlabel('Years');
set(haxes(1), 'yTickLabel','')
set(haxes(1), 'yLim',[roundTo(1.75*min(chinn_lower_bound_bust(1,:)),2) roundTo(1.75*max(chinn_upper_bound_bust(1,:)),2)])
set(haxes(1),'YTick',[roundTo(1.75*min(chinn_lower_bound_bust(1,:)),2) 0 roundTo(1.75*max(chinn_upper_bound_bust(1,:)),2)], 'YTickLabel',[roundTo(1.75*min(chinn_lower_bound_bust(1,:)),2) 0 roundTo(1.75*max(chinn_upper_bound_bust(1,:)),2)],'FontSize',10);
t=title('Bust','FontWeight','bold');
set(t,'FontSize',8);
hold on
set(haxes(1),'Nextplot','add');
hline3=plot(chinn_lower_bound_bust(1,:),'k-.');
hold on
set(haxes(1),'Nextplot','add');
plot(chinn_upper_bound_bust(1,:),'k-.');
box off
hold off

%Klein's exercise

%Boom
subplot(3,2,5)
[haxes,hline1,hline2] = plotyy(average_indext_klein_boom(1,:,2), 'b', 100*average_boom_klein,'r-*','plot');
set(haxes,'Xlim',[1 5])
set(hline1,'LineWidth',2)
set(hline2,'LineWidth',2)
set(haxes, 'xTickLabel','')
set(gca, 'XTick', 1:5, 'XTickLabel', label_x,'FontSize',8);
xlabel('Years');
set(haxes(1), 'yTickLabel','')
set(haxes(1), 'yLim',[roundTo(1.75*min(lower_bound_boom_klein(1,:,2)),2) roundTo(1.75*max(upper_bound_boom_klein(1,:,2)),2)])
set(haxes(1),'YTick',[roundTo(1.75*min(lower_bound_boom_klein(1,:,2)),2) 0 roundTo(1.75*max(upper_bound_boom_klein(1,:,2)),2)], 'YTickLabel', [roundTo(1.75*min(lower_bound_boom_klein(1,:,2)),2) 0 roundTo(1.75*max(upper_bound_boom_klein(1,:,2)),2)],'FontSize',10);
t=title('Boom','FontWeight','bold');
set(t,'FontSize',8);
hold on
set(haxes(1),'Nextplot','add');
hline3=plot(lower_bound_boom_klein(1,:,2),'k-.');
hold on
set(haxes(1),'Nextplot','add');
plot(upper_bound_boom_klein(1,:,2),'k-.');
box off
hold off
% Bust
subplot(3,2,6)
[haxes,hline1,hline2] = plotyy(average_indext_klein_bust(1,:,2), 'b', 100*average_bust_klein ,'r-*','plot');
set(haxes,'Xlim',[1 5])
set(hline1,'LineWidth',2)
set(hline2,'LineWidth',2)
set(haxes, 'xTickLabel','')
set(gca, 'XTick', 1:5, 'XTickLabel', label_x,'FontSize',8);
xlabel('Years');
set(haxes(1), 'yTickLabel','')
set(haxes(1), 'yLim',[roundTo(1.75*min(lower_bound_bust_klein(1,:,2)),2) roundTo(1.75*max(upper_bound_bust_klein(1,:,2)),2)])
set(haxes(1),'YTick',[roundTo(1.75*min(lower_bound_bust_klein(1,:,2)),2) 0 roundTo(1.75*max(upper_bound_bust_klein(1,:,2)),2)], 'YTickLabel', [roundTo(1.75*min(lower_bound_bust_klein(1,:,2)),2) 0 roundTo(1.75*max(upper_bound_bust_klein(1,:,2)),2)],'FontSize',10);
t=title('Bust','FontWeight','bold');
set(t,'FontSize',8);
hold on
set(haxes(1),'Nextplot','add');
hline3=plot(lower_bound_bust_klein(1,:,2),'k-.');
hold on
set(haxes(1),'Nextplot','add');
plot(upper_bound_bust_klein(1,:,2),'k-.');
box off
hold off


legend1 = legend([hline1 hline2 hline3],'Average Index(lhs)','Average Output Gap(rhs)','Two Standard Deviation for the Index(lhs)');
set(legend1,'Orientation','horizontal','Position',[0.360807291666667 0.0177845528455285 0.336979166666667 0.0274390243902439],'FontSize',8,'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 9. Alternative Measures of Capital-Inflow Controls','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) Quinn','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) Chinn-Ito','Position',[0.519140625 0.665080906148867 9.16025403784439],'HorizontalAlignment','center');
sub_ha3 = axes('Visible','off','Position',[0 0 1 1]);
text('Parent',sub_ha3,'String','\bf (c) Countries With Active Capital-Control Policy','Position',[0.519140625 0.365080906148867 9.16025403784439],'HorizontalAlignment','center');






%% Create matrices as above divided by country groups

%BOOM
%Divide ouput gap in country groups
[boom_values_adv, boom_values_mid, boom_values_poor] = country_groups_boom_bust(num_gdp, num_boom, boom_matrix, boom_values);

%Divide detrended index in country groups
[indext_values_boom_adv, indext_values_boom_mid, indext_values_boom_poor] = country_groups_boom_bust(num_index, num_boom, boom_matrix, indext_values_boom);

%BUST
%Divide output gap in country groups
[bust_values_adv, bust_values_mid, bust_values_poor] = country_groups_boom_bust(num_gdp, num_bust, bust_matrix, bust_values);

%Divide detrended index in country groups
[indext_values_bust_adv, indext_values_bust_mid, indext_values_bust_poor] = country_groups_boom_bust(num_index, num_bust, bust_matrix, indext_values_bust);

%% Calculate average and standard deviations for income group

%BOOM
% Average output gap for the different time horizons
for i=1:5
    average_boom_values_adv(1,i)=nanmean(boom_values_adv(:,i+1),1);
    average_boom_values_mid(1,i)=nanmean(boom_values_mid(:,i+1),1);
    average_boom_values_poor(1,i)=nanmean(boom_values_poor(:,i+1),1);
end    

% Average Chinn-Ito index for the different time horizons
for i=1:5
    average_boom_chinn_adv(1,i)=nanmean(boom_values_adv(:,i+1),1);
    average_boom_chinn_mid(1,i)=nanmean(boom_values_mid(:,i+1),1);
    average_boom_chinn_poor(1,i)=nanmean(boom_values_poor(:,i+1),1);
end    

%Standard Deviation
for i=1:5
    std_indext_boom_adv_chinn(1,i)=nanstd(indext_values_boom_adv(:,i+1),1);
    std_indext_boom_mid_chinn(1,i)=nanstd(indext_values_boom_mid(:,i+1),1);
    std_indext_boom_poor_chinn(1,i)=nanstd(indext_values_boom_poor(:,i+1),1);
end

%Confidence interval for the detrended index
for i=1:5
    upper_bound_boom_adv(1,i)=average_boom_chinn_adv(1,i)+ 2*std_indext_boom_adv_chinn(1,i);
    lower_bound_boom_adv(1,i)=average_boom_chinn_adv(1,i)- 2*std_indext_boom_adv_chinn(1,i);
    upper_bound_boom_mid(1,i)=average_boom_chinn_mid(1,i)+ 2*std_indext_boom_mid_chinn(1,i);
    lower_bound_boom_mid(1,i)=average_boom_chinn_mid(1,i)- 2*std_indext_boom_mid_chinn(1,i);
    upper_bound_boom_poor(1,i)=average_boom_chinn_poor(1,i)+ 2*std_indext_boom_poor_chinn(1,i);
    lower_bound_boom_poor(1,i)=average_boom_chinn_poor(1,i)- 2*std_indext_boom_poor_chinn(1,i);
end

%BUST
% Average output gap for the different time horizons
for i=1:5
    average_bust_values_adv(1,i)=nanmean(bust_values_adv(:,i+1),1);
    average_bust_values_mid(1,i)=nanmean(bust_values_mid(:,i+1),1);
    average_bust_values_poor(1,i)=nanmean(bust_values_poor(:,i+1),1);
end    
 
% Average Chinn-Ito index for the different time horizons
for i=1:5
    average_bust_chinn_adv(1,i)=nanmean(bust_values_adv(:,i+1),1);
    average_bust_chinn_mid(1,i)=nanmean(bust_values_mid(:,i+1),1);
    average_bust_chinn_poor(1,i)=nanmean(bust_values_poor(:,i+1),1);
end    
 
%Standard Deviation
for i=1:5
    std_indext_bust_adv_chinn(1,i)=nanstd(indext_values_bust_adv(:,i+1),1);
    std_indext_bust_mid_chinn(1,i)=nanstd(indext_values_bust_mid(:,i+1),1);
    std_indext_bust_poor_chinn(1,i)=nanstd(indext_values_bust_poor(:,i+1),1);
end
 
%Confidence interval for the detrended index
for i=1:5
    upper_bound_bust_adv(1,i)=average_bust_chinn_adv(1,i)+ 2*std_indext_bust_adv_chinn(1,i);
    lower_bound_bust_adv(1,i)=average_bust_chinn_adv(1,i)- 2*std_indext_bust_adv_chinn(1,i);
    upper_bound_bust_mid(1,i)=average_bust_chinn_mid(1,i)+ 2*std_indext_bust_mid_chinn(1,i);
    lower_bound_bust_mid(1,i)=average_bust_chinn_mid(1,i)- 2*std_indext_bust_mid_chinn(1,i);
    upper_bound_bust_poor(1,i)=average_bust_chinn_poor(1,i)+ 2*std_indext_bust_poor_chinn(1,i);
    lower_bound_bust_poor(1,i)=average_bust_chinn_poor(1,i)- 2*std_indext_bust_poor_chinn(1,i);
end

    case 7
load case_KLEIN
load case_GDP1
load case_GDP2
load case_GDP3
load case_GDP4
load case_GDP7
load case_GDP24
load case_GDP25

%CHANGE MANUALLY!!!!
%Define countries in Klein sample
%Argentina, Australia, Brazil, Chile, France, Germany, Iceland, Ireland, Israel, Korea, Mexico, Peru, Portugal, Sweden, Turkey
%Three countries of the Klein sample excluded because we don't have the
%data: Czech Rep, Hungary and Poland
klein_countries=[2 3 8 12 23 24 29 32 33 38 44 54 56 64 70]';

%Count # of countries in Klein sample
num_klein=size(klein_countries,1);

%Construct boom matrix for Klein countries
count=1;
for i=1:num_boom
    for j=1:num_klein
        if boom_matrix(i,1)==klein_countries(j,1)
            boom_klein(count,:)=boom_matrix(i,:);
            count=count+1;
        end
    end
end
num_boom_klein=size(boom_klein,1);

%Construct bust matrix for Klein countries
count=1;
for i=1:num_bust
    for j=1:num_klein
        if bust_matrix(i,1)==klein_countries(j,1)
            bust_klein(count,:)=bust_matrix(i,:);
            count=count+1;
        end
    end
end
num_bust_klein=size(bust_klein,1);

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

num_index=3;

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

%BOOM
%Calculate average, standard deviation and confidence interval
[average_boom_klein,~,~,~, boom_values_klein] = average_boom_bust(num_gdp, num_boom_klein, boom_klein, xt);

%BUST
%Calculate average, standard deviation and confidence interval
[average_bust_klein,~,~,~, bust_values_klein] = average_boom_bust(num_gdp, num_bust_klein, bust_klein, xt);
        
%BOOM
%Calculate average, standard deviation and confidence interval
[average_indext_eq_klein_boom, std_indext_eq_klein_boom, upper_bound_eq_boom_klein, lower_bound_eq_boom_klein, indext_eq_boom_klein] = average_boom_bust(num_index, num_boom_klein, boom_klein, indext_eq);

%BUST
%Calculate average, standard deviation and confidence interval
[average_indext_eq_klein_bust, std_indext_eq_klein_bust, upper_bound_eq_bust_klein, lower_bound_eq_bust_klein, indext_eq_bust_klein] = average_boom_bust(num_index, num_bust_klein, bust_klein, indext_eq);

%BOOM
%Calculate average, standard deviation and confidence interval
[average_indext_bo_klein_boom, std_indext_bo_klein_boom, upper_bound_bo_boom_klein, lower_bound_bo_boom_klein, indext_bo_boom_klein] = average_boom_bust(num_index, num_boom_klein, boom_klein, indext_bo);

%BUST
%Calculate average, standard deviation and confidence interval
[average_indext_bo_klein_bust, std_indext_bo_klein_bust, upper_bound_bo_bust_klein, lower_bound_bo_bust_klein, indext_bo_bust_klein] = average_boom_bust(num_index, num_bust_klein, bust_klein, indext_bo);


%Boom
subplot(2,2,1)
[haxes,hline1,hline2] = plotyy(average_indext_bo_klein_boom(1,:,2), 'b', 100*average_boom_klein,'r-*','plot');
set(haxes,'Xlim',[1 5])
set(hline1,'LineWidth',2)
set(hline2,'LineWidth',2)
set(haxes, 'xTickLabel','')
set(gca, 'XTick', 1:5, 'XTickLabel', label_x,'FontSize',8);
xlabel('Years');
set(haxes(1), 'yTickLabel','')
set(haxes(1), 'yLim',[roundTo(1.75*min(lower_bound_bo_boom_klein(1,:,2)),2) roundTo(1.75*max(upper_bound_bo_boom_klein(1,:,2)),2)])
set(haxes(1),'YTick',[roundTo(1.75*min(lower_bound_bo_boom_klein(1,:,2)),2) 0 roundTo(1.75*max(upper_bound_bo_boom_klein(1,:,2)),2)], 'YTickLabel', [roundTo(1.75*min(lower_bound_bo_boom_klein(1,:,2)),2) 0 roundTo(1.75*max(upper_bound_bo_boom_klein(1,:,2)),2)],'FontSize',10);
t=title('Boom','FontWeight','bold');
set(t,'FontSize',8);
hold on
set(haxes(1),'Nextplot','add');
hline3=plot(lower_bound_bo_boom_klein(1,:,2),'k-.');
hold on
set(haxes(1),'Nextplot','add');
plot(upper_bound_bo_boom_klein(1,:,2),'k-.');
box off
hold off
% Bust
subplot(2,2,2)
[haxes,hline1,hline2] = plotyy(average_indext_bo_klein_bust(1,:,2), 'b', 100*average_bust_klein ,'r-*','plot');
set(haxes,'Xlim',[1 5])
set(hline1,'LineWidth',2)
set(hline2,'LineWidth',2)
set(haxes, 'xTickLabel','')
set(gca, 'XTick', 1:5, 'XTickLabel', label_x,'FontSize',8);
xlabel('Years');
set(haxes(1), 'yTickLabel','')
set(haxes(1), 'yLim',[roundTo(1.75*min(lower_bound_bo_bust_klein(1,:,2)),2) roundTo(1.75*max(upper_bound_bo_bust_klein(1,:,2)),2)])
set(haxes(1),'YTick',[roundTo(1.75*min(lower_bound_bo_bust_klein(1,:,2)),2) 0 roundTo(1.75*max(upper_bound_bo_bust_klein(1,:,2)),2)], 'YTickLabel', [roundTo(1.75*min(lower_bound_bo_bust_klein(1,:,2)),2) 0 roundTo(1.75*max(upper_bound_bo_bust_klein(1,:,2)),2)],'FontSize',10);
t=title('Bust','FontWeight','bold');
set(t,'FontSize',8);
hold on
set(haxes(1),'Nextplot','add');
hline3=plot(lower_bound_bo_bust_klein(1,:,2),'k-.');
hold on
set(haxes(1),'Nextplot','add');
plot(upper_bound_bo_bust_klein(1,:,2),'k-.');
box off
hold off

%Boom
subplot(2,2,3)
[haxes,hline1,hline2] = plotyy(average_indext_bo_klein_boom(1,:,3), 'b', 100*average_boom_klein,'r-*','plot');
set(haxes,'Xlim',[1 5])
set(hline1,'LineWidth',2)
set(hline2,'LineWidth',2)
set(haxes, 'xTickLabel','')
set(gca, 'XTick', 1:5, 'XTickLabel', label_x,'FontSize',8);
xlabel('Years');
set(haxes(1), 'yTickLabel','')
set(haxes(1), 'yLim',[roundTo(1.75*min(lower_bound_bo_boom_klein(1,:,3)),2) roundTo(1.75*max(upper_bound_bo_boom_klein(1,:,3)),2)])
set(haxes(1),'YTick',[roundTo(1.75*min(lower_bound_bo_boom_klein(1,:,3)),2) 0 roundTo(1.75*max(upper_bound_bo_boom_klein(1,:,3)),2)], 'YTickLabel', [roundTo(1.75*min(lower_bound_bo_boom_klein(1,:,3)),2) 0 roundTo(1.75*max(upper_bound_bo_boom_klein(1,:,3)),2)],'FontSize',10);
t=title('Boom','FontWeight','bold');
set(t,'FontSize',8);
hold on
set(haxes(1),'Nextplot','add');
hline3=plot(lower_bound_bo_boom_klein(1,:,3),'k-.');
hold on
set(haxes(1),'Nextplot','add');
plot(upper_bound_bo_boom_klein(1,:,3),'k-.');
box off
hold off
% Bust
subplot(2,2,4)
[haxes,hline1,hline2] = plotyy(average_indext_bo_klein_bust(1,:,3), 'b', 100*average_bust_klein ,'r-*','plot');
set(haxes,'Xlim',[1 5])
set(hline1,'LineWidth',2)
set(hline2,'LineWidth',2)
set(haxes, 'xTickLabel','')
set(gca, 'XTick', 1:5, 'XTickLabel', label_x,'FontSize',8);
xlabel('Years');
set(haxes(1), 'yTickLabel','')
set(haxes(1), 'yLim',[roundTo(1.75*min(lower_bound_bo_bust_klein(1,:,3)),2) roundTo(1.75*max(upper_bound_bo_bust_klein(1,:,3)),2)])
set(haxes(1),'YTick',[roundTo(1.75*min(lower_bound_bo_bust_klein(1,:,3)),2) 0 roundTo(1.75*max(upper_bound_bo_bust_klein(1,:,3)),2)], 'YTickLabel', [roundTo(1.75*min(lower_bound_bo_bust_klein(1,:,3)),2) 0 roundTo(1.75*max(upper_bound_bo_bust_klein(1,:,3)),2)],'FontSize',10);
t=title('Bust','FontWeight','bold');
set(t,'FontSize',8);
hold on
set(haxes(1),'Nextplot','add');
hline3=plot(lower_bound_bo_bust_klein(1,:,3),'k-.');
hold on
set(haxes(1),'Nextplot','add');
plot(upper_bound_bo_bust_klein(1,:,3),'k-.');
box off
hold off

legend1 = legend([hline1 hline2 hline3],'Average Index(lhs)','Average Output Gap(rhs)','Two Standard Deviation for the Index(lhs)');
set(legend1,'Orientation','horizontal','Position',[0.360807291666667 0.0177845528455285 0.336979166666667 0.0274390243902439],'FontSize',8,'Box','off');
sub_ha1 = axes('Visible','off','Position',[0 0 1 1]);
text('Parent',sub_ha1,'String','\bf (a) Inflows','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) Outflows','Position',[0.519140625 0.5 9.16025403784439],'HorizontalAlignment','center');
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 9.A.1 Countries With Active Capital-Control Policy on Bonds','Position',[0.508203125 0.978604294478528 9.16025403784439],'HorizontalAlignment','center')

figure(2)

%Boom
subplot(2,2,1)
[haxes,hline1,hline2] = plotyy(average_indext_eq_klein_boom(1,:,2), 'b', 100*average_boom_klein,'r-*','plot');
set(haxes,'Xlim',[1 5])
set(hline1,'LineWidth',2)
set(hline2,'LineWidth',2)
set(haxes, 'xTickLabel','')
set(gca, 'XTick', 1:5, 'XTickLabel', label_x,'FontSize',8);
xlabel('Years');
set(haxes(1), 'yTickLabel','')
set(haxes(1), 'yLim',[roundTo(1.75*min(lower_bound_eq_boom_klein(1,:,2)),2) roundTo(1.75*max(upper_bound_eq_boom_klein(1,:,2)),2)])
set(haxes(1),'YTick',[roundTo(1.75*min(lower_bound_eq_boom_klein(1,:,2)),2) 0 roundTo(1.75*max(upper_bound_eq_boom_klein(1,:,2)),2)], 'YTickLabel', [roundTo(1.75*min(lower_bound_eq_boom_klein(1,:,2)),2) 0 roundTo(1.75*max(upper_bound_eq_boom_klein(1,:,2)),2)],'FontSize',10);
t=title('Boom','FontWeight','bold');
set(t,'FontSize',8);
hold on
set(haxes(1),'Nextplot','add');
hline3=plot(lower_bound_eq_boom_klein(1,:,2),'k-.');
hold on
set(haxes(1),'Nextplot','add');
plot(upper_bound_eq_boom_klein(1,:,2),'k-.');
box off
hold off
% Bust
subplot(2,2,2)
[haxes,hline1,hline2] = plotyy(average_indext_eq_klein_bust(1,:,2), 'b', 100*average_bust_klein ,'r-*','plot');
set(haxes,'Xlim',[1 5])
set(hline1,'LineWidth',2)
set(hline2,'LineWidth',2)
set(haxes, 'xTickLabel','')
set(gca, 'XTick', 1:5, 'XTickLabel', label_x,'FontSize',8);
xlabel('Years');
set(haxes(1), 'yTickLabel','')
set(haxes(1), 'yLim',[roundTo(1.75*min(lower_bound_eq_bust_klein(1,:,2)),2) roundTo(1.75*max(upper_bound_eq_bust_klein(1,:,2)),2)])
set(haxes(1),'YTick',[roundTo(1.75*min(lower_bound_eq_bust_klein(1,:,2)),2) 0 roundTo(1.75*max(upper_bound_eq_bust_klein(1,:,2)),2)], 'YTickLabel', [roundTo(1.75*min(lower_bound_eq_bust_klein(1,:,2)),2) 0 roundTo(1.75*max(upper_bound_eq_bust_klein(1,:,2)),2)],'FontSize',10);
t=title('Bust','FontWeight','bold');
set(t,'FontSize',8);
hold on
set(haxes(1),'Nextplot','add');
hline3=plot(lower_bound_eq_bust_klein(1,:,2),'k-.');
hold on
set(haxes(1),'Nextplot','add');
plot(upper_bound_eq_bust_klein(1,:,2),'k-.');
box off
hold off

%Boom
subplot(2,2,3)
[haxes,hline1,hline2] = plotyy(average_indext_eq_klein_boom(1,:,3), 'b', 100*average_boom_klein,'r-*','plot');
set(haxes,'Xlim',[1 5])
set(hline1,'LineWidth',2)
set(hline2,'LineWidth',2)
set(haxes, 'xTickLabel','')
set(gca, 'XTick', 1:5, 'XTickLabel', label_x,'FontSize',8);
xlabel('Years');
set(haxes(1), 'yTickLabel','')
set(haxes(1), 'yLim',[roundTo(1.75*min(lower_bound_eq_boom_klein(1,:,3)),2) roundTo(1.75*max(upper_bound_eq_boom_klein(1,:,3)),2)])
set(haxes(1),'YTick',[roundTo(1.75*min(lower_bound_eq_boom_klein(1,:,3)),2) 0 roundTo(1.75*max(upper_bound_eq_boom_klein(1,:,3)),2)], 'YTickLabel', [roundTo(1.75*min(lower_bound_eq_boom_klein(1,:,3)),2) 0 roundTo(1.75*max(upper_bound_eq_boom_klein(1,:,3)),2)],'FontSize',10);
t=title('Boom','FontWeight','bold');
set(t,'FontSize',8);
hold on
set(haxes(1),'Nextplot','add');
hline3=plot(lower_bound_eq_boom_klein(1,:,3),'k-.');
hold on
set(haxes(1),'Nextplot','add');
plot(upper_bound_eq_boom_klein(1,:,3),'k-.');
box off
hold off
% Bust
subplot(2,2,4)
[haxes,hline1,hline2] = plotyy(average_indext_eq_klein_bust(1,:,3), 'b', 100*average_bust_klein ,'r-*','plot');
set(haxes,'Xlim',[1 5])
set(hline1,'LineWidth',2)
set(hline2,'LineWidth',2)
set(haxes, 'xTickLabel','')
set(gca, 'XTick', 1:5, 'XTickLabel', label_x,'FontSize',8);
xlabel('Years');
set(haxes(1), 'yTickLabel','')
set(haxes(1), 'yLim',[roundTo(1.75*min(lower_bound_eq_bust_klein(1,:,3)),2) roundTo(1.75*max(upper_bound_eq_bust_klein(1,:,3)),2)])
set(haxes(1),'YTick',[roundTo(1.75*min(lower_bound_eq_bust_klein(1,:,3)),2) 0 roundTo(1.75*max(upper_bound_eq_bust_klein(1,:,3)),2)], 'YTickLabel', [roundTo(1.75*min(lower_bound_eq_bust_klein(1,:,3)),2) 0 roundTo(1.75*max(upper_bound_eq_bust_klein(1,:,3)),2)],'FontSize',10);
t=title('Bust','FontWeight','bold');
set(t,'FontSize',8);
hold on
set(haxes(1),'Nextplot','add');
hline3=plot(lower_bound_eq_bust_klein(1,:,3),'k-.');
hold on
set(haxes(1),'Nextplot','add');
plot(upper_bound_eq_bust_klein(1,:,3),'k-.');
box off
hold off

legend1 = legend([hline1 hline2 hline3],'Average Index(lhs)','Average Output Gap(rhs)','Two Standard Deviation for the Index(lhs)');
set(legend1,'Orientation','horizontal','Position',[0.360807291666667 0.0177845528455285 0.336979166666667 0.0274390243902439],'FontSize',8,'Box','off');
sub_ha1 = axes('Visible','off','Position',[0 0 1 1]);
text('Parent',sub_ha1,'String','\bf (a) Inflows','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) Outflows','Position',[0.519140625 0.5 9.16025403784439],'HorizontalAlignment','center');
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 9.A.2 Countries With Active Capital-Control Policy on Equity','Position',[0.508203125 0.978604294478528 9.16025403784439],'HorizontalAlignment','center')

    case 8
load case_KLEIN

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

%Klein's exercise

figure(1)

%Boom
subplot(3,2,5)
[haxes,hline1,hline2] = plotyy(average_indext_klein_boom(1,:,2), 'b', 100*average_boom_klein,'r-*','plot');
set(haxes,'Xlim',[1 5])
set(hline1,'LineWidth',2)
set(hline2,'LineWidth',2)
set(haxes, 'xTickLabel','')
set(gca, 'XTick', 1:5, 'XTickLabel', label_x,'FontSize',8);
xlabel('Years');
set(haxes(1), 'yTickLabel','')
set(haxes(1), 'yLim',[roundTo(1.75*min(lower_bound_boom_klein(1,:,2)),2) roundTo(1.75*max(upper_bound_boom_klein(1,:,2)),2)])
set(haxes(1),'YTick',[roundTo(1.75*min(lower_bound_boom_klein(1,:,2)),2) 0 roundTo(1.75*max(upper_bound_boom_klein(1,:,2)),2)], 'YTickLabel', [roundTo(1.75*min(lower_bound_boom_klein(1,:,2)),2) 0 roundTo(1.75*max(upper_bound_boom_klein(1,:,2)),2)],'FontSize',10);
t=title('Boom','FontWeight','bold');
set(t,'FontSize',8);
hold on
set(haxes(1),'Nextplot','add');
hline3=plot(lower_bound_boom_klein(1,:,2),'k-.');
hold on
set(haxes(1),'Nextplot','add');
plot(upper_bound_boom_klein(1,:,2),'k-.');
box off
hold off
% Bust
subplot(3,2,6)
[haxes,hline1,hline2] = plotyy(average_indext_klein_bust(1,:,3), 'b', 100*average_bust_klein ,'r-*','plot');
set(haxes,'Xlim',[1 5])
set(hline1,'LineWidth',2)
set(hline2,'LineWidth',2)
set(haxes, 'xTickLabel','')
set(gca, 'XTick', 1:5, 'XTickLabel', label_x,'FontSize',8);
xlabel('Years');
set(haxes(1), 'yTickLabel','')
set(haxes(1), 'yLim',[roundTo(1.75*min(lower_bound_bust_klein(1,:,3)),2) roundTo(1.75*max(upper_bound_bust_klein(1,:,3)),2)])
set(haxes(1),'YTick',[roundTo(1.75*min(lower_bound_bust_klein(1,:,3)),2) 0 roundTo(1.75*max(upper_bound_bust_klein(1,:,3)),2)], 'YTickLabel', [roundTo(1.75*min(lower_bound_bust_klein(1,:,3)),2) 0 roundTo(1.75*max(upper_bound_bust_klein(1,:,3)),2)],'FontSize',10);
t=title('Bust','FontWeight','bold');
set(t,'FontSize',8);
hold on
set(haxes(1),'Nextplot','add');
hline3=plot(lower_bound_bust_klein(1,:,3),'k-.');
hold on
set(haxes(1),'Nextplot','add');
plot(upper_bound_bust_klein(1,:,3),'k-.');
box off
hold off

legend1 = legend([hline1 hline2 hline3],'Average Index(lhs)','Average Output Gap(rhs)','Two Standard Deviation for the Index(lhs)');
set(legend1,'Orientation','horizontal','Position',[0.360807291666667 0.0177845528455285 0.336979166666667 0.0274390243902439],'FontSize',8,'Box','off');
sub_ha1 = axes('Visible','off','Position',[0 0 1 1]);
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.7 Countries With Active Capital-Control Policy on Outflows','Position',[0.508203125 0.43 9.16025403784439],'HorizontalAlignment','center')

end