% INFORMATION

% The code must be run in the order (sections) that it is constructed here. 
% Some of the code requires it to be organized in seperate folders.
% Some subsections in for example: Cumulative plots and histogram plots (US)
% must be run seperately such as "Plot Long 2" and then % Plot Long 3" etc

%% Swap spread arbitrage - This code creates the return indices etc




clear;
clc;
format short
warning off

% Loading the data
opts1   = detectImportOptions('US.xlsx','NumHeaderLines',0);
opts2   = detectImportOptions('UK.xlsx','NumHeaderLines',0);
opts3   = detectImportOptions('JPY.xlsx','NumHeaderLines',0);
DataUS  = readtable('US.xlsx', opts1, 'ReadVariableNames',true);
DataUK  = readtable('UK.xlsx', opts2, 'ReadVariableNames',true);
DataJPY = readtable('JPY.xlsx', opts3, 'ReadVariableNames',true);

% Datefunction
DataUS.Var1  = datetime(DataUS.Var1,'Format','dd-MM-yyyy');
DataUK.Var1  = datetime(DataUK.Var1,'Format','dd-MM-yyyy');
DataJPY.Var1 = datetime(DataJPY.Var1,'Format','dd-MM-yyyy');

% Define variable names
DataUS.Properties.VariableNames = {'Dates' 'C0823M' 'C0826M' 'C0821Y'...
    'C0822Y' 'C0823Y' 'C0825Y' 'C0827Y' 'C08210Y' 'USSW1' 'USSW2'...
    'USSW3' 'USSW5' 'USSW7' 'USSW10' 'US0001M' 'US0003M' 'US0006M' 'USRGCGC'};

DataUK.Properties.VariableNames = {'Dates' 'C1103M' 'C1106M' 'C1101Y'...
    'C1102Y' 'C1103Y' 'C1105Y' 'C1107Y' 'C11010Y' 'BPSW1' 'BPSW2'...
    'BPSW3' 'BPSW5' 'BPSW7' 'BPSW10' 'BP0001M' 'BP0003M' 'BP0006M' 'BPRPF'};

DataJPY.Properties.VariableNames = {'Dates' 'C1053M' 'C1056M' 'C1051Y'...
    'C1052Y' 'C1053Y' 'C1055Y' 'C1057Y' 'C10510Y' 'JYSW1' 'JYSW2'...
    'JYSW3' 'JYSW5' 'JYSW7' 'JYSW10' 'JY0001M' 'JY0003M' 'JY0006M' 'JYRPF'};

% Remove NaN and NaT
DataUS = rmmissing(DataUS,'DataVariables',{'Dates' 'C0823M' 'C0826M' 'C0821Y'...
    'C0822Y' 'C0823Y' 'C0825Y' 'C0827Y' 'C08210Y' 'USSW1' 'USSW2'...
    'USSW3' 'USSW5' 'USSW7' 'USSW10' 'US0001M' 'US0003M' 'US0006M' 'USRGCGC'});

DataUK = rmmissing(DataUK,'DataVariables',{'Dates' 'C1103M' 'C1106M' 'C1101Y'...
    'C1102Y' 'C1103Y' 'C1105Y' 'C1107Y' 'C11010Y' 'BPSW1' 'BPSW2'...
    'BPSW3' 'BPSW5' 'BPSW7' 'BPSW10' 'BP0001M' 'BP0003M' 'BP0006M' 'BPRPF'});

DataJPY = rmmissing(DataJPY,'DataVariables',{'Dates' 'C1053M' 'C1056M' 'C1051Y'...
    'C1052Y' 'C1053Y' 'C1055Y' 'C1057Y' 'C10510Y' 'JYSW1' 'JYSW2'...
    'JYSW3' 'JYSW5' 'JYSW7' 'JYSW10' 'JY0001M' 'JY0003M' 'JY0006M' 'JYRPF'});

% Define variables
SwapBidAsk     = 0.01;
TreasuryBidAsk = 1/32;
RepoBidAsk     = 0.1;
Trigger        = 0.1;

% Define length
DataUS = DataUS(1:271,:);
DataUK = DataUK(1:246,:);
DataJPY = DataJPY(1:246,:);


% Use this when everything is done
% Defines the correct data based on user input
prompt = {'Enter strategy. 2, 3, 5, 7, 10 or ALL:','Enter US, UK or JPY:'};
titles  = 'Swap spread arbitrage strategy';
dims   = 4;
Info   = inputdlg(prompt,titles,dims);

Strategy = str2double(Info(1,1));
AllStrategies = string(Info(1,1));
Country = string(Info(2,1));

if Country == "US"
   Bonds = DataUS(:,[2 3 4 5 6 7 8 9]);
   Data = DataUS;
   Freq = 4;
   if Strategy == 2
      Maturity = DataUS(:,[1 5 11 17 19]);
      numIterations = 1;
      maxIterations = 1;
      stra = 2;
   end
   if Strategy == 3     
      Maturity = DataUS(:,[1 6 12 17 19]);
      numIterations = 1;
      maxIterations = 1;
      stra = 3;
   end
   if Strategy == 5
      Maturity = DataUS(:,[1 7 13 17 19]);
      numIterations = 1;
      maxIterations = 1;
      stra = 5;
   end
   if Strategy == 7
      Maturity = DataUS(:,[1 8 14 17 19]);
      numIterations = 1;
      maxIterations = 1;
      stra = 7;
   end
   if Strategy == 10
      Maturity = DataUS(:,[1 9 15 17 19]);
      numIterations = 1;
      maxIterations = 1;
      stra = 10;
   end
   if AllStrategies == "ALL"
      Strategy = 1;
      numIterations = 1;
      maxIterations = 5;
      CountryAll = 1; 
   end
end

if Country == "UK"
   Bonds = DataUK(:,[2 3 4 5 6 7 8 9]);
   Data = DataUK;
   Freq = 2;
   if Strategy == 2
      Maturity = DataUK(:,[1 5 11 18 19]);
      numIterations = 1;
      maxIterations = 1;
      stra = 2;
   end
   if Strategy == 3     
      Maturity = DataUK(:,[1 6 12 18 19]);
      numIterations = 1;
      maxIterations = 1;
      stra = 3;
   end
   if Strategy == 5
      Maturity = DataUK(:,[1 7 13 18 19]);
      numIterations = 1;
      maxIterations = 1;
      stra = 5;
   end
   if Strategy == 7
      Maturity = DataUK(:,[1 8 14 18 19]); 
      numIterations = 1;
      maxIterations = 1;
      stra = 7;
   end
   if Strategy == 10
      Maturity = DataUK(:,[1 9 15 18 19]);
      numIterations = 1;
      maxIterations = 1;
      stra = 10;
   end
   if AllStrategies == "ALL"
      Strategy = 1;
      numIterations = 1;
      maxIterations = 5;
      CountryAll = 2; 
   end
end

if Country == "JPY"
   Bonds = DataJPY(:,[2 3 4 5 6 7 8 9]);
   Data = DataJPY;
   Freq = 2;
   if Strategy == 2
      Maturity = DataJPY(:,[1 5 11 18 19]);
      numIterations = 1;
      maxIterations = 1;
      stra = 2;
   end
   if Strategy == 3     
      Maturity = DataJPY(:,[1 6 12 18 19]);
      numIterations = 1;
      maxIterations = 1;
      stra = 3;
   end
   if Strategy == 5
      Maturity = DataJPY(:,[1 7 13 18 19]);
      numIterations = 1;
      maxIterations = 1;
      stra = 5;
   end
   if Strategy == 7
      Maturity = DataJPY(:,[1 8 14 18 19]); 
      numIterations = 1;
      maxIterations = 1;
      stra = 7;
   end
   if Strategy == 10
      Maturity = DataJPY(:,[1 9 15 18 19]);
      numIterations = 1;
      maxIterations = 1;
      stra = 10;
   end
   if AllStrategies == "ALL"
      Strategy = 1;
      numIterations = 1;
      maxIterations = 5;
      CountryAll = 3; 
   end
end


while numIterations <= maxIterations

     if numIterations == 1 && AllStrategies == "ALL"
        Strategy = 2;  
        if CountryAll == 1
            Maturity = DataUS(:,[1 5 11 17 19]);
            Bonds = DataUS(:,[2 3 4 5 6 7 8 9]);  
        elseif CountryAll == 2
            Maturity = DataUK(:,[1 5 11 18 19]);
            Bonds = DataUK(:,[2 3 4 5 6 7 8 9]);
        elseif CountryAll == 3
            Maturity = DataJPY(:,[1 5 11 18 19]);
            Bonds = DataJPY(:,[2 3 4 5 6 7 8 9]);
        end      
     end
     if numIterations == 2 && AllStrategies == "ALL"
        Strategy = 3;
        if CountryAll == 1
            Maturity = DataUS(:,[1 6 12 17 19]);
            Bonds = DataUS(:,[2 3 4 5 6 7 8 9]);
        elseif CountryAll == 2
            Maturity = DataUK(:,[1 6 12 18 19]);
            Bonds = DataUK(:,[2 3 4 5 6 7 8 9]);
        elseif CountryAll == 3
            Maturity = DataJPY(:,[1 6 12 18 19]);
            Bonds = DataJPY(:,[2 3 4 5 6 7 8 9]);
        end 
     end
     if numIterations == 3 && AllStrategies == "ALL"
        Strategy = 5;
        if CountryAll == 1
            Maturity = DataUS(:,[1 7 13 17 19]);
            Bonds = DataUS(:,[2 3 4 5 6 7 8 9]);
        elseif CountryAll == 2
            Maturity = DataUK(:,[1 7 13 18 19]);
            Bonds = DataUK(:,[2 3 4 5 6 7 8 9]);
        elseif CountryAll == 3
            Maturity = DataJPY(:,[1 7 13 18 19]);
            Bonds = DataJPY(:,[2 3 4 5 6 7 8 9]);
        end 
     end
     if numIterations == 4 && AllStrategies == "ALL"
        Strategy = 7;
        if CountryAll == 1
            Maturity = DataUS(:,[1 8 14 17 19]);
            Bonds = DataUS(:,[2 3 4 5 6 7 8 9]);
        elseif CountryAll == 2
            Maturity = DataUK(:,[1 8 14 18 19]);
            Bonds = DataUK(:,[2 3 4 5 6 7 8 9]);
        elseif CountryAll == 3
            Maturity = DataJPY(:,[1 8 14 18 19]);
            Bonds = DataJPY(:,[2 3 4 5 6 7 8 9]);
        end 
      end
      if numIterations == 5 && AllStrategies == "ALL"
         Strategy = 10;
         if CountryAll == 1
            Maturity = DataUS(:,[1 9 15 17 19]);
            Bonds = DataUS(:,[2 3 4 5 6 7 8 9]);
         elseif CountryAll == 2
            Maturity = DataUK(:,[1 9 15 18 19]);
            Bonds = DataUK(:,[2 3 4 5 6 7 8 9]); 
         elseif CountryAll == 3
            Maturity = DataJPY(:,[1 9 15 18 19]);
            Bonds = DataJPY(:,[2 3 4 5 6 7 8 9]);
        end 
      end

    % First interpolation of BONDS 

   % x = zeros(height(Bonds),1);
   % x = array2table(x);
    y = [3/12, 6/12, 1, 2, 3, 5, 7, 10];
  %  y = [0, 3/12, 6/12, 1, 2, 3, 5, 7, 10];
    y = array2table(y);
%    Bonds = [x,Bonds];
  %  y.Properties.VariableNames = {'x' 'M3' 'M6' 'Y1' 'Y2', ...
   %     'Y3' 'Y5' 'Y7' 'Y10'} ;
    y.Properties.VariableNames = {'M3' 'M6' 'Y1' 'Y2', ...
        'Y3' 'Y5' 'Y7' 'Y10'} ;
  
%    Bonds.Properties.VariableNames = {'x' 'M3' 'M6' 'Y1' 'Y2', ...
 %       'Y3' 'Y5' 'Y7' 'Y10'} ;
  Bonds.Properties.VariableNames = { 'M3' 'M6' 'Y1' 'Y2', ...
        'Y3' 'Y5' 'Y7' 'Y10'} ;

    Bonds = [y;Bonds];

    % Bootstrap and discountfactor calculation/estimation (BONDS)

    T = zeros(1,20);
    for v = 1:20
        T(v)= v/2;
    end

    pr = zeros(20,1);
    pr(:,1) = 100;
    Discount = zeros(height(Bonds)-1,20);

    for t = 1:height(Bonds)-1
        Bond1interp = interp1(table2array(Bonds(1,1:end)),table2array(Bonds(1+t,1:end)),T,'spline'); % +t because the upper row is maturity
        XR = zeros(20,20);
        for v= 1:20
            XR(v,1) = Bond1interp(v)./2;
            XR(v,1:v) = XR(v,1);
            XR(v,v) = XR(v,1)+100;
            XR(1,1)= 100 + (Bonds{1+t,1})./2 ; % new
            XR(2,1)=0; %new
            XR(2,2)= 100 + (Bonds{1+t,2} ); %new
        end
        Discount(t,:) = inv(XR)*pr;
    end 

    Discount = [100./(table2array(Bonds(2:end,2))./4 + 100), Discount]; % Check if divide by 2 or 4
    Discount = [3/12 , T;Discount];
    for i = 1:1:12*10
        V(i)=i/12;
    end

    Bond2interp = zeros(1000,120); % way too many rows in order to make valuations later on correct
    for i = 1:height(Bonds)-1
        Bond2interp(i,:) = interp1(Discount(1,1:end),Discount(1+i,1:end),V,'spline'); % +t because the upper row is maturity
    end

    % FIRST INTERPOLATION of SWAP
    % creating synthetic 6m swap

  %  f = [0, 6/12 , 1 , 2 , 3 , 5, 7 , 10];
        f = [ 6/12 , 1 , 2 , 3 , 5, 7 , 10];

    f = array2table(f);
%    f.Properties.VariableNames = {'x' 'M6' 'Swap1' 'Swap2', ...
 %       'Swap3' 'Swap5' 'Swap7' 'Swap10'} ;
f.Properties.VariableNames = { 'M6' 'Swap1' 'Swap2', ...
        'Swap3' 'Swap5' 'Swap7' 'Swap10'} ;

   % SwapDataset = [x, Data(:,18), Data(:,10:15)]; % should the 3m libor be included?
        SwapDataset = [ Data(:,18), Data(:,10:15)]; % should the 3m libor be included?

    %SwapDataset.Properties.VariableNames = {'x' 'M6' 'Swap1' 'Swap2', ...
     %   'Swap3' 'Swap5' 'Swap7' 'Swap10'} ;
    SwapDataset.Properties.VariableNames = { 'M6' 'Swap1' 'Swap2', ...
        'Swap3' 'Swap5' 'Swap7' 'Swap10'} ;
    SwapDataset = [f;SwapDataset];

    pr = zeros(20,1);
    pr(:,1) = 100;
    DiscountSwap = zeros(height(SwapDataset)-1,20);

    % ignoring nan -> could Set NaN values on 1yr swap equal to 1yr treasury

    for t = 1:height(SwapDataset)-1 % -1 because of maturity as first row
        Swap1interp = interp1(table2array(SwapDataset(1,1:end)),table2array(SwapDataset(1+t,1:end)),T,'spline'); % +t because the upper row is maturity
        XV = zeros(20,20);
        for v = 1:20
            XV(v,1) = Swap1interp(v)./2;
            XV(v,1:v) = XV(v,1);
            XV(v,v) = XV(v,1)+100;
            XV(1,1)= 100 + (SwapDataset{1+t,1})./2 ; % new
            XR(2,1)=0; %new
            XR(2,2)= 100 + (SwapDataset{1+t,2} ); %new
        end
        DiscountSwap(t,:) = inv(XV)*pr; 
    end 

    DiscountSwap = [100./((table2array(Data(1:end,17))./4) +100), DiscountSwap]; %correct?? divide by 4 or 2
    DiscountSwap = [3/12 , T;DiscountSwap];
    Swap2interp = zeros(1000,120); % way too many rows in order to make valuations later on correct

    for i = 1:length(DiscountSwap)-1 % -1 because of maturity as first row
        Swap2interp(i,:) = interp1(DiscountSwap(1,1:end),DiscountSwap(1+i,1:end),V,'spline'); % +t because the upper row is maturity
    end


    % CASH FLOW SECTION
    
    
    % Fixed: SS = CMS - CMT and SS = CMT - CMS : long and short
    Maturity.SS_long = (Maturity{:,3} - (SwapBidAsk /2)) - (Maturity{:,2} + (TreasuryBidAsk /2));
    Maturity.SS_short = (Maturity{:,2} - (TreasuryBidAsk /2)) - (Maturity{:,3} + (SwapBidAsk /2));

    % Floating: S = r - L (long) and S = L - r (short) : long and short
    Maturity.S_long = (Maturity{:,5} - (RepoBidAsk /2)) - (Maturity{:,4});
    Maturity.S_short = (Maturity{:,4}) - (Maturity{:,5} + (RepoBidAsk /2));

    % Long and short spread
    Maturity.LongSpread = Maturity{:,6} + Maturity{:,8};
    Maturity.ShortSpread = Maturity{:,7} + Maturity{:,9};

    % Finding when going into a trade
    Maturity.LongPos = logical(Maturity.LongSpread >= Trigger);
    Maturity.ShortPos = logical(Maturity.ShortSpread >= Trigger);

    % Indexing the trade positions
    idxLong = find(Maturity.LongPos == 1);
    idxShort = find(Maturity.ShortPos == 1);

    % Define the width of the table
    Widt1 = width(Maturity);

    % This loop creates date variable names when the trade starts for the long
    % positions
    a = width(Maturity) + 1; 
    for b = 1:length(Maturity{:,1}) 
        if Maturity{b,12} == 1
           Variab = matlab.lang.makeValidName(datestr(Maturity{b,1}));
           Maturity.a = zeros(1,height(Maturity))';
           Maturity.Properties.VariableNames{a} = Variab;
           a = a + 1;
        end 
    end

    % This loop adds a one when the trade should stop based on covergence of
    % the swap and/or the maturity of the swap (long positions)
    for k = 1:length(idxLong) % 1 to 96
        n = 0;
            for j = idxLong(k):1:idxLong(k)+(Strategy*12)
                n = n+1;
                if (Maturity{idxLong(k),6} + Maturity{j,8} <= 0 || n == ((Strategy*12) + 1) ...
                        || Maturity{j,6} == Maturity{end,6})
                    Maturity(j,Widt1+k) = array2table(1); 
                    break
                end
            end
    end

    % Redefine the width of the table
    Widt2 = width(Maturity);

    % This loop creates date variable names when the trade starts for the short
    % positions
    a = width(Maturity) + 1; 
    for b = 1:length(Maturity{:,1}) 
        if Maturity{b,13} == 1
           Variab = matlab.lang.makeValidName(datestr(Maturity{b,1}));
           Maturity.a = zeros(1,height(Maturity))';
           Maturity.Properties.VariableNames{a} = Variab;
           a = a + 1;
        end 
    end

    % This loop adds a one when the trade should stop based on covergence of
    % the swap and/or the maturity of the swap (short positions)
    for k = 1:length(idxShort) 
        n = 0;
            for j = idxShort(k):1:idxShort(k)+(Strategy*12)
                n = n+1; 
                if (Maturity{idxShort(k),7} + Maturity{j,9} <= 0 || n == ((Strategy*12) + 1) ...
                        || Maturity{j,7} == Maturity{end,7})
                    Maturity(j,Widt2+k) = array2table(1); 
                    break
                end
            end
    end

    % Tests the number of ones so that its not more than one
    Test = zeros(width(Maturity)-13,1);
    for m = 14:width(Maturity)
        Test(m-13) = sum(table2array(Maturity(:,m)));
    end
    Control = sum(Test);

    % Index out of contract
    idxLongOut = zeros(length(idxLong),1);

    for i = 1:length(idxLong)
        idxLongOut(i) = find(Maturity{:,13+i} == 1);
    end

    idxShortOut = zeros(length(idxShort),1);

    for i = 1:length(idxShort)
       idxShortOut(i) = find(Maturity{:,13+length(idxLong)+i} == 1); 
    end 

    % Cash flow long position
    MaturityCFlong = [Maturity(:,1),Maturity(:,6),Maturity(:,8), Maturity(:,Widt1+1:Widt2)];
    MaturityCFlong(:,4:end) = array2table(0);

    % This loop adds the CF from the fixed leg in the long position trade
    for t = 1:length(idxLong)  
        for k = idxLong(t)+6:6:find(table2array(Maturity(:,Widt1+t)) == 1)
            MaturityCFlong(k,t+3) =  array2table(Maturity{idxLong(t),6}./2);
        end
    end

    % This loop adds the CF from the floating leg in the long position trade
    for t= 1:length(idxLong)  
        for k = idxLong(t)+(12/Freq):(12/Freq):find(table2array(Maturity(:,Widt1+t)) == 1)
            MaturityCFlong(k,t+3) = array2table(table2array(MaturityCFlong(k,t+3)) + ...
            (table2array(MaturityCFlong(k-3,3))./Freq));
        end
    end

    % Cash flow short position
    MaturityCFshort = [Maturity(:,1),Maturity(:,7),Maturity(:,9), Maturity(:,Widt2+1:end)];
    MaturityCFshort(:,4:end) = array2table(0);

    % This loop adds the CF from the fixed leg in the short position trade
    for t = 1:length(idxShort)  
        for k = idxShort(t)+6:6:find(table2array(Maturity(:,Widt2+t)) == 1)
            MaturityCFshort(k,t+3) =  array2table(Maturity{idxShort(t),7}./2);
        end
    end

    % This loop adds the CF from the floating leg in the short position trade
    for t= 1:length(idxShort)  
        for k = idxShort(t)+(12/Freq):(12/Freq):find(table2array(Maturity(:,Widt2+t)) == 1)
            MaturityCFshort(k,t+3) = array2table(table2array(MaturityCFshort(k,t+3)) + ...
            (table2array(MaturityCFshort(k-3,3))./Freq));
        end
    end



    % BOND SECTION
    disp('Bond Section')
    % Bond CF Long calculation
    CFBondLong = [MaturityCFlong(:,1), MaturityCFlong(:,4:end)];
    CFBondLong(:,2:end) = array2table(zeros(height(MaturityCFlong),width(CFBondLong)-1));

    for t = 1:length(idxLong)
        for k = idxLong(t)+6:6:idxLong(t)+(Strategy*12)
            CFBondLong(k,t+1) =  array2table(Maturity{idxLong(t),2}./2);
        end
        CFBondLong(idxLong(t)+(Strategy*12),t+1) = ...
            array2table(table2array(CFBondLong(idxLong(t)+(Strategy*12),t+1)) + 100);
        if t == length(idxLong)
            CFBondLong(idxLong(t)+(Strategy*12)+200,2) = array2table(0);
        end
    end

    % Bond CF Short calculation
    CFBondShort = [MaturityCFshort(:,1), MaturityCFshort(:,4:end)];
    CFBondShort(:,2:end) = array2table(zeros(height(MaturityCFshort),width(CFBondShort)-1));

    for t = 1:length(idxShort)
        for k = idxShort(t)+6:6:idxShort(t)+(Strategy*12)
            CFBondShort(k,t+1) =  array2table(Maturity{idxShort(t),2}./2);
        end
        CFBondShort(idxShort(t)+(Strategy*12),t+1) = ...
            array2table(table2array(CFBondShort(idxShort(t)+(Strategy*12),t+1)) + 100);
        if t == length(idxShort)
            CFBondShort(idxShort(t)+(Strategy*12)+200,2) = array2table(0);
        end
    end

    

    % Valuation BOND long contracts
    ValueBondLong = CFBondLong;
    ValueBondLong(:,2:end) = array2table(0);
    PVsumLong = zeros(Strategy*12+1,length(idxLong));

    for j = 1:length(idxLong)
        for t = 0:Strategy*12
            PV = zeros(Strategy*12,Strategy*12+1);
            if idxLong(j) + t >= idxLongOut(j) +1 % fjernet +1 på rhs
                break
            end
        for i = 1:Strategy*12
            PV(i,t+1) = table2array(CFBondLong(idxLong(j)+i+t,1+j)) .* Bond2interp(idxLong(j)+t,i); % ex dividend
        end
        PVsumLong(t+1,j) = sum(PV(:,t+1));
        ValueBondLong(idxLong(j)+t,1+j) = array2table(PVsumLong(t+1,j)); % ex dividend valuation
        end
    end

    % Valuation BOND short contracts
    ValueBondShort = CFBondShort;
    ValueBondShort(:,2:end) = array2table(0);
    PVsumShort = zeros(Strategy*12+1,length(idxShort));

    for j = 1:length(idxShort)
        for t = 0:Strategy*12
            PV = zeros(Strategy*12,1);
            if idxShort(j) + t >= idxShortOut(j)+1 % tok +1 for å få verdi når en går ut, kontroller at dette blir riktig
                break
            end
        for i = 1:Strategy*12
            PV(i,t+1) = table2array(CFBondShort(idxShort(j)+i+t,1+j)) .* Bond2interp(idxShort(j)+t,i); % ex dividend
        end
        PVsumShort(t+1,j) = sum(PV(:,t+1));
        ValueBondShort(idxShort(j)+t,1+j) = array2table(PVsumShort(t+1,j));
        end
    end

    
    % Returns BONDS Long-positions
    ReturnBondLong = ValueBondLong;
    ReturnBondLong(:,2:end) = array2table(0);

    for i = 1:length(idxLong)
        if idxLong(i) == 1
           for k = idxLong(i):idxLongOut(i)
               if idxLong(i) == 1 && k == 1
                  ReturnBondLong(k,1+i) = array2table(table2array(ValueBondLong(k,1+i)) - 0);
               else
                  ReturnBondLong(k,1+i) = array2table(table2array(ValueBondLong(k,1+i)) - table2array(ValueBondLong(k-1,1+i)));
               end
           end
        else
        ReturnBondLong(idxLong(i):idxLongOut(i),1+i) = array2table(table2array(ValueBondLong(idxLong(i):idxLongOut(i),1+i)) ...
            - table2array(ValueBondLong(idxLong(i)-1:idxLongOut(i)-1,1+i)));
        end   
    end

    % adding face at maturity if held to maturity
    for j = 1:length(idxLong)
        if idxLong(j) + Strategy*12 == idxLongOut(j)
            ReturnBondLong(idxLong(j) + Strategy*12,1+j) = array2table(table2array(ReturnBondLong(idxLong(j)+ Strategy*12,1+j)) + 100);
        end
    end

    for i = 1:length(idxLong)
        ReturnBondLong(idxLong(i),1+i) = array2table(table2array(ReturnBondLong(idxLong(i),1+i)) - 100);
    end

    for i = 1:length(idxLong)
        for j = 1:idxLongOut(i) - idxLong(i)
            ReturnBondLong(idxLong(i)+j,1+i) = array2table(table2array(ReturnBondLong(idxLong(i)+j,1+i)) ./ 100);
        end
    end

    ReturnBondLong(1:end,2:end) = array2table(table2array(ReturnBondLong(1:end,2:end)) .* (-1));

    
    % Returns BONDS Short-positions
    ReturnBondShort = ValueBondShort;
    ReturnBondShort(:,2:end) = array2table(0);

    for i = 1:length(idxShort)
        if idxShort(i) == 1
            for k = idxShort(i):idxShortOut(i)
                if idxShort(i) == 1 && k == 1
                   ReturnBondShort(k,1+i) = array2table(table2array(ValueBondShort(k,1+i)) - 0);
                else
                ReturnBondShort(k,1+i) = array2table(table2array(ValueBondShort(k,1+i)) - table2array(ValueBondShort(k-1,1+i)));
                end
            end
        else
            ReturnBondShort(idxShort(i):idxShortOut(i),1+i) =  array2table(table2array(ValueBondShort(idxShort(i):idxShortOut(i),1+i)) ...
                - table2array(ValueBondShort(idxShort(i)-1:idxShortOut(i)-1,1+i)));
        end
    end

    % adding face at maturity if held to maturity
    for j = 1:length(idxShort)
        if idxShort(j)+ Strategy*12 == idxShortOut(j)
            ReturnBondShort(idxShort(j) + Strategy*12,1+j) = array2table(table2array(ReturnBondShort(idxShort(j) + Strategy*12,1+j)) + 100);
        end
    end

    for i = 1:length(idxShort)
        ReturnBondShort(idxShort(i),1+i) = array2table(table2array(ReturnBondShort(idxShort(i),1+i)) - 100);
    end

    for i = 1:length(idxShort)
        for j = 1:idxShortOut(i)-idxShort(i)
            ReturnBondShort(idxShort(i)+j,1+i) = ...
                array2table(table2array(ReturnBondShort(idxShort(i)+j,1+i)) ./ 100);
        end
    end


    % SWAP SECTION
    disp('Swap Section')
    % Swap Valuation / Fixed leg valuation Long
    % swap rate pmt every 6mth

    SwapData = [Maturity(1:end,1),Maturity(1:end,3)];
    SwapCFLong= [Maturity(:,1), Maturity(:,14:13+length(idxLong))];
    SwapCFLong(:,2:end) = array2table(0);

    for t = 1:length(idxLong)
        for k = idxLong(t)+6:6:idxLong(t)+Strategy*12
            SwapCFLong(k,t+1) =  array2table(table2array(SwapData(idxLong(t),2))./2);
        end
        SwapCFLong(idxLong(t)+Strategy*12,t+1) = array2table(table2array(SwapCFLong(idxLong(t)+Strategy*12,t+1)) + 100);
        if t == length(idxLong)
           SwapCFLong(idxLong(t)+Strategy*12+200,2) = array2table(0);
        end
    end

    % LONG
    % Valuation SWAP Fixed leg Long
    ValueFixedLong = SwapCFLong;
    ValueFixedLong(:,2:end) = array2table(0);

    PVsumSwap = zeros(Strategy*12+1,length(idxLong)); 

    for j = 1:length(idxLong)
        for t = 0:Strategy*12
            PVSwap = zeros(Strategy*12,Strategy*12+1);
            if idxLong(j) +t >= idxLongOut(j) + 1 % fjernet +1  på rhs
                break
            end
            for i = 1:Strategy*12
                PVSwap(i,t+1) = table2array(SwapCFLong(idxLong(j)+i+t,1+j)) .* Swap2interp(idxLong(j)+t,i); % ex dividend
            end
            PVsumSwap(t+1,j) = sum(PVSwap(:,t+1));
            ValueFixedLong(idxLong(j)+t,1+j) = array2table(PVsumSwap(t+1,j)); % ex dividend valuation
        end
    end

    % Return SWAP Fixed leg long
    ReturnFixedLong = ValueFixedLong;
    ReturnFixedLong(:,2:end) = array2table(0);

    for i = 1:length(idxLong)
        if idxLong(i) == 1
            for k = idxLong(i):idxLongOut(i)
                if idxLong(i) == 1 && k == 1
                   ReturnFixedLong(k,1+i) = array2table(table2array(ValueFixedLong(k,1+i)) - 0);
                else
                ReturnFixedLong(k,1+i) = array2table(table2array(ValueFixedLong(k,1+i)) - table2array(ValueFixedLong(k-1,1+i)));
                end
            end
        else
            ReturnFixedLong(idxLong(i):idxLongOut(i),1+i) =  array2table(table2array(ValueFixedLong(idxLong(i):idxLongOut(i),1+i)) ...
                - table2array(ValueFixedLong(idxLong(i)-1:idxLongOut(i)-1,1+i)));
        end
    end

    % adding face at maturity if held to maturity
    for j = 1:length(idxLong)
        if idxLong(j) + Strategy*12 == idxLongOut(j)
            ReturnFixedLong(idxLong(j)+Strategy*12,1+j) = array2table(table2array(ReturnFixedLong(idxLong(j)+Strategy*12,1+j)) + 100);
        end
    end

    for i = 1:length(idxLong)
        ReturnFixedLong(idxLong(i),1+i) = array2table(table2array(ReturnFixedLong(idxLong(i),1+i)) - 100);
    end

    for i = 1:length(idxLong)
        for j = 1:idxLongOut(i)-idxLong(i)
            ReturnFixedLong(idxLong(i)+j,1+i) = array2table(table2array(ReturnFixedLong(idxLong(i)+j,1+i)) ./ 100);
        end
    end

    
    % Fixed leg CF Short
    SwapCFShort = CFBondShort(:,1:end);
    SwapCFShort(:,2:end) = array2table(0);

    for t = 1:length(idxShort)  
        for k = idxShort(t)+6:6:idxShort(t)+Strategy*12
            SwapCFShort(k,t+1) =  array2table(table2array(SwapData(idxShort(t),2))./2);
        end
        SwapCFShort(idxShort(t)+Strategy*12,t+1) = ...
                array2table(table2array(SwapCFShort(idxShort(t)+Strategy*12,t+1)) + 100);
        if t == length(idxShort)
           SwapCFShort(idxShort(t)+Strategy*12+200,2) = array2table(0); 
        end
    end
    

    % Valuation Fixed leg Short
    ValueFixedShort = SwapCFShort;
    ValueFixedShort(:,2:end) = array2table(0);
    PVsumSwap = zeros(Strategy*12+1,length(idxShort));

    for j = 1:length(idxShort)
        for t = 0:Strategy*12
            PVSwap = zeros(Strategy*12,Strategy*12+1);
            if idxShort(j) +t >= idxShortOut(j)+1 % fjernet +1 på rhs
                break
            end
            for i = 1:Strategy*12
                PVSwap(i,t+1) = table2array(SwapCFShort(idxShort(j)+i+t,1+j)) .*...
                    Swap2interp(idxShort(j)+t,i); % ex dividend
            end
        PVsumSwap(t+1,j) = sum(PVSwap(:,t+1));
        ValueFixedShort(idxShort(j)+t,1+j) = array2table(PVsumSwap(t+1,j)); % ex dividend valuation
        end
    end

    % Return Fixed leg Short
    ReturnFixedShort = ValueFixedShort;
    ReturnFixedShort(:,2:end) = array2table(0);

    for i = 1:length(idxShort)
        if idxShort(i) == 1
            for k = idxShort(i):idxShortOut(i)
                if idxShort(i) == 1 && k == 1
                   ReturnFixedShort(k,1+i) = array2table(table2array(ValueFixedShort(k,1+i)) - 0);
                else
                ReturnFixedShort(k,1+i) = array2table(table2array(ValueFixedShort(k,1+i)) - table2array(ValueFixedShort(k-1,1+i)));
                end
            end
        else
            ReturnFixedShort(idxShort(i):idxShortOut(i),1+i) = array2table( table2array(ValueFixedShort(idxShort(i):idxShortOut(i),1+i)) ...
                - table2array(ValueFixedShort(idxShort(i)-1:idxShortOut(i)-1,1+i)));
        end
    end

    % adding face at maturity if held to maturity
    for j = 1:length(idxShort)
        if idxShort(j)+Strategy*12 == idxShortOut(j)
            ReturnFixedShort(idxShort(j)+Strategy*12,1+j) = ...
                array2table(table2array(ReturnFixedShort(idxShort(j)+Strategy*12,1+j)) + 100);
        end
    end

    for i = 1:length(idxShort)
        ReturnFixedShort(idxShort(i),1+i) = array2table(table2array(ReturnFixedShort(idxShort(i),1+i)) - 100);
    end

    for i = 1:length(idxShort)
        for j = 1:idxShortOut(i)-idxShort(i)
            ReturnFixedShort(idxShort(i)+j,1+i) = ...
                array2table(table2array(ReturnFixedShort(idxShort(i)+j,1+i)) ./ 100);
        end
    end

    ReturnFixedShort(:,2:end)= array2table(table2array(ReturnFixedShort(:,2:end)) .* (-1));


    % CF calculation    
    CFLong = MaturityCFlong(:,[1,4:end]);
    CFLong(:,2:end) = array2table((table2array(CFLong(:,2:end)) ./100 ));

    CFShort = MaturityCFshort(:,[1,4:end]);
    CFShort(:,2:end) = array2table((table2array(CFShort(:,2:end)) ./100 ));   
    
 
    % [REPO] AND [LIBOR]
    
    % Repo and LIBOR CF when closing position before quarterly and half-yearly cf Long
    if isempty(idxLong) ~= 1
        RepoCFLongOut = MaturityCFlong(:,[1,4:end]);
        RepoCFLongOut(:,2:end) = array2table(0);
        
        LiborCFLongOut = MaturityCFlong(:,[1,4:end]);
        LiborCFLongOut(:,2:end) = array2table(0);

        idxRepoLong = zeros(height(MaturityCFlong),width(MaturityCFlong)-3);
        lastCFLong = zeros(width(MaturityCFlong)-3,1);

        for i = 1:width(MaturityCFlong)-3
            idxRepoLong(:,i) = logical(MaturityCFlong{:,3+i} ~=0);
        end

        for i = 1:width(MaturityCFlong)-3
            if sum(idxRepoLong(:,i)) == 0
               lastCFLong(i) = idxLong(i);
            else

            lastCFLong(i) = max(find(idxRepoLong(:,i)==1));
            end
        end
        
        % Becuase of ACT/360 day convention. 3-m LIBOR and REPO, hence
        % divide by 4
        if Country == "US"
            for i = 1:width(RepoCFLongOut)-1
                RepoCFLongOut{idxLongOut(i),1+i} = ((Maturity{lastCFLong(i),5} - (RepoBidAsk /2)) ./4 )...
                    * (daysact(Maturity{lastCFLong(i),1},Maturity{idxLongOut(i),1}) / 90);
                
                LiborCFLongOut{idxLongOut(i),1+i} = ( (-1)*Maturity{lastCFLong(i),4} ./ 4)...
                    * (daysact(Maturity{lastCFLong(i),1},Maturity{idxLongOut(i),1}) / 90);
            end
        end
        
        % Becuase of ACT/365 day convention. 6-m LIBOR and REPO, hence
        % divide by 13
        if Country == "UK" || Country == "JPY"
            for i = 1:width(RepoCFLongOut)-1
                RepoCFLongOut{idxLongOut(i),1+i} = ((Maturity{lastCFLong(i),5} - (RepoBidAsk /2)) ./2 )...
                    * (daysact(Maturity{lastCFLong(i),1},Maturity{idxLongOut(i),1}) / (365/2));
                
                LiborCFLongOut{idxLongOut(i),1+i} = ( (-1)*Maturity{lastCFLong(i),4} ./ 2)...
                    * (daysact(Maturity{lastCFLong(i),1},Maturity{idxLongOut(i),1}) / (365/2));
            end
        end

        
        for i = 1:width(CFLong)-1
            if (CFLong{idxLongOut(i),1+i} ~= 0) %then repo is already accounted for so we need to remove the repo cf
                RepoCFLongOut{idxLongOut(i),1+i} = 0 ;
                LiborCFLongOut{idxLongOut(i),1+i} = 0;
            end    
        end
        
        % To make it into decimal
        RepoCFLongOut{:,2:end} = RepoCFLongOut{:,2:end} ./ 100 ;
        LiborCFLongOut{:,2:end} = LiborCFLongOut{:,2:end} ./ 100;
    else
        RepoCFLongOut = MaturityCFlong(:,[1,4:end]);
        RepoCFLongOut(:,2:end) = array2table(0);
        
        LiborCFLongOut = MaturityCFlong(:,[1,4:end]);
        LiborCFLongOut(:,2:end) = array2table(0);
    
    end
    
    % Repo and LIBOR CF when closing position before quarterly and
    % half-yearly cf SHORT
    if isempty(idxShort) ~= 1
        RepoCFShortOut = MaturityCFshort(:,[1,4:end]);
        RepoCFShortOut(:,2:end) = array2table(0);
        
        LiborCFShortOut = MaturityCFshort(:,[1,4:end]);
        LiborCFShortOut(:,2:end) = array2table(0);

        idxRepoShort = zeros(height(MaturityCFshort),width(MaturityCFshort)-3);
        lastCFShort = zeros(width(MaturityCFshort)-3,1);
        for i = 1:width(MaturityCFshort)-3
            idxRepoShort(:,i) = logical(MaturityCFshort{:,3+i} ~=0);
        end

        for i = 1:width(MaturityCFshort)-3
            if sum(idxRepoShort(:,i)) == 0
                lastCFShort(i)=idxShort(i);
            else
            lastCFShort(i) = max(find(idxRepoShort(:,i)==1));
            end
        end
        
        % Becuase of ACT/360 day convention. 3-m LIBOR and REPO, hence
        % divide by 4
        if Country == "US"
            for i = 1:width(RepoCFShortOut)-1
                RepoCFShortOut{idxShortOut(i),1+i} = ((-1)*(Maturity{lastCFShort(i),5} + (RepoBidAsk /2)) ./4 )...
                        * (daysact(Maturity{lastCFShort(i),1},Maturity{idxShortOut(i),1}) / 90);

                LiborCFShortOut{idxShortOut(i),1+i} = (Maturity{lastCFShort(i),4} ./ 4)...
                        * (daysact(Maturity{lastCFShort(i),1},Maturity{idxShortOut(i),1}) / 90);
            end
        end
        
        % Becuase of ACT/365 day convention. 6-m LIBOR and REPO, hence
        % divide by 2
        if Country == "UK" || Country == "JPY"
            for i = 1:width(RepoCFShortOut)-1
                RepoCFShortOut{idxShortOut(i),1+i} = ((-1)*(Maturity{lastCFShort(i),5} + (RepoBidAsk /2)) ./2 )...
                        * (daysact(Maturity{lastCFShort(i),1},Maturity{idxShortOut(i),1}) / (365/2));

                LiborCFShortOut{idxShortOut(i),1+i} = (Maturity{lastCFShort(i),4} ./ 2)...
                        * (daysact(Maturity{lastCFShort(i),1},Maturity{idxShortOut(i),1}) / (365/2));
            end
        end

               
        for i = 1:width(CFShort)-1
            if (CFShort{idxShortOut(i),1+i} ~= 0) %then repo is already accounted for so we need to remove the repo cf
                RepoCFShortOut{idxShortOut(i),1+i} = 0 ;
                LiborCFShortOut{idxShortOut(i),1+i} = 0 ;
            end    
        end

        % To make it from percentage view to decimal view
        RepoCFShortOut{:,2:end} = RepoCFShortOut{:,2:end} ./100 ;
        LiborCFShortOut{:,2:end} = LiborCFShortOut{:,2:end} ./100 ;
        
    else
        
        RepoCFShortOut = MaturityCFshort(:,[1,4:end]);
        RepoCFShortOut(:,2:end) = array2table(0);
        
        LiborCFShortOut = MaturityCFshort(:,[1,4:end]);
        LiborCFShortOut(:,2:end) = array2table(0);
    end
    
    
    % Total return INDEX
    ReturnBondLong = rmmissing(ReturnBondLong,'DataVariables',{'Dates'});
    ReturnBondShort = rmmissing(ReturnBondShort,'DataVariables',{'Dates'});

    ReturnSwapLong = ReturnFixedLong;
    ReturnSwapLong = rmmissing(ReturnSwapLong,'DataVariables',{'Dates'});

    ReturnSwapShort = ReturnFixedShort;
    ReturnSwapShort = rmmissing(ReturnSwapShort,'DataVariables',{'Dates'});

    TotRetLong = ReturnSwapLong(:,:);
    TotRetLong(:,2:end) = {0};
    TotRetLong(1:end,2:end) = array2table((table2array(ReturnBondLong(1:end,2:end)) + ...
        table2array(CFLong(1:end,2:end)) + table2array(ReturnSwapLong(1:end,2:end)))...
        + table2array(RepoCFLongOut(:,2:end)) + table2array(LiborCFLongOut(:,2:end)));

    TotRetShort = ReturnSwapShort(:,:);
    TotRetShort(:,2:end) = {0};
    TotRetShort(1:end,2:end) = array2table((table2array(ReturnBondShort(1:end,2:end)) ...
        + table2array(CFShort(1:end,2:end)) + table2array(ReturnSwapShort(1:end,2:end)))...
        + table2array(RepoCFShortOut(:,2:end)) + table2array(LiborCFShortOut(:,2:end)) );

    TempReturnIndex = Maturity(:,1:7);
    TempReturnIndex.Properties.VariableNames(2) = {'Long'};
    TempReturnIndex.Properties.VariableNames(3) = {'Short'};
    TempReturnIndex.Properties.VariableNames(4) = {'LongPLUSShort'};
    TempReturnIndex.Properties.VariableNames(5) = {'ActivePosLong'};
    TempReturnIndex.Properties.VariableNames(6) = {'ActivePosShort'};
    TempReturnIndex.Properties.VariableNames(7) = {'EW'};
    TempReturnIndex(:,2:7) = {0};

    % Finding the active positions
    ActiveLongPos = TotRetLong(:,:);
    ActiveLongPos(:,2:end) = array2table(0);

    for j = 1:length(idxLong)
       ActiveLongPos(idxLong(j):idxLongOut(j),1+j) = array2table(1);
    end
    LongPos = zeros(height(ActiveLongPos),1);
    for i = 1:height(ActiveLongPos)
        LongPos(i,1) = sum(table2array(ActiveLongPos(i,2:end)),2);
    end

    % Finds active short positions
    ActiveShortPos = TotRetShort(:,:);
    ActiveShortPos(:,2:end) = array2table(0);

    for j = 1:length(idxShort)
       ActiveShortPos(idxShort(j):idxShortOut(j),1+j) = array2table(1);
    end
    ShortPos = zeros(height(ActiveShortPos),1);
    for i = 1:height(ActiveShortPos)
        ShortPos(i,1) = sum(table2array(ActiveShortPos(i,2:end)),2);
    end

    % Adds all elements in the return index 
    for k = 1:height(TempReturnIndex)
        TempReturnIndex(k,2) = array2table(sum(TotRetLong{k,2:end}));
    end

    for k = 1:height(TempReturnIndex)
        TempReturnIndex(k,3) = array2table(sum(TotRetShort{k,2:end}));
    end

    for k = 1:height(TempReturnIndex)
        TempReturnIndex(k,4) = array2table(sum(TempReturnIndex{k,2:3}));
    end

    for k = 1:height(TempReturnIndex)
        TempReturnIndex{k,5} = LongPos(k,1);
    end

    for k = 1:height(TempReturnIndex)
        TempReturnIndex{k,6} = ShortPos(k,1);
    end

    for k = 1:height(TempReturnIndex) % EW
        if sum(TempReturnIndex{k,5:6}) == 0
           TempReturnIndex(k,7) = {0};
        else
           TempReturnIndex(k,7) = array2table(table2array(TempReturnIndex(k,4)) ./ sum(TempReturnIndex{k,5:6}));
        end
    end
    
    ReturnIndex(:,numIterations) = TempReturnIndex(:,7);
    
    if AllStrategies == "ALL"
        if numIterations == 1
            TempReturn_Two = TempReturnIndex(:,:);
            TotRetLong_Two = TotRetLong(:,:);
            TotRetShort_Two = TotRetShort(:,:);
            idxLongOut_Two = idxLongOut(:,:);
            idxShortOut_Two = idxShortOut(:,:);
        elseif numIterations == 2
            TempReturn_Three = TempReturnIndex(:,:);
            TotRetLong_Three = TotRetLong(:,:);
            TotRetShort_Three = TotRetShort(:,:);
            idxLongOut_Three = idxLongOut(:,:);
            idxShortOut_Three = idxShortOut(:,:);
        elseif numIterations == 3
            TempReturn_Five = TempReturnIndex(:,:);
            TotRetLong_Five = TotRetLong(:,:);
            TotRetShort_Five = TotRetShort(:,:);
            idxLongOut_Five = idxLongOut(:,:);
            idxShortOut_Five = idxShortOut(:,:);
        elseif numIterations == 4
            TempReturn_Seven = TempReturnIndex(:,:);
            TotRetLong_Seven = TotRetLong(:,:);
            TotRetShort_Seven = TotRetShort(:,:);
            idxLongOut_Seven = idxLongOut(:,:);
            idxShortOut_Seven = idxShortOut(:,:);
        elseif numIterations == 5
            TempReturn_Ten = TempReturnIndex(:,:);
            TotRetLong_Ten = TotRetLong(:,:);
            TotRetShort_Ten = TotRetShort(:,:);
            idxLongOut_Ten = idxLongOut(:,:);
            idxShortOut_Ten = idxShortOut(:,:);
        end
    end
        
    
    if AllStrategies == "ALL" && numIterations < 5
       clearvars -except ReturnIndex Country Data DataJPY DataUK DataUS dims AllStrategies Info maxIterations numIterations opts1 opts2 ...
            opts3 prompt RepoBidAsk Strategy SwapBidAsk title TreasuryBidAsk Trigger Freq CountryAll TempReturn_Two TempReturn_Three ...
            TempReturn_Five TempReturn_Seven TempReturn_Ten TotRetLong_Two TotRetLong_Three TotRetLong_Five TotRetLong_Seven TotRetLong_Ten ...
            TotRetShort_Two TotRetShort_Three TotRetShort_Five TotRetShort_Seven TotRetShort_Ten idxLongOut_Two idxShortOut_Two ...
            idxLongOut_Three idxShortOut_Three idxLongOut_Five idxShortOut_Five idxLongOut_Seven idxShortOut_Seven ...
            idxLongOut_Ten idxShortOut_Ten
            
    end
    if numIterations == 1
        disp('Done with first run')
    elseif numIterations == 2
        disp('Done with second run')
    elseif numIterations == 3
        disp('Done with third run')
    elseif numIterations == 4
        disp('Done with fourth run')
    elseif numIterations == 5
        disp('Done with fifth run')
    end
               
    numIterations = numIterations + 1;
end


if AllStrategies == "ALL"
   ReturnIndex.Properties.VariableNames(1) = {'TwoYear'};
   ReturnIndex.Properties.VariableNames(2) = {'ThreeYear'};
   ReturnIndex.Properties.VariableNames(3) = {'FiveYear'};
   ReturnIndex.Properties.VariableNames(4) = {'SevenYear'};
   ReturnIndex.Properties.VariableNames(5) = {'TenYear'};
   ReturnIndex = [Maturity(:,1) ReturnIndex(:,:)];
   if CountryAll == 1
      save('ReturnIndexALL_US.mat', 'ReturnIndex')
      
      save('TempReturn_Two_US.mat', 'TempReturn_Two')
      save('TempReturn_Three_US.mat', 'TempReturn_Three')
      save('TempReturn_Five_US.mat', 'TempReturn_Five')
      save('TempReturn_Seven_US.mat', 'TempReturn_Seven')
      save('TempReturn_Ten_US.mat', 'TempReturn_Ten')
      
      save('TotRetLong_Two_US.mat', 'TotRetLong_Two')
      save('TotRetLong_Three_US.mat', 'TotRetLong_Three')
      save('TotRetLong_Five_US.mat', 'TotRetLong_Five')
      save('TotRetLong_Seven_US.mat', 'TotRetLong_Seven')
      save('TotRetLong_Ten_US.mat', 'TotRetLong_Ten')
      
      save('TotRetShort_Two_US.mat', 'TotRetShort_Two')
      save('TotRetShort_Three_US.mat', 'TotRetShort_Three')
      save('TotRetShort_Five_US.mat', 'TotRetShort_Five')
      save('TotRetShort_Seven_US.mat', 'TotRetShort_Seven')
      save('TotRetShort_Ten_US.mat', 'TotRetShort_Ten')
      
      save('idxLongOut_Two_US.mat', 'idxLongOut_Two')
      save('idxLongOut_Three_US.mat', 'idxLongOut_Three')
      save('idxLongOut_Five_US.mat', 'idxLongOut_Five')
      save('idxLongOut_Seven_US.mat', 'idxLongOut_Seven')
      save('idxLongOut_Ten_US.mat', 'idxLongOut_Ten')
      
      save('idxShortOut_Two_US.mat', 'idxShortOut_Two')
      save('idxShortOut_Three_US.mat', 'idxShortOut_Three')
      save('idxShortOut_Five_US.mat', 'idxShortOut_Five')
      save('idxShortOut_Seven_US.mat', 'idxShortOut_Seven')
      save('idxShortOut_Ten_US.mat', 'idxShortOut_Ten')
      
   elseif CountryAll == 2
      save('ReturnIndexALL_UK.mat', 'ReturnIndex')
      
      save('TempReturn_Two_UK.mat', 'TempReturn_Two')
      save('TempReturn_Three_UK.mat', 'TempReturn_Three')
      save('TempReturn_Five_UK.mat', 'TempReturn_Five')
      save('TempReturn_Seven_UK.mat', 'TempReturn_Seven')
      save('TempReturn_Ten_UK.mat', 'TempReturn_Ten')
      
      save('TotRetLong_Two_UK.mat', 'TotRetLong_Two')
      save('TotRetLong_Three_UK.mat', 'TotRetLong_Three')
      save('TotRetLong_Five_UK.mat', 'TotRetLong_Five')
      save('TotRetLong_Seven_UK.mat', 'TotRetLong_Seven')
      save('TotRetLong_Ten_UK.mat', 'TotRetLong_Ten')
      
      save('TotRetShort_Two_UK.mat', 'TotRetShort_Two')
      save('TotRetShort_Three_UK.mat', 'TotRetShort_Three')
      save('TotRetShort_Five_UK.mat', 'TotRetShort_Five')
      save('TotRetShort_Seven_UK.mat', 'TotRetShort_Seven')
      save('TotRetShort_Ten_UK.mat', 'TotRetShort_Ten')
      
      save('idxLongOut_Two_UK.mat', 'idxLongOut_Two')
      save('idxLongOut_Three_UK.mat', 'idxLongOut_Three')
      save('idxLongOut_Five_UK.mat', 'idxLongOut_Five')
      save('idxLongOut_Seven_UK.mat', 'idxLongOut_Seven')
      save('idxLongOut_Ten_UK.mat', 'idxLongOut_Ten')
      
      save('idxShortOut_Two_UK.mat', 'idxShortOut_Two')
      save('idxShortOut_Three_UK.mat', 'idxShortOut_Three')
      save('idxShortOut_Five_UK.mat', 'idxShortOut_Five')
      save('idxShortOut_Seven_UK.mat', 'idxShortOut_Seven')
      save('idxShortOut_Ten_UK.mat', 'idxShortOut_Ten')
      
   elseif CountryAll == 3   
      save('ReturnIndexALL_JPY.mat', 'ReturnIndex')
      
      save('TempReturn_Two_JPY.mat', 'TempReturn_Two')
      save('TempReturn_Three_JPY.mat', 'TempReturn_Three')
      save('TempReturn_Five_JPY.mat', 'TempReturn_Five')
      save('TempReturn_Seven_JPY.mat', 'TempReturn_Seven')
      save('TempReturn_Ten_JPY.mat', 'TempReturn_Ten')
      
      save('TotRetLong_Two_JPY.mat', 'TotRetLong_Two')
      save('TotRetLong_Three_JPY.mat', 'TotRetLong_Three')
      save('TotRetLong_Five_JPY.mat', 'TotRetLong_Five')
      save('TotRetLong_Seven_JPY.mat', 'TotRetLong_Seven')
      save('TotRetLong_Ten_JPY.mat', 'TotRetLong_Ten')
      
      save('TotRetShort_Two_JPY.mat', 'TotRetShort_Two')
      save('TotRetShort_Three_JPY.mat', 'TotRetShort_Three')
      save('TotRetShort_Five_JPY.mat', 'TotRetShort_Five')
      save('TotRetShort_Seven_JPY.mat', 'TotRetShort_Seven')
      save('TotRetShort_Ten_JPY.mat', 'TotRetShort_Ten')
      
      save('idxLongOut_Two_JPY.mat', 'idxLongOut_Two')
      save('idxLongOut_Three_JPY.mat', 'idxLongOut_Three')
      save('idxLongOut_Five_JPY.mat', 'idxLongOut_Five')
      save('idxLongOut_Seven_JPY.mat', 'idxLongOut_Seven')
      save('idxLongOut_Ten_JPY.mat', 'idxLongOut_Ten')
      
      save('idxShortOut_Two_JPY.mat', 'idxShortOut_Two')
      save('idxShortOut_Three_JPY.mat', 'idxShortOut_Three')
      save('idxShortOut_Five_JPY.mat', 'idxShortOut_Five')
      save('idxShortOut_Seven_JPY.mat', 'idxShortOut_Seven')
      save('idxShortOut_Ten_JPY.mat', 'idxShortOut_Ten')
      
   end
elseif stra == 2
   ReturnIndex.Properties.VariableNames(1) = {'TwoYear'};
   ReturnIndex = [Maturity(:,1) ReturnIndex(:,:)];
   save('ReturnIndex2.mat', 'ReturnIndex')
elseif stra == 3
   ReturnIndex.Properties.VariableNames(1) = {'ThreeYear'};
   ReturnIndex = [Maturity(:,1) ReturnIndex(:,:)];
   save('ReturnIndex3.mat', 'ReturnIndex')
elseif stra == 5
   ReturnIndex.Properties.VariableNames(1) = {'FiveYear'};
   ReturnIndex = [Maturity(:,1) ReturnIndex(:,:)];
   save('ReturnIndex5.mat', 'ReturnIndex')
elseif stra == 7
   ReturnIndex.Properties.VariableNames(1) = {'SevenYear'};
   ReturnIndex = [Maturity(:,1) ReturnIndex(:,:)];
   save('ReturnIndex7.mat', 'ReturnIndex')
elseif stra == 10
   ReturnIndex.Properties.VariableNames(1) = {'TenYear'};
   ReturnIndex = [Maturity(:,1) ReturnIndex(:,:)];
   save('ReturnIndex10.mat', 'ReturnIndex')
end

%% Valuation test

clear;
clc;
format short
warning off

% Loading the data
opts1 = detectImportOptions('US.xlsx','NumHeaderLines',0);
DataUS = readtable('US.xlsx', opts1, 'ReadVariableNames',true);
DataUS.Var1 = datetime(DataUS.Var1,'Format','dd-MM-yyyy');

DataUS.Properties.VariableNames = {'Dates' 'C0823M' 'C0826M' 'C0821Y'...
    'C0822Y' 'C0823Y' 'C0825Y' 'C0827Y' 'C08210Y' 'USSW1' 'USSW2'...
    'USSW3' 'USSW5' 'USSW7' 'USSW10' 'US0001M' 'US0003M' 'US0006M' 'USRGCGC'};

DataUS = rmmissing(DataUS,'DataVariables',{'Dates' 'C0823M' 'C0826M' 'C0821Y'...
    'C0822Y' 'C0823Y' 'C0825Y' 'C0827Y' 'C08210Y' 'USSW1' 'USSW2'...
    'USSW3' 'USSW5' 'USSW7' 'USSW10' 'US0001M' 'US0003M' 'US0006M' 'USRGCGC'});
   Bonds = DataUS(:,[2 3 4 5 6 7 8 9]);


% First interpolation of BONDS 

    y = [3/12, 6/12, 1, 2, 3, 5, 7, 10];

    y = array2table(y);
     y.Properties.VariableNames = { 'M3' 'M6' 'Y1' 'Y2', ...
        'Y3' 'Y5' 'Y7' 'Y10'} ;
    
  Bonds.Properties.VariableNames = {'M3' 'M6' 'Y1' 'Y2', ...
        'Y3' 'Y5' 'Y7' 'Y10'} ;
    Bonds = [y;Bonds];
  
% Bootstrap and discountfactor calculation/estimation (BONDS)

    T = zeros(1,20);
    for v = 1:20
        T(v)= v/2;
    end

    pr = zeros(20,1);
    pr(:,1) = 100;
    Discount = zeros(height(Bonds)-1,20);

    for t = 1:height(Bonds)-1
        Bond1interp = interp1(table2array(Bonds(1,1:end)),table2array(Bonds(1+t,1:end)),T,'spline'); % +t because the upper row is maturity
        XR = zeros(20,20);
        for v= 1:20
            XR(v,1) = Bond1interp(v)./2;
            XR(v,1:v) = XR(v,1);
            XR(v,v) = XR(v,1)+100;
        end
        Discount(t,:) = inv(XR)*pr;
    end 

    Discount = [100./(table2array(Bonds(2:end,2))./4 + 100), Discount];
    Discount = [3/12 , T;Discount];
    for i = 1:1:12*10
        V(i)=i/12;
    end

    Bond2interp = zeros(1000,120); % way too many rows in order to make valuations later on correct
    for i = 1:height(Bonds)-1
        Bond2interp(i,:) = interp1(Discount(1,1:end),Discount(1+i,1:end),V,'pchip'); % +t because the upper row is maturity
    end


% bond prices section
BondPrices= readtable('Bond_Prices1.xlsx');
discBond=[DataUS(:,1),array2table(Bond2interp(1:height(DataUS),:))];

Coupon=str2double(BondPrices{3,2:end})';

test2= array2table(datetime(BondPrices{8:end,1}));
test2.Properties.VariableNames(1)={'Dates'};
test=array2table(str2double(BondPrices{8:end,2:end}));
test3=[test2,test];

for j=1:width(test3)-1

idxBondPricesIssue{j,1}=min(find(test3{:,1+j} > 0 )) ;
idxBondPricesMaturity{j,1}=max(find(test3{:,1+j} > 0 )) ;
MaturityYears(j,1)=((sum(logical(test3{:,1+j} >0))-1)./ 12) ;
end

% remove bond 23,61, 48,65,67,71 because of missing prices
test3=[test3(:,1:23),test3(:,25:48),test3(:,50:61),test3(:,63:65),test3(:,67),test3(:,69:71),test3(:,73:end)];

clear idxBondPricesIssue idxBondPricesMaturity MaturityYears ;
for j=1:width(test3)-1

idxBondPricesIssue{j,1}=min(find(test3{:,1+j} > 0 )) ;
idxBondPricesMaturity{j,1}=max(find(test3{:,1+j} > 0 )) ;
MaturityYears(j,1)=((sum(logical(test3{:,1+j} >0))-1)./ 12) ;
end

clear Coupon;
Coupon=[str2double(BondPrices{3,2:23}),str2double(BondPrices{3,25:48}),str2double(BondPrices{3,50:61}) ... 
str2double(BondPrices{3,63:65}),str2double(BondPrices{3,67}),str2double(BondPrices{3,69:71}),str2double(BondPrices{3,73:end})]' ;

Coupon=Coupon(:,1).*100;
test3=test3(1:end-1,:);
for i=1:height(test3)
sjekk{i}=find(test3{i,1} == discBond{:,1});
end


minSjekk=5;

CFbondtest=test3;
CFbondtest(:,2:end)={0};

for j=1:width(test3)-1
    CFbondtest{(idxBondPricesIssue{j,1}+6):6:(idxBondPricesIssue{j,1}+(MaturityYears(j,1)*12)),1+j}= (Coupon(j,1)./200)*100;
    CFbondtest{idxBondPricesIssue{j,1}+ (MaturityYears(j,1))*12,1+j}=CFbondtest{idxBondPricesIssue{j,1}+MaturityYears(j,1)*12,1+j} + 100;
end

Valuebondtest=CFbondtest(:,1:end);
Valuebondtest(:,2:end)={0};

for j=1:width(test3)-1
for t=0:(MaturityYears(j,1))*12
    PVtest=zeros((MaturityYears(j,1))*12,(MaturityYears(j,1))*12+1);
    if idxBondPricesIssue{j,1} +t >= idxBondPricesMaturity{j,1}  
                break         
     end
    for i=1:(MaturityYears(j,1))*12
       if idxBondPricesIssue{j,1}+i+t  >=  height(test3) +1
       break
    end
    PVtest(i,t+1)=  table2array(CFbondtest(idxBondPricesIssue{j,1}+i+t,1+j)) .* discBond{idxBondPricesIssue{j,1}+t-minSjekk+1,1+i}; % -1 for å få riktig?
    
    end
    PVsumbondtest(t+1,j) = sum(PVtest(:,t+1));
    Valuebondtest(idxBondPricesIssue{j,1}+t,1+j) = array2table(PVsumbondtest(t+1,j)); % ex dividend valuation  
end
end

% Accrued interest section
ValuebondAccruals=Valuebondtest(:,:);
ValuebondAccruals(:,2:end)={0};



j=1;
for j=1:width(ValuebondAccruals)-1
for i=6:6:MaturityYears(j)*12
    for t=1:6
ValuebondAccruals{idxBondPricesIssue{j}+t+i-6,1+j}=(Coupon(j,1)./2).* ...
(( daysact( ValuebondAccruals{idxBondPricesIssue{j}+i-6,1},ValuebondAccruals{idxBondPricesIssue{j}+i-6+t,1}) ) ...
./( daysact(ValuebondAccruals{idxBondPricesIssue{j}+i-6,1},ValuebondAccruals{idxBondPricesIssue{j}+i,1}) ))   ;
    end
end
end

InvoicePrice=test3(:,:);
InvoicePrice{:,2:end}=InvoicePrice{:,2:end} + ValuebondAccruals{:,2:end};

InvoicePriceEx=InvoicePrice(:,:);
InvoicePriceEx{:,2:end}=InvoicePriceEx{:,2:end} -CFbondtest{:,2:end};

for j=1:width(InvoicePriceEx)-1

CorrBond_j(j)=corr(InvoicePriceEx{idxBondPricesIssue{j,1}:(idxBondPricesMaturity{j,1}-1),1+j}, ... 
    Valuebondtest{idxBondPricesIssue{j,1}:(idxBondPricesMaturity{j,1}-1),1+j});
end

min(CorrBond_j(:))
mean(CorrBond_j(:))

% Correlation of changes
ChangeInvoicePriceEx=InvoicePriceEx(:,:);
ChangeInvoicePriceEx(:,2:end)={0};
for j=1:width(InvoicePrice)-1
ChangeInvoicePriceEx{idxBondPricesIssue{j}+1:idxBondPricesMaturity{j},1+j}= InvoicePriceEx{idxBondPricesIssue{j}+1:idxBondPricesMaturity{j},1+j} ...
    - InvoicePriceEx{idxBondPricesIssue{j}:idxBondPricesMaturity{j}-1,1+j};
ChangeInvoicePriceEx{idxBondPricesMaturity{j},1+j}=0;
end

ChangeModelPrice=Valuebondtest(:,:);
ChangeModelPrice(:,2:end)={0};
for j=1:width(InvoicePrice)-1
ChangeModelPrice{idxBondPricesIssue{j}+1:idxBondPricesMaturity{j},1+j}= Valuebondtest{idxBondPricesIssue{j}+1:idxBondPricesMaturity{j},1+j} ...
    - Valuebondtest{idxBondPricesIssue{j}:idxBondPricesMaturity{j}-1,1+j};
ChangeModelPrice{idxBondPricesMaturity{j},1+j}=0;
end


for j=1:width(InvoicePriceEx)-1

Corr_change(j)=corr(ChangeModelPrice{idxBondPricesIssue{j,1}:(idxBondPricesMaturity{j,1}-1),1+j}, ... 
    ChangeInvoicePriceEx{idxBondPricesIssue{j,1}:(idxBondPricesMaturity{j,1}-1),1+j});
end

mean_corr_change=mean(Corr_change(:))
min_corr_change=min(Corr_change(:))


% corr Returns
RetInvoicePriceEx=InvoicePriceEx(:,:) ;
RetInvoicePriceEx(:,2:end)={0} ;

for j=1:width(InvoicePrice)-1
RetInvoicePriceEx{idxBondPricesIssue{j}+1:idxBondPricesMaturity{j},1+j}= (InvoicePriceEx{idxBondPricesIssue{j}+1:idxBondPricesMaturity{j},1+j}) ./ ...
    (InvoicePriceEx{idxBondPricesIssue{j}:idxBondPricesMaturity{j}-1,1+j}) -1 ;
RetInvoicePriceEx{idxBondPricesMaturity{j},1+j}=0;
end


RetModelPrice=Valuebondtest(:,:);
RetModelPrice(:,2:end)={0};
for j=1:width(InvoicePrice)-1
RetModelPrice{idxBondPricesIssue{j}+1:idxBondPricesMaturity{j},1+j}= ((Valuebondtest{idxBondPricesIssue{j}+1:idxBondPricesMaturity{j},1+j}) ./ ...
     (Valuebondtest{idxBondPricesIssue{j}:idxBondPricesMaturity{j}-1,1+j}))-1;
RetModelPrice{idxBondPricesMaturity{j},1+j}=0;
end

for j=1:width(InvoicePriceEx)-1

Corr_ret(j)=corr(RetInvoicePriceEx{idxBondPricesIssue{j,1}:(idxBondPricesMaturity{j,1}-1),1+j}, ... 
    RetModelPrice{idxBondPricesIssue{j,1}:(idxBondPricesMaturity{j,1}-1),1+j});
end

mean_corr_ret=mean(Corr_change(:))
min_corr_ret=min(Corr_change(:))

%% Key numbers - Capital, mean etc

% Remeber to dowload olshac package to make this section work properly
% Using olshac downloaded from the matlab file exchange to correct t-stats
% https://se.mathworks.com/matlabcentral/fileexchange/43259-ols-with-newey-west-and-hansen-hodrick-se

clear;
clc;
format short
warning off

question = questdlg('Which country do you want?', ...
	'Key numbers', ...
	'United States','United Kingdom','Japan','');

% Handle response
switch question
    case 'United States'
        % Loading data
        load('ReturnIndexALL_US.mat');
        ReturnIndex_US = ReturnIndex;

        % Making the table show keynumbers in percent
        ReturnIndex_US{:,2:end} = ReturnIndex_US{:,2:end}*100;

        Keynumbers_US = array2table(zeros(6,14));
        Keynumbers_US.Properties.VariableNames = {'N', 'Capital', 'Mean', 'Mean_Wo_Zeros' , 't_Stat', 'std_Dev', ...
        'Min', 'Max' 'Skewness', 'Kurtosis', 'Ratio_Neg', 'Serial_Corr', 'Gain_Loss','Sharpe_Ratio'};
        Strategy = [{'SS2'};{'SS3'};{'SS5'};{'SS7'};{'SS10'};{'EW_Tot'}];
        Keynumbers_US.Properties.RowNames = Strategy;

        for i = 1:5 
        syms w
        eqn = std(ReturnIndex_US{:,1+i} .* w) .* sqrt(12) == 10;
        Capital(i,1) = double(solve(eqn, w));
        Keynumbers_US.Capital(i) = Capital(i,1);
        ReturnIndex_US{:,1+i} = ReturnIndex_US{:,1+i}.*Capital(i,1);
        end
        Keynumbers_US.Capital(6) = sum(Keynumbers_US.Capital([1:5])) ./ 5;

        % EW_All return
        for i =1:height(ReturnIndex_US)
        ReturnIndex_US{i,7} = sum(ReturnIndex_US{i,2:6}) ./ 5 ;
        end
        ReturnIndex_US.Properties.VariableNames(7) = {'EW_All'};

        % Number of observations
        Keynumbers_US.N(:) = height(ReturnIndex_US);

        % Mean
        for i = 1:width(ReturnIndex_US)-1
        Keynumbers_US.Mean(i) = mean(ReturnIndex_US{:,1+i});
        end

        % Mean without zeros
        for i = 1:width(ReturnIndex_US)-1
        Keynumbers_US.Mean_Wo_Zeros(i) = mean(nonzeros(ReturnIndex_US{:,1+i}));
        end
        
        % T-stat corrected for heteroescadicity and autocorr. 
        % Using olshac downloaded from the matlab file exchange
        % https://se.mathworks.com/matlabcentral/fileexchange/43259-ols-with-newey-west-and-hansen-hodrick-se
        % Using lag = 4, from the formula T^1/4
        X = ones(height(ReturnIndex_US),1);
        for i = 1:width(ReturnIndex_US)-1
        [beta, R2, R2adj, X2_NW, X2_HH, X2_R, std_NW, std_HH, std_R, t_NW, t_HH, t_R] = olshac(ReturnIndex_US{:,1+i},X,4,0);
        Keynumbers_US.t_Stat(i) = t_NW;
        end

        % Std.dev
        for i = 1:width(ReturnIndex_US)-1
        Keynumbers_US.std_Dev(i) = std(ReturnIndex_US{:,1+i});
        end

        % Min
        for i=1:width(ReturnIndex_US)-1
        Keynumbers_US.Min(i) = min(ReturnIndex_US{:,1+i});
        end

        % Max
        for i = 1:width(ReturnIndex_US)-1
        Keynumbers_US.Max(i) = max(ReturnIndex_US{:,1+i});
        end

        % Skewness
        for i = 1:width(ReturnIndex_US)-1
        Keynumbers_US.Skewness(i) = skewness(ReturnIndex_US{:,1+i});
        end

        % Kurtosis
        for i = 1:width(ReturnIndex_US)-1
        Keynumbers_US.Kurtosis(i) = kurtosis(ReturnIndex_US{:,1+i});
        end

        % Ratio negative
        for i = 1:width(ReturnIndex_US)-1
        Keynumbers_US.Ratio_Neg(i) = length(find(ReturnIndex_US{:,1+i} <0)) / height(ReturnIndex_US);
        end
        
        % Serial_Corr
        for i = 1:width(ReturnIndex_US)-1
        acf = autocorr(ReturnIndex_US{:,1+i},'NumLags',1);
        Keynumbers_US.Serial_Corr(i) = acf(2);
        end

        % Gain loss ratio
        for i = 1:width(ReturnIndex_US)-1
        Keynumbers_US.Gain_Loss(i) = sum(ReturnIndex_US{:,1+i}>0) / sum((-1)*ReturnIndex_US{:,1+i}>0);
        end

        % Sharpe Ratio 
        for i = 1:width(ReturnIndex_US)-1
        Keynumbers_US.Sharpe_Ratio(i) = (Keynumbers_US.Mean(i) * sqrt(12)) /Keynumbers_US.std_Dev(i);
        end
        
        disp(Keynumbers_US)        
        
        plot(ReturnIndex_US{:,1},cumsum(ReturnIndex_US{:,2}))
        hold on
        plot(ReturnIndex_US{:,1},cumsum(ReturnIndex_US{:,3}))
        plot(ReturnIndex_US{:,1},cumsum(ReturnIndex_US{:,4}))
        plot(ReturnIndex_US{:,1},cumsum(ReturnIndex_US{:,5}))
        plot(ReturnIndex_US{:,1},cumsum(ReturnIndex_US{:,6}))
        plot(ReturnIndex_US{:,1},cumsum(ReturnIndex_US{:,7}))
        line(xlim(), [0,0], 'LineWidth', 1, 'Color', 'k', 'LineStyle',':');

                
        legend({'Two-year','Three-year','Five-year','Seven-year','Ten-year','Equally weighted','Zero line'},'Location','southoutside','NumColumns',4)
        ylabel('Return')
        xlabel('Date')
        title('Cumulative return - US')
        datetick('x','yyyy','keeplimits')
        grid on;
        hold off

        save('ReturnIndex_Capital_US.mat','ReturnIndex_US')
        save('Keynumber_US.mat','Keynumbers_US')
        
        
    case 'United Kingdom'
        % Loading data
        load('ReturnIndexALL_UK.mat');
        ReturnIndex_UK = ReturnIndex;

        % Making the table show keynumbers in percent
        ReturnIndex_UK{:,2:end} = ReturnIndex_UK{:,2:end}*100;

        Keynumbers_UK = array2table(zeros(6,14));
        Keynumbers_UK.Properties.VariableNames = {'N', 'Capital', 'Mean', 'Mean_Wo_Zeros' , 't_Stat', 'std_Dev', ...
            'Min', 'Max' 'Skewness', 'Kurtosis', 'Ratio_Neg', 'Serial_Corr', 'Gain_Loss','Sharpe_Ratio'};
        Strategy = [{'SS2'};{'SS3'};{'SS5'};{'SS7'};{'SS10'};{'EW_Tot'}];
        Keynumbers_UK.Properties.RowNames = Strategy;

        for i = 1:5 
            syms w
            eqn = std(ReturnIndex_UK{:,1+i} .* w) .* sqrt(12) == 10;
            Capital(i,1) = double(solve(eqn, w));
            Keynumbers_UK.Capital(i) = Capital(i,1);
            ReturnIndex_UK{:,1+i} = ReturnIndex_UK{:,1+i}.*Capital(i,1);
        end
        Keynumbers_UK.Capital(6) = sum(Keynumbers_UK.Capital([1:5])) ./ 5;

        % EW_All return
        for i =1:height(ReturnIndex_UK)
            ReturnIndex_UK{i,7} = sum(ReturnIndex_UK{i,2:6}) ./ 5 ;
        end
        ReturnIndex_UK.Properties.VariableNames(7) = {'EW_All'};

        % Number of observations
        Keynumbers_UK.N(:) = height(ReturnIndex_UK);

        % Mean
        for i = 1:width(ReturnIndex_UK)-1
            Keynumbers_UK.Mean(i) = mean(ReturnIndex_UK{:,1+i});
        end

        % Mean without zeros
        for i = 1:width(ReturnIndex_UK)-1
            Keynumbers_UK.Mean_Wo_Zeros(i) = mean(nonzeros(ReturnIndex_UK{:,1+i}));
        end
        
        % T-stat corrected for heteroescadicity and autocorr. 
        % Using olshac downloaded from the matlab file exchange
        % https://se.mathworks.com/matlabcentral/fileexchange/43259-ols-with-newey-west-and-hansen-hodrick-se
        % Using lag = 4, from the formula T^1/4
        X = ones(height(ReturnIndex_UK),1);
        for i = 1:width(ReturnIndex_UK)-1
        [beta, R2, R2adj, X2_NW, X2_HH, X2_R, std_NW, std_HH, std_R, t_NW, t_HH, t_R] = olshac(ReturnIndex_UK{:,1+i},X,4,0);
        Keynumbers_UK.t_Stat(i) = t_NW;
        end

        % Std.dev
        for i = 1:width(ReturnIndex_UK)-1
            Keynumbers_UK.std_Dev(i) = std(ReturnIndex_UK{:,1+i});
        end

        % Min
        for i=1:width(ReturnIndex_UK)-1
            Keynumbers_UK.Min(i) = min(ReturnIndex_UK{:,1+i});
        end

        % Max
        for i = 1:width(ReturnIndex_UK)-1
            Keynumbers_UK.Max(i) = max(ReturnIndex_UK{:,1+i});
        end

         % Skewness
        for i = 1:width(ReturnIndex_UK)-1
            Keynumbers_UK.Skewness(i) = skewness(ReturnIndex_UK{:,1+i});
        end

        % Kurtosis
        for i = 1:width(ReturnIndex_UK)-1
            Keynumbers_UK.Kurtosis(i) = kurtosis(ReturnIndex_UK{:,1+i});
        end

        % Ratio negative
        for i = 1:width(ReturnIndex_UK)-1
            Keynumbers_UK.Ratio_Neg(i) = length(find(ReturnIndex_UK{:,1+i} <0)) / height(ReturnIndex_UK);
        end
        
         % Serial_Corr
        for i = 1:width(ReturnIndex_UK)-1
        acf = autocorr(ReturnIndex_UK{:,1+i},'NumLags',1);
        Keynumbers_UK.Serial_Corr(i) = acf(2);
        end

        % Gain loss ratio
        for i = 1:width(ReturnIndex_UK)-1
            Keynumbers_UK.Gain_Loss(i) = sum(ReturnIndex_UK{:,1+i}>0) / sum((-1)*ReturnIndex_UK{:,1+i}>0);
        end

        % Sharpe Ratio 
        for i = 1:width(ReturnIndex_UK)-1
            Keynumbers_UK.Sharpe_Ratio(i) = (Keynumbers_UK.Mean(i) * sqrt(12)) /Keynumbers_UK.std_Dev(i);
        end
        
        disp(Keynumbers_UK)
        
        plot(ReturnIndex_UK{:,1},cumsum(ReturnIndex_UK{:,2}))
        hold on
        plot(ReturnIndex_UK{:,1},cumsum(ReturnIndex_UK{:,3}))
        plot(ReturnIndex_UK{:,1},cumsum(ReturnIndex_UK{:,4}))
        plot(ReturnIndex_UK{:,1},cumsum(ReturnIndex_UK{:,5}))
        plot(ReturnIndex_UK{:,1},cumsum(ReturnIndex_UK{:,6}))
        plot(ReturnIndex_UK{:,1},cumsum(ReturnIndex_UK{:,7}))
        line(xlim(), [0,0], 'LineWidth', 1, 'Color', 'k', 'LineStyle',':');

                
        legend({'Two-year','Three-year','Five-year','Seven-year','Ten-year','Equally weighted','Zero line'},'Location','southoutside','NumColumns',4)
        ylabel('Return')
        xlabel('Date')
        title('Cumulative return - UK')
        grid on;
        hold off

        save('ReturnIndex_Capital_UK.mat','ReturnIndex_UK')
        save('Keynumber_UK.mat','Keynumbers_UK')
                
    case 'Japan'
        % Loading data
        load('ReturnIndexALL_JPY.mat');
        ReturnIndex_JPY = ReturnIndex;

        % Making the table show keynumbers in percent
        ReturnIndex_JPY{:,2:end} = ReturnIndex_JPY{:,2:end}*100;

        Keynumbers_JPY = array2table(zeros(6,14));
        Keynumbers_JPY.Properties.VariableNames = {'N', 'Capital', 'Mean', 'Mean_Wo_Zeros' , 't_Stat', 'std_Dev', ...
            'Min', 'Max' 'Skewness', 'Kurtosis', 'Ratio_Neg', 'Serial_Corr', 'Gain_Loss','Sharpe_Ratio'};
        Strategy = [{'SS2'};{'SS3'};{'SS5'};{'SS7'};{'SS10'};{'EW_Tot'}];
        Keynumbers_JPY.Properties.RowNames = Strategy;

        for i = 1:5 
            syms w
            eqn = std(ReturnIndex_JPY{:,1+i} .* w) .* sqrt(12) == 10;
            Capital(i,1) = double(solve(eqn, w));
            Keynumbers_JPY.Capital(i) = Capital(i,1);
            ReturnIndex_JPY{:,1+i} = ReturnIndex_JPY{:,1+i}.*Capital(i,1);
        end
        Keynumbers_JPY.Capital(6) = sum(Keynumbers_JPY.Capital([1:5])) ./ 5;

        % EW_All return
        for i =1:height(ReturnIndex_JPY)
            ReturnIndex_JPY{i,7} = sum(ReturnIndex_JPY{i,2:6}) ./ 5 ;
        end
        ReturnIndex_JPY.Properties.VariableNames(7) = {'EW_All'};

        % Number of observations
        Keynumbers_JPY.N(:) = height(ReturnIndex_JPY);

        % Mean
        for i = 1:width(ReturnIndex_JPY)-1
            Keynumbers_JPY.Mean(i) = mean(ReturnIndex_JPY{:,1+i});
        end

        % Mean without zeros
        for i = 1:width(ReturnIndex_JPY)-1
            Keynumbers_JPY.Mean_Wo_Zeros(i) = mean(nonzeros(ReturnIndex_JPY{:,1+i}));
        end
        
        % T-stat corrected for heteroescadicity and autocorr. 
        % Using olshac downloaded from the matlab file exchange
        % https://se.mathworks.com/matlabcentral/fileexchange/43259-ols-with-newey-west-and-hansen-hodrick-se
        % Using lag = 4, from the formula T^1/4
        X = ones(height(ReturnIndex_JPY),1);
        for i = 1:width(ReturnIndex_JPY)-1
        [beta, R2, R2adj, X2_NW, X2_HH, X2_R, std_NW, std_HH, std_R, t_NW, t_HH, t_R] = olshac(ReturnIndex_JPY{:,1+i},X,4,0);
        Keynumbers_JPY.t_Stat(i) = t_NW;
        end

        % Std.dev
        for i = 1:width(ReturnIndex_JPY)-1
            Keynumbers_JPY.std_Dev(i) = std(ReturnIndex_JPY{:,1+i});
        end

        % Min
        for i=1:width(ReturnIndex_JPY)-1
            Keynumbers_JPY.Min(i) = min(ReturnIndex_JPY{:,1+i});
        end

        % Max
        for i = 1:width(ReturnIndex_JPY)-1
            Keynumbers_JPY.Max(i) = max(ReturnIndex_JPY{:,1+i});
        end

         % Skewness
        for i = 1:width(ReturnIndex_JPY)-1
            Keynumbers_JPY.Skewness(i) = skewness(ReturnIndex_JPY{:,1+i});
        end

        % Kurtosis
        for i = 1:width(ReturnIndex_JPY)-1
            Keynumbers_JPY.Kurtosis(i) = kurtosis(ReturnIndex_JPY{:,1+i});
        end

        % Ratio negative
        for i = 1:width(ReturnIndex_JPY)-1
            Keynumbers_JPY.Ratio_Neg(i) = length(find(ReturnIndex_JPY{:,1+i} <0)) / height(ReturnIndex_JPY);
        end
        
        % Serial_Corr
        for i = 1:width(ReturnIndex_JPY)-1
        acf = autocorr(ReturnIndex_JPY{:,1+i},'NumLags',1);
        Keynumbers_JPY.Serial_Corr(i) = acf(2);
        end

        % Gain loss ratio
        for i = 1:width(ReturnIndex_JPY)-1
            Keynumbers_JPY.Gain_Loss(i) = sum(ReturnIndex_JPY{:,1+i}>0) / sum((-1)*ReturnIndex_JPY{:,1+i}>0);
        end

        % Sharpe Ratio 
        for i = 1:width(ReturnIndex_JPY)-1
            Keynumbers_JPY.Sharpe_Ratio(i) = (Keynumbers_JPY.Mean(i) * sqrt(12)) /Keynumbers_JPY.std_Dev(i);
        end
        disp(Keynumbers_JPY)
        
        plot(ReturnIndex_JPY{:,1},cumsum(ReturnIndex_JPY{:,2}))
        hold on
        plot(ReturnIndex_JPY{:,1},cumsum(ReturnIndex_JPY{:,3}))
        plot(ReturnIndex_JPY{:,1},cumsum(ReturnIndex_JPY{:,4}))
        plot(ReturnIndex_JPY{:,1},cumsum(ReturnIndex_JPY{:,5}))
        plot(ReturnIndex_JPY{:,1},cumsum(ReturnIndex_JPY{:,6}))
        plot(ReturnIndex_JPY{:,1},cumsum(ReturnIndex_JPY{:,7}))
        line(xlim(), [0,0], 'LineWidth', 1, 'Color', 'k', 'LineStyle',':');

                
        legend({'Two-year','Three-year','Five-year','Seven-year','Ten-year','Equally weighted','Zero line'},'Location','southoutside','NumColumns',4)
        ylabel('Return')
        xlabel('Date')
        title('Cumulative return - Japan')
        grid on;
        hold off

        save('ReturnIndex_Capital_JPY.mat','ReturnIndex_JPY')
        save('Keynumber_JPY.mat','Keynumbers_JPY')
        
end

%% Regression US excluding noise measure
clear;
clc;
format short
warning off

% Loading data
load('BankFactors.mat')
load('BrokerDealer.mat')
load('CorpReturnsJPY.mat')
load('CorpReturnsUK.mat')
load('CorpReturnsUS.mat')
load('DefRisk.mat')
load('JPY_Fama.mat')
load('UK_Fama.mat')
load('US_Fama.mat')
load('Noise_Measure.mat')

% Full dataset 
% Regression US EXCLUDING Noise measure from 28/06/96 to 28/09/18
load('ReturnIndex_Capital_US.mat')
ReturnIndex = ReturnIndex_US(1:269,:);
BankFactors = BankFactors(1:269,:);
CorpReturnsUS = CorpReturnsUS(1:269,:);
US_Fama = US_Fama(1:269,:);
BrokerDealer = BrokerDealer(1:269,:);
DefaultRisk = DefaultRisk(1:269,:);
% To make bankfactors and CorpReturn excess return (minus Risk free)
BankFactors{:,2} = (BankFactors{:,2} - US_Fama{:,7});
CorpReturnsUS{:,2} = (CorpReturnsUS{:,2} - US_Fama{:,7});

Regression_US = [ReturnIndex(:,2:end) US_Fama(:,2:end) BankFactors(:,2:end) CorpReturnsUS(:,2:end) BrokerDealer(:,2) DefaultRisk(:,2:end)];
mdl_US_Two = fitlm(Regression_US,'TwoYear ~ Mkt_RF + SMB + HML + RMW + CMA + Mom + BAB + SPTR5BNK + CorpReturns + intermediary_capital_ratio + TERM_Tradable + CREDIT_Tradable')
mdl_US_Three = fitlm(Regression_US,'ThreeYear ~ Mkt_RF + SMB + HML + RMW + CMA + Mom + BAB + SPTR5BNK + CorpReturns + intermediary_capital_ratio + TERM_Tradable + CREDIT_Tradable')
mdl_US_Five = fitlm(Regression_US,'FiveYear ~ Mkt_RF + SMB + HML + RMW + CMA + Mom + BAB + SPTR5BNK + CorpReturns + intermediary_capital_ratio + TERM_Tradable + CREDIT_Tradable')
mdl_US_Seven = fitlm(Regression_US,'SevenYear ~ Mkt_RF + SMB + HML + RMW + CMA + Mom + BAB + SPTR5BNK + CorpReturns + intermediary_capital_ratio + TERM_Tradable + CREDIT_Tradable')
mdl_US_Ten = fitlm(Regression_US,'TenYear ~ Mkt_RF + SMB + HML + RMW + CMA + Mom + BAB + SPTR5BNK + CorpReturns + intermediary_capital_ratio + TERM_Tradable + CREDIT_Tradable')
mdl_US_EW = fitlm(Regression_US,'EW_All ~ Mkt_RF + SMB + HML + RMW + CMA + Mom + BAB + SPTR5BNK + CorpReturns + intermediary_capital_ratio + TERM_Tradable + CREDIT_Tradable')

% To find t-stats with robust Newey-West SE 
for i = 1:6
    if i == 1
       [EstCov,se,coeff] = hac(mdl_US_Two,'display','full'); 
       t_stat = coeff./se;
       t_stat = t_stat';
       t_stat2(i,:) = t_stat(1,:);
    end
    if i == 2
       [EstCov,se,coeff] = hac(mdl_US_Three,'display','full'); 
       t_stat = coeff./se;
       t_stat = t_stat';
       t_stat2(i,:) = t_stat(1,:);
    end
    if i == 3
       [EstCov,se,coeff] = hac(mdl_US_Five,'display','full'); 
       t_stat = coeff./se;
       t_stat = t_stat';
       t_stat2(i,:) = t_stat(1,:);
    end
    if i == 4
       [EstCov,se,coeff] = hac(mdl_US_Seven,'display','full'); 
       t_stat = coeff./se;
       t_stat = t_stat';
       t_stat2(i,:) = t_stat(1,:);
    end
    if i == 5
       [EstCov,se,coeff] = hac(mdl_US_Ten,'display','full'); 
       t_stat = coeff./se;
       t_stat = t_stat';
       t_stat2(i,:) = t_stat(1,:);
    end
    if i == 6
       [EstCov,se,coeff] = hac(mdl_US_EW,'display','full'); 
       t_stat = coeff./se;
       t_stat = t_stat';
       t_stat2(i,:) = t_stat(1,:);
    end
end

%% Regression UK excluding noise measure
clear;
clc;
format short
warning off

% Loading data
load('BankFactors.mat')
load('BrokerDealer.mat')
load('CorpReturnsJPY.mat')
load('CorpReturnsUK.mat')
load('CorpReturnsUS.mat')
load('DefRisk.mat')
load('JPY_Fama.mat')
load('UK_Fama.mat')
load('US_Fama.mat')
load('Noise_Measure.mat')

% Full dataset 
% Regression UK EXCLUDING Noise measure from 31/07/98 to 29/12/2017
load('ReturnIndex_Capital_UK.mat')
ReturnIndex = ReturnIndex_UK(1:234,:);
BankFactors = BankFactors(26:259,:);
CorpReturnsUK = CorpReturnsUK(1:234,:);
UK_Fama = UK_Fama(1:234,:);
BrokerDealer = BrokerDealer(26:259,:);
DefaultRisk = DefaultRisk(26:259,:);

% To make bankfactors and CorpReturn excess return (minus Risk free)
BankFactors{:,4} = (BankFactors{:,4} - UK_Fama{:,5});
CorpReturnsUK{:,2} = (CorpReturnsUK{:,2} - UK_Fama{:,5});

Regression_UK1 = [ReturnIndex(:,2:end) UK_Fama(:,2:end) BankFactors(:,2:end) CorpReturnsUK(:,2:end) BrokerDealer(:,2) DefaultRisk(:,2:end)];

Regression_UK = [Regression_UK1(:,1:6) Regression_UK1(:,12) Regression_UK1(:,7:9) Regression_UK1(:,13) Regression_UK1(:,16:20)];

mdl_UK_Two = fitlm(Regression_UK,'TwoYear ~ Mkt_RF + SMB + HML + Mom + BAB + F3BANK + CorpReturns + intermediary_capital_ratio + TERM_Tradable + CREDIT_Tradable')
mdl_UK_Three = fitlm(Regression_UK,'ThreeYear ~ Mkt_RF + SMB + HML + Mom + BAB + F3BANK + CorpReturns + intermediary_capital_ratio + TERM_Tradable + CREDIT_Tradable')
mdl_UK_Five = fitlm(Regression_UK,'FiveYear ~ Mkt_RF + SMB + HML + Mom + BAB + F3BANK + CorpReturns + intermediary_capital_ratio + TERM_Tradable + CREDIT_Tradable')
mdl_UK_Seven = fitlm(Regression_UK,'SevenYear ~ Mkt_RF + SMB + HML + Mom + BAB + F3BANK + CorpReturns + intermediary_capital_ratio + TERM_Tradable + CREDIT_Tradable')
mdl_UK_Ten = fitlm(Regression_UK,'TenYear ~ Mkt_RF + SMB + HML + Mom + BAB + F3BANK + CorpReturns + intermediary_capital_ratio + TERM_Tradable + CREDIT_Tradable')
mdl_UK_EW = fitlm(Regression_UK,'EW_All ~ Mkt_RF + SMB + HML + Mom + BAB + F3BANK + CorpReturns + intermediary_capital_ratio + TERM_Tradable + CREDIT_Tradable')

% To find t-stats with robust Newey-West SE
for i = 1:6
    if i == 1
       [EstCov,se,coeff] = hac(mdl_UK_Two,'display','full'); 
       t_stat = coeff./se;
       t_stat = t_stat';
       t_stat2(i,:) = t_stat(1,:);
    end
    if i == 2
       [EstCov,se,coeff] = hac(mdl_UK_Three,'display','full'); 
       t_stat = coeff./se;
       t_stat = t_stat';
       t_stat2(i,:) = t_stat(1,:);
    end
    if i == 3
       [EstCov,se,coeff] = hac(mdl_UK_Five,'display','full'); 
       t_stat = coeff./se;
       t_stat = t_stat';
       t_stat2(i,:) = t_stat(1,:);
    end
    if i == 4
       [EstCov,se,coeff] = hac(mdl_UK_Seven,'display','full'); 
       t_stat = coeff./se;
       t_stat = t_stat';
       t_stat2(i,:) = t_stat(1,:);
    end
    if i == 5
       [EstCov,se,coeff] = hac(mdl_UK_Ten,'display','full'); 
       t_stat = coeff./se;
       t_stat = t_stat';
       t_stat2(i,:) = t_stat(1,:);
    end
    if i == 6
       [EstCov,se,coeff] = hac(mdl_UK_EW,'display','full'); 
       t_stat = coeff./se;
       t_stat = t_stat';
       t_stat2(i,:) = t_stat(1,:);
    end
end

%% Regression Japan excluding noise measure
clear;
clc;
format short
warning off

% Loading data
load('BankFactors.mat')
load('BrokerDealer.mat')
load('CorpReturnsJPY.mat')
load('CorpReturnsUK.mat')
load('CorpReturnsUS.mat')
load('DefRisk.mat')
load('JPY_Fama.mat')
load('UK_Fama.mat')
load('US_Fama.mat')
load('Noise_Measure.mat')

% Full dataset 
% Regression US EXCLUDING Noise measure from 31/07/98 to 31-10/2018
load('ReturnIndex_Capital_JPY.mat')
ReturnIndex = ReturnIndex_JPY(1:244,:);
BankFactors = BankFactors(26:269,:);
CorpReturnsJPY = CorpReturnsJPY(1:244,:);
JPY_Fama = JPY_Fama(1:244,:);
BrokerDealer = BrokerDealer(26:269,:);
DefaultRisk = DefaultRisk(26:269,:);

% To make bankfactors and CorpReturn excess return (minus Risk free)
BankFactors{:,3} = (BankFactors{:,3} - JPY_Fama{:,7});
CorpReturnsJPY{:,2} = (CorpReturnsJPY{:,2} - JPY_Fama{:,7});

Regression_JPY = [ReturnIndex(:,2:end) JPY_Fama(:,2:end) BankFactors(:,2:end) CorpReturnsJPY(:,2:end) BrokerDealer(:,2) DefaultRisk(:,2:end)];

mdl_JPY_Two = fitlm(Regression_JPY,'TwoYear ~ Mkt_RF + SMB + HML + RMW + CMA + Mom + BAB + N5BANK + CorpReturns + intermediary_capital_ratio + TERM_Tradable + CREDIT_Tradable')
mdl_JPY_Three = fitlm(Regression_JPY,'ThreeYear ~ Mkt_RF + SMB + HML + RMW + CMA + Mom + BAB + N5BANK + CorpReturns + intermediary_capital_ratio + TERM_Tradable + CREDIT_Tradable')
mdl_JPY_Five = fitlm(Regression_JPY,'FiveYear ~ Mkt_RF + SMB + HML + RMW + CMA + Mom + BAB + N5BANK + CorpReturns + intermediary_capital_ratio + TERM_Tradable + CREDIT_Tradable')
mdl_JPY_Seven = fitlm(Regression_JPY,'SevenYear ~ Mkt_RF + SMB + HML + RMW + CMA + Mom + BAB + N5BANK + CorpReturns + intermediary_capital_ratio + TERM_Tradable + CREDIT_Tradable')
mdl_JPY_Ten = fitlm(Regression_JPY,'TenYear ~ Mkt_RF + SMB + HML + RMW + CMA + Mom + BAB + N5BANK + CorpReturns + intermediary_capital_ratio + TERM_Tradable + CREDIT_Tradable')
mdl_JPY_EW = fitlm(Regression_JPY,'EW_All ~ Mkt_RF + SMB + HML + RMW + CMA + Mom + BAB + N5BANK + CorpReturns + intermediary_capital_ratio + TERM_Tradable + CREDIT_Tradable')

% To find t-stats with robust Newey-West SE
for i = 1:6
    if i == 1
       [EstCov,se,coeff] = hac(mdl_JPY_Two,'display','full'); 
       t_stat = coeff./se;
       t_stat = t_stat';
       t_stat2(i,:) = t_stat(1,:);
    end
    if i == 2
       [EstCov,se,coeff] = hac(mdl_JPY_Three,'display','full'); 
       t_stat = coeff./se;
       t_stat = t_stat';
       t_stat2(i,:) = t_stat(1,:);
    end
    if i == 3
       [EstCov,se,coeff] = hac(mdl_JPY_Five,'display','full'); 
       t_stat = coeff./se;
       t_stat = t_stat';
       t_stat2(i,:) = t_stat(1,:);
    end
    if i == 4
       [EstCov,se,coeff] = hac(mdl_JPY_Seven,'display','full'); 
       t_stat = coeff./se;
       t_stat = t_stat';
       t_stat2(i,:) = t_stat(1,:);
    end
    if i == 5
       [EstCov,se,coeff] = hac(mdl_JPY_Ten,'display','full'); 
       t_stat = coeff./se;
       t_stat = t_stat';
       t_stat2(i,:) = t_stat(1,:);
    end
    if i == 6
       [EstCov,se,coeff] = hac(mdl_JPY_EW,'display','full'); 
       t_stat = coeff./se;
       t_stat = t_stat';
       t_stat2(i,:) = t_stat(1,:);
    end
end

%% Regression US INCLUDING noise measure
clear;
clc;
format short
warning off

% Loading data
load('BankFactors.mat')
load('BrokerDealer.mat')
load('CorpReturnsJPY.mat')
load('CorpReturnsUK.mat')
load('CorpReturnsUS.mat')
load('DefRisk.mat')
load('JPY_Fama.mat')
load('UK_Fama.mat')
load('US_Fama.mat')
load('Noise_Measure.mat')

% Full dataset 
% Regression US INCLUDING Noise measure from 28/06/96 to 30/12/2016
load('ReturnIndex_Capital_US.mat')
ReturnIndex = ReturnIndex_US(1:247,:);
BankFactors = BankFactors(1:247,:);
CorpReturnsUS = CorpReturnsUS(1:247,:);
US_Fama = US_Fama(1:247,:);
BrokerDealer = BrokerDealer(1:247,:);
DefaultRisk = DefaultRisk(1:247,:);
% To make bankfactors and CorpReturn excess return (minus Risk free)
BankFactors{:,2} = (BankFactors{:,2} - US_Fama{:,7});
CorpReturnsUS{:,2} = (CorpReturnsUS{:,2} - US_Fama{:,7});


Regression_US = [ReturnIndex(:,2:end) US_Fama(:,2:end) BankFactors(:,2:end) CorpReturnsUS(:,2:end) BrokerDealer(:,2) DefaultRisk(:,2:end) Noise_Measure(:,2)];
mdl_US_Two = fitlm(Regression_US,'TwoYear ~ Mkt_RF + SMB + HML + RMW + CMA + Mom + BAB + SPTR5BNK + CorpReturns + intermediary_capital_ratio + TERM_Tradable + CREDIT_Tradable + Noise')
mdl_US_Three = fitlm(Regression_US,'ThreeYear ~ Mkt_RF + SMB + HML + RMW + CMA + Mom + BAB + SPTR5BNK + CorpReturns + intermediary_capital_ratio + TERM_Tradable + CREDIT_Tradable + Noise')
mdl_US_Five = fitlm(Regression_US,'FiveYear ~ Mkt_RF + SMB + HML + RMW + CMA + Mom + BAB + SPTR5BNK + CorpReturns + intermediary_capital_ratio + TERM_Tradable + CREDIT_Tradable + Noise')
mdl_US_Seven = fitlm(Regression_US,'SevenYear ~ Mkt_RF + SMB + HML + RMW + CMA + Mom + BAB + SPTR5BNK + CorpReturns + intermediary_capital_ratio + TERM_Tradable + CREDIT_Tradable + Noise')
mdl_US_Ten = fitlm(Regression_US,'TenYear ~ Mkt_RF + SMB + HML + RMW + CMA + Mom + BAB + SPTR5BNK + CorpReturns + intermediary_capital_ratio + TERM_Tradable + CREDIT_Tradable + Noise')
mdl_US_EW = fitlm(Regression_US,'EW_All ~ Mkt_RF + SMB + HML + RMW + CMA + Mom + BAB + SPTR5BNK + CorpReturns + intermediary_capital_ratio + TERM_Tradable + CREDIT_Tradable + Noise')

% To find t-stats with robust Newey-West SE
for i = 1:6
    if i == 1
       [EstCov,se,coeff] = hac(mdl_US_Two,'display','full'); 
       t_stat = coeff./se;
       t_stat = t_stat';
       t_stat2(i,:) = t_stat(1,:);
    end
    if i == 2
       [EstCov,se,coeff] = hac(mdl_US_Three,'display','full'); 
       t_stat = coeff./se;
       t_stat = t_stat';
       t_stat2(i,:) = t_stat(1,:);
    end
    if i == 3
       [EstCov,se,coeff] = hac(mdl_US_Five,'display','full'); 
       t_stat = coeff./se;
       t_stat = t_stat';
       t_stat2(i,:) = t_stat(1,:);
    end
    if i == 4
       [EstCov,se,coeff] = hac(mdl_US_Seven,'display','full'); 
       t_stat = coeff./se;
       t_stat = t_stat';
       t_stat2(i,:) = t_stat(1,:);
    end
    if i == 5
       [EstCov,se,coeff] = hac(mdl_US_Ten,'display','full'); 
       t_stat = coeff./se;
       t_stat = t_stat';
       t_stat2(i,:) = t_stat(1,:);
    end
    if i == 6
       [EstCov,se,coeff] = hac(mdl_US_EW,'display','full'); 
       t_stat = coeff./se;
       t_stat = t_stat';
       t_stat2(i,:) = t_stat(1,:);
    end
end

%% Regression UK INCLUDING noise measure
clear;
clc;
format short
warning off

% Loading data
load('BankFactors.mat')
load('BrokerDealer.mat')
load('CorpReturnsJPY.mat')
load('CorpReturnsUK.mat')
load('CorpReturnsUS.mat')
load('DefRisk.mat')
load('JPY_Fama.mat')
load('UK_Fama.mat')
load('US_Fama.mat')
load('Noise_Measure.mat')

% Full dataset 
% Regression UK INCLUDING Noise measure from 31/07/98 to 30/12/2016
load('ReturnIndex_Capital_UK.mat')
ReturnIndex = ReturnIndex_UK(1:222,:);
BankFactors = BankFactors(26:247,:);
CorpReturnsUK = CorpReturnsUK(1:222,:);
UK_Fama = UK_Fama(1:222,:);
BrokerDealer = BrokerDealer(26:247,:);
DefaultRisk = DefaultRisk(26:247,:);
Noise_Measure = Noise_Measure(26:end,:);

% To make bankfactors and CorpReturn excess return (minus Risk free)
BankFactors{:,4} = (BankFactors{:,4} - UK_Fama{:,5});
CorpReturnsUK{:,2} = (CorpReturnsUK{:,2} - UK_Fama{:,5});

Regression_UK1 = [ReturnIndex(:,2:end) UK_Fama(:,2:end) BankFactors(:,2:end) CorpReturnsUK(:,2:end) BrokerDealer(:,2) DefaultRisk(:,2:end) Noise_Measure(:,2)];

Regression_UK = [Regression_UK1(:,1:6) Regression_UK1(:,12) Regression_UK1(:,7:9) Regression_UK1(:,13) Regression_UK1(:,16:21)];



mdl_UK_Two = fitlm(Regression_UK,'TwoYear ~ Mkt_RF + SMB + HML + Mom + BAB + F3BANK + CorpReturns + intermediary_capital_ratio + TERM_Tradable + CREDIT_Tradable + Noise')
mdl_UK_Three = fitlm(Regression_UK,'ThreeYear ~ Mkt_RF + SMB + HML + Mom + BAB + F3BANK + CorpReturns + intermediary_capital_ratio + TERM_Tradable + CREDIT_Tradable + Noise')
mdl_UK_Five = fitlm(Regression_UK,'FiveYear ~ Mkt_RF + SMB + HML + Mom + BAB + F3BANK + CorpReturns + intermediary_capital_ratio + TERM_Tradable + CREDIT_Tradable + Noise')
mdl_UK_Seven = fitlm(Regression_UK,'SevenYear ~ Mkt_RF + SMB + HML + Mom + BAB + F3BANK + CorpReturns + intermediary_capital_ratio + TERM_Tradable + CREDIT_Tradable + Noise')
mdl_UK_Ten = fitlm(Regression_UK,'TenYear ~ Mkt_RF + SMB + HML + Mom + BAB + F3BANK + CorpReturns + intermediary_capital_ratio + TERM_Tradable + CREDIT_Tradable + Noise')
mdl_UK_EW = fitlm(Regression_UK,'EW_All ~ Mkt_RF + SMB + HML + Mom + BAB + F3BANK + CorpReturns + intermediary_capital_ratio + TERM_Tradable + CREDIT_Tradable + Noise')

% To find t-stats with robust Newey-West SE
for i = 1:6
    if i == 1
       [EstCov,se,coeff] = hac(mdl_UK_Two,'display','full'); 
       t_stat = coeff./se;
       t_stat = t_stat';
       t_stat2(i,:) = t_stat(1,:);
    end
    if i == 2
       [EstCov,se,coeff] = hac(mdl_UK_Three,'display','full'); 
       t_stat = coeff./se;
       t_stat = t_stat';
       t_stat2(i,:) = t_stat(1,:);
    end
    if i == 3
       [EstCov,se,coeff] = hac(mdl_UK_Five,'display','full'); 
       t_stat = coeff./se;
       t_stat = t_stat';
       t_stat2(i,:) = t_stat(1,:);
    end
    if i == 4
       [EstCov,se,coeff] = hac(mdl_UK_Seven,'display','full'); 
       t_stat = coeff./se;
       t_stat = t_stat';
       t_stat2(i,:) = t_stat(1,:);
    end
    if i == 5
       [EstCov,se,coeff] = hac(mdl_UK_Ten,'display','full'); 
       t_stat = coeff./se;
       t_stat = t_stat';
       t_stat2(i,:) = t_stat(1,:);
    end
    if i == 6
       [EstCov,se,coeff] = hac(mdl_UK_EW,'display','full'); 
       t_stat = coeff./se;
       t_stat = t_stat';
       t_stat2(i,:) = t_stat(1,:);
    end
end

%% Regression Japan INCLUDING noise measure
clear;
clc;
format short
warning off

% Loading data
load('BankFactors.mat')
load('BrokerDealer.mat')
load('CorpReturnsJPY.mat')
load('CorpReturnsUK.mat')
load('CorpReturnsUS.mat')
load('DefRisk.mat')
load('JPY_Fama.mat')
load('UK_Fama.mat')
load('US_Fama.mat')
load('Noise_Measure.mat')

% Full dataset 
% Regression US INCLUDING Noise measure from 31/07/98 to 30/12/2016
load('ReturnIndex_Capital_JPY.mat')
ReturnIndex = ReturnIndex_JPY(1:222,:);
BankFactors = BankFactors(26:247,:);
CorpReturnsJPY = CorpReturnsJPY(1:222,:);
JPY_Fama = JPY_Fama(1:222,:);
BrokerDealer = BrokerDealer(26:247,:);
DefaultRisk = DefaultRisk(26:247,:);
Noise_Measure = Noise_Measure(26:end,:);

% To make bankfactors and CorpReturn excess return (minus Risk free)
BankFactors{:,3} = (BankFactors{:,3} - JPY_Fama{:,7});
CorpReturnsJPY{:,2} = (CorpReturnsJPY{:,2} - JPY_Fama{:,7});

Regression_JPY = [ReturnIndex(:,2:end) JPY_Fama(:,2:end) BankFactors(:,2:end) CorpReturnsJPY(:,2:end) BrokerDealer(:,2) DefaultRisk(:,2:end) Noise_Measure(:,2)];

mdl_JPY_Two = fitlm(Regression_JPY,'TwoYear ~ Mkt_RF + SMB + HML + RMW + CMA + Mom + BAB + N5BANK + CorpReturns + intermediary_capital_ratio + TERM_Tradable + CREDIT_Tradable + Noise')
mdl_JPY_Three = fitlm(Regression_JPY,'ThreeYear ~ Mkt_RF + SMB + HML + RMW + CMA + Mom + BAB + N5BANK + CorpReturns + intermediary_capital_ratio + TERM_Tradable + CREDIT_Tradable + Noise')
mdl_JPY_Five = fitlm(Regression_JPY,'FiveYear ~ Mkt_RF + SMB + HML + RMW + CMA + Mom + BAB + N5BANK + CorpReturns + intermediary_capital_ratio + TERM_Tradable + CREDIT_Tradable + Noise')
mdl_JPY_Seven = fitlm(Regression_JPY,'SevenYear ~ Mkt_RF + SMB + HML + RMW + CMA + Mom + BAB + N5BANK + CorpReturns + intermediary_capital_ratio + TERM_Tradable + CREDIT_Tradable + Noise')
mdl_JPY_Ten = fitlm(Regression_JPY,'TenYear ~ Mkt_RF + SMB + HML + RMW + CMA + Mom + BAB + N5BANK + CorpReturns + intermediary_capital_ratio + TERM_Tradable + CREDIT_Tradable + Noise')
mdl_JPY_EW = fitlm(Regression_JPY,'EW_All ~ Mkt_RF + SMB + HML + RMW + CMA + Mom + BAB + N5BANK + CorpReturns + intermediary_capital_ratio + TERM_Tradable + CREDIT_Tradable + Noise')

% To find t-stats with robust Newey-West SE
for i = 1:6
    if i == 1
       [EstCov,se,coeff] = hac(mdl_JPY_Two,'display','full'); 
       t_stat = coeff./se;
       t_stat = t_stat';
       t_stat2(i,:) = t_stat(1,:);
    end
    if i == 2
       [EstCov,se,coeff] = hac(mdl_JPY_Three,'display','full'); 
       t_stat = coeff./se;
       t_stat = t_stat';
       t_stat2(i,:) = t_stat(1,:);
    end
    if i == 3
       [EstCov,se,coeff] = hac(mdl_JPY_Five,'display','full'); 
       t_stat = coeff./se;
       t_stat = t_stat';
       t_stat2(i,:) = t_stat(1,:);
    end
    if i == 4
       [EstCov,se,coeff] = hac(mdl_JPY_Seven,'display','full'); 
       t_stat = coeff./se;
       t_stat = t_stat';
       t_stat2(i,:) = t_stat(1,:);
    end
    if i == 5
       [EstCov,se,coeff] = hac(mdl_JPY_Ten,'display','full'); 
       t_stat = coeff./se;
       t_stat = t_stat';
       t_stat2(i,:) = t_stat(1,:);
    end
    if i == 6
       [EstCov,se,coeff] = hac(mdl_JPY_EW,'display','full'); 
       t_stat = coeff./se;
       t_stat = t_stat';
       t_stat2(i,:) = t_stat(1,:);
    end
end

%% Correlation of independent variables - R is the correlation matrix

% US
Regression_Corr = Regression_US(:,7:end);
Regression_Corr = Regression_Corr(:,[1 2 3 4 5 7 8 9 12 13 14 15 16]);
R = corrcoef(Regression_Corr{:,:});

R = array2table(R);
Strategy = [{'Mkt_RF'};{'SMB'};{'HML'};{'RMW'};{'CMA'};{'MOM'};{'BAB'};{'SPTR5BNK'};{'CorpReturns'};{'Intermediary_capital_ratio'};{'TERM_Tradable'};{'CREDIT_Tradable'};{'Noise'}];
R.Properties.RowNames = Strategy;
R.Properties.VariableNames = Strategy;
save('R_US.mat','R')

clear R Regression_Corr Strategy

% UK 
Regression_Corr = Regression_UK(:,7:end);
Regression_Corr = Regression_Corr(:,[6 1 2 3 7 10 11 12 13 14 15]);
R = corrcoef(Regression_Corr{:,:});

R = array2table(R);
Strategy = [{'Mkt_RF'};{'SMB'};{'HML'};{'MOM'};{'BAB'};{'F3BANK'};{'CorpReturns'};{'Intermediary_capital_ratio'};{'TERM_Tradable'};{'CREDIT_Tradable'};{'Noise'}];
R.Properties.RowNames = Strategy;
R.Properties.VariableNames = Strategy;
save('R_UK.mat','R')

clear R Regression_Corr Strategy

% Japan
Regression_Corr = Regression_JPY(:,7:end);
Regression_Corr = Regression_Corr(:,[1 2 3 4 5 7 8 10 12 13 14 15 16]);
R = corrcoef(Regression_Corr{:,:});

R = array2table(R);
Strategy = [{'Mkt_RF'};{'SMB'};{'HML'};{'RMW'};{'CMA'};{'MOM'};{'BAB'};{'N5BANK'};{'CorpReturns'};{'Intermediary_capital_ratio'};{'TERM_Tradable'};{'CREDIT_Tradable'};{'Noise'}];
R.Properties.RowNames = Strategy;
R.Properties.VariableNames = Strategy;

save('R_JPY.mat','R')

%% Swap spread and floating spread plots
clear;
clc;
format short
warning off

% Loading the data
opts1   = detectImportOptions('US.xlsx','NumHeaderLines',0);
opts2   = detectImportOptions('UK.xlsx','NumHeaderLines',0);
opts3   = detectImportOptions('JPY.xlsx','NumHeaderLines',0);
DataUS  = readtable('US.xlsx', opts1, 'ReadVariableNames',true);
DataUK  = readtable('UK.xlsx', opts2, 'ReadVariableNames',true);
DataJPY = readtable('JPY.xlsx', opts3, 'ReadVariableNames',true);

% Datefunction
DataUS.Var1  = datetime(DataUS.Var1,'Format','dd-MM-yyyy');
DataUK.Var1  = datetime(DataUK.Var1,'Format','dd-MM-yyyy');
DataJPY.Var1 = datetime(DataJPY.Var1,'Format','dd-MM-yyyy');

% Define variable names
DataUS.Properties.VariableNames = {'Dates' 'C0823M' 'C0826M' 'C0821Y'...
    'C0822Y' 'C0823Y' 'C0825Y' 'C0827Y' 'C08210Y' 'USSW1' 'USSW2'...
    'USSW3' 'USSW5' 'USSW7' 'USSW10' 'US0001M' 'US0003M' 'US0006M' 'USRGCGC'};

DataUK.Properties.VariableNames = {'Dates' 'C1103M' 'C1106M' 'C1101Y'...
    'C1102Y' 'C1103Y' 'C1105Y' 'C1107Y' 'C11010Y' 'BPSW1' 'BPSW2'...
    'BPSW3' 'BPSW5' 'BPSW7' 'BPSW10' 'BP0001M' 'BP0003M' 'BP0006M' 'BPRPF'};

DataJPY.Properties.VariableNames = {'Dates' 'C1053M' 'C1056M' 'C1051Y'...
    'C1052Y' 'C1053Y' 'C1055Y' 'C1057Y' 'C10510Y' 'JYSW1' 'JYSW2'...
    'JYSW3' 'JYSW5' 'JYSW7' 'JYSW10' 'JY0001M' 'JY0003M' 'JY0006M' 'JYRPF'};

% Remove NaN and NaT
DataUS = rmmissing(DataUS,'DataVariables',{'Dates' 'C0823M' 'C0826M' 'C0821Y'...
    'C0822Y' 'C0823Y' 'C0825Y' 'C0827Y' 'C08210Y' 'USSW1' 'USSW2'...
    'USSW3' 'USSW5' 'USSW7' 'USSW10' 'US0001M' 'US0003M' 'US0006M' 'USRGCGC'});

DataUK = rmmissing(DataUK,'DataVariables',{'Dates' 'C1103M' 'C1106M' 'C1101Y'...
    'C1102Y' 'C1103Y' 'C1105Y' 'C1107Y' 'C11010Y' 'BPSW1' 'BPSW2'...
    'BPSW3' 'BPSW5' 'BPSW7' 'BPSW10' 'BP0001M' 'BP0003M' 'BP0006M' 'BPRPF'});

DataJPY = rmmissing(DataJPY,'DataVariables',{'Dates' 'C1053M' 'C1056M' 'C1051Y'...
    'C1052Y' 'C1053Y' 'C1055Y' 'C1057Y' 'C10510Y' 'JYSW1' 'JYSW2'...
    'JYSW3' 'JYSW5' 'JYSW7' 'JYSW10' 'JY0001M' 'JY0003M' 'JY0006M' 'JYRPF'});

% Define variables
SwapBidAsk     = 0.01;
TreasuryBidAsk = 1/32;
RepoBidAsk     = 0.1;
Trigger        = 0.1;

% Define length
DataUS = DataUS(1:271,:);
DataUK = DataUK(1:246,:);
DataJPY = DataJPY(1:246,:);

% US
% 2 year
plot(DataUS{:,1},DataUS{:,11} - DataUS{:,5})
hold on
plot(DataUS{:,1},DataUS{:,17} - DataUS{:,19})
title('Swap spread vs floating spread - 2 year')
xlabel('Dates')
ylabel('Percent')
legend('SS = CMS - CMT','FS = L - r')
grid on

% 3 year
plot(DataUS{:,1},DataUS{:,12} - DataUS{:,6})
hold on
plot(DataUS{:,1},DataUS{:,17} - DataUS{:,19})
title('Swap spread vs floating spread - 3 year')
xlabel('Dates')
ylabel('Percent')
legend('SS = CMS - CMT','FS = L - r')
grid on

% 5 year
plot(DataUS{:,1},DataUS{:,13} - DataUS{:,7})
hold on
plot(DataUS{:,1},DataUS{:,17} - DataUS{:,19})
title('Swap spread vs floating spread - 5 year')
xlabel('Dates')
ylabel('Percent')
legend('SS = CMS - CMT','FS = L - r')
grid on

% 7 year
plot(DataUS{:,1},DataUS{:,14} - DataUS{:,8})
hold on
plot(DataUS{:,1},DataUS{:,17} - DataUS{:,19})
title('Swap spread vs floating spread - 7 year')
xlabel('Dates')
ylabel('Percent')
legend('SS = CMS - CMT','FS = L - r')
grid on

% 10 year
plot(DataUS{:,1},DataUS{:,15} - DataUS{:,9})
hold on
plot(DataUS{:,1},DataUS{:,17} - DataUS{:,19})
title('Swap spread vs floating spread - 10 year')
xlabel('Dates')
ylabel('Percent')
legend('SS = CMS - CMT','FS = L - r')
grid on


% UK
% 2 year
plot(DataUK{:,1},DataUK{:,11} - DataUK{:,5})
hold on
plot(DataUK{:,1},DataUK{:,18} - DataUK{:,19})
title('Swap spread vs floating spread - 2 year')
xlabel('Dates')
ylabel('Percent')
legend('SS = CMS - CMT','FS = L - r')
grid on

% 3 year
plot(DataUK{:,1},DataUK{:,12} - DataUK{:,6})
hold on
plot(DataUK{:,1},DataUK{:,18} - DataUK{:,19})
title('Swap spread vs floating spread - 3 year')
xlabel('Dates')
ylabel('Percent')
legend('SS = CMS - CMT','FS = L - r')
grid on

% 5 year
plot(DataUK{:,1},DataUK{:,13} - DataUK{:,7})
hold on
plot(DataUK{:,1},DataUK{:,18} - DataUK{:,19})
title('Swap spread vs floating spread - 5 year')
xlabel('Dates')
ylabel('Percent')
legend('SS = CMS - CMT','FS = L - r')
grid on

% 7 year
plot(DataUK{:,1},DataUK{:,14} - DataUK{:,8})
hold on
plot(DataUK{:,1},DataUK{:,18} - DataUK{:,19})
title('Swap spread vs floating spread - 7 year')
xlabel('Dates')
ylabel('Percent')
legend('SS = CMS - CMT','FS = L - r')
grid on

% 10 year
plot(DataUK{:,1},DataUK{:,15} - DataUK{:,9})
hold on
plot(DataUK{:,1},DataUK{:,18} - DataUK{:,19})
title('Swap spread vs floating spread - 10 year')
xlabel('Dates')
ylabel('Percent')
legend('SS = CMS - CMT','FS = L - r')
grid on


% JPY
% 2 year
plot(DataJPY{:,1},DataJPY{:,11} - DataJPY{:,5})
hold on
plot(DataJPY{:,1},DataJPY{:,18} - DataJPY{:,19})
title('Swap spread vs floating spread - 2 year')
xlabel('Dates')
ylabel('Percent')
legend('SS = CMS - CMT','FS = L - r')
grid on

% 3 year
plot(DataJPY{:,1},DataJPY{:,12} - DataJPY{:,6})
hold on
plot(DataJPY{:,1},DataJPY{:,18} - DataJPY{:,19})
title('Swap spread vs floating spread - 3 year')
xlabel('Dates')
ylabel('Percent')
legend('SS = CMS - CMT','FS = L - r')
grid on

% 5 year
plot(DataJPY{:,1},DataJPY{:,13} - DataJPY{:,7})
hold on
plot(DataJPY{:,1},DataJPY{:,18} - DataJPY{:,19})
title('Swap spread vs floating spread - 5 year')
xlabel('Dates')
ylabel('Percent')
legend('SS = CMS - CMT','FS = L - r')
grid on

% 7 year
plot(DataJPY{:,1},DataJPY{:,14} - DataJPY{:,8})
hold on
plot(DataJPY{:,1},DataJPY{:,18} - DataJPY{:,19})
title('Swap spread vs floating spread - 7 year')
xlabel('Dates')
ylabel('Percent')
legend('SS = CMS - CMT','FS = L - r')
grid on

% 10 year
plot(DataJPY{:,1},DataJPY{:,15} - DataJPY{:,9})
hold on
plot(DataJPY{:,1},DataJPY{:,18} - DataJPY{:,19})
title('Swap spread vs floating spread - 10 year')
xlabel('Dates')
ylabel('Percent')
legend('SS = CMS - CMT','FS = L - r')
grid on

%% Marking to market plots (long)
% This code must be run right after "Swap spread arbitrage" code to work
MTM_Long = array2table((table2array(ReturnBondLong(1:end,2:end)) + table2array(ReturnSwapLong(1:end,2:end))));
MTM_Long_sum = sum(MTM_Long{:,:},2);

for i = 1:length(MTM_Long_sum)
    if MTM_Long_sum(i) == 0
       MTM_Long_sum(i) = MTM_Long_sum(i);
    else
       MTM_Long_sum(i) = MTM_Long_sum(i) / LongPos(i);
    end
end

figure
plot(Maturity{:,1}, MTM_Long_sum(:,1))
datetick('x','yyyy','keeplimits')
grid on
ylabel('Return')
xlabel('Date')
ylim([-0.025 0.02])
title('Marking to market time series (long) - 10 year strategy')

%% Cash flow plots (long)
% This code must be run right after "Swap spread arbitrage" code to work
CFplot_Long = array2table( table2array(CFLong(1:end,2:end))  + table2array(RepoCFLongOut(:,2:end))...
    + table2array(LiborCFLongOut(:,2:end)));

CFplot_Long_sum = sum(CFplot_Long{:,:},2);

for i = 1:length(CFplot_Long_sum)
    if CFplot_Long_sum(i) == 0
       CFplot_Long_sum(i) = CFplot_Long_sum(i);
    else
       CFplot_Long_sum(i) = CFplot_Long_sum(i) / LongPos(i);
    end
end

figure
plot(Maturity{:,1}, CFplot_Long_sum(:,1)*100)
datetick('x','yyyy','keeplimits')
grid on
ylabel('Return')
xlabel('Date')
ylim([-0.25 0.3])
title('Cash flow time series (long) - 10 year strategy')

%% Diversification benefits
clear;
clc;
format short
warning off


load('ReturnIndexALL_US.mat')
ReturnIndex_US=ReturnIndex;

load('ReturnIndexALL_UK.mat')
ReturnIndex_UK=ReturnIndex;
load('ReturnIndexALL_JPY.mat')
ReturnIndex_JPY=ReturnIndex;

opts1   = detectImportOptions('Exchange.xlsx','NumHeaderLines',0);
FX_Rate  = readtable('Exchange.xlsx', opts1, 'ReadVariableNames',true);
FX_Rate.Var1  = datetime(FX_Rate.Var1,'Format','dd-MM-yyyy');

divers=ReturnIndex_JPY{:,2:end} + ReturnIndex_UK{:,2:end} + ReturnIndex_US{:,2:end};
divers(:,:)=divers(:,:)./3;

for i=1:5
       Sharpe_Ratio2(i) = (mean(divers(:,i)) * sqrt(12)) / std(divers(:,i));
end


FX_Rate.Properties.VariableNames = {'Dates' 'USDJPY_Ask' 'USDJPY_Bid' 'GBPUSD_Ask' 'GBPUSD_Bid' 'GBPJPY_Ask' 'GBPJPY_Bid'};

FX_Rate = rmmissing(FX_Rate,'DataVariables',{'Dates'});

ReturnIndex_US.Properties.VariableNames = {'Dates' 'TwoYear_US' 'ThreeYear_US' 'FiveYear_US' 'SevenYear_US' 'TenYear_US'};
ReturnIndex_UK.Properties.VariableNames = {'Dates' 'TwoYear_UK' 'ThreeYear_UK' 'FiveYear_UK' 'SevenYear_UK' 'TenYear_UK'};
ReturnIndex_JPY.Properties.VariableNames = {'Dates' 'TwoYear_JPY' 'ThreeYear_JPY' 'FiveYear_JPY' 'SevenYear_JPY' 'TenYear_JPY'};
FX_Rate = FX_Rate(26:end,:);

% All positions of strastegy on notional USD 100
ReturnIndex_JPY{:,2:end}=ReturnIndex_JPY{:,2:end} .* (100*(FX_Rate{1,3})); % 100USD notional on japanese return index
ReturnIndex_UK{:,2:end}=ReturnIndex_UK{:,2:end} .* (100/(FX_Rate{1,4})); % 100USD notional on japanese return index
ReturnIndex_US{:,2:end}=ReturnIndex_US{:,2:end}.*100;
% changes back to USD for Japan 
ReturnIndex_JPY_USInvestor=ReturnIndex_JPY;
for i=1:height(ReturnIndex_JPY)
ReturnIndex_JPY_USInvestor{i,2:end}=ReturnIndex_JPY{i,2:end} .*(1/(FX_Rate{i,2}));
end
% changes back to USD for UK 
ReturnIndex_UK_USInvestor=ReturnIndex_UK;
for i=1:height(ReturnIndex_UK)-1
ReturnIndex_UK_USInvestor{i,2:end}=ReturnIndex_UK{i,2:end} .*((FX_Rate{i,5}));
end


divers_US=ReturnIndex_JPY_USInvestor{:,2:end} + ReturnIndex_UK_USInvestor{:,2:end} + ReturnIndex_US{:,2:end};
for i=1:5
       Sharpe_Ratio_US(i) = (mean(divers_US(:,i)) * sqrt(12)) / std(divers_US(:,i));
end

% in the view of the japanese investor
ReturnIndex_US_JPYInvestor=ReturnIndex_US;
for i=1:height(ReturnIndex_US)
ReturnIndex_US_JPYInvestor{i,2:end}=ReturnIndex_US{i,2:end} .*((FX_Rate{i,3}));
end

ReturnIndex_UK_JPYInvestor=ReturnIndex_UK;
for i=1:height(ReturnIndex_UK)
ReturnIndex_UK_JPYInvestor{i,2:end}=ReturnIndex_UK{i,2:end} .*((FX_Rate{i,7}));
end

divers_JPY=ReturnIndex_US_JPYInvestor{:,2:end} + ReturnIndex_UK_JPYInvestor{:,2:end} + ReturnIndex_JPY{:,2:end};
for i=1:5
       Sharpe_Ratio_JPY(i) = (mean(divers_JPY(:,i)) * sqrt(12)) / std(divers_JPY(:,i));
end

% in the view of the UK investor
ReturnIndex_US_UKInvestor=ReturnIndex_US;
for i=1:height(ReturnIndex_US)
ReturnIndex_US_UKInvestor{i,2:end}=ReturnIndex_US{i,2:end} .*(1/(FX_Rate{i,4}));
end

ReturnIndex_JPY_UKInvestor=ReturnIndex_JPY;
for i=1:height(ReturnIndex_JPY)
ReturnIndex_JPY_UKInvestor{i,2:end}=ReturnIndex_JPY{i,2:end} .*(1/(FX_Rate{i,6}));
end

divers_UK=ReturnIndex_US_UKInvestor{:,2:end} + ReturnIndex_JPY_UKInvestor{:,2:end} + ReturnIndex_UK{:,2:end};
for i=1:5
       Sharpe_Ratio_UK(i) = (mean(divers_UK(:,i)) * sqrt(12)) / std(divers_UK(:,i));
end

divers_US=[ReturnIndex(:,1),array2table(divers_US)];
divers_US.Properties.VariableNames={'Dates' 'TwoYear' 'ThreeYear' 'FiveYear' 'SevenYear'   'TenYear'};
divers_UK=[ReturnIndex(:,1),array2table(divers_UK)];
divers_UK.Properties.VariableNames={'Dates' 'TwoYear' 'ThreeYear' 'FiveYear' 'SevenYear'   'TenYear'};
divers_JPY=[ReturnIndex(:,1),array2table(divers_JPY)];
divers_JPY.Properties.VariableNames={'Dates' 'TwoYear' 'ThreeYear' 'FiveYear' 'SevenYear'   'TenYear'};

save('divers_US.mat','divers_US');
save('divers_UK.mat','divers_UK');
save('divers_JPY.mat','divers_JPY');

%% Cumulative plots and histogram plots (US)
% Need to run swap spread code in order to work
clear;
clc;
format short
warning off

load('Keynumber_US.mat')
Keynumbers = Keynumbers_US;
load('TotRetLong_Two_US.mat')
load('TotRetLong_Three_US.mat')
load('TotRetLong_Five_US.mat')
load('TotRetLong_Seven_US.mat')
load('TotRetLong_Ten_US.mat')
load('TotRetShort_Two_US.mat')
load('TotRetShort_Three_US.mat')
load('TotRetShort_Five_US.mat')
load('TotRetShort_Seven_US.mat')
load('TotRetShort_Ten_US.mat')
load('idxLongOut_Two_US.mat')
load('idxLongOut_Three_US.mat')
load('idxLongOut_Five_US.mat')
load('idxLongOut_Seven_US.mat')
load('idxLongOut_Ten_US.mat')
load('idxShortOut_Two_US.mat')
load('idxShortOut_Three_US.mat')
load('idxShortOut_Five_US.mat')
load('idxShortOut_Seven_US.mat')
load('idxShortOut_Ten_US.mat')

TotRetLong_Two{:,2:end} = (TotRetLong_Two{:,2:end} .* Keynumbers{1,2})*100;
TotRetLong_Two{:,2:end} = cumsum(TotRetLong_Two{:,2:end});

TotRetLong_Three{:,2:end} = (TotRetLong_Three{:,2:end} .* Keynumbers{2,2})*100;
TotRetLong_Three{:,2:end} = cumsum(TotRetLong_Three{:,2:end});

TotRetLong_Five{:,2:end} = (TotRetLong_Five{:,2:end} .* Keynumbers{3,2})*100;
TotRetLong_Five{:,2:end} = cumsum(TotRetLong_Five{:,2:end});

TotRetLong_Seven{:,2:end} = (TotRetLong_Seven{:,2:end} .* Keynumbers{4,2})*100;
TotRetLong_Seven{:,2:end} = cumsum(TotRetLong_Seven{:,2:end});

TotRetLong_Ten{:,2:end} = (TotRetLong_Ten{:,2:end} .* Keynumbers{5,2})*100;
TotRetLong_Ten{:,2:end} = cumsum(TotRetLong_Ten{:,2:end});

for j = 2:width(TotRetLong_Two)
    TotRetLong_Two{idxLongOut_Two(j-1)+1:end,j} = NaN;  
end

for j = 2:width(TotRetLong_Three)
    TotRetLong_Three{idxLongOut_Three(j-1)+1:end,j} = NaN;  
end

for j = 2:width(TotRetLong_Five)
    TotRetLong_Five{idxLongOut_Five(j-1)+1:end,j} = NaN;  
end

for j = 2:width(TotRetLong_Seven)
    TotRetLong_Seven{idxLongOut_Seven(j-1)+1:end,j} = NaN;  
end

for j = 2:width(TotRetLong_Ten)
    TotRetLong_Ten{idxLongOut_Ten(j-1)+1:end,j} = NaN;  
end
    
% Plot Long 2
plot(TotRetLong_Two{:,1},TotRetLong_Two{:,2:end})
ylabel('Return')
xlabel('Date')
title('Cumulative return per trade - 2-year strategy (long)')
grid on
% Plot Long 3
plot(TotRetLong_Three{:,1},TotRetLong_Three{:,2:end})
ylabel('Return')
xlabel('Date')
title('Cumulative return per trade - 3-year strategy (long)')
grid on
% Plot Long 5
plot(TotRetLong_Five{:,1},TotRetLong_Five{:,2:end})
ylabel('Return')
xlabel('Date')
title('Cumulative return per trade - 5-year strategy (long)')
grid on
% Plot Long 7
plot(TotRetLong_Seven{:,1},TotRetLong_Seven{:,2:end})
ylabel('Return')
xlabel('Date')
title('Cumulative return per trade - 7-year strategy (long)')
grid on
% Plot Long 10
plot(TotRetLong_Ten{:,1},TotRetLong_Ten{:,2:end})
ylabel('Return')
xlabel('Date')
title('Cumulative return per trade - 10-year strategy (long)')
grid on

% Short
TotRetShort_Two{:,2:end} = (TotRetShort_Two{:,2:end} .* Keynumbers{1,2})*100;
TotRetShort_Two{:,2:end} = cumsum(TotRetShort_Two{:,2:end});

TotRetShort_Three{:,2:end} = (TotRetShort_Three{:,2:end} .* Keynumbers{2,2})*100;
TotRetShort_Three{:,2:end} = cumsum(TotRetShort_Three{:,2:end});

TotRetShort_Five{:,2:end} = (TotRetShort_Five{:,2:end} .* Keynumbers{3,2})*100;
TotRetShort_Five{:,2:end} = cumsum(TotRetShort_Five{:,2:end});

TotRetShort_Seven{:,2:end} = (TotRetShort_Seven{:,2:end} .* Keynumbers{4,2})*100;
TotRetShort_Seven{:,2:end} = cumsum(TotRetShort_Seven{:,2:end});

TotRetShort_Ten{:,2:end} = (TotRetShort_Ten{:,2:end} .* Keynumbers{5,2})*100;
TotRetShort_Ten{:,2:end} = cumsum(TotRetShort_Ten{:,2:end});

for j = 2:width(TotRetShort_Two)
    TotRetShort_Two{idxShortOut_Two(j-1)+1:end,j} = NaN;  
end

for j = 2:width(TotRetShort_Three)
    TotRetShort_Three{idxShortOut_Three(j-1)+1:end,j} = NaN;  
end

for j = 2:width(TotRetShort_Five)
    TotRetShort_Five{idxShortOut_Five(j-1)+1:end,j} = NaN;  
end

for j = 2:width(TotRetShort_Seven)
    TotRetShort_Seven{idxShortOut_Seven(j-1)+1:end,j} = NaN;  
end

for j = 2:width(TotRetShort_Ten)
    TotRetShort_Ten{idxShortOut_Ten(j-1)+1:end,j} = NaN;  
end

% Plot Short 2
plot(TotRetShort_Two{:,1},TotRetShort_Two{:,2:end})
ylabel('Return')
xlabel('Date')
title('Cumulative return per trade - 2-year strategy (short)')
grid on
% Plot Short 3
plot(TotRetShort_Three{:,1},TotRetShort_Three{:,2:end})
ylabel('Return')
xlabel('Date')
title('Cumulative return per trade - 3-year strategy (short)')
grid on
% Plot Short 5
plot(TotRetShort_Five{:,1},TotRetShort_Five{:,2:end})
ylabel('Return')
xlabel('Date')
title('Cumulative return per trade - 5-year strategy (short)')
grid on
% Plot Short 7
plot(TotRetShort_Seven{:,1},TotRetShort_Seven{:,2:end})
ylabel('Return')
xlabel('Date')
title('Cumulative return per trade - 7-year strategy (short)')
grid on
% Plot Short 10
plot(TotRetShort_Ten{:,1},TotRetShort_Ten{:,2:end})
ylabel('Return')
xlabel('Date')
title('Cumulative return per trade - 10-year strategy (short)')
grid on


% Histogram 2 year
for i = 2:width(TotRetLong_Two)
    Two(i-1,1) = double(TotRetLong_Two{idxLongOut_Two(i-1),i});
end

histogram(Two)
title('Cumulative return per trade - Two year strategy')
xlabel('Return')
grid on

% Histogram 3 year
for i = 2:width(TotRetLong_Three)
    Three(i-1,1) = double(TotRetLong_Three{idxLongOut_Three(i-1),i});
end

histogram(Three)
title('Cumulative return per trade - Three year strategy')
xlabel('Return')
grid on
% Histogram 5 year
for i = 2:width(TotRetLong_Five)
    Five(i-1,1) = double(TotRetLong_Five{idxLongOut_Five(i-1),i});
end

histogram(Five)
title('Cumulative return per trade - Five year strategy')
xlabel('Return')
grid on
% Histogram 7 year
for i = 2:width(TotRetLong_Seven)
    Seven(i-1,1) = double(TotRetLong_Seven{idxLongOut_Seven(i-1),i});
end

histogram(Seven)
title('Cumulative return per trade - Seven year strategy')
xlabel('Return')
grid on
% Histogram 10 year
for i = 2:width(TotRetLong_Ten)
    Ten(i-1,1) = double(TotRetLong_Ten{idxLongOut_Ten(i-1),i});
end

histogram(Ten)
title('Cumulative return per trade - Ten year strategy')
xlabel('Return')
grid on

%% Cumulative plots and histogram plots (UK)
% Need to run swap spread code in order to work
clear;
clc;
format short
warning off

load('Keynumber_UK.mat')
Keynumbers = Keynumbers_UK;
load('TotRetLong_Two_UK.mat')
load('TotRetLong_Three_UK.mat')
load('TotRetLong_Five_UK.mat')
load('TotRetLong_Seven_UK.mat')
load('TotRetLong_Ten_UK.mat')
load('TotRetShort_Two_UK.mat')
load('TotRetShort_Three_UK.mat')
load('TotRetShort_Five_UK.mat')
load('TotRetShort_Seven_UK.mat')
load('TotRetShort_Ten_UK.mat')
load('idxLongOut_Two_UK.mat')
load('idxLongOut_Three_UK.mat')
load('idxLongOut_Five_UK.mat')
load('idxLongOut_Seven_UK.mat')
load('idxLongOut_Ten_UK.mat')
load('idxShortOut_Two_UK.mat')
load('idxShortOut_Three_UK.mat')
load('idxShortOut_Five_UK.mat')
load('idxShortOut_Seven_UK.mat')
load('idxShortOut_Ten_UK.mat')

% Long
TotRetLong_Two{:,2:end} = (TotRetLong_Two{:,2:end} .* Keynumbers{1,2})*100;
TotRetLong_Two{:,2:end} = cumsum(TotRetLong_Two{:,2:end});

TotRetLong_Three{:,2:end} = (TotRetLong_Three{:,2:end} .* Keynumbers{2,2})*100;
TotRetLong_Three{:,2:end} = cumsum(TotRetLong_Three{:,2:end});

TotRetLong_Five{:,2:end} = (TotRetLong_Five{:,2:end} .* Keynumbers{3,2})*100;
TotRetLong_Five{:,2:end} = cumsum(TotRetLong_Five{:,2:end});

TotRetLong_Seven{:,2:end} = (TotRetLong_Seven{:,2:end} .* Keynumbers{4,2})*100;
TotRetLong_Seven{:,2:end} = cumsum(TotRetLong_Seven{:,2:end});

TotRetLong_Ten{:,2:end} = (TotRetLong_Ten{:,2:end} .* Keynumbers{5,2})*100;
TotRetLong_Ten{:,2:end} = cumsum(TotRetLong_Ten{:,2:end});

for j = 2:width(TotRetLong_Two)
    TotRetLong_Two{idxLongOut_Two(j-1)+1:end,j} = NaN;  
end

for j = 2:width(TotRetLong_Three)
    TotRetLong_Three{idxLongOut_Three(j-1)+1:end,j} = NaN;  
end

for j = 2:width(TotRetLong_Five)
    TotRetLong_Five{idxLongOut_Five(j-1)+1:end,j} = NaN;  
end

for j = 2:width(TotRetLong_Seven)
    TotRetLong_Seven{idxLongOut_Seven(j-1)+1:end,j} = NaN;  
end

for j = 2:width(TotRetLong_Ten)
    TotRetLong_Ten{idxLongOut_Ten(j-1)+1:end,j} = NaN;  
end
    
% Plot Long 2
plot(TotRetLong_Two{:,1},TotRetLong_Two{:,2:end})
ylabel('Return')
xlabel('Date')
title('Cumulative return per trade - 2-year strategy (long)')
grid on
% Plot Long 3
plot(TotRetLong_Three{:,1},TotRetLong_Three{:,2:end})
ylabel('Return')
xlabel('Date')
title('Cumulative return per trade - 3-year strategy (long)')
grid on
% Plot Long 5
plot(TotRetLong_Five{:,1},TotRetLong_Five{:,2:end})
ylabel('Return')
xlabel('Date')
title('Cumulative return per trade - 5-year strategy (long)')
grid on
% Plot Long 7
plot(TotRetLong_Seven{:,1},TotRetLong_Seven{:,2:end})
ylabel('Return')
xlabel('Date')
title('Cumulative return per trade - 7-year strategy (long)')
grid on
% Plot Long 10
plot(TotRetLong_Ten{:,1},TotRetLong_Ten{:,2:end})
ylabel('Return')
xlabel('Date')
title('Cumulative return per trade - 10-year strategy (long)')
grid on

% Short
TotRetShort_Two{:,2:end} = (TotRetShort_Two{:,2:end} .* Keynumbers{1,2})*100;
TotRetShort_Two{:,2:end} = cumsum(TotRetShort_Two{:,2:end});

TotRetShort_Three{:,2:end} = (TotRetShort_Three{:,2:end} .* Keynumbers{2,2})*100;
TotRetShort_Three{:,2:end} = cumsum(TotRetShort_Three{:,2:end});

TotRetShort_Five{:,2:end} = (TotRetShort_Five{:,2:end} .* Keynumbers{3,2})*100;
TotRetShort_Five{:,2:end} = cumsum(TotRetShort_Five{:,2:end});

TotRetShort_Seven{:,2:end} = (TotRetShort_Seven{:,2:end} .* Keynumbers{4,2})*100;
TotRetShort_Seven{:,2:end} = cumsum(TotRetShort_Seven{:,2:end});

TotRetShort_Ten{:,2:end} = (TotRetShort_Ten{:,2:end} .* Keynumbers{5,2})*100;
TotRetShort_Ten{:,2:end} = cumsum(TotRetShort_Ten{:,2:end});

for j = 2:width(TotRetShort_Two)
    TotRetShort_Two{idxShortOut_Two(j-1)+1:end,j} = NaN;  
end

for j = 2:width(TotRetShort_Three)
    TotRetShort_Three{idxShortOut_Three(j-1)+1:end,j} = NaN;  
end

for j = 2:width(TotRetShort_Five)
    TotRetShort_Five{idxShortOut_Five(j-1)+1:end,j} = NaN;  
end

for j = 2:width(TotRetShort_Seven)
    TotRetShort_Seven{idxShortOut_Seven(j-1)+1:end,j} = NaN;  
end

for j = 2:width(TotRetShort_Ten)
    TotRetShort_Ten{idxShortOut_Ten(j-1)+1:end,j} = NaN;  
end

% Plot Short 2
plot(TotRetShort_Two{:,1},TotRetShort_Two{:,2:end})
ylabel('Return')
xlabel('Date')
title('Cumulative return per trade - 2-year strategy (short)')
grid on
% Plot Short 3
plot(TotRetShort_Three{:,1},TotRetShort_Three{:,2:end})
ylabel('Return')
xlabel('Date')
title('Cumulative return per trade - 3-year strategy (short)')
grid on
% Plot Short 5
plot(TotRetShort_Five{:,1},TotRetShort_Five{:,2:end})
ylabel('Return')
xlabel('Date')
title('Cumulative return per trade - 5-year strategy (short)')
grid on
% Plot Short 7
plot(TotRetShort_Seven{:,1},TotRetShort_Seven{:,2:end})
ylabel('Return')
xlabel('Date')
title('Cumulative return per trade - 7-year strategy (short)')
grid on
% Plot Short 10
plot(TotRetShort_Ten{:,1},TotRetShort_Ten{:,2:end})
ylabel('Return')
xlabel('Date')
title('Cumulative return per trade - 10-year strategy (short)')
grid on


% Histogram 2 year
for i = 2:width(TotRetLong_Two)
    Two(i-1,1) = double(TotRetLong_Two{idxLongOut_Two(i-1),i});
end

histogram(Two)
title('Cumulative return per trade - Two year strategy')
xlabel('Return')
grid on

% Histogram 3 year
for i = 2:width(TotRetLong_Three)
    Three(i-1,1) = double(TotRetLong_Three{idxLongOut_Three(i-1),i});
end

histogram(Three)
title('Cumulative return per trade - Three year strategy')
xlabel('Return')
grid on
% Histogram 5 year
for i = 2:width(TotRetLong_Five)
    Five(i-1,1) = double(TotRetLong_Five{idxLongOut_Five(i-1),i});
end

histogram(Five)
title('Cumulative return per trade - Five year strategy')
xlabel('Return')
grid on
% Histogram 7 year
for i = 2:width(TotRetLong_Seven)
    Seven(i-1,1) = double(TotRetLong_Seven{idxLongOut_Seven(i-1),i});
end

histogram(Seven)
title('Cumulative return per trade - Seven year strategy')
xlabel('Return')
grid on
% Histogram 10 year
for i = 2:width(TotRetLong_Ten)
    Ten(i-1,1) = double(TotRetLong_Ten{idxLongOut_Ten(i-1),i});
end

histogram(Ten)
title('Cumulative return per trade - Ten year strategy')
xlabel('Return')
grid on

%% Cumulative plots and histogram plots (Japan)
% Need to run swap spread code in order to work
clear;
clc;
format short
warning off

load('Keynumber_JPY.mat')
Keynumbers = Keynumbers_JPY;
load('TotRetLong_Two_JPY.mat')
load('TotRetLong_Three_JPY.mat')
load('TotRetLong_Five_JPY.mat')
load('TotRetLong_Seven_JPY.mat')
load('TotRetLong_Ten_JPY.mat')
load('TotRetShort_Two_JPY.mat')
load('TotRetShort_Three_JPY.mat')
load('TotRetShort_Five_JPY.mat')
load('TotRetShort_Seven_JPY.mat')
load('TotRetShort_Ten_JPY.mat')
load('idxLongOut_Two_JPY.mat')
load('idxLongOut_Three_JPY.mat')
load('idxLongOut_Five_JPY.mat')
load('idxLongOut_Seven_JPY.mat')
load('idxLongOut_Ten_JPY.mat')
load('idxShortOut_Two_JPY.mat')
load('idxShortOut_Three_JPY.mat')
load('idxShortOut_Five_JPY.mat')
load('idxShortOut_Seven_JPY.mat')
load('idxShortOut_Ten_JPY.mat')

% Long
TotRetLong_Two{:,2:end} = (TotRetLong_Two{:,2:end} .* Keynumbers{1,2})*100;
TotRetLong_Two{:,2:end} = cumsum(TotRetLong_Two{:,2:end});

TotRetLong_Three{:,2:end} = (TotRetLong_Three{:,2:end} .* Keynumbers{2,2})*100;
TotRetLong_Three{:,2:end} = cumsum(TotRetLong_Three{:,2:end});

TotRetLong_Five{:,2:end} = (TotRetLong_Five{:,2:end} .* Keynumbers{3,2})*100;
TotRetLong_Five{:,2:end} = cumsum(TotRetLong_Five{:,2:end});

TotRetLong_Seven{:,2:end} = (TotRetLong_Seven{:,2:end} .* Keynumbers{4,2})*100;
TotRetLong_Seven{:,2:end} = cumsum(TotRetLong_Seven{:,2:end});

TotRetLong_Ten{:,2:end} = (TotRetLong_Ten{:,2:end} .* Keynumbers{5,2})*100;
TotRetLong_Ten{:,2:end} = cumsum(TotRetLong_Ten{:,2:end});

for j = 2:width(TotRetLong_Two)
    TotRetLong_Two{idxLongOut_Two(j-1)+1:end,j} = NaN;  
end

for j = 2:width(TotRetLong_Three)
    TotRetLong_Three{idxLongOut_Three(j-1)+1:end,j} = NaN;  
end

for j = 2:width(TotRetLong_Five)
    TotRetLong_Five{idxLongOut_Five(j-1)+1:end,j} = NaN;  
end

for j = 2:width(TotRetLong_Seven)
    TotRetLong_Seven{idxLongOut_Seven(j-1)+1:end,j} = NaN;  
end

for j = 2:width(TotRetLong_Ten)
    TotRetLong_Ten{idxLongOut_Ten(j-1)+1:end,j} = NaN;  
end
    
% Plot Long 2
plot(TotRetLong_Two{:,1},TotRetLong_Two{:,2:end})
ylabel('Return')
xlabel('Date')
title('Cumulative return per trade - 2-year strategy (long)')
grid on
% Plot Long 3
plot(TotRetLong_Three{:,1},TotRetLong_Three{:,2:end})
ylabel('Return')
xlabel('Date')
title('Cumulative return per trade - 3-year strategy (long)')
grid on
% Plot Long 5
plot(TotRetLong_Five{:,1},TotRetLong_Five{:,2:end})
ylabel('Return')
xlabel('Date')
title('Cumulative return per trade - 5-year strategy (long)')
grid on
% Plot Long 7
plot(TotRetLong_Seven{:,1},TotRetLong_Seven{:,2:end})
ylabel('Return')
xlabel('Date')
title('Cumulative return per trade - 7-year strategy (long)')
grid on
% Plot Long 10
plot(TotRetLong_Ten{:,1},TotRetLong_Ten{:,2:end})
ylabel('Return')
xlabel('Date')
title('Cumulative return per trade - 10-year strategy (long)')
grid on

% Short
TotRetShort_Two{:,2:end} = (TotRetShort_Two{:,2:end} .* Keynumbers{1,2})*100;
TotRetShort_Two{:,2:end} = cumsum(TotRetShort_Two{:,2:end});

TotRetShort_Three{:,2:end} = (TotRetShort_Three{:,2:end} .* Keynumbers{2,2})*100;
TotRetShort_Three{:,2:end} = cumsum(TotRetShort_Three{:,2:end});

TotRetShort_Five{:,2:end} = (TotRetShort_Five{:,2:end} .* Keynumbers{3,2})*100;
TotRetShort_Five{:,2:end} = cumsum(TotRetShort_Five{:,2:end});

TotRetShort_Seven{:,2:end} = (TotRetShort_Seven{:,2:end} .* Keynumbers{4,2})*100;
TotRetShort_Seven{:,2:end} = cumsum(TotRetShort_Seven{:,2:end});

TotRetShort_Ten{:,2:end} = (TotRetShort_Ten{:,2:end} .* Keynumbers{5,2})*100;
TotRetShort_Ten{:,2:end} = cumsum(TotRetShort_Ten{:,2:end});

for j = 2:width(TotRetShort_Two)
    TotRetShort_Two{idxShortOut_Two(j-1)+1:end,j} = NaN;  
end

for j = 2:width(TotRetShort_Three)
    TotRetShort_Three{idxShortOut_Three(j-1)+1:end,j} = NaN;  
end

for j = 2:width(TotRetShort_Five)
    TotRetShort_Five{idxShortOut_Five(j-1)+1:end,j} = NaN;  
end

for j = 2:width(TotRetShort_Seven)
    TotRetShort_Seven{idxShortOut_Seven(j-1)+1:end,j} = NaN;  
end

for j = 2:width(TotRetShort_Ten)
    TotRetShort_Ten{idxShortOut_Ten(j-1)+1:end,j} = NaN;  
end

% Plot Short 2
plot(TotRetShort_Two{:,1},TotRetShort_Two{:,2:end})
ylabel('Return')
xlabel('Date')
title('Cumulative return per trade - 2-year strategy (short)')
grid on
% Plot Short 3
plot(TotRetShort_Three{:,1},TotRetShort_Three{:,2:end})
ylabel('Return')
xlabel('Date')
title('Cumulative return per trade - 3-year strategy (short)')
grid on
% Plot Short 5
plot(TotRetShort_Five{:,1},TotRetShort_Five{:,2:end})
ylabel('Return')
xlabel('Date')
title('Cumulative return per trade - 5-year strategy (short)')
grid on
% Plot Short 7
plot(TotRetShort_Seven{:,1},TotRetShort_Seven{:,2:end})
ylabel('Return')
xlabel('Date')
title('Cumulative return per trade - 7-year strategy (short)')
grid on
% Plot Short 10
plot(TotRetShort_Ten{:,1},TotRetShort_Ten{:,2:end})
ylabel('Return')
xlabel('Date')
title('Cumulative return per trade - 10-year strategy (short)')
grid on


% Histogram 2 year
for i = 2:width(TotRetLong_Two)
    Two(i-1,1) = double(TotRetLong_Two{idxLongOut_Two(i-1),i});
end

histogram(Two)
title('Cumulative return per trade - Two year strategy')
xlabel('Return')
grid on

% Histogram 3 year
for i = 2:width(TotRetLong_Three)
    Three(i-1,1) = double(TotRetLong_Three{idxLongOut_Three(i-1),i});
end

histogram(Three)
title('Cumulative return per trade - Three year strategy')
xlabel('Return')
grid on
% Histogram 5 year
for i = 2:width(TotRetLong_Five)
    Five(i-1,1) = double(TotRetLong_Five{idxLongOut_Five(i-1),i});
end

histogram(Five)
title('Cumulative return per trade - Five year strategy')
xlabel('Return')
grid on
% Histogram 7 year
for i = 2:width(TotRetLong_Seven)
    Seven(i-1,1) = double(TotRetLong_Seven{idxLongOut_Seven(i-1),i});
end

histogram(Seven)
title('Cumulative return per trade - Seven year strategy')
xlabel('Return')
grid on
% Histogram 10 year
for i = 2:width(TotRetLong_Ten)
    Ten(i-1,1) = double(TotRetLong_Ten{idxLongOut_Ten(i-1),i});
end

histogram(Ten)
title('Cumulative return per trade - Ten year strategy')
xlabel('Return')
grid on

%%

