%%% computes Bbserved Herding Rates. 
close all;
clear;
clc;


%% Load data

load('A_DataBase_TSE_Filtered.mat')


% extract Closing price Data
Data = HRMarketData.Close;

% calculate Returns
nproduct = size(Data,2);
nTimestep = size(Data,1);
RetData = [nan(1,size(Data,2)); price2ret(Data)];

% make full Data array
rettttt   = RetData(:)*100;
Preicesss = Data(:);

% preallocation
Herd_Rate_ijt_observ = cell(nproduct);
HR_Bi_Product_observed   = nan(nproduct);
Herd_Rate_ijt_tot = nan(nproduct,nproduct,nTimestep);

% calculate Hering rates
for ii= 1:nproduct-1

    a = RetData(:,ii);


    for jj= ii+1:nproduct

        b = RetData(:,jj);

        Herd_Rate_ijt_observ{ii,jj} = 100* ( 1 - (abs(a-b)./ (max(abs(a),abs(b))) ));
        Herd_Rate_ijt_tot(ii,jj,:) = Herd_Rate_ijt_observ{ii,jj} ;
        HR_Bi_Product_observed(ii,jj) = nanmean(Herd_Rate_ijt_observ{ii,jj});
    end

end

% primary  description
HIII = nanmean(HR_Bi_Product_observed);
nanmean(nanmean(HR_Bi_Product_observed))
nanstd(nanstd(HR_Bi_Product_observed))

 
 
bb = HR_Bi_Product_observed;
bb(isnan(bb)) =0;
hh =  bb + bb';

Hr_i =  nanmean(hh);
 
 

Descibtive(1).Mean   = nanmean(Hr_i);
Descibtive(1) .Std   = nanstd(Hr_i);
Descibtive(1).Median = nanmedian(Hr_i);
Descibtive(1).Min    = min(Hr_i);
Descibtive(1).Max    = max(Hr_i);





%% saving

save('B_Observed_HR','HR_Bi_Product_observed','RetData')
save('B_Herd_Rate_ijt_observ','Herd_Rate_ijt_tot')







