Академический Документы
Профессиональный Документы
Культура Документы
Brad Baxter
Department of Economics, Mathematics and Statistics,
Birkbeck College, University of London,
Malet Street, London WC1E 7HX
b.baxter@bbk.ac.uk
1. Introduction
These notes can be obtained from
http://econ109.econ.bbk.ac.uk/brad/matlab/
and you can download lots of relevant material for MSc Financial Engineering from
http://econ109.econ.bbk.ac.uk/brad/Methods/
This should also be useful for GDFE students. In particular, this folder
should always contain a recent version of methods notes.pdf and nabook.pdf.
You should already be able to use your College UserId in the departmental
computer room. The door code for this room is 5858 and you are welcome
to use it whenever it is available. All machines should be equipped with
MATLAB and other useful software.
You can buy the MATLAB Student Edition from MathWorks at
http://www.mathworks.com/academia/student_version/
Unfortunately, legal restrictions prevent our simply providing you with a
free copy of MATLAB. However, the free product Octave is provided with
many linux distributions and a Windows version can be obtained from
http://www.gnu.org/software/octave/index.html
1
Version: 201010141435
Brad Baxter
An Introduction to MATLAB
% Plot a histogram
%
nbins = 30;
hist(v,nbins);
Exercise 1.1. Now experiment with this code: change N and nbins.
Exercise 1.2. MATLAB can also generate uniformly distributed random
numbers: change randn to rand in the last example to see this.
As we have already seen, MATLAB can easily construct histograms for
Gaussian pseudorandom numbers. Now a normalized Gaussian random variable Z N (0, 1) has the probability density function (PDF)
p(s) = (2)1/2 es
2 /2
for s R,
that is,
Z
P(a < Z < b) =
p(s) ds.
a
The next example shows that the histogram approximates the PDF, and
introduces some more advanced use of graphics. It also introduces the extremely useful MATLAB colon notation: in MATLAB, [1:10] generates
the row vector (1, 2, . . . , 10).
Example 1.3. Generate a histogram approximating the Gaussian PDF:
% We generate a 1 x 5000 array of N(0,1) numbers
a = randn(1,5000);
% histogram from -3 to 3 using bins of size .2
[n,x] = hist(a, [-3:.2:3]);
% draw a normalized bar chart of this histogram
bar(x,n/(5000*.2));
% draw the next curve on the same plot
hold on
% draw the Gaussian probability density function
plot(x, exp(-x.^2/2)/sqrt(2*pi))
%
% Note the MATLAB syntax here: x.^2 generates a new array
% whose elements are the squares of the original array x.
hold off
Exercise 1.3. Now repeat this experiment several times to get a feel for
how the histogram matches the density for the standard normal distribution.
Replace the magic numbers 5000 and 0.2 by N and Delta and see for yourself
how much it helps or hinders to take more samples or smaller size bins.
Brad Baxter
Exercise 1.4. Type [1:5], [1:5] and [1:0.5:5] to explore the colon
notation. Further, type the following:
A = [1:3, 1:2]
A.^2
The final example illustrates one form of the Central Limit Theorem:
averages of independent, uniformly distributed random variables converge
to the Gaussian distribution.
Example 1.4. A Central Limit Theorem example:
%
% This program illustrates the Central Limit Theorem: suitably
% scaled averages of uniformly distributed random variables
% look Gaussian.
%
% First we create a 20 x 10000 matrix of pseudorandom numbers uniformly
% distributed on the interval [0,1]
%
m = 20;
n = 10000;
v = rand(20,10000);
%
% We now use the MATLAB histogram function to see the distribution of
% one row of this matrix
%
nbins = 20;
hist(v(1,:), nbins);
%
% We now sum each column of this matrix, divide by sqrt(m)
% and histogram the new sequence
%
w = sum(v)/sqrt(m);
hist(w,nbins);
%
% Now play with the constants, m, n, and nbins.
%
1.2. Brownian Motion
The mathematics of Brownian motion is covered in my Mathematical Methods lectures, during the first term of MSc Financial Engineering. However,
it is possible to obtain a good feel for Brownian motion using some simple
MATLAB examples.
An Introduction to MATLAB
Our next example generates discrete Brownian motion, as well as introducing some more MATLAB language tools. Mathematically, were generating a random function W : [0, ) R using the equation
W (kh) = h (Z1 + Z2 + + Zk ) ,
for k = 1, 2, . . . ,
where h > 0 is a positive time step and Z1 , Z2 , . . . , Zk are independent
N (0, 1) random variables.
Example 1.5. One basic way to generate Brownian motion:
T = 1; N = 500; dt = T/N;
dW = zeros(1,N);
W = zeros(1,N);
dW(1) = sqrt(dt)*randn;
W(1) = dW(1);
for j = 2:N
dW(j) = sqrt(dt)*randn;
W(j) = W(j-1) + dW(j);
end
plot([0:dt:T],[0,W])
In fact, because MATLAB is an interpreted language, for loops are inefficient. Theres a MATLAB function cumsum to calculate the cumulative
sum performed by the for loop in the last program.
Example 1.6. A more concise way to generate Brownian motion:
T = 1; N = 500; dt = T/N;
dW = sqrt(dt)*randn(1,N);
W = cumsum(dW);
plot([0:dt:T],[0,W])
Exercise 1.5. Now play with this code: increase N and change T . I
recommend you condense the previous code, to ease repetition:
T = 1; N = 500; dt = T/N;
dW = sqrt(dt)*randn(1,N); plot([0:dt:T],[0,cumsum(dW)])
Example 1.7. Generating several Brownian sample paths:
T = 1; N = 500; dt = T/N;
nsamples = 10;
Brad Baxter
hold on
for k=1:nsamples
dW = sqrt(dt)*randn(1,N); plot([0:dt:T],[0,cumsum(dW)])
end
Exercise 1.6. It can be shown that EW (t) = 0 and E(W (t)2 ) = t. Can
you modify the last example to check this?
1.3. Geometric Brownian Motion (GBM)
The idea that it can be useful to model asset prices using random functions
was both surprising and implausible when Louis Bachelier first suggested
Brownian motion in his thesis in 1900. There is an excellent translation of
his pioneering work in Louis Bacheliers Theory of Speculation: The Origins
of Modern Finance, by M. Davis and A. Etheridge. However, as you have
already seen, a Brownian motion can be both positive and negative, whilst a
share price can only be positive, so Brownian motion isnt quite suitable as a
mathematical model for share prices. Its modern replacement is to take the
exponential, and the result is called Geometric Brownian Motion (GBM).
In other words, the most common mathematical model in modern finance is
given by
S(t) = S(0)et+W (t) ,
for t > 0,
where R is called the drift and is called the volatility.
Example 1.8. Generating GBM:
T = 1; N = 500; dt = T/N;
t = 0:dt:T;
dW = sqrt(dt)*randn(1,N);
mu = 0.1; sigma = 0.01;
plot(t,exp(mu*t + sigma*[0,cumsum(dW)]))
Exercise 1.7.
sigma.
This name originated with the brilliant mathematician John von Neumann, during his
work on the Manhattan Project, the secret project building the first American atomic
bombs during World War II. In the first Monte Carlo simulation, the sample paths
were those of neutrons passing through Uranium, the aim being to estimate the mass
An Introduction to MATLAB
Gaussian random numbers, all of which are N (0, 1). We now need to tell
the cumsum function to cumulatively sum along each row, and this is slightly
more tricky.
Example 1.9. Generating several GBM sample paths:
T = 1; N = 500; dt = T/N;
t = 0:dt:T;
M=10;
dW = sqrt(dt)*randn(M,N);
mu = 0.1; sigma = 0.01;
S = exp(mu*ones(M,1)*t + sigma*[zeros(M,1), cumsum(dW,2)]);
plot(t,S)
Here the MATLAB function ones(p,q) creates a p q matrix of ones,
whilst zeros(p,q) creates a p q matrix of zeros. The matrix product
ones(M,1)*t is a simple way to create an M N matrix whose every row
is a copy of t.
Exercise 1.8. Experiment with various values of the drift and volatility.
Exercise 1.9. Copy the use of the cumsum function in Example 1.9 to
avoid the for loop in Example 1.7.
1.4. Graphics
Lets learn more about graphics.
Example 1.10. Plotting a sine curve:
t = 0: pi/200: 2*pi;
y = sin(3*t);
plot(t,y)
Exercise 1.10. Replace plot(t,y) by plot(t,y,o) in the last example.
MATLAB can also produce polar graphs.
of the Uranium isotope U235 required for a successful fission bomb. The American
team used some of the first computers (more like programmable calculators, by our
standards) to estimate some 64 kg of U235 would be sufficient, which was achievable
using the cumbersome technology required to separate the 0.07% of U235 from common
Uranium ore; they were correct in their estimates. The German team, led by Werner
Heisenberg, had neither computers nor simulation. Heisenberg estimated a 1000 kg
of U235 would be required, and therefore gave up, ending the German atomic bomb
project.
Brad Baxter
2 2)t+W (t)
for t > 0,
where W (t) is Brownian motion, S(0) = 42, r = 0.1 and = 0.2. These parameters were fairly typical for the NYSE in the 1990s, and this example was
taken from Options, Futures and Other Derivative Securities, by J. C. Hull.
We can easily gain some idea of the likely future behaviour for this stock
over the next 6 months by a small modification of our earlier example.
Example 1.12. Generating GBM sample paths for Hull, Example 11.6:
T = 0.5; N = 100; dt = T/N;
t = 0:dt:T;
%
% M = number of sample paths
%
An Introduction to MATLAB
M=20;
%
% generate Gaussian increments
%
dW = sqrt(dt)*randn(M,N);
%
S0 = 42; r=0.1; sigma = 0.2; mu = r - (sigma^2)/2;
%
% generate M x N matrix of M sample paths and plot them
%
S = S0*exp(mu*ones(M,1)*t + sigma*[zeros(M,1), cumsum(dW,2)]);
plot(t,S)
In fact, for our purposes, our primary interest is the distribution of the
possible final values S(T ), so there is no need to generate the sample paths
themselves. Instead, we shall use the mathematical fact that W (T )
N (0, T ) to generate some possible share prices S(T ) at the expiry time T .
Example 1.13. Generating future asset prices at expiry time T :
S0 = 42;
r = 0.1;
T = 0.5;
sigma = 0.2;
%
% N = number of samples
%
N = 10000;
%
% generate asset prices at expiry
%
Z = randn(N,1);
ST = S0*exp( (r-(sigma^2)/2)*T + sigma*sqrt(T)*Z );
%
% display histogram of possible prices at expiry
%
hist(ST,40);
Once we know how to generate likely future prices in this way, we can
price a Euro put option: let us suppose we own the share already and wish
to insure ourselves against a decrease in its value over the next 6 months.
Specifically, we wish to buy the right, but not the obligation, to sell the
share at the exercise price K = $40 at T = 0.5. Such a contract is called a
European put option, with exercise price (or strike price) K and expiry time
T = 0.5. Obviously we want to compute the fair price of such a contract.
10
Brad Baxter
An Introduction to MATLAB
11
12
Brad Baxter
imation for a European call, for which the contract value at expiry is given
by
fcall = max(ST - K, 0)
and putcall parity provides the useful relation
Call Put = S(0) KerT .
You could also modify the program to calculate the Monte Carlo approximation to a digital call, for which the contract value at expiry is given
by
fdcall = (ST > K);
2. Further programs
Ive provided more MATLAB programs which you can obtain from my office
linux box http://econ109.econ.bbk.ac.uk/brad/matlab/. Theres also
lots of useful information in http://econ109.econ.bbk.ac.uk/brad/Methods
2.1. An advanced example
Please ignore this on your first reading unless youre fairly confident with
both MATLAB and linear algebra.
There are often surprising patterns in random structures. The next program illustrates the Wigner semi-circle law: the distribution of eigenvalues
from a random symmetric matrix appears as a semi-circle when plotted on
a suitable scale. Random matrices were originally studied in theoretical
physics, but there are now attempts to model the covariance structure of
stock markets as a deterministic component combined with a certain random matrix. [As with any interesting, somewhat dubious, new idea, you
can assume that a hedge fund is trying to sell it to someone!]
Example 2.1. Illustrating the Wigner semi-circle law for random matrices:
n = 50;
% size of matrix
s = 200;
% number of samples
e = [];
% this is going to be our array of eigenvalues
%
% We generate s symmetric Gaussian random n x n matrices
% and store all their eigenvalues in the array
%
for i=1:s
a = randn(n);
a = (a + a)/2;
An Introduction to MATLAB
13
e = [e eig(a)];
end
e = e/sqrt(2*n);
%
% This is fiddly to explain: youll learn more by playing with
% this code than reading help hist or help bar
%
hold off
[m,x] = hist(e, -1:.1:1);
bar(x, m*5*pi/(n*s));
axis(square)
axis([-1.5 1.5 -1 2])
hold on
t = -1:.01:1;
plot(t, sqrt(1-t.^2));
2.2. Another advanced example
runge1.m: This illustrates the Runge phenomenon, whose purpose is to convince you to distrust data fitting using polynomials. Here were interpolating
the infinitely differentiable function
1
,
x R,
f (x) =
1 + 5x2
at equally spaced points in the interval [1, 1]. MATLAB makes this very
easy, although illustrating such a disastrous fit is harder than it looks! You
should experiment with the parameters. For example, change the number
of interpolation points, or alter the function to f (x) = (1 + 100x2 )1 . My
aim is for you to play with MATLAB. Heres the MATLAB program.
Example 2.2. The Runge example:
%
% This program illustrates the Runge phenomenon: data fitting
% with polynomials can be terrible! Hence the need for other
% methods, such as radial basis functions.
%
n=24;
x=-1:1/n:1;
y=1 ./ (1 + 5*(x.^2));
d = length(x)-1;
p=polyfit(x,y,d);
N=1000;
xx=-1:1/N:1;
14
yy=1 ./ (1 + 5*(xx.^2));
zz=polyval(p,xx);
plot(xx,yy)
hold on
pause
plot(xx,zz,r)
Brad Baxter