Sei sulla pagina 1di 23

Introduction to Matlab

Alex Philipov, philipov@bc.edu


November 8, 2003

Objectives

Learn:
The Matlab interface: command window, workspace, help browser
Matlab data and variable types, operators, functions
Types of Matlab files and loading data
Creating Matlab programs and functions
Matlab graphs and visualization

Examples:
1. Load text, csv, and Matlab data files
2. Create descriptive statistics program
3. Create OLS regression program
4. Compute efficient frontier under unconstrained optimization
5. Compute efficient frontier under constrained optimization
6. Use the financial toolbox to compute the efficient frontier
7. Program the Black-Scholes option pricing formula
8. Create program to compute implied volatility
9. Use the financial toolbox to compute the option price and implied volatility

10. Create program for simulating from N (, 2 ) distribution


1

The Matlab Environment

3.1

What is Matlab?

MATLAB is a high-performance language for technical computing. It integrates computation,


visualization, and programming in an easy-to-use environment where problems and solutions
are expressed in familiar mathematical notation. With Matlab, one can program with matrix
and vector formulations in a fraction of the time it would take to write a program in a scalar
noninteractive language such as C or Fortran.
Toolboxes are comprehensive collections of MATLAB functions (M-files) that extend the
MATLAB environment to solve particular classes of problems.

3.2

The MATLAB System

The MATLAB system consists of five main parts:


1. Development Environment This is the set of tools and facilities that help you use
MATLAB functions and files. Many of these tools are graphical user interfaces. It includes the MATLAB desktop and Command Window, a command history, an editor and
debugger, and browsers for viewing help, the workspace, files, and the search path.
2. The MATLAB Mathematical Function Library. This is a vast collection of computational algorithms ranging from elementary functions like sum, sine, cosine, and complex
arithmetic, to more sophisticated functions like matrix inverse, matrix eigenvalues, Bessel
functions, and fast Fourier transforms.
3. The MATLAB Language. This is a high-level matrix/array language with control flow
statements, functions, data structures, input/output, and object-oriented programming
features. It allows both programming in the small to rapidly create quick and dirty
throw-away programs, and programming in the large to create complete large and
complex application programs.
4. Graphics. MATLAB has extensive facilities for displaying vectors and matrices as graphs,
as well as annotating and printing these graphs. It includes high-level functions for twodimensional and three-dimensional data visualization, image processing, animation, and
2

presentation graphics. It also includes low-level functions that allow you to fully customize
the appearance of graphics as well as to build complete graphical user interfaces on your
MATLAB applications.
5. The MATLAB Application Program Interface (API). This is a library that allows you
to write C and Fortran programs that interact with MATLAB. It includes facilities for
calling routines from MATLAB (dynamic linking), calling MATLAB as a computational
engine, and for reading and writing MAT-files.
Use the
Command Window for running functions and entering variables,
Start button for launching tools, demos, and documentation,
Help browser for accessing documentation,
Current Directory browser for accessing files,
Workspace browser for viewing variables,
Editor/Debugger for modifying MATLAB program files (M-files), and
Profiler for optimizing M-file performance.

Matlab variable types


Double numerical variable, a scalar, a vector, a matrix
Example:
x=0.2342
Character a text string
Example:
x=Jan-10-1991
name=Dow Jones Industrials

Cell.
Example: x={Jan-10-1991}
Unlike a character array, a cell array does not need all elements in the different rows to
have the same number of characters. E.G. if you want to put the date, Jan-10-1991 and
the name, Dow Jones Industrials, in the same character array, you need to add 10 spaces
to Jan-10-1991:
C=[Jan-10-1991

;Dow Jones Industrials];

Structure
Example:
X.data=0.2342
X.date=Jan-10-1991
X.name={Dow Jones Industrials}

Matlab Operators
Operators and special characters.

Arithmetic operators.
plus

- Plus

uplus

- Unary plus

minus

- Minus

uminus

- Unary minus

mtimes

- Matrix multiply

times

- Array multiply

.*

mpower

- Matrix power

power

- Array power

.^

mldivide

- Backslash or left matrix divide

mrdivide

- Slash or right matrix divide

ldivide

- Left array divide

.\

rdivide

- Right array divide

./
4

kron

- Kronecker tensor product

kron

Relational operators.
eq

- Equal

==

ne

- Not equal

~=

lt

- Less than

<

gt

- Greater than

>

le

- Less than or equal

<=

ge

- Greater than or equal

>=

Logical operators.
Short-circuit logical AND

&&

Short-circuit logical OR

||

and

- Element-wise logical AND

&

or

- Element-wise logical OR

not

- Logical NOT

xor

- Logical EXCLUSIVE OR

any

- True if any element of vector is nonzero

all

- True if all elements of vector are nonzero

Special characters.
colon

- Colon

paren

- Parentheses and subscripting

( )

paren

- Brackets

[ ]

paren

- Braces and subscripting

{ }

punct

- Function handle creation

punct

- Decimal point

punct

- Structure field access

punct

- Parent directory

..

punct

- Continuation

...

punct

- Separator

punct

- Semicolon

;
5

punct

- Comment

punct

- Invoke operating system command

punct

- Assignment

punct

- Quote

transpose

- Transpose

ctranspose - Complex conjugate transpose

6
6.1

horzcat

- Horizontal concatenation

[,]

vertcat

- Vertical concatenation

[;]

subsasgn

- Subscripted assignment

( ),{ },.

subsref

- Subscripted reference

( ),{ },.

Entering and Loading Data


Example: Enter a 5 1 vector

>>x=[1;3;4;1;9]

6.2

Example: Enter a 1 5 vector

>>x=[1,3,4,1,9]

6.3

Example: Enter a 4 4 matrix

>>A=[3,2,5,4;2,2,9,1;1,3,0,5;-3,1,9,2]

6.4

Example: Create a 4 1 vector of ones

>>iota=ones(4,1)

Basic Matrix Operations. Examples

7.1

transpose

>> At=A

At =

7.2

-3

Get the diagonal elements of a matrix

>> Ad=diag(A)

Ad =

3
2
0
2

7.3

Inverse

>> Ai=inv(A)

Ai =
0.1989

0.0359

-0.1077

-0.1464

-0.6464

0.5083

0.4751

-0.1492

0.0608

0.0249

-0.0746

0.0525

0.3481

-0.3122

-0.0635

0.1188
7

7.4

Matrix multiplication

>> Ai*A

ans =

1.0000

0.0000

-0.0000

0.0000

0.0000

1.0000

0.0000

-0.0000

-0.0000

1.0000

-0.0000

0.0000

0.0000

1.0000

>> A*iota

ans =

14
14
9
9

>> sum(A,2)

ans =

14
14
9
9

7.5

Determinant of a matrix

>> det_A=det(A)

det_A =

-362

7.6

Loading a data file

7.6.1

Loading a comma-delimited file of numeric values

csvread(<directory path\>file name)


Example: X=csvread(data.csv);
X=csvread(c:\temp\data.csv)

7.6.2

Loading a numeric value file with some delimiter

The delimiter can be a tab, whitespace, comma, some character (e.g. {), etc.
Example: X=dlmread(data.txt,\t)

7.6.3

Reading text from file

Reading a list of names from a file. The output is a cell array:


Example: names=textread(names.txt,%s,delimiter,\n)

Example: dates=textread(dates.txt,%s,delimiter,\n)

7.6.4

Reading mixed data from file

This example works for a limited number of variables as all they need to be specified in the
output:
Example:
[dates,x1,x2,x3,x4]=textread(data1.dat,%s%f%f%f%f% [^\n],...
delimiter,\t,headerlines,1)
names=textread(data1.dat,%s,5,delimiter,\t)

Indexing

If we have a T k matrix, X, we can select subsections of it.


Examples
- All rows, columns 1 through 5
X1=X(:,1:5);
- Rows 3 through 6, all columns after the 8th :
X2=X(3:6,8:end)
- All rows, the last five columns
X3=X(:,end-4:end)
- Rows and columns that are not adjacent, e.g. rows
X4=X([1,4:6,9,12],:)

Loops

Example Sampling 100 samples of 504 samples of data from a multivariate normal an putting
them in a 3-D array
D=zeros(50,4,100);
for i=1:100
D(:,:,i)=mvnrnd(mu,C,50)%mu=4x1 mean vector, C=4x4 covariance matrix
end

10

if clauses

Example
if rand>=0.5
10

disp(Bigger than 0.5)


else
disp(Less than 0.5)
end

11

Saving the workspace or parts of it in a Matlab data


file

You can save the whole workspace with all data types in it in a single file:
Example:
save my_workspace
Example: Save some of the variables in a Matlab data file
save my_workspace X1 X2 dates names

12

Programming in Matlab

There are two main types of Matlab programs: scripts and functions:
scripts do not accept input arguments or return output arguments. They are a collection
of commands written in the way they would be typed in the workspace. They allow the
sequential execution of commands
f unctions can accept input arguments and return output arguments
Example: Creating a script for performing an OLS regression:

11

Operations to program:
= (X0 X)1 X0 y

(1)

e = y X
T
X
e2i
e2 =
T k
i=1

(2)

e2 =

1
(e0 e)
T k

(3)

= e2 (X0 X)1
q
S.E.() =
diag( )

(4)

t-values = ./S.E()
2
2
Radjusted
= 1 e2
y

(6)

DW =

0e e
e0 e

(5)

(7)
et = et et1

(8)

Example: Creating a function for performing an OLS regression. The program contains
the same commands as the script but it begins with the line:
function r=ols(y,x)
where r may be structure containing the output, for example:
r.beta
r.t_values
r.R_sqr
The function is saved as a matlab command file (with extension .m) and has the same
name as the function. In this case: ols.m

12

Example
function r=ols(y,x) %function r=ols(y,x);
%performs OLS regression
%INPUTS:
%y is a Tx1 vector with the dependent variable
%x is a Txk matrix with the independent variables
%OUTPUT: a structure r with fields:
%

b:

sb:

tv:

Ra:

ser:

e:

dw:

[n,k]=size(x);
b=x\y;
e=y-x*b;
s=sum(e.^2)/(n-k);
cb=s*inv(x*x);
sb=sqrt(diag(cb));
tv=b./sb;
Ra=1-(s)/(var(y));
r.b=b;
r.sb=sb;
r.tv=tv;
r.Ra=Ra;
r.ser=s;
r.e=e;
ediff = e(2:n) -e(1:n-1);
r.dw=ediff*ediff/(e*e);
13

13

Creating a program to compute descriptive statistics

The descriptive statistics are computed for a single variable or for a number of variables.
The function to compute these are contained in the statistics toolbox. These are:
mean
std
skewness
kurtosis
min
max
Example
function r=dstats(x)
%function r=dstats(x)
%This function computes descriptive statistics
%INPUTS: a matrix x
%OUTPUTS: a structure r

[T,k]=size(x);
mu=mean(x);
s=std(x);
sem=s/sqrt(T);
kurt=kurtosis(x);
skew=skewness(x);
min_x=min(x);
max_x=max(x);
rng_x=max(x)-min(x);

r.mean=mu
r.standard_deviation=s;
r.st_error_of_mean=sem;
14

r.kurtosis=kurt;
r.skewness=skew;
r.minimum=min_x;
r.maximum=max_x;
r.range=rng_x;

14

Compute the efficient frontier with unconstrained weights

The frontier in this case has an analytical solution. It can be seen in Campbell, Lo, and
MacKinlay (1997, pp.184-185).
Example Efficient set mathematics with unconstrained weights.
function r=eff_set_math(mu,Omega)
mu=mu(:);
n=length(mu);

iota=ones(n,1);
invOmu=inv(Omega)*mu;
invOi=inv(Omega)*iota;

A=iota*invOmu;
B=mu*invOmu;
C=iota*invOi;
D=B*C-A^2;

g=1/D*(B*(invOi)-A*(invOmu));
h=1/D*(C*(invOmu)-A*(invOi));

w_g=1/C*invOi;
mu_g=A/C;
var_g=1/C;

15

%set interval for the frontier


mu_vec=(mu_g:mu_g/4:8*mu_g);
for i=1:length(mu_vec);
w=g+h*mu_vec(i);
w_p(:,i)=w;
s_p(i,1)=w*Omega*w;
end
s_p1=C/D*(mu_vec-A/C).^2+1/C;

r.A=A;
r.B=B;
r.C=C;
r.D=D;
r.mu_g=mu_g;
r.var_g=var_g;
r.w_g=w_g;
r.mu_p=mu_vec;
r.w_p=w_p;
r.h=h;
r.g=g;
r.s_p=s_p;
r.s_p1=s_p1;

16

15

Constrained Optimization Problem

The mathematical setup:


min
w

w0 Cw

(9)

Subject to:
Et [r]0 w =

(10)

w 0

(11)

1w = 1

(12)

where w is the vector of portfolio weights


We use the Matlab optimization program quadprog:
X=QUADPROG(H,f,A,b,Aeq,beq) solves the quadratic programming problem:

min 0.5*x*H*x + f*x

subject to:

A*x <= b

Aeq*x

Example
Data used in the optimization, a data matrix x:
x =
-0.0216
0.0074
0.0097
0.0410
0.0490
0.0526
-0.0020
-0.0013
0.0072
0
0.0048
0.0537

-0.0330
0.0046
0.0086
0.0422
0.0368
0.0570
-0.0075
0.0004
0.0078
0.0021
0.1124
-0.0476

0.3023
0.0045
0.0085
0.0333
0.0366
0.0603
-0.0048
0.0031
0.0127
0.0048
0.0078
0.0581

-0.0306
0.0090
0.0097
0.0377
0.0408
0.0628
-0.0033
0.0051
0.0127
0.0065
0.0079
0.0592

Setting the optimization constraints.


>> A=[-eye(5);eye(5)]

17

-0.0172
-0.0109
0.0260
0.0152
-0.0253
-0.0510
-0.1361
0.0216
-0.1116
-0.0410
0.0491
-0.0392

= beq

A =
-1
0
0
0
0
1
0
0
0
0

0
-1
0
0
0
0
1
0
0
0

0
0
-1
0
0
0
0
1
0
0

0
0
0
-1
0
0
0
0
1
0

0
0
0
0
-1
0
0
0
0
1

>> b=[zeros(5,1);ones(5,1)]
b =
0
0
0
0
0
1
1
1
1
1
>> Aeq=[ones(1,5);mean(x)]
Aeq =
1.0000
0.0167

1.0000
0.0153

1.0000
0.0439

1.0000
0.0181

1.0000
-0.0267

beq =
1.0000
<target portfolio return>
The second row of Aeq is the mean vector, mu_x. We constrain it to be the target portfolio
return, that is, on one point of the frontier. (e.g 0.0244). By changing the values for target
portfolio return, we can trace the efficient frontier. Implementing the optimization function
quadprog, we have:
[w,fval,exflag]=quadprog(var_x,-mu_x,A,b,Aeq,beq)
18

By selecting different target portfolio returns we can trace the frontier.


Example
target_return=
0.0188
0.0216
0.0244
0.0271
0.0299
0.0327
0.0355
0.0383
0.0411
0.0439
for i=1:10
beq(2)=target_return(i);
[wgt(:,i),fval(i),exflag]=quadprog(var_x,-mu_x,A,b,Aeq,beq);
Ret_p(i)=wgt(:,i)*mu_x;
Var_p(i)=wgt(:,i)*var_x*wgt(:,i);
end
plot(Var_p,Ret_p)

16

Computing the efficient frontier using the financial


toolbox

We use the Matlab command frontcon.


Example:
[sig_p, r_p, w_p] = frontcon(mu_x, var_x,10)
plot(sig_p,r_p)

17

Computing the Black-Scholes formula

We need to compute the following elements of the formula:


d1
d2

P
ln X
+ (r + 2 /2)T

=
T
P
p
ln X
+ (r 2 /2)T

=
= d1 (T )
T

Example
19

(13)
(14)

function [call,put]=bs_opt_price(S,X,r,tau,stdev)
%[call,put]=bs_opt_price(S,X,r,stdev,tau)
d1=(log(S/X)+(r+stdev^2/2)*tau)/(stdev*sqrt(tau));
d2=d1-stdev*sqrt(tau);
call=S*normcdf(d1)-X*exp(-r*tau)*normcdf(d2);
put=X*exp(-r*tau)*normcdf(-d2)-S*normcdf(-d1);

18

Computing the Black-Scholes option price using the


financial toolbox

We can use the function blsprice which takes the same arguments as above.
Example:
>> [c, p] = blsprice(68.2978, 98, 0.11, 3, 0.025)
c =
0.4162

p =
2.5729

Compare with:

>> [c1 p1]=bs_opt_price(68.2978,98,0.11,3,0.025)


c1 =
0.4162

p1 =
2.5729

20

19

Computing implied volatility using the Black-Scholes


Formula

Here is a simple example of a function that computes the implied volatility by computing all
possible prices for all candidate volatilities and picking the best one. On the other side, the
finance toolbox function computes implied volatility using optimization which sometimes may
fail to converge. Our simple constructed function is failsafe in this respect:
Example: A function to compute implied volatility

function impv=bs_iv(S,X,r,tau,call_price)
%impv=bs_iv(S,X,r,tau,call_price)
%simple algorithm for computing implied vol
%vector of candicate volatilities:
highest_vol=1;
step=0.0001;
cand_vol=(0:step:highest_vol);
%compute the vector of Black-Scholes prices
cand_prices=blsprice(S,X,r,tau,cand_vol);
abs_diff=abs(cand_prices-call_price);
idx_vol=find(abs_diff==min(abs_diff));
impv=cand_vol(idx_vol);

Example Using the above function:


>> impv=bs_iv(68.2972,98,0.11,3,0.4162)
impv =
0.0250
Alternatively, we can use the function blsimpv from the financial toolbox.
Example
>> impv=blsimpv(68.2972,98,0.11,3,0.4162)
impv =
-1.0947e+154
This is an example in which the toolbox function fails to provide a reliable solution.
21

20

Simulating from a normal distribution

Simulations use the statistics toolbox.


Example Simulating from a standard normal distribution:
x=randn
X=randn(100,10)

The above function is very fast and can be modified to draw from any normal distribution
(multivariate or univariate)
Example Constructing a function to draw from multivariate normal
function y=norm_rand(mu,sig)
%y=N_rand(mu,Sig)
%
mu=mu(:); %make sure that mu is a column vector
h = chol(sig);
[nrow, ncol] = size(sig);
x = randn(nrow,1);
y = h*x+mu;

21

Plotting in Matlab

Example A line plot.


plot(y)
The currently active figure is referred to as gcf if it is assigned no name.
Example Printing the figure in an .eps file:
print(gcf,-depsc,c:\temp\my_figure.eps)

21.1

Modifying the properties of the graph

The properties may be modified using the mouse and the graph editor or you can use the
command line. gca refers to the current axis object
Example Setting graph properties
set(gca,XLim,[0 100],YLim,[0 1],FontSize,8,XTickLabel,dates(1:12:end),...
YGrid,on)

22

L=get(gca,Children)
get(L,type)
set(L(1),Color,[0,1,1],LineWidth,2,LineStyle,:)
set(L(2),Marker,s,MarkerEdgeColor,r,Color,MarkerFaceColor,y,...
MarkerSize,5)

21.2

Histograms and bar graphs

Example Histogram
hist(x)
hist(x,20)
hist(x,40),colormap(cool)
histfit(x,41)
[pc,latent,explained]=pcacov(Cov(X));
bar([explained,cumsum(explained)-explained],stacked);colormap(autumn)

References
Campbell, J., A. Lo, and A.C. MacKinlay, 1997, The Econometrics of Financial Markets.
(Princeton University Press Princeton, NJ).

23

Potrebbero piacerti anche