Application of Matlab for Finance
Week 2
Shi, Yining
September 13, 2016
Shi, Yining Application of Matlab for Finance Week 2
Today’s Class
I Input and Output, Reading from and Writing data into Excel
I Logical Expressions and Operators
I Flow control
I Loop structure
I User-defined functions
Shi, Yining Application of Matlab for Finance Week 2
Input/Output
I xlsread(.) xlswrite(.)
I csvread(.) csvwrite(.)
I readtable(.) writetable(.)
I save(.) load(.)
Shi, Yining Application of Matlab for Finance Week 2
xlsread(.)
I num = xlsread(filename) reads numeric data from the first
sheet of Excel file named filename, and store the data into a
matrix called num
I num = xlsread(filename, sheet) reads the specified worksheet
I num = xlsread(filename, sheet, range) reads the specified
worksheet and range
I filename, sheet and range are strings enclosed in single quotes:
data = xlsread('Stock.xls','Price', 'A1:B100')
I xlsread(.) ignores any outer rows or columns of the spreadsheet
that contain no numeric data. Also any nonnumeric cells are
assigned as NaN (Not-a-Number element).
I [num,txt,raw] = xlsread(.) store the entire worksheet in raw,
all numerical data in num and text data in txt
Shi, Yining Application of Matlab for Finance Week 2
xlswrite(.)
I xlswrite(filename, M) writes matrix M to the first worksheet in the
Excel file filename
I xlswrite(filename, M, sheet) writes matrix M to the specified
worksheet sheet in the Excel file filename
I xlswrite(filename, M, sheet, range) writes matrix M to a
rectangular region specified by range
I filename, sheet and range are strings enclosed in single quotes
I Eg. xlswrite ('MyOutput.xls',Returns,'SP500','A1:A50')
Shi, Yining Application of Matlab for Finance Week 2
csvread(.)
I M = csvread(filename) reads a comma-separated value formatted file
from filename and stored the data in M.
he file can only contain numeric values.
I M = csvread(filename, R1, C1); reads data from file starting the
specific row R1 and column C1. The R1 and C1 arguments are zero based, so
that R1=0 and C1=0 specify the first value in the file (Cell ’A1’).
I Hint: row (col) = actual file row (column) number -1
I M = csvread(filename, R1, C1, [R1 C1 R2 C2]); reads only
the range specified.
I Eg. M = csvread('data.csv',0,0,[0,0,6,1]) reads data in range
of ’A1’ to ’B7’ from file data.csv
Shi, Yining Application of Matlab for Finance Week 2
csvwrite(.)
I csvwrite(filename,M); writes matrix M into .csv file filename,
which is a string enclosed in single quotes.
I csvwrite(filename, M,R1,C1) writes matrix M into the
specified row R1 and column C1 offset. Note R1=0 and C1=0 specify
the first value in the file.
I Note1: xlsread and xlswrite may not work with the Mac/Linux system.
Suggestion: save .xls file as .csv → Use csvread().
I Note2: csvread() and csvwrite only work with numeric values, and won’t
not work for csv files with a mix of text and numeric values. Mac users please
use the readtable() with a ‘mcodeFormat‘ parameter to specify the data
types for each columns.
Shi, Yining Application of Matlab for Finance Week 2
readtable and writetable
I T = readtable(filename, 'Format', format_specs) create
a table T from column-oriented data such .csv, .txt or .dat.
I myTable = readtable('Price.xls','Format', '%D%s%f%d')
I myTable is output table and 'Price.xls' is the data file
I 'Format' is a option name argument indicating the following
argument is the format specification
I '%D%s%f%d' is the specification value of ’Format’. '%' stands a
column. There are 4 columns in our data file.
I 1st column has datetime object ('%D'), the 2nd column is string
('%s'), the 3rd one is floating number('%f') while the last one
contains decimal integers ('%d').
I writetable(your_table, filename) saves the Matlab table to
an external data file.
Shi, Yining Application of Matlab for Finance Week 2
save and load
I save('my_dataset.mat', var1, var2, ..) saves a selected
number of variables (var1, var2, ...) in the current workspace to the
matfile named 'my_dataset.mat'.
I load('my_dataset.mat', var1, var2, ..) loads variables
(var1, var2, ...) from datafile 'my_dataset.mat' into the current
workspace.
I matfile is Matlab’s proprietary data structure and it is designed to
work with Matlab only. Other programming language may have
difficulties to read data from matfile, so the portability of matfile is
quite limited.
Shi, Yining Application of Matlab for Finance Week 2
Exercises 1
I Download the file
stock.xls from HUB. Read the data into MATLAB using
the xlsread() function in a matrix called data.
I Store the first column of data in a variable called stock_price_1 and the
second column of data in a variable called stock_price_2.
I Compute log returns of each stock by using rt = log (pt ) − log (pt−1 )
(Hint: use the diff(.) and log(.) functions)
I Write the returns into a news excel file called Returns.xls with two new
sheets named returns_1 and returns_2 respectively.
I Read Stock.csv using csvread() function. Perform the same processing
as above. With new sheet named Returns.csv
Shi, Yining Application of Matlab for Finance Week 2
Exercises 1
1 data = xlsread('Stock.xls', 'Stock');
2
3 stock_price_1 = data(:,1);
4 stock_price_2 = data(:,2);
5
6 % calculate return
7 stock_return_1 = diff(log(stock_price_1));
8 stock_return_2 = diff(log(stock_price_2));
9
10 xlswrite('Returns.xls', stock_return_1, 'return_1');
11 xlswrite('Returns.xls', stock_return_2, 'return_2');
Shi, Yining Application of Matlab for Finance Week 2
Exercises 2
I Read AAPL.csv using readtable() function into table name aapl
I The data type of each column in AAPL.csv are Datetime, float, float, float,
float, integer, float. So the format specification is '%D%f%f%f%d%f'
I Calculate log return of AAPL by using its adjusted close price.
I Note: Use the dot notation to extract data from the table aapl.AdjClose
to read the adjusted close price from the aapl table
I Store the return into the aapl table under column name Return (Ensure the
size of returns matches with length of the table)
I Save the updated table to a new csv file named output_AAPL.csv.
I Save the table as AAPL.mat matfile. Clear the current workspace, and then
load the dataset back to our workspace using load().
Shi, Yining Application of Matlab for Finance Week 2
Exercises 2
1 aapl = readtable('AAPL.csv', 'Format', '%D%f%f%f%f%d%f');
2 aapl_ret = diff(log(aapl.AdjClose));
3
4 % match the return length with the table
5 returns = [0; aapl_ret];
6 aapl.Return = returns;
7 writetable(aapl, 'output_AAPL.csv');
8
9 % save and load
10 save('AAPL.mat','aapl')
11 clear all
12 load('AAPL.mat')
Shi, Yining Application of Matlab for Finance Week 2
Logical Expressions
I A logical expression tests a conditional statement among arguments
by using relational operator or logical functions
I There are six basic relational operators:
I less than: <
I less than or equal to: <=
I greater than: >
I greater than or equal to: >=
I equal to: ==
I not equal to: ∼=
I Logical function: isempty, isnan, all(.), any(.) etc
I Logical expressions have only two possible outcomes:
I TRUE with value of 1
I FALSE with value of 0
Shi, Yining Application of Matlab for Finance Week 2
Logical Operators
The logical operators operate between simple expressions in order to
create compound expressions.
I Logical AND (&): returns logical 1 (true) if both inputs evaluate to
true, and logical 0 (false) if they do not.
I Logical OR (|): returns logical 1 (true) if either input, or both,
evaluate to true, and logical 0 (false) if they do not.
I Logical NOT (∼): return s logical 1 (true) if the single input
evaluates to false, and logical 0 (false) if it evaluates to true
Shi, Yining Application of Matlab for Finance Week 2
Logical Indexing
I A = 1 −5 5 2 and set B = A > 2
I B = 0 0 1 0 is a matrix of logical expressions corresponding
to the operation for each element of A.
I A(B) = 10, which indexes the matrix A with the logical matrix B,
returning a vector of elements where A > 2.
I find(.) performs similar function but return directly the element
index of matrix A that satisfied the logical expression
I find(A>2) returns index value 3, A(find(A>2))=10
Shi, Yining Application of Matlab for Finance Week 2
Flow Control
I The results of logical operation are often used for decision making
under flow controls
I Eg. if A > B, perform operation 1; otherwise, perform operation 2
I Main flow control structures:
I if
I switch
Shi, Yining Application of Matlab for Finance Week 2
If structure
I The if structure evaluates a logical expression and executes a group
of statements based on the value of the expression.
1 if logical_expression
2 statements
3 end
4
5 x = -5;
6 if x < 0
7 disp('Warning: x is negative');
8 end
I If the logical expression is TRUE, then all the statements between
the if and end lines are EXECUTED.
I If the logical expression is FALSE, then all the statements between
the if and end lines are SKIPPED.
Shi, Yining Application of Matlab for Finance Week 2
else and elseif
I if..else ⇒ There is no logical expression behind else. The statements
associated with else are executed only if the preceding logical expression
behind if is false
I if..elseif ⇒ There is a logical expression behind the elseif, and will be
executed if the preceding logical expression behind if is false.
I You can have multiple elseif statements within an if block, but only one
else statement.
1 if logical_expression1
2 statement1
3 elseif logical_expression2
4 statement2
5 else
6 statement3
7 end
Shi, Yining Application of Matlab for Finance Week 2
else and elseif examples
1 F = 50;
2 if F < 100
3 b = 3.5;
4 else
5 b = 6;
6 end
1 F = 150;
2 if F < 100
3 b = 3.5;
4 elseif 100 < F < 200
5 b = 6;
6 else
7 error('Applied load exceeds 200 maximum.');
8 end
Shi, Yining Application of Matlab for Finance Week 2
Switch structure
The switch structure executes certain statements based on the value of
the expression
expression requires input from users
1 switch expression % expression is scalar/string
2 case value1
3 statement1
4 case value2
5 statement2
6 ...
7 case value10
8 statement10
9
10 % executes if expression does not match any case
11 otherwise
12 default_statement
13 end
Shi, Yining Application of Matlab for Finance Week 2
Switch structure
I input(.): ask the user via a message that is printed in the command window
('Enter a number') to input a value
I The value of input by the user is assigned to variable mynumber
1 mynumber = input('Enter a number:');
2
3 switch mynumber
4 case -1
5 disp('negative one');
6 case 0
7 disp('zero');
8 case 1
9 disp('positive one');
10 otherwise
11 disp('other value');
12 end
Shi, Yining Application of Matlab for Finance Week 2
Display Results
disp(.) prints in the command window
I a variable or matrix disp(X)
I a text message disp('Hello World')
I a combination of text and numbers
disp(['X=',num2str(X), 'Y=',num2str(Y)])
[] used the combination case
I
num2str(.) converts numbers to strings in order to transform each
I
variable into a text string.
fprintf('X is %4.2f. \n Y is %.2f. \n',X,Y)
I %4.2f is formatSpec input specifies that the first value (X) in each line of
output is a floating-point number with four digits, including two digits after the
decimal point
I %.2f is formatSpec input specifies that the second value (Y) in each line of
output is a floating-point number with two decimal point
I \n is a control character that starts a new line.
Shi, Yining Application of Matlab for Finance Week 2
Loop structure
I Loops are used to repeat sequences of calculations.
I Main loop structure:
I for
I while
Shi, Yining Application of Matlab for Finance Week 2
The for loop
I The for loop structure executes repeatedly a statement or group of statements
for a predetermined number of times.
I The loop counter variable index is
I initialized to value start val at the start of the first pass through
the loop,
I automatically increments by increment each time through the
loop.
I The program makes repeated passes through statements until index has
incremented to the value end val when the loop is terminated.
1 for index = start_val:increment:end_val
2 statements
3 end
Shi, Yining Application of Matlab for Finance Week 2
The for loop
I Simplest form: utitary increment for the loop control (increment=1)
1 for index = start_val:end_val
2 statements
3 end
I Nested multiple for loops. Be sure to end every loop with a matching end
statement.
1 A = zeros(5,100);
2
3 for m = 1:5
4 for n = 1:100
5 A(m,n) = m + n;
6 end
7 end
Shi, Yining Application of Matlab for Finance Week 2
The while loop
The while loop structure executes a statement or group of statements
repeatedly, as long as the controlling logical expression is true (that is, if
it evaluates to logical 1).
Example:
1 while logical_expression
2 statements
3 end
4
5 i = 0;
6 while (i < 10)
7 i = i + 1;
8 disp(i)
9 end
Shi, Yining Application of Matlab for Finance Week 2
Exercises
(3.1) Create a simple if structure that returns the absolute value of a variable X.
(use input(.) abs(.))
(3.2) Extend the if structure with a variable control. Perform the calculation as
(i) the absolute value, (ii) the square, (iii) the square root, in case it is positive,
of variable X, when control = 1,2, or 3 respectively. Store the output in variable
result
(3.3) Perform the same tasks as in exercise 2 and 3 with the use of a switch
structure.
(3.4) Create a 1-by-8 row vector of zeros and set each element equal to the product
(row number)*(column number), with the use of a for loop.
(3.5) Extend exercise 5 to a 6-by-7 matrix. Notice that you need two for loops.
(3.6) Use a while loop to count the number of uniformly distributed realizations
(use the rand(.)) between 0 and 1 that it takes to add up to 20 (or more).
Shi, Yining Application of Matlab for Finance Week 2
Exercises 3.1
1 x = input('Please enter a number: ');
2
3 if (x ≥ 0)
4 res = x; % in case that x is non-negative, return ...
itself
5 else
6 res = -x; % in case that x is negative, return its ...
negated value
7 end
8 % display results: display
9 display (['Input = ', num2str(x)])
10 display (['Result = ', num2str(res)])
11
12 % display results: fprintf
13 fprintf('Input value is %.2f.\nResult is %.2f.\n', x, res)
Shi, Yining Application of Matlab for Finance Week 2
Exercises 3.2
1 control = input('Please specify the control variable.\n ...
1 for abs, 2 for squared, 3 forsquare root: ');
2 x = input('Please enter a number: ');
3 if (control == 1)
4 res = abs(x);
5 elseif (control == 2)
6 res = x * x;
7 elseif (control == 3)
8 if (x > 0)
9 res = sqrt(x);
10 else
11 error('Negative number has no squared root.')
12 end
13 else
14 error('Invalid control variable.\n')
15 end
16 fprintf('Input value is %.2f.\nResult is %.2f.\n', x, res)
Shi, Yining Application of Matlab for Finance Week 2
Exercises 3.3
1 control = input('Please specify the control variable.\n ...
1 for abs, 2 for squared, 3 forsquare root: ');
2 x = input('Please enter a number: ');
3 switch control
4 case 1
5 res = abs(x);
6 case 2
7 res = x * x;
8 case 3
9 if (x > 0)
10 res = sqrt(x);
11 else
12 error('Negative number has no squared root.')
13 end
14 otherwise
15 fprintf('Invalid control variable.\n')
16 x = 0;
17 res = 0;
18 end
Shi, Yining Application of Matlab for Finance Week 2
Exercises 3.4 & 3.5
1 x = zeros(1,8); disp(x)
2 cols = size(x,2); % read the col num of x
3 for j = 1:cols
4 x(1, j) = 1 * j;
5 end
6 disp(x)
1 x = zeros(6,7); disp(x)
2 [rows, cols] = size(x);
3 for i = 1:rows
4 for j = 1:cols
5 x(i, j) = i * j;
6 end
7 end
8 disp(x)
Shi, Yining Application of Matlab for Finance Week 2
Exercises 3.6
1 my_sum = 0.0;
2
3
4 while (my_sum < 20)
5 temp = rand(1);
6 my_sum = my_sum +temp;
7
8 end
9
10
11 disp(my_sum)
Shi, Yining Application of Matlab for Finance Week 2
User-defined functions
1 function [ out1, out2] = my_func( in1, in2 )
2 % function body, do some stuff here
3 end
I An separate .m file starts with function to declare its a function file defines a
user-defined function.
I [out1, out2] is the declared output of the function
I my_func is the name of the function, so as the name of the .m file
I in1, in2 is the required input the function
I The function body performs calculations and produces output for the user
I The function needs to be located in the current working dictionary to be called.
Shi, Yining Application of Matlab for Finance Week 2
Exercises 4
(4.1) Create a function called myabs(.) that returns the absolute value of the
argument. To get |n|, you can also use MATLAB’s predefined function abs(n).
(4.2) Create a function called myfact(.) that returns the factorial of an integer
value. Remember that 0! = 1. To get n!, MATLAB’s predefined function
prod(1:n) or even the simpler factorial(n) do perform the same task.
(4.3) Create a function called stats(.) that returns the maximum, the minimum
and the average of a vector of numbers. Create two different implementations;
one that returns the three values as individual numbers and one that returns the
three values in a single vector.
Shi, Yining Application of Matlab for Finance Week 2
Exercises 4.1
Function
1 function [ res ] = myabs( X )
2 % this function computes the absolute value of a real ...
variable X
3 % input: any real number (scalar)
4 % output: the absolute value of input variable
5 if (X ≥ 0)
6 res = X; % in case that X is non-negative, return ...
itself
7 else
8 res = -X; % in case that X is negative, return its ...
negated value
9 end
10 end
Main Command
1 myabs(-10)
Shi, Yining Application of Matlab for Finance Week 2
Exercises 4.2
Function
1 function [ res ] = myfact( n )
2
3 res = prod(1:n);
4
5 end
Main Command
1 myfact(10)
Shi, Yining Application of Matlab for Finance Week 2
Exercises 4.3
Function
1 function [max_val, min_val, avg_val ] = stats_1( vec )
2 max_val = max(vec);
3 min_val = min(vec);
4 avg_val = mean(vec);
5 end
1 function [ res ] = stats_2( vec )
2 res = [max(vec), min(vec), mean(vec)];
3 end
Main Command
1 x = [1,2,3,4,5];
2 [a, b, c] = stats_1(x)
3 res = stats_2(x)
Shi, Yining Application of Matlab for Finance Week 2