|On this page…|
Financial Toolbox™ and MATLAB® graphics functions work together to produce presentation quality graphics, as these examples show. The examples ship with the toolbox as MATLAB files. Try them by entering the commands directly or by executing the code. For help using MATLAB plotting functions, see "Creating Line Plots" in the MATLAB documentation.
This example plots the efficient frontier of a hypothetical portfolio of three assets. It illustrates how to specify the expected returns, standard deviations, and correlations of a portfolio of assets, how to convert standard deviations and correlations into a covariance matrix, and how to compute and plot the efficient frontier from the returns and covariance matrix. The example also illustrates how to randomly generate a set of portfolio weights, and how to add the random portfolios to an existing plot for comparison with the efficient frontier. The file for this example is ftgex1.m.
First, specify the expected returns, standard deviations, and correlation matrix for a hypothetical portfolio of three assets.
Returns = [0.1 0.15 0.12]; STDs = [0.2 0.25 0.18]; Correlations = [ 1 0.3 0.4 0.3 1 0.3 0.4 0.3 1 ];
Convert the standard deviations and correlation matrix into a variance-covariance matrix with the Financial Toolbox function corr2cov.
Covariances = corr2cov(STDs, Correlations);
Evaluate and plot the efficient frontier at 20 points along the frontier, using the function portopt and the expected returns and corresponding covariance matrix. Although rather elaborate constraints can be placed on the assets in a portfolio, for simplicity accept the default constraints and scale the total value of the portfolio to 1 and constrain the weights to be positive (no short-selling).
portopt(Returns, Covariances, 20)
Now that the efficient frontier is displayed, randomly generate the asset weights for 1000 portfolios starting from the MATLAB initial state.
rng('default') Weights = rand(1000, 3);
The previous line of code generates three columns of uniformly distributed random weights, but does not guarantee they sum to 1. The following code segment normalizes the weights of each portfolio so that the total of the three weights represent a valid portfolio.
Total = sum(Weights, 2); % Add the weights Total = Total(:,ones(3,1)); % Make size-compatible matrix Weights = Weights./Total; % Normalize so sum = 1
Given the 1000 random portfolios just created, compute the expected return and risk of each portfolio associated with the weights.
[PortRisk, PortReturn] = portstats(Returns, Covariances, ... Weights);
Finally, hold the current graph, and plot the returns and risks of each portfolio on top of the existing efficient frontier for comparison. After plotting, annotate the graph with a title and return the graph to default holding status (any subsequent plots will erase the existing data). The efficient frontier appears in blue, while the 1000 random portfolios appear as a set of red dots on or below the frontier.
hold on plot (PortRisk, PortReturn, '.r') title('Mean-Variance Efficient Frontier and Random Portfolios') hold off
This example creates a three-dimensional plot showing how gamma changes relative to price for a Black-Scholes option. Recall that gamma is the second derivative of the option price relative to the underlying security price. The plot shows a three-dimensional surface whose z-value is the gamma of an option as price (x-axis) and time (y-axis) vary. It adds yet a fourth dimension by showing option delta (the first derivative of option price to security price) as the color of the surface. The file for this example is ftgex2.m.
First set the price range of the options, and set the time range to one year divided into half-months and expressed as fractions of a year.
Range = 10:70; Span = length(Range); j = 1:0.5:12; Newj = j(ones(Span,1),:)'/12;
For each time period create a vector of prices from 10 to 70 and create a matrix of all ones.
JSpan = ones(length(j),1); NewRange = Range(JSpan,:); Pad = ones(size(Newj));
Calculate the toolbox gamma and delta sensitivity functions (greeks). (Recall that gamma is the second derivative of the option price with respect to the stock price, and delta is the first derivative of the option price with respect to the stock price.) The exercise price is $40, the risk-free interest rate is 10%, and volatility is 0.35 for all prices and periods.
ZVal = blsgamma(NewRange, 40*Pad, 0.1*Pad, Newj, 0.35*Pad); Color = blsdelta(NewRange, 40*Pad, 0.1*Pad, Newj, 0.35*Pad);
Display the greeks as a function of price and time. Gamma is the z-axis; delta is the color.
mesh(Range, j, ZVal, Color); xlabel('Stock Price ($)'); ylabel('Time (months)'); zlabel('Gamma'); title('Call Option Price Sensitivity'); axis([10 70 1 12 -inf inf]); view(-40, 50); colorbar('horiz');
This example plots gamma as a function of price and time for a portfolio of 10 Black-Scholes options. The plot shows a three-dimensional surface. For each point on the surface, the height (z-value) represents the sum of the gammas for each option in the portfolio weighted by the amount of each option. The x-axis represents changing price, and the y-axis represents time. The plot adds a fourth dimension by showing delta as surface color. This has applications in hedging.
The file for this example is ftgex3.m.
First set up the portfolio with arbitrary data. Current prices range from $20 to $90 for each option. Set corresponding exercise prices for each option.
Range = 20:90; PLen = length(Range); ExPrice = [75 70 50 55 75 50 40 75 60 35];
Rate = 0.1*ones(10,1); Time = [36 36 36 27 18 18 18 9 9 9]; Sigma = 0.35*ones(10,1); NumOpt = 1000*[4 8 3 5 5.5 2 4.8 3 4.8 2.5]; ZVal = zeros(36, PLen); Color = zeros(36, PLen);
For each instrument, create a matrix (of size Time by PLen) of prices for each period.
for i = 1:10 Pad = ones(Time(i),PLen); NewR = Range(ones(Time(i),1),:);
Create a vector of time periods 1 to Time; and a matrix of times, one column for each price.
T = (1:Time(i))'; NewT = T(:,ones(PLen,1));
Call the toolbox gamma and delta sensitivity functions to compute gamma and delta.
ZVal(36-Time(i)+1:36,:) = ZVal(36-Time(i)+1:36,:) ... + NumOpt(i) * blsgamma(NewR, ExPrice(i)*Pad, ... Rate(i)*Pad, NewT/36, Sigma(i)*Pad); Color(36-Time(i)+1:36,:) = Color(36-Time(i)+1:36,:) ... + NumOpt(i) * blsdelta(NewR, ExPrice(i)*Pad, ... Rate(i)*Pad, NewT/36, Sigma(i)*Pad); end
Draw the surface as a mesh, set the viewpoint, and reverse the x-axis because of the viewpoint. The axes range from 20 to 90, 0 to 36, and -∞ to ∞.
mesh(Range, 1:36, ZVal, Color); view(60,60); set(gca, 'xdir','reverse', 'tag', 'mesh_axes_3'); axis([20 90 0 36 -inf inf]);
Add a title and axis labels and draw a box around the plot. Annotate the colors with a bar and label the colorbar.
title('Call Option Portfolio Sensitivity'); xlabel('Stock Price ($)'); ylabel('Time (months)'); zlabel('Gamma'); set(gca, 'box', 'on'); colorbar('horiz');