Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
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
3.1
What is Matlab?
3.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.
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
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
mrdivide
ldivide
.\
rdivide
./
4
kron
kron
Relational operators.
eq
- Equal
==
ne
- Not equal
~=
lt
- Less than
<
gt
- Greater than
>
le
<=
ge
>=
Logical operators.
Short-circuit logical AND
&&
Short-circuit logical OR
||
and
&
or
- Element-wise logical OR
not
- Logical NOT
xor
- Logical EXCLUSIVE OR
any
all
Special characters.
colon
- Colon
paren
( )
paren
- Brackets
[ ]
paren
{ }
punct
punct
- Decimal point
punct
punct
- Parent directory
..
punct
- Continuation
...
punct
- Separator
punct
- Semicolon
;
5
punct
- Comment
punct
punct
- Assignment
punct
- Quote
transpose
- Transpose
6
6.1
horzcat
- Horizontal concatenation
[,]
vertcat
- Vertical concatenation
[;]
subsasgn
- Subscripted assignment
( ),{ },.
subsref
- Subscripted reference
( ),{ },.
>>x=[1;3;4;1;9]
6.2
>>x=[1,3,4,1,9]
6.3
>>A=[3,2,5,4;2,2,9,1;1,3,0,5;-3,1,9,2]
6.4
>>iota=ones(4,1)
7.1
transpose
>> At=A
At =
7.2
-3
>> 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
7.6.1
7.6.2
The delimiter can be a tab, whitespace, comma, some character (e.g. {), etc.
Example: X=dlmread(data.txt,\t)
7.6.3
Example: dates=textread(dates.txt,%s,delimiter,\n)
7.6.4
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
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
11
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
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
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
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
w0 Cw
(9)
Subject to:
Et [r]0 w =
(10)
w 0
(11)
1w = 1
(12)
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
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
16
17
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
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:
p1 =
2.5729
20
19
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);
20
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
21.1
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
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