%% KRG Backtesting Example
% Portfolio managers determine the estimated market impact cost for a trade
% as part of their portfolio backtesting analysis using historical market 
% impact parameters.
%
% Users enter the Trade List that they would like to analyze. 
%
% The trade list includes:
% 1) Symbol
% 2) Date
% 3) Side
% 4) Size or Shares & ADV
% 5) Volatility
% 6) TradeTime or POV Rate
% 7) Price in Local Currency
% 8) FX Rate Local to Target Currency
%
% Market Impact is then calculated for the specified order on the specified
% date using the market impact parameters, date and for the date and market
% impact code defined in the KRG object.

%   Copyright 2016-2020 The MathWorks, Inc.

% Load the market impact data provided by the Kissell Research Group
f = ftp('ftp.kissellresearch.com','username','password');
cd(f,'MI_Parameters');
mget(f,'MI_Encrypted_Parameters.csv');

% Create KRG object
miData = readtable('MI_Encrypted_Parameters.csv','Format','auto','delimiter',',','ReadRowNames',false,'ReadVariableNames',true);
k = krg(miData,datetime('today'),1,250);

% Load data
load KRGExampleData TradeDataBackTest

% Number of stocks in portfolio
numRecords = length(TradeDataBackTest.Symbol);   

% Preallocate output table
o = table(TradeDataBackTest.Symbol,TradeDataBackTest.Side,TradeDataBackTest.Date,NaN(numRecords,1),NaN(numRecords,1),'VariableNames',{'Symbol','Side','Date','MI','MIDollar'});

% MI Cost is always positive and based on Positive Shares Quantities
% need to take absolute value
TradeDataBackTest.Shares = abs(TradeDataBackTest.Shares);

% ADV factor in TradeTime is different than tradetime2pov calc.
TradeDataBackTest.TradeTime = TradeDataBackTest.TradeTime .* TradeDataBackTest.ADV;
TradeDataBackTest.POV = krg.tradetime2pov(TradeDataBackTest.TradeTime,TradeDataBackTest.Shares);
    
% Compute Historical Market Impact Costs
for ii = 1:numRecords
    
    k.MiDate = TradeDataBackTest.Date(ii);
    k.MiCode = TradeDataBackTest.MICode(ii);

    o.MI(ii) = marketImpact(k,TradeDataBackTest(ii,:));
    MIDollars = (TradeDataBackTest.Shares(ii) * TradeDataBackTest.Price(ii)) * o.MI(ii)/10000 * TradeDataBackTest.FXRate(ii);

    % Save Results
    o.MIDollar(ii) = MIDollars;
        
end