Matlab Intro For Asset Pricing
Matlab Intro For Asset Pricing
Matlab Intro For Asset Pricing
1 Basic setup
- Command window
- Current directory
o Default: C:\MATLAB7\work
o To change it: drop-down menu or cd 'C:\[...path...]\myfolder'
2 Data Structures
- Simple variables:
o A = 5
o a = 10*3^(5-2)
o Warning: Matlab is case sensitive!!
- Matrix:
o A = [110 120; 210 220]
o To get the values stored in the matrix use subscripts:
A(1,2)
A(1,:)
- Multidimensional arrays, strings, structures (see tutorial)
3 Matrix operators
- Standard rules: A + B , A – B , A * B
- Element-wise operations: A .* B , A ./ B
- Transpose and inverse: A’ , inv(A)
4 Built-in functions
- Ex: exp(5) , log(10)
- Ex: sum(A) , mean(A) , std(A)
- Easy way to create some useful matrices:
o ones(5,1)
o eye(5)
o zeros(3,2)
- Generate random numbers from standard normal distribution:
o randn(5,1)
- The help system is very good – just type the name of what you need to do.
Page 1 of 5
Function:
Write the following in a separate .m file and save it as add2num.m.
function out = add2num(in1,in2)
out = in1 + in2;
6 Toolboxes
- Some come with matlab. Important toolboxes: optimization, statistics.
- Public domain:
o www.mathworks.com has many functions posted by users
o http://www.spatial-econometrics.com/ is a useful toolbox for
econometrics
o Search with Google…
- Functions written in C or Fortran can be compiled and integrated into Matlab
7 Plots
7.1 Simple x-y plot
c = 0.5:0.1:1.5;
u = log(c);
plot(c,u);
% draw density
subplot(2,1,1);
x = (-5:0.01:5)';
y = normpdf(x,0,1);
plot(x,y)
Page 2 of 5
Script:
N = xlsread('datafile.xls');
y = N(:,1);
X = N(:,2:3);
% do a linear regression:
beta = inv(X'*X)*X'*y
10 Programming
10.1 Example: for cycle, if statement
% remove outliers
prices = [23 25 2000 22 21]'
[T ~] = size(prices);
for t = 1:T
if prices(t) > 1000
prices(t) = NaN;
end
end
clear; clc;
% input data
temp = xlsread('10_Industry_Portfolios');
ret = temp(:,2:end)/100;
rf = 0.4/100;
% compute moments
er = (mean(ret))';
V = cov(ret);
Page 3 of 5
figure(1);
plot(varfront.^.5,rfront);
title('Mean-Std Frontier');
ylabel('E[ret]'); xlabel('\sigma(ret)');
T = length(er);
retp = weights'*er;
varp = weights'*V*weights;
Page 4 of 5
The Optimization toolbox has several functions for other optimization problems
(constrained, etc)
10.4 Debugger
Matlab has an excellent debugger. If your code has an error or is not giving the expected
result, using the debugger is the best way to fix the code.
1. In the Editor, click the “-“ next to the line number(s) you want to audit. A red dot
will appear.
2. Run the code (F5)
3. Matlab will pause on the line you marked and allow you to see all the current
variables.
4. Click on the buttons or press F5 to continue to the next lines.
Page 5 of 5