% CAPITAL CONTROL PROJECT
% Author: Muratori Umberto
% Date: July, 18th 2013

%PURPOSE: CALCULATE BOOM AND BUST AND CONSTRUCT CHARTS AND TABLES FOR
%OVERALL INDEX, INDEX SPLIT FOR COUNTRIES CA

format long g

%list of tasks made in the code:
% TASK 1= IMPORT AND MANIPULATE CURRENT ACCOUNT DATA
% TASK 2= QUADRATIC DETREND, PLOTS AND DESCRIPTIVE STATISTICS FOR CA
% TASK 3= IMPORT AND MANIPULATE SCHINDLER INDEX
% TASK 4= LINEAR DETREND FOR SCHINDLER INDEX
% TASK 5= IDENTIFY BOOM AND BUST AND DESCRIPITVE STATISTICS
% TASK 6= BOOM/BUST AND DETRENDED INDEX

%data path
BasePath=pwd;

global num_c vect_adv num_adv vect_mid num_mid vect_poor num_poor schindler_years Countries Years

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

num_index=3;
num_ca=1;
num_subindex=6;

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


switch variable

    case 1

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%IMPORT AND MANIPULATE CA DATA%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%% Import data on Current Account
if mac_user==1
[vardat,textdata, raw]=xlsread(strcat(BasePath, '\current_account.xls') ,char('weoreptc')); 
else
[vardat,textdata, raw]=xlsread(strcat(BasePath, '/current_account.xls') ,char('weoreptc')); 
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);

%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

%Create variable CA
CA = vardat;

save  case_CA1bis CA lenght Countries idx_first num_c Years Full_sample

    case 2
        
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%QUADRATIC TREND FOR CA AND PLOTS%%%%%%%%%%%%%5%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
load case_CA1bis

%% Quadratic Trend

% To make the plots unocmment the part of script in the function
% quadratic_trend
ylabel={'Current Account'};

[cat] = quadratic_trend(lenght, idx_first, CA, ylabel);

%Create matrices for the output gap divided by country groups
[cat_adv, cat_mid, cat_poor] = country_groups(num_ca, cat);

save case_CA2bis cat cat_adv cat_mid cat_poor

    case 3

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%IMPORT AND MANIPULATE SCHINDLER INDEX%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
load case_CA1bis
load case_CA2bis

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

%Import Schindler index data
index_data= vardat_2;

%Create shaped matrix

index_matrix=permute(reshape(vardat_2,[17,91,40]),[2 1 3]);

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

index_matrix_eq=nan(79,schindler_years,num_index);
index_matrix_bo=nan(79,schindler_years,num_index);

for j=1:79
    for t=1:schindler_years
        for k=1:num_index
        if k==1
            index_matrix_eq(j,t,k)=index_matrix(j,t,5);
        elseif k==2
            index_matrix_eq(j,t,k)=index_matrix(j,t,6);
        else
            index_matrix_eq(j,t,k)=index_matrix(j,t,7);
        end
        end
    end
end 

for j=1:79
    for tau=1:schindler_years
        for k=1:num_index
        if k==1
            index_matrix_bo(j,tau,k)=index_matrix(j,tau,12);
        elseif k==2
            index_matrix_bo(j,tau,k)=index_matrix(j,tau,13);
        else
            index_matrix_bo(j,tau,k)=index_matrix(j,tau,14);
        end
        end
    end
end
        
%Create matrices for the index divided by country groups
[index_adv, index_mid, index_poor] = country_groups(num_index, index_matrix);

save case_CA3bis index_matrix index_data index_matrix_bo index_matrix_eq

    case 4

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%LINEAR DETREND FOR SCHINDLER INDEX%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
load case_CA1bis
load case_CA2bis
load case_CA3bis

%% Remove the country specific linear trend and divide by income groups

%Lineraly detrend the subcomponents of the index
[indext_eq] = linear_trend(num_index,schindler_years,index_matrix_eq);

%Detrend the series of bonds starting from the first valid value (third
%observation)
%CHANGE MANUALLY!!!!!
[index_matrix_bo_prova] = linear_trend(num_index,schindler_years-2,index_matrix_bo(:,3:end,:));

indext_bo=nan(79,17,3);

for k=1:num_index
    for j=1:79
        indext_bo(j,3:end,k)=index_matrix_bo_prova(j,:,k);
    end
end

% Linear detrending for the Schindler Index
[indext] = linear_trend(num_index, schindler_years, index_matrix);

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

save case_CA4bis indext_eq indext_bo indext indext_adv indext_mid indext_poor

 case 5

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%IDENTIFY BOOM AND BUST AND DESCRIPITVE STATISTICS%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
load case_CA1bis
load case_CA2bis

%% Identify Boom and Bust

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

% 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_ca, num_boom, boom_matrix, boom_matrix);

%Divide bustes in country groups
[bust_adv, bust_mid, bust_poor] = country_groups_boom_bust(num_ca,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, duration_boom_adv, duration_bust_adv, amplitude_average_boom_adv, amplitude_average_bust_adv, average_boom_adv, average_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, duration_boom_mid, duration_bust_mid, amplitude_average_boom_mid, amplitude_average_bust_mid, average_boom_mid, average_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, duration_boom_poor, duration_bust_poor, amplitude_average_boom_poor, amplitude_average_bust_poor, average_boom_poor, average_bust_poor] = des_stats_boom_bust(num_poor, boom_poor, bust_poor);

%% Make Tables for descriptive statistics boom and bust

%Define labels for descriptive statistics table
Labels_v = {'Number of episodes'; 'Episodes per country'; 'Average Duration'; 'Average Amplitude'};
Labels_h = {'','Total', 'Advanced Economies', 'Emerging Markets', 'Low-Income Countries'};

%Create vectors for title for descriptive statistics on Boom and bust
subtitle_boom_des={'(c) Current Account-Boom','','','',''};
subtitle_bust_des={'(d) Current Account-Bust','','','',''};

%Create tables for descriptive statistics of the boom
boom_des=[num_boom num_boom_adv num_boom_mid num_boom_poor
    average_boom average_boom_adv average_boom_mid average_boom_poor
    duration_boom duration_boom_adv duration_boom_mid duration_boom_poor
    amplitude_average_boom amplitude_average_boom_adv amplitude_average_boom_mid amplitude_average_boom_poor];

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

boom_des1 = num2cell(boom_des);
table_boom_des_ca = [subtitle_boom_des; Labels_v  boom_des1];

%Create tables for descriptive statistics of the bust
bust_des=[num_bust num_bust_adv num_bust_mid num_bust_poor
    average_bust average_bust_adv average_bust_mid average_bust_poor
    duration_bust duration_bust_adv duration_bust_mid duration_bust_poor
    amplitude_average_bust amplitude_average_bust_adv amplitude_average_bust_mid amplitude_average_bust_poor];

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

bust_des1=num2cell(bust_des);
table_bust_des_ca = [subtitle_bust_des; Labels_v  bust_des1];

save case_CA5bis 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 INDEX%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
load case_CA1bis
load case_CA2bis
load case_CA3bis
load case_CA4bis
load case_CA5bis

%% 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_ca,~,~,~, boom_values_ca] = average_boom_bust(num_ca, num_boom, boom_matrix, cat);

%BUST
%Calculate average, standard deviation and confidence interval
[average_bust_values_ca,~,~,~, bust_values_ca] = average_boom_bust(num_ca, num_bust, bust_matrix, cat);

%% 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_indext_values_boom_ca, std_indext_values_boom_ca, upper_bound_boom_ca, lower_bound_boom_ca, indext_values_boom_ca] = average_boom_bust(num_index, num_boom, boom_matrix, indext);

%BUST
%Calculate average, standard deviation and confidence interval
[average_indext_values_bust_ca, std_indext_values_bust_ca, upper_bound_bust_ca, lower_bound_bust_ca, indext_values_bust_ca] = average_boom_bust(num_index, num_bust, bust_matrix, indext);

%% Make plots with average detrended index and average current account (reference point boom/bust)

save case_CA7bis num_boom num_bust average_boom_values_ca average_bust_values_ca boom_values_ca bust_values_ca average_indext_values_boom_ca std_indext_values_boom_ca upper_bound_boom_ca lower_bound_boom_ca indext_values_boom_ca average_indext_values_bust_ca std_indext_values_bust_ca upper_bound_bust_ca lower_bound_bust_ca indext_values_bust_ca

end