Code covered by the BSD License  

Highlights from
Pricing Derivatives Securities using MATLAB

image thumbnail

Pricing Derivatives Securities using MATLAB

by

 

02 Apr 2007 (Updated )

Examples of pricing derivatives securities using MATLAB

exampleBDT.m
%% Pricing Derivatives Securities using Matlab
%
% This demo illustrates how Matlab can be used to create a portfolio of 
% interest rate derivatives securities, and price it using a Zero Curve and
% the  Black-Derman-Toy interest rate model. 
% The demo also demonstrates some hedging strategies to minimize exposure
% to market movements.

% Copyright 1995-2010 The MathWorks, Inc.

%% Create the Interest Rate Term Structure based on reported data
%
% The structure RateSpec is an interest rate term structure that defines the
% initial rate specification from which the tree rates are derived.
% Use the information of annualized zero coupon rates in the table below
% to populate the RateSpec structure. 
% This data will be retrieved from the Federal Reserve Statistical Release page  
% by using the Datafeed Toolbox.
%
%    From             To           Rate
% 27 Feb 2007    27 Feb 2008      0.0493
% 27 Feb 2007    27 Feb 2009      0.0459
% 27 Feb 2007    27 Feb 2010      0.0450
% 27 Feb 2007    27 Feb 2012      0.0446
% 27 Feb 2007    27 Feb 2014      0.0445
% 27 Feb 2007    27 Feb 2017      0.0450
% 27 Feb 2007    27 Feb 2027      0.0473
% 
% The Datafeed Toolbox will connect to FRED and pull back the rates of the 
% following treasury notes.
%
%    Terms    Symbol
%   =======   ======
%      1   =  DGS1
%      2   =  DGS2
%      3   =  DGS3
%      5   =  DGS5
%      7   =  DGS7
%      10  =  DGS10
%      20  =  DGS20

% Create connection object
c = fred;

% Create symbol fetch list
FredNames   = { ...    
    'DGS1'; ...      % 1  Year
    'DGS2'; ...      % 2  Year
    'DGS3'; ...      % 3  Year
    'DGS5'; ...      % 5  Year
    'DGS7'; ...      % 7  Year
    'DGS10'; ...     % 10 Year
    'DGS20'};        % 20 Year

% Define Terms
Terms = [ ...
    1; ...      % 1  Year
    2; ...      % 2  Year
    3; ...      % 3  Year
    5; ...      % 5  Year
    7; ...      % 7  Year
    10; ...     % 10 Year
    20];        % 20 Year

% Set StartDate to Feb 27, 2007
StartDate = datenum('Feb-27-2007');
FredRet = fetch(c,FredNames,StartDate); 

% Set ValuationDate based on StartDate
ValuationDate = StartDate;
    
EndDates = [];
Rates =[];

% Create EndDates
for idx = 1:length(FredRet)    
    
    % Pull the rates associated with Feb 27, 2007
    Rates = [Rates; ...
        FredRet(idx).Data(1,2) / 100];% all the Fred Rates come back as percents


    % Determine the EndDates by adding the Term to the year of the
    % StartDate
     
    EndDates = [EndDates; ...
        round(datenum(...
            year(StartDate)+Terms(idx,1), ...
            month(StartDate),...
            day(StartDate)))];

end

% Use intenvset to create the RateSpec
Compounding = 1;
RateSpec = intenvset('Compounding',Compounding,'StartDates', StartDate,...
                     'EndDates', EndDates, 'Rates', Rates,'ValuationDate', ValuationDate)

%% Specify the Volatility Model
%
% Create the structure VolSpec that specifies the volatility process with 
% the following data.  

Volatility = [0.011892; 0.01563; 0.02021; 0.02125; 0.02165; 0.02065; 0.01803];

VolSpec = bdtvolspec(ValuationDate, EndDates, Volatility)

%% Specify the Time Structure of the Tree
%
% The structure TimeSpec specifies the time structure for an interest rate
% tree. This structure defines the mapping between the observation times at 
% each level of the tree and the corresponding dates. 

TimeSpec = bdttimespec(ValuationDate, EndDates)

%% Create the BDT Tree
%
% Use the previously computed values for RateSpec, VolSpec and TimeSpec
% to create the BDT tree. 

BDTTree = bdttree(VolSpec, RateSpec, TimeSpec)


%% 
% Observe the Interest Rate Tree
%
% Visualize the interest rate evolution along the tree by looking at the
% output structure BDTTree. The function 'bdttree' returns an inverse 
% discount tree, which you can convert into an interest rate tree with 
% the 'cvtree' function.

BDTTreeR = cvtree(BDTTree)

%%
% Look at the upper branch and lower branch paths of the tree:
format short

%Rate at root node:
RateRoot      = treepath(BDTTreeR.RateTree, 0) 

%Rates along upper branch:
RatePathUp    = treepath(BDTTreeR.RateTree, [1 1 1 1]) 

%Rates along lower branch:
RatePathDown = treepath(BDTTreeR.RateTree, [2 2 2 2]) 


%%
% You can also display a graphical representation of the tree to examine 
% interactively the rates on the nodes of the tree until maturity. 
% The function treeviewer displays the structure of the rate tree in the
% left window. The tree visualization in the right window is blank, but by 
% selecting Table/Diagram and clicking on the nodes you can examine the 
% rates along the paths.

treeviewer(BDTTreeR);


%% Create an instrument portfolio
%
% Create a portfolio consisting of two bonds instruments and an option on the 5% Bond. 

% Two Bonds
CouponRate = [0.04;0.05]; 
Settle = '27 Feb 2007'; 
Maturity = {'27 Feb 2009';'27 Feb 2010'};
Period = 1;

% American Option on the 5% Bond
OptSpec = {'call'};
Strike = 98;
ExerciseDates = '27 Feb 2010';
AmericanOpt = 1;

InstSet = instadd('Bond',CouponRate, Settle,  Maturity, Period);
InstSet = instadd(InstSet,'OptBond', 2, OptSpec, Strike, ExerciseDates, AmericanOpt);

% Assign Names and Holdings
Holdings = [10; 15;3];
Names = {'4% Bond'; '5% Bond'; 'Option 98'};

InstSet = instsetfield(InstSet, 'Index',1:3, 'FieldName', {'Quantity'}, 'Data', Holdings );
InstSet = instsetfield(InstSet, 'Index',1:3, 'FieldName', {'Name'}, 'Data', Names );

%%
% Examine the set of instruments contained in the variable InstSet.

instdisp(InstSet)


%% Price the bond instruments using the Zero Curve
%
PriceBond = bondbyzero(RateSpec, CouponRate, Settle, Maturity, Period)


%% Price the portfolio using the BDT model
%
% Calculate the price of each instrument in the portfolio. 

[Price, PTree] = bdtprice(BDTTree, InstSet)

%% 
% The prices in the output vector Price correspond to the prices at
% observation time zero (tObs = 0), which is defined as the Valuation Date
% of the interest-rate tree.
%
% In the Price vector, the first element, 98.8841, represents the price of
% the first instrument (4% Bond); the second element,  101.3470, represents 
% the price of the second instrument (5% Bond), and 3.3470 represents the
% price of the Option.

%%
% You can also display a graphical representation of the price tree to examine 
% the prices on the nodes of the tree until maturity. 

treeviewer(PTree,InstSet);

%% Add more instrumenst to the existing portfolio
%
% Add instruments to the existing portfolio:  cap, floor, floating rate
% note and a vanilla swap.

% Cap
StrikeC =0.035;
InstSet = instadd(InstSet,'Cap', StrikeC, Settle, '27 Feb 2010');

% Floor
StrikeF =0.05;
InstSet = instadd(InstSet,'Floor', StrikeF, Settle, '27 Feb 2009');

% Floating Rate Note
InstSet = instadd(InstSet,'Float', 30, Settle, '27 Feb 2009');

% Vanilla Swap
 LegRate =[0.04 5];
 InstSet = instadd(InstSet,'Swap', LegRate, Settle, '27 Feb 2010');

% Process Names and Holdings
Holdings = [15 ;5 ;8; 7];
Names = {'3.5% Cap';'5% Floor';'30BP Float';'4%/5BP Swap' };

InstSet = instsetfield(InstSet, 'Index',4:7, 'FieldName', {'Quantity'}, 'Data', Holdings );
InstSet = instsetfield(InstSet, 'Index',4:7, 'FieldName', {'Name'}, 'Data', Names );
%%
% Examine the set of instruments contained in the variable InstSet.
instdisp(InstSet)


%% Price the portfolio using other interest rate models
%
% Matlab provides several models to price interest rate derivatives securities. 
%
% Recombining tree models: Black-Derman-Toy (BDT), Hull-White (HW) and Black-Karasinski (BK)
%
% Bushy tree model: Heath-Jarrow-Morton (HJM)

% Let's take a look at the priced portfolio using these four interest rate
% models. In this demo the number of time steps have been decreased so that 
% results could be visualized better.

load treedemonew
treedemonew

%% Hedging
%
% The idea behind hedging is to minimize exposure to market movements. As
% the underlying changes, the proportions of the instruments forming the 
% portfolio may need to be adjusted to keep the sensitivities within the 
% desired range.
% 
% Calculate sensitivities using the BDT model
[Delta, Gamma, Vega, Price] = bdtsens(BDTTree, InstSet);

%%
% Get the current portfolio holdings.
Holdings = instget(InstSet, 'FieldName', 'Quantity');

%%
% Create a matrix of sensitivities
Sensitivities = [Delta Gamma Vega];

%%
% Each row of the Sensitivities matrix is associated with a different
% instrument in the portfolio, and each column with a different sensitivity
% measure.

%%
% Display the information
format bank
disp([Price  Holdings  Sensitivities])

%%
% The first column above is the dollar unit price of each instrument,
% the second is number of contracts of each instrument, and the third, 
% fourth, and fifth columns are the dollar delta, gamma, and vega
% sensitivities. 
%
% The current portfolio sensitivities are a weighted average of the instruments
% in the portfolio.

TargetSens  = Holdings' * Sensitivities


%% Obtain a neutral sensitivity portfolio
% Suppose you want to obtain a delta, gamma and vega neutral portfolio.
% The function hedgeslf finds the reallocation in a portfolio of financial
% instruments closest to being self-financing  (maintaining constant portfolio value). 

[Sens, Value1, Quantity]= hedgeslf(Sensitivities, Price,Holdings)

%%
% The function hedgeslf returns the portfolio dollar sensitivities (Sens), 
% the value of the rebalanced portfolio (Value1) and the new allocation 
% for each instrument (Quantity). 
% If Value0 and Value1 represent the portfolio value before and after 
% rebalancing,  you can verify the cost by comparing the portfolio values.

Value0 = Holdings' * Price

%%
% In this example, the portfolio is fully hedged (simultaneous delta,
% gamma, and vega neutrality) and self-financing (the values of the portfolio
% before and after balancing (Value0 and Value1) are the same.


%% Adding constraints to hegde a portfolio
%
% Suppose that you want to place upper and lower bounds on the individual 
% instruments in the portfolio. 
% Let's say that you want to bound the position of  all instruments to
% within +/- 15 contracts.

%%
% Applying these constraints disallows the current position in the sixth instrument.
% All other instruments are currently within the upper/lower bounds.

% Specify the lower and upper bounds
LowerBounds = [-15  -15  -15   -15   -15    -15  -15];
UpperBounds = [ 15   15   15    15    15     15   15];

% Use the function portcons to build the constraints
ConSet = portcons('AssetLims', LowerBounds, UpperBounds);

% Apply the constraints to the portfolio
[Sens, Value, Quantity1] = hedgeslf(Sensitivities, Price, Holdings, [], ConSet)


%%
%
% Observe that hedgeslf enforces the upper bound on the sixth instrument, 
% and the portfolio continues to be fully hedged and self-financing.

displayEndOfDemoMessage(mfilename)

Contact us