% Find Biannual Extremes in Standardized Returns

clear all;
small = 1.0e-10;
pinv_tol = 1.0e-05;
big = 1.0e+8;

% -- File Directories   
outdir = 'out/';
figdir = 'fig/';
matdir = 'mat/';

% Read in Data
fname = [matdir 'SP500_VW_Daily_StandardizedReturns_1926_2022.mat'];
load(fname);
% Data are yr, mth, ret, ret_std
fy = 1926;
ly = 2022;
ny = ly - fy + 1;
% Standardized Returns
ret_std_l = zeros(2*ny,1);  % Largest
ret_std_s = zeros(2*ny,1);  % Smallest

imth1 = mth <= 6.001;
imth2 = mth >= 6.999;
[~,calvec,~]=calendar_make([fy 1],[ly 2],2);

for t = fy:ly
    i = t - fy + 1;
    j = 2*(i-1);

    iyr = yr == t;
    i1 = iyr.*imth1;
    i2 = iyr.*imth2;

    ret_tmp = ret_std(i1==1);
    ret_srt = sort(ret_tmp);
    ret_std_l(j+1) = ret_srt(end);
    ret_std_s(j+1) = ret_srt(1);

    ret_tmp = ret_std(i2==1);
    ret_srt = sort(ret_tmp);
    ret_std_l(j+2) = ret_srt(end);
    ret_std_s(j+2) = ret_srt(1);
end

% Save Extremes: Biannual Extremes
fname = [matdir 'SP500_StandardizedReturns_Extremes_Biannual_' num2str(fy) '_' num2str(ly) '.mat'];
save(fname,'calvec','ret_std_l','ret_std_s');