Documente Academic
Documente Profesional
Documente Cultură
Introduction to MATLAB
Spring 2012 21996 Axel Kind
WW Z
(I)
Matrix-based calculations (MATLAB = MATrix LABoratory) Graphical output Symbolic mathematics (but Mathematica is likely superior to MATLAB) less complicated than C, C++, Fortran, or C# but still quite fast
WW Z
(II)
No need to perform low-level administrative tasks (declaring variables, specifying data types, and allocating memory) MATLAB code can often replace several lines of C or C++ code MATLAB is an standard for prototyping (development of trading strategies, pricing tools, academic work) MATLAB uses a Just-in-Time (JIT) compiler (code is converted at runtime). Blocks of code will not be processed line-by-line as with an interpreter and not as with conventional (Ahead-of-Time) compilers before the execution of the program. Provides all features of a traditional programming language [e.g. objectoriented programming (OOP), debugging] MATLAB Compiler enables the use of MATLAB applications outside the MATLAB environment (.NET components , Excel add-ins)
WW Z
WW Z
Software Tools
WW Z
2) File/Set Path
4) Workspace
WW Z
WW Z
WW Z
WW Z
WW Z
10
WW Z
11
WW Z
Exercise I
What do you expect MATLAB to do after copying the following commands in the command window and press the return button? Command 1: % firstVariable = 1; Command 2: secondVariable = 2; Command 3: thirdVariable = 3 Command 4: 4thVariable = 4 Command 5: variable5 = 5; variable5a = 5.1; Command 6: variable6 = 6, variable5a = 6.1; Command 7: v7 = 7; Command 8: v8 ... = 8;
WW Z
13
WW Z
14
Exercise II
Create a variable called MRP (for Market Risk Premium) and assign it a value of 0.05 without displaying the result on the screen.
Create, by using only one line of code, the following two variables (without displaying the result on the screen): 1. a variable called betaA (for the beta of stock A) with a value of 1.2, 2. a variable called rF (for risk-free rate) with a value of 0.03.
Calculate the expected return of stock A according to the CAPM model and store the result in a variable called ERA by letting it display on the screen.
WW Z
15
Exercise II (Continued)
Clear the variable ERA and check that it disappears from the workspace.
Clear all variables and check that they disappear from the workspace.
WW Z
16
Accessing i-th element: x(i) Accessing the last element: x(end) Deleting the i-th element: x(i) = [ ]
: n
WW Z
17
WW Z
18
WW Z
19
Content
1 4 7 2 5 8 3 6 9
1 2 3
4 5 6
7 8 9
1 4 7
2 5 8
3 6 9
Example: X(3,2) and X(6) refer to the same cell of the matrix with a value of 8
WW Z
Quantitative Security Analysis Axel Kind 20
WW Z
21
Exercise III
Consider the vector of stock prices generated by the code below [Assumptions: log-returns of stocks follow an arithm. Brownian motion, r(t) = a*t + sigma*W(t), 261 daily stock prices; initial stock price of 100, drift of 0.1, and volatility of 40%]. % input parameters mu = 0.1; %drift sigma = 0.5; %volatility dt = 1/260; %(daily) time step % calculations dailyReturnV = (mu - 0.5*sigma^2)*dt + sigma*sqrt(dt)*randn(260,1); dailyPriceV = [100; 100*exp(cumsum(dailyReturnV))]; plot(dailyPriceV)
WW Z
22
Extract from dailyReturnV the five lowest returns and store them in a variable called lowestRet. [Hint: look up how the built-in function sort works by using help in the command window]
WW Z
23
Calling functions
output_variable = function_name(input_variable) [output1, output2] = function_name(input1, input2, input3)
Built-in functions
e.g. sqrt(x), exp(x), log(x), abs(x), ceil(x), floor(x), sum(x), min(x), max(x), mean(x), geomean(x), std(x), var(x), repmat(x,m,n), inv(x)
WW Z
24
Exercise IV
Consider the following end-of-month prices of a stock that you are considering to purchase (Jan-Dec): 100, 110, 120, 80, 75, 90, 110, 120, 120, 150, 145, 140. Store those values in a column vector named priceV.
WW Z
25
Exercise IV (Continued)
Calculate the geometric mean of simple returns and store it in retSimpleBar.
Calculate the annualized standard deviation of both simple and logarithmic returns and store them in sigmaSimpleRet and sigmaLogRet.
WW Z
26
WW Z
27
Exercise V
Create a MATLAB function called ExpectedReturnCAPM that calculates the expected returns of a vector of stocks (ERV) based on the risk-free interest rate (rF), equity betas (betaV), and the market risk premium (MRP).
WW Z
29
Exercise V (Continued)
Show the description of the function by calling it from the command window.
Use the previous function to calculate expected returns of five stocks with betas of 0.5, 0.8, 1.0, 1.2, and 1.8. Assume that the risk-free interest rate is 0.03 and the market risk premium is 0.05. Store the results in a variable called ERStockV.
Can you use the same function to calculate expected returns using different risk-free rates and different market risk premiums?
WW Z
30
Write formatted data to command window: fprintf(format, A, ...) x=rand(1); fprintf('The random number is %1.4f.\n',x);
This prints The random number is 0.0975. to the command window. Write formatted data to string: sprintf(format, A, ...) x=rand(1); strX=sprintf('The random number is %1.4f.\n',x); strX
WW Z
31
WW Z
32
WW Z
33
WW Z
34
WW Z
35
WW Z
36
Exercise VI
Consider the following vectors with ten years of weekly returns of the market portfolio (retM) and stock A (retA): % input parameters rf = 0.03; % risk-free rate MRP = 0.1; % market risk premium sigmaM = 0.2; % volatility dt = 1/52; % (weekly) time step nRet = 10*52; % number of simulated monthly returns sigmaA = 0.15; % idiosyncratic volatility betaA = 1.8; % CAPM beta of stock A % calculations retM = (rf+MRP- 0.5*sigmaM^2)*dt + sigmaM*sqrt(dt)*randn(nRet,1); retA = rf*dt + betaA*(retM-rf*dt) + sigmaA*sqrt(dt)*randn(nRet,1);
WW Z
Quantitative Security Analysis Axel Kind 37
Exercise VI (Continued)
Plot the returns retA as a blue line and returns retM as a red line in the same figure.
WW Z
38
Exercise VI (Continued)
Plot returns of stock A against market returns by using blue dots.
Label axes and add Return Plot Stock A as a title to the figure.
WW Z
39
Exercise VI (Continued)
Add a regression line to the figure.
Save the figure as a .jpg file with name GreatPlot to your hard drive.
WW Z
40
WW Z
41
WW Z
42
WW Z
43
WW Z
44
WW Z
45
WW Z
46
WW Z
47
WW Z
48
WW Z
49
WW Z
50
Not-So-Key Concepts
(I)
Benchmark the performance of your computer: bench Calculate the execution time of MATLAB tasks: tic; toc, toc, toc Produce a warning sound: beep Generate a warning message: warning(Warning but the execution of the code will not be stopped!') Generate an error message: error(Error! The execution of the code will be stopped!') Set display format for output: format type (default type: short; other types: long, short e, long e, short g, bank, format short; pi ans = 3.1416 format bank; pi ans = 3.14 format long; pi ans = 3.14159265358979 To get the current format: get(0,'Format') Hyperlink in function description: <a href="matlab:help normcdf">normcdf</a>
WW Z
51
WW Z
52
Not-So-Key Concepts
Optional output parameters in a function: nargout
(III)
function [meanValue, standardDeviation] = MeanStandardDeviation(matrix) %MeanVar calculates the mean and the standard deviation of a matrix n = size(matrix,1); meanValue = mean(matrix); if nargout > 1 standardDeviation = std(matrix); end
WW Z
53
Not-So-Key Concepts
(IV)
Avoid stopping the code when executing an wrong command: try; possibly wrong command catch; alternative command end
Example: matrix1 = [1 2;3 4]; matrix2 = [1 3 4]; try multMatrix = matrix1*matrix2; catch multMatrix = 'Matrix cannot be multiplied.' end
WW Z
54
Not-So-Key Concepts
SENDMAIL(TO,SUBJECT,MESSAGE,ATTACHMENTS)
% Define these variables appropriately: mail = 'axel.kind@unibas.ch'; %Your unibas email address password = '123456'; %Your unibas password % Then this code will set up the preferences properly: setpref('Internet','E_mail',mail); setpref('Internet','SMTP_Server','smtp.unibas.ch'); setpref('Internet','SMTP_Username',mail); setpref('Internet','SMTP_Password',password); props = java.lang.System.getProperties; props.setProperty('mail.smtp.auth','true'); props.setProperty('mail.smtp.socketFactory.class', 'javax.net.ssl.SSLSocketFactory'); props.setProperty('mail.smtp.socketFactory.port','465'); % Send the email sendmail('axel.kind@unibas.ch','Test from MATLAB', ... 'Hello! This is a test from MATLAB!', ... 'H:\teaching_academics\quantitative_security_analysis\matlab_tutorials.m')
WW Z
Quantitative Security Analysis Axel Kind 55
WW Z
56
WW Z
57
Editor
For creating script and function m-files Scripts are the simplest m-files because they have no input and output arguments. Scripts are useful for automating repetitive tasks. Functions are program routines that accept input arguments and return output arguments Functionalities: Blue coloring of MATLAB syntax variables (if, for, while, end, switch ), green coloring of comments, and purple coloring of strings Automatically indents part of the code Indicates possible code errors and potential improvements while writing code Debugging Run m-file with F5 Line-by-line debugging with F11 Cell mode (%%): Execute code cell-by-cell Run highlighted code with F9 Profiler (Tools Open Profiler): Profile execution time for option
Quantitative Security Analysis Axel Kind 58
WW Z
Editor - Debugging
WW Z
59
Rules of thumb when programming and working with MATLAB: 1) Use matrix operations whenever possible, 2) Avoid loops (but not as much as before MATLAB 6.5 ), 3) Avoid matrix expansions (if known, initialize matrices according to their size) 4) Use built-in functions when available, 5) Create functions instead of huge files (modular programming), 6) Add line-by-line comments and descriptions, 7) Do not try to be smart
WW Z
60
WW Z
61
WW Z
WW Z
WW Z
66
WW Z
67
WW Z
WW Z
69