mathworks nordic - counterparty credit risk and cva - matlab & simulink

290

Upload: paaatrik

Post on 01-Nov-2014

252 views

Category:

Documents


4 download

DESCRIPTION

CVAMonte CarloMatlab

TRANSCRIPT

Page 1: MathWorks Nordic - Counterparty Credit Risk and CVA - MATLAB & Simulink

2012-11-12MathWorks Nordic - Counterparty Credit Risk and CVA - MATLAB & Simulink

1/14www.mathworks.se/help/fininst/counterparty-credit-risk-and-cva.html

Counterparty Credit Risk and CVA

This example show s how to compute the unilateral Credit Value (Valuation) Adjustment (CVA) for a bank holding a

portfolio of vanilla interest rate sw aps w ith several counterparties. CVA is the expected loss on an over-the-

counter instrument or portfolio of instruments due to counterparty default. The CVA for a particular counterparty is

defined as the sum over all points in time of the discounted expected exposure at each moment multiplied by the

probability that the counterparty defaults at that moment, all multiplied by 1 minus the recovery rate. The Credit Value

(Valuation) Adjustment (CVA) formula is:

Where R is the recovery, discEE the discounted expected exposure at time t, and PD the default probability

distribution.

The expected exposure is computed by f irst simulating many future scenarios of risk factors for the given

instrument or portfolio. Risk factors can be interest rates, FX rates, equity or commodity prices, or anything that w ill

affect the market value of the instruments. Once a suff icient set of scenarios has been simulated, the contract or

portfolio can be priced on a series of future dates for each scenario. The result is a matrix, or "cube", of instrument

values.

These prices are converted into exposures after taking into account collateral agreements that the bank might have

in place as w ell as netting agreements w here the values of several instruments may offset each other, low ering

their total exposure.

The instrument values for each scenario are discounted to compute the discounted exposures. The discounted

expected exposures can then be computed by a simple average of the discounted exposures at each simulation

date.

Finally, counterparty default probabilities are typically derived from credit default sw ap market quotes and the CVA

for the counterparty can be computed according to the above formula.

For this example w e w ill w ork w ith a portfolio of vanilla interest rate sw aps w ith the goal of computing the CVA for

a particular counterparty.

This example can run slow ly on some machines. If you have the Parallel Computing Toolbox™ installed it can

improve the performance.

Read Swap Portfolio

The portfolio of sw aps is close to zero value at time t=0. Each sw ap is associated w ith a counterparty and may or

may not be included in a netting agreement.

% Read swaps from spreadsheet

swapFile = 'cva-swap-portfolio.xls';

swapData = dataset('XLSFile',swapFile);

swaps = struct(...

'Counterparty',[],...

'NettingID',[],...

'Principal',[],...

'Maturity',[],...

'LegRate',[],...

Page 2: MathWorks Nordic - Counterparty Credit Risk and CVA - MATLAB & Simulink

2012-11-12MathWorks Nordic - Counterparty Credit Risk and CVA - MATLAB & Simulink

2/14www.mathworks.se/help/fininst/counterparty-credit-risk-and-cva.html

'LegType',[],...

'LatestFloatingRate',[],...

'LastFloatingDate',[]);

swaps.Counterparty = swapData.CounterpartyID;

swaps.NettingID = swapData.NettingID;

swaps.Principal = swapData.Principal;

swaps.Maturity = swapData.Maturity;

swaps.LegType = [swapData.LegType ~swapData.LegType];

swaps.LegRate = [swapData.LegRateReceiving swapData.LegRatePaying];

swaps.LatestFloatingRate = swapData.LatestFloatingRate;

swaps.Period = swapData.Period;

numSwaps = numel(swaps.Counterparty);

numCounterparties = max(swaps.Counterparty);

Create RateSpec from the Interest Rate Curve

Settle = datenum('14-Dec-2007');

Tenor = [3 6 12 5*12 7*12 10*12 20*12 30*12]';

ZeroRates = [0.033 0.034 0.035 0.040 0.042 0.044 0.048 0.0475]';

ZeroDates = datemnth(Settle,Tenor);

Compounding = 2;

Basis = 0;

RateSpec = intenvset('StartDates', Settle,'EndDates', ZeroDates,...

'Rates', ZeroRates,'Compounding',Compounding,'Basis',Basis);

% Create an IRCurve object. We will use this for computing

instantaneous

% forward rates during the calculation of the Hull-White short rate

path.

RateCurveObj = IRDataCurve('Zero',Settle,ZeroDates,ZeroRates,...

'Compounding', Compounding,'Basis', Basis);

Setup Tunable Simulation Parameters

We can vary the number of simulated interest rate scenarios w e generate by tuning the variable here. We set our

simulation dates to be more frequent at f irst, then turning less frequent further in the future.

% Number of Monte Carlo simulations

numScenarios = 64;

% Compute monthly simulation dates, then quarterly dates later.

simulationDates = datemnth(Settle+1,1:12);

simulationDates = [simulationDates

datemnth(simulationDates(end),3:3:64)];

Compute Initial Prices for All Swaps

currentPrices = swapbyzero(RateSpec,...

swaps.LegRate,...

Settle,...

Page 3: MathWorks Nordic - Counterparty Credit Risk and CVA - MATLAB & Simulink

2012-11-12MathWorks Nordic - Counterparty Credit Risk and CVA - MATLAB & Simulink

3/14www.mathworks.se/help/fininst/counterparty-credit-risk-and-cva.html

swaps.Maturity,...

'Principal',swaps.Principal,...

'LegType',swaps.LegType,...

'LatestFloatingRate',swaps.LatestFloatingRate);

% For each simulation date, compute last floating reset date per swap

floatDates = cfdates(Settle-360,swaps.Maturity,swaps.Period);

swaps.LastFloatingDate = zeros(numSwaps,numel(simulationDates));

for i = numel(simulationDates):-1:1

thisDate = simulationDates(i);

floatDates(floatDates > thisDate) = 0;

swaps.LastFloatingDate(:,i) = max(floatDates,[],2);

end

Setup Hull-White Single Factor Model

The risk factor w e w ill simulate to value our instruments is the zero curve. For this example w e w ill model the

interest rate term structure using the one-factor Hull-White model. This is a model of the short rate and is defined as:

w here

: Change in the short rate after a small change in time,

: Mean reversion rate

: Volatility of the short rate

: A Weiner process (a standard normal process)

: Drift function defined as:

: Instantaneous forw ard rate at time

: Partial derivative of w ith respect to time

Once w e have simulated a path of the short rate w e generate a full yield curve at each simulation date using the

formula:

: Zero rate at time for a period of

: Price of a zero coupon bond at time that pays one dollar at time

Page 4: MathWorks Nordic - Counterparty Credit Risk and CVA - MATLAB & Simulink

2012-11-12MathWorks Nordic - Counterparty Credit Risk and CVA - MATLAB & Simulink

4/14www.mathworks.se/help/fininst/counterparty-credit-risk-and-cva.html

Each scenario contains the full term structure moving forw ard through time, modeled at each of our selected

simulation dates.

Refer to "Calibrating the Hull-White Model Using Market Data" example in the Financial Instruments Toolbox Users'

Guide for more details on Hull-White single factor model calibration.

Alpha = 0.2;

Sigma = 0.015;

r0 = RateCurveObj.getZeroRates(Settle+1,'Compounding',-1);

t0 = Settle;

% Construct SDE object

hullwhite1 = hwv(Alpha,@(t,x)

hw1LevelFun(t0,t,RateCurveObj,Alpha,Sigma),...

Sigma,'StartState',r0);

% Store all model calibration information

calibration.RateCurveObj = RateCurveObj;

calibration.Tenor = Tenor;

calibration.ShortRateModel = hullwhite1;

calibration.Alpha = Alpha;

calibration.Sigma = Sigma;

Simulate Scenarios and Compute Mark-To-Market Values

For each scenario the sw ap portfolio is priced at each future simulation date. Prices are computed using

swapbyzero and the simulated zero curve at each date. The prices are then aggregated into a "cube" of vales

w hich contains all future instrument values at each simulation date for each scenario. The resulting cube of

instrument prices is a 3 dimensional matrix w here each row represents an instrument, each column a simulation

date, and each "page" a different simulated scenario.

% Allocate cube of simulated values: rows correspond to instruments,

% columns to valuation dates, "pages" to scenarios

simulatedValues = zeros(numSwaps,numel(simulationDates),numScenarios);

% Pre-allocate scenarios data structure

sampleScenario = hgenerateScenario(calibration,Settle,simulationDates);

scenarios = repmat(sampleScenario,numScenarios,1);

initialOneYearRate = RateCurveObj.getZeroRates(Settle +

365,'Compounding',-1);

For each scenario, w e model a future interest rate curve at each valuation date. Using the complete future interest

rate path, w e compute the value of all instruments at each valuation date.

Since the simulation dates do not correspond to the sw aps cash f low dates (w here the f loating rates are reset) w e

estimate the latest f loating rate w ith the 1-year rate (all of these sw aps have period 1 year) interpolated betw een

the nearest simulated rate curves.

The scenario generation and pricing are done in parallel using the parfor loop if the Parallel Computing Toolbox is

installed. The scenarios and their respective instrument values are computed in parallel across all MATLAB

w orkers.

Page 5: MathWorks Nordic - Counterparty Credit Risk and CVA - MATLAB & Simulink

2012-11-12MathWorks Nordic - Counterparty Credit Risk and CVA - MATLAB & Simulink

5/14www.mathworks.se/help/fininst/counterparty-credit-risk-and-cva.html

% Use reproducible random number generator (vary the seed to produce

% different random scenarios)

stream = RandStream.create('mrg32k3a','NumStreams',numScenarios,...

'Seed',0);

% Simulate all scenarios and compute instrument values in parallel. If

you

% have the Parallel Computing Toolbox, you should open a matlabpool

before

% running this section.

parfor scenarioIdx = 1:numScenarios

% Save state of random number generator

defaultStreamLocal = RandStream.getGlobalStream();

savedStateLocal = defaultStreamLocal.State;

% Setup new random number generator state for each scenario

RandStream.setGlobalStream(stream);

set(stream,'Substream',scenarioIdx);

% Create a scenario

scenarios(scenarioIdx) = hgenerateScenario(calibration,...

Settle,simulationDates);

% Compute all mark-to-market values for this scenario

thisScenarioValues = hcomputeMTMValues(swaps,simulationDates,...

scenarios(scenarioIdx),Settle,initialOneYearRate);

% Aggregate data

simulatedValues(:,:,scenarioIdx) = thisScenarioValues;

% Restore random number generator state

RandStream.setGlobalStream(defaultStreamLocal);

defaultStreamLocal.State = savedStateLocal;

end

Visualize Simulated Portfolio Values

We plot the total portfolio value for each scenario of our simulation. As each scenario moves forw ard in time the

values of the instruments w ill move up or dow n depending on how the modeled interest rate term structure

changes. As the sw aps get closer to maturity, their values w ill begin to approach zero since the aggregate value of

all remaining cash f low s w ill decrease after each cash f low date.

% Append initial prices/date to our simulation data

values = cat(2,repmat(currentPrices,[1 1

numScenarios]),simulatedValues);

dates = [Settle simulationDates];

% View portfolio value over time

figure;

totalPortValues = squeeze(sum(values));

plot(dates,totalPortValues);

title('Simulated MTM Portfolio Value');

datetick('x','mmmyy')

Page 6: MathWorks Nordic - Counterparty Credit Risk and CVA - MATLAB & Simulink

2012-11-12MathWorks Nordic - Counterparty Credit Risk and CVA - MATLAB & Simulink

www.mathworks.se/help/fininst/counterparty-credit-risk-and-cva.html

ylabel('Portfolio Value ($)')

xlabel('Simulation Dates')

Compute Exposure by Counterparty

The exposure of a particular contract (i) at time t is the maximum of the contract value (Vi) and 0:

And the exposure for a particular counterparty is simply a sum of the individual contract exposures:

In the presence of netting agreements, how ever, contracts are aggregated together and can offset each other.

Therefore the total exposure of all instruments in a netting agreement is

We compute these exposures for each counterparty at each simulation date.

% Additive exposure is computed at the netting set level. Exposure of

an

% unnetted instrument is equal to the market value of the instrument if

the

% instrument has positive value, otherwise it is zero.

instrument_exposures = zeros(size(values));

unnettedIdx = swaps.NettingID == 0;

instrument_exposures(unnettedIdx,:,:) = max(values(unnettedIdx,:,:),0);

% Instruments included in a netting agreement have exposure equal to

their

% value when the netting agreement has positive aggregate value,

otherwise

Page 7: MathWorks Nordic - Counterparty Credit Risk and CVA - MATLAB & Simulink

2012-11-12MathWorks Nordic - Counterparty Credit Risk and CVA - MATLAB & Simulink

7/14www.mathworks.se/help/fininst/counterparty-credit-risk-and-cva.html

% their exposure is zero. We compute this per netting agreement, but in

% this case each counterparty has only a single netting agreement.

for j = 1:numCounterparties

nettedIdx = swaps.NettingID == j;

% Exposures for instruments under netting agreements

nettedValues = values(nettedIdx,:,:);

nettedExposure = max(sum(nettedValues,1),0);

positiveIdx = nettedExposure > 0;

instrument_exposures(nettedIdx,positiveIdx) =

values(nettedIdx,positiveIdx);

end

% Sum the instrument exposures for each counterparty

exposures = zeros(numCounterparties,numel(dates),numScenarios);

for j = 1:numCounterparties

cpSwapIdx = swaps.Counterparty == j;

exposures(j,:,:) =

squeeze(sum(instrument_exposures(cpSwapIdx,:,:),1));

end

We plot the total portfolio exposure for each scenario in our simulation. Similar to the plot of instrument values, the

exposures for each scenario w ill approach zero as the sw aps mature.

% View portfolio exposure over time

figure

totalPortExposure = squeeze(sum(exposures,1));

plot(dates,totalPortExposure);

title('Simulated Portfolio Exposure');

datetick('x','mmmyy')

ylabel('Exposure ($)')

xlabel('Simulation Dates')

Page 8: MathWorks Nordic - Counterparty Credit Risk and CVA - MATLAB & Simulink

2012-11-12MathWorks Nordic - Counterparty Credit Risk and CVA - MATLAB & Simulink

8/14www.mathworks.se/help/fininst/counterparty-credit-risk-and-cva.html

Exposure Profiles

Several exposure profiles are useful w hen analyzing the potential future exposure of a bank to a counterparty.

Here w e compute several (non-discounted) exposure profiles per counterparty as w ell as for the entire portfolio.

PE : Peak Exposure : A high percentile (95%) of the distribution of exposures at any particular future date

MPE : Maximum Peak Exposure : The maximum peak exposure across all dates

EE : Expected Exposure : The mean (average) of the distribution of exposures at each date

EPE : Expected Positive Exposure : Weighted average over time of the expected exposure

EffEE : Effective Expected Exposure : The maximum expected exposure at any time, t, or previous time

EffEPE : Effective Expected Positive Exposure : The w eighted average of the effective expected exposure

For further definitions, see for example Basel II document in references.

% Compute entire portfolio exposure

expPort = squeeze(sum(exposures))';

% Peak Exposure (same as Potential Future Exposure)

PEcp = prctile(exposures,95,3);

PEport = prctile(expPort,95);

% Maximum Peak Exposure

MPEcp = max(PEcp,[],2);

MPEport = max(PEport);

% Expected Exposure

EEcp = mean(exposures,3);

EEport = mean(expPort);

% Expected Positive Exposure: Weighted average over time of EE

% * In continuous time, this is the average expected exposures over

time,

% an integral of EE(t) over the time interval, divided by the length

Page 9: MathWorks Nordic - Counterparty Credit Risk and CVA - MATLAB & Simulink

MathWorks Nordic - Counterparty Credit Risk and CVA - MATLAB & Simulink

9/14www.mathworks.se/help/fininst/counterparty-credit-risk-and-cva.html

of

% the interval

% * Compute using a "trapezoidal" approach here

simTimeInterval = yearfrac(Settle, dates, 1);

simTotalTime = simTimeInterval(end)-simTimeInterval(1);

EPEcp = 0.5*(EEcp(:,1:end-

1)+EEcp(:,2:end))*diff(simTimeInterval)'/simTotalTime;

EPEport = 0.5*(EEport(1:end-

1)+EEport(2:end))*diff(simTimeInterval)'/simTotalTime;

% Effective Expected Exposure: Max EE up to time simTimeInterval

EffEEcp = zeros(size(EEcp));

for i = 1:size(EEcp,1)

% Compute cumulative maximum

m = EEcp(i,1);

for j = 1:numel(dates)

if EEcp(i,j) > m

m = EEcp(i,j);

end

EffEEcp(i,j) = m;

end

end

% Compute cumulative maximum for portfolio

EffEEport = zeros(size(EEport));

m = EEport(1);

for j = 1:numel(dates)

if EEport(j) > m

m = EEport(j);

end

EffEEport(j) = m;

end

% Effective Expected Positive Exposure: Weighted average over time of

EffEE

EffEPEcp = 0.5*(EffEEcp(:,1:end-

1)+EffEEcp(:,2:end))*diff(simTimeInterval)'/simTotalTime;

EffEPEport = 0.5*(EffEEport(1:end-

1)+EffEEport(2:end))*diff(simTimeInterval)'/simTotalTime;

We visualize the exposure profiles, f irst for the entire portfolio, then for a particular counterparty.

% Visualize portfolio exposure profiles

figure

plot(dates,PEport,...

dates,MPEport*ones(size(PEport)),...

dates,EEport,...

dates,EPEport*ones(size(PEport)),...

dates,EffEEport,...

dates,EffEPEport*ones(size(PEport)))

legend({'PE (95%)','MPE (95%)','EE','EPE','EffEE','EffEPE'})

datetick('x','mmmyy')

title('Portfolio Exposure Profiles');

ylabel('Exposure ($)')

Page 10: MathWorks Nordic - Counterparty Credit Risk and CVA - MATLAB & Simulink

2012-11-12MathWorks Nordic - Counterparty Credit Risk and CVA - MATLAB & Simulink

10/14www.mathworks.se/help/fininst/counterparty-credit-risk-and-cva.html

xlabel('Simulation Dates')

% Visualize exposure profiles for a particular counterparty

cpIdx = 5;

figure

plot(dates,PEcp(cpIdx,:),...

dates,MPEcp(cpIdx,:)*ones(size(PEcp(cpIdx,:))),...

dates,EEcp(cpIdx,:),...

dates,EPEcp(cpIdx,:)*ones(size(PEcp(cpIdx,:))),...

dates,EffEEcp(cpIdx,:),...

dates,EffEPEcp(cpIdx,:)*ones(size(PEcp(cpIdx,:))))

legend({'PE (95%)','MPE (95%)','EE','EPE','EffEE','EffEPE'})

datetick('x','mmmyy')

title(sprintf('Counterparty %d Exposure Profiles',cpIdx));

ylabel('Exposure ($)')

xlabel('Simulation Dates')

Page 11: MathWorks Nordic - Counterparty Credit Risk and CVA - MATLAB & Simulink

2012-11-12MathWorks Nordic - Counterparty Credit Risk and CVA - MATLAB & Simulink

11/14www.mathworks.se/help/fininst/counterparty-credit-risk-and-cva.html

Discounted Exposures

We compute the discounted expected exposures using the discount factors from each simulated interest rate

scenario. The discount factor for a given valuation date in a given scenario is the product of the incremental

discount factors from one simulation date to the next, along the interest rate path of that scenario.

% Get discounted exposures per counterparty, for each scenario

discExp = zeros(size(exposures));

for i=1:numScenarios

discExp(:,:,i) = bsxfun(@times,scenarios(i).Disc,exposures(:,:,i));

end

% Discounted expected exposure

discEE = mean(discExp,3);

We plot the discounted expected exposures for the aggregate portfolio as w ell as for each counterparty.

% Portfolio discounted EE

figure;

plot(dates,sum(discEE))

datetick('x','mmmyy')

title('Discounted Expected Exposure for Portfolio');

ylabel('Discounted Exposure ($)')

xlabel('Simulation Dates')

% Counterparty discounted EE

figure;

plot(dates,discEE)

datetick('x','mmmyy')

title('Discounted Expected Exposure for Each Counterparty');

ylabel('Discounted Exposure ($)')

xlabel('Simulation Dates')

Page 12: MathWorks Nordic - Counterparty Credit Risk and CVA - MATLAB & Simulink

2012-11-12MathWorks Nordic - Counterparty Credit Risk and CVA - MATLAB & Simulink

12/14www.mathworks.se/help/fininst/counterparty-credit-risk-and-cva.html

Calibrating Probability of Default Curve for One Counterparty

The default probability for a given counterparty is implied by the current market spreads of the counterparty's credit

default sw aps. We use the function cdsbootstrap to generate the cumulative probability of default at each

simulation date.

% CDS Market Information for the counterparty cpIdx

CDSDates = datenum({'20-Mar-08','20-Mar-09','20-Mar-10','20-Mar-11',...

'20-Mar-12'});

CDSSpreads = [140 175 210 265 310]';

CDSData = [CDSDates CDSSpreads];

ZeroData = [RateSpec.EndDates RateSpec.Rates];

% Calibrate Default Probability to CDS Quotes

Page 13: MathWorks Nordic - Counterparty Credit Risk and CVA - MATLAB & Simulink

2012-11-12MathWorks Nordic - Counterparty Credit Risk and CVA - MATLAB & Simulink

13/14www.mathworks.se/help/fininst/counterparty-credit-risk-and-cva.html

DefProbData = cdsbootstrap(ZeroData,CDSData,Settle,...

'ProbDates',dates');

We plot of the cumulative probability of default for the counterparty in question.

figure

plot(DefProbData(:,1),DefProbData(:,2))

title(sprintf('Default Probability Curve for Counterparty %d',cpIdx));

xlabel('Date')

ylabel('Cumulative Probability')

datetick('x','mmmyy')

ylabel('Probability of Default')

xlabel('Simulation Dates')

CVA Computation

The Credit Value (Valuation) Adjustment (CVA) formula is:

Where R is the recovery, discEE the discounted expected exposure at time t, and PD the default probability

distribution. This assumes the exposure is independent of default (no w rong-w ay risk), and it also assumes the

exposure w ere obtained using risk-neutral probabilities.

Here w e approximate the integral w ith a f inite sum over the valuation dates as:

w here t_1 is todays date, t_2,...,t_n the future valuation dates.

We assume CDS info corresponds to counterparty w ith index cpIdx. The computed CVA is the present market value

of our credit exposure to counterparty cpIdx. For this example w e set the recovery rate at 40%.

Page 14: MathWorks Nordic - Counterparty Credit Risk and CVA - MATLAB & Simulink

2012-11-12MathWorks Nordic - Counterparty Credit Risk and CVA - MATLAB & Simulink

14/14www.mathworks.se/help/fininst/counterparty-credit-risk-and-cva.html

Try MATLAB, Simulink, and Other Products

Get trial now

Recovery = 0.4;

CVA = (1-Recovery)*sum(discEE(cpIdx,2:end)'.*diff(DefProbData(:,2)));

fprintf('CVA for counterparty %d = $%.2f\n',cpIdx,CVA)

CVA for counterparty 5 = $4684.57

References

1. Pykhtin, Michael, and Steven Zhu, A Guide to Modelling Counterparty Credit Risk, GARP, July/August 2007,

issue 37, pp. 16-22. Available at: http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1032522.

2. Basel II: http://w w w .bis.org/publ/bcbs128.pdf page 256

Was this topic helpful? Yes No