%% Compute Exposures for Counterparties Under Collateral Agreement
% Load the data (ccr.mat) containing the mark-to-market contract values for a portfolio of swaps over many scenarios.

load ccr.mat

%
% Only look at a single counterparty for this example.

cpID = 4;
cpIdx = swaps.Counterparty == cpID;
cpValues = values(:,cpIdx,:);

%
% Compute the uncollateralized exposures.

exposures = creditexposures(cpValues,swaps.Counterparty(cpIdx),...
'NettingID',swaps.NettingID(cpIdx));

%
% View the credit exposure over time for the counterparty.

plot(simulationDates,squeeze(exposures));
expYLim = get(gca,'YLim');
title(sprintf('Exposures for Counterparty: %d',cpID));
datetick('x','mmmyy')
ylabel('Exposure ($)')
xlabel('Simulation Dates')

%
% Add a collateral agreement for the counterparty. The 'CollateralTable' parameter is a MATLAB® table. You can create tables from spreadsheets or other data sources, in addition to building them inline as seen here. For more information, see table.

collateralVariables = {'Counterparty';'PeriodOfRisk';'Threshold';'MinimumTransfer'};
periodOfRisk = 14;
threshold = 100000;
minTransfer = 10000;
collateralTable = table(cpID,periodOfRisk,threshold,minTransfer,...
'VariableNames',collateralVariables)

%
% Compute the collateralized exposures.

[collatExp, collatcpty, collateral] = creditexposures(cpValues,...
    swaps.Counterparty(cpIdx),'NettingID',swaps.NettingID(cpIdx),...
    'CollateralTable',collateralTable,'Dates',simulationDates);

%
% Plot the collateral levels and collateralized exposures.

figure;
subplot(2,1,1)
plot(simulationDates,squeeze(collateral));
set(gca,'YLim',expYLim);
title(sprintf('Collateral for counterparty: %d',cpID));
datetick('x','mmmyy')
ylabel('Collateral ($)')
xlabel('Simulation Dates')

subplot(2,1,2)
plot(simulationDates,squeeze(collatExp));
set(gca,'YLim',expYLim);
title(sprintf('Collateralized Exposure for Counterparty: %d',cpID));
datetick('x','mmmyy')
ylabel('Exposure ($)')
xlabel('Simulation Dates');

% Copyright 2012 The MathWorks, Inc.