Anda di halaman 1dari 69

Quantitative Security Analysis - Part I -

Introduction to MATLAB
Spring 2012 21996 Axel Kind

WW Z

What MATLAB is Good in


Numeric computations (also simulations)

(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

Quantitative Security Analysis Axel Kind

What MATLAB is Good in


(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

Quantitative Security Analysis Axel Kind

What MATLAB is NOT (!) so Good in


Limited already implemented econometric tools and packages (J. LeSage toolbox is an exception: http://www.spatial-econometrics.com) Matlab is not database-oriented (as SAS or Stata) => Data manipulation, such as merging databases can be costly (programming time and running time) Not suitable for very large data sets (SAS might be a better alternative) Not an industry standard for high performing financial applications (trading floors)

WW Z

Quantitative Security Analysis Axel Kind

Software Tools

Statistical Software EViews Minitab OxMetrics SAS SPSS Stata XploRe

Programming Language C C++ C# Fortran Java VBA VB.NET Python

Scientific Software R GAUSS Mathematica Maple Mathcad MATLAB SciLab

WW Z

Quantitative Security Analysis Axel Kind

Getting Started: Launch MATLAB


1) Path of current directory 3) Command Window

2) File/Set Path

4) Workspace

WW Z

Quantitative Security Analysis Axel Kind

Getting Started: MATLAB Material and Resources


Books:
Finanzderivate mit MATLAB by Michael Gnther and Ansgar Jngel Numerical Methods in Finance and Economics - A MATLAB-based Introduction by Paolo Brandimarte

A huge number of tutorials on the internet:


Official MATLAB manuals (www.mathworks.org) Google expressions like: matlab tutorial, matlab manual,matlab tutorial pdf, introduction to matlab pdf, etc. http://www.mathematik.uni-kassel.de/~birken/matlab.pdf, http://www.maths.dundee.ac.uk/~ftp/na-reports/MatlabNotes.pdf, Paul Soederlind's homepage: http://home.tiscalinet.ch/paulsoderlind/, Kevin Sheppard's homepage: http://www.kevinsheppard.com/wiki/MFE_MATLAB_Introduction [with video demonstrations]

WW Z

Quantitative Security Analysis Axel Kind

MATLAB and Octave


Octave is an open-source clone of MATLAB which is freely downloadable from www.octave.org For a free online trial of Octave (almost the same syntax as MATLAB) go to the following internet address: http://lavica.fesb.hr/octave/octave-on-line_en.php
MATLAB Product Editor Functionality Activation costs: Commercial Own user-friendly editor Wide range of functions CHF 2000+, Students: CHF 100 Octave Free, General Public Licence (GPL) External editor Ca. 95% functionality of MATLAB CHF 0 + your time

WW Z

Quantitative Security Analysis Axel Kind

Getting Started: How to Work with MATLAB


There are three ways to work with MATLAB. You can 1) type the commands directly in the command window, or 2) collect all the commands in MATLAB scripts/programs (a sequence of MATLAB commands stored as .m file) This file is easily created in the MATLAB editor and launched by writing the name of the .m file in the command window (without extension .m) or printing F5. 3) Complementary to that, you will use MATLAB functions and write your own functions (routines with specified inputs and outputs and local variables)

WW Z

Quantitative Security Analysis Axel Kind

Key Concepts: Basic MATLAB Rules


Ctrl + c stops the execution of a command/command sequence. MATLAB displays the result of (almost) any command, unless the command ends with a ; (semi-colon). MATLAB executes commands line-by-line. Therefore, each line must contain one or more complete commands, separated by , (display) or ; (no display). One command cannot be written on several lines, unless (three dots) are set at the end of a line to tell MATLAB that the command continues on the next line. Lines starting with % will not be executed and can be used to comment the code.

WW Z

Quantitative Security Analysis Axel Kind

10

Key Concepts: Variables in MATLAB (I)


Every variable has a name Example of valid variable names: you, var_vec, Big, BigApple, BA3 Variable names are case sensitive: var1 Var1 Variable names must start with a letter: 3Var is not a valid name Variable names may contain (lower-case or capital) letters and numbers, but no spaces or special signs (max of 63 characters) Avoid variable names that can be confused with names of functions: mean is a bad variable name (although it is allowed) Use and stick to a name convention: my_variable or myVariable (camel case or medial capitals) Use variable names that are related to the content of the variable, i.e. they should be self-explaining: call_option_value or CallOptionValue

WW Z

Quantitative Security Analysis Axel Kind

11

Key Concepts: Variables in MATLAB (II)


Every variable has a content Different value types: numbers (1.1, 3, 3.14) or characters (a, b, c) Different dimensions: scalar, vector (one-dimensional array), matrix (twodimensional array), tensor (three-dimensional array), etc. In MATLAB variable definitions and variable initiations coincide: A = 2.3 defines a variable A that is of type number and dimension scalar and initiates it with the value of 2.3. B = 'cipollino' defines a variable B that is of type character and dimension 1x9. Clear variables: clear A clear A B clear all
Quantitative Security Analysis Axel Kind 12

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

Quantitative Security Analysis Axel Kind

13

Key Concepts: Workspace


Shows stored variables and their properties Double clicking a variable opens the Variable Editor. It displays the content of the variable, and where data can be manipulated

WW Z

Quantitative Security Analysis Axel Kind

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

Quantitative Security Analysis Axel Kind

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

Quantitative Security Analysis Axel Kind

16

Key Concepts: Vectors


When initiating a vector (one-dimensional array), the content is included in square brackets [ ] Row vectors: x = [1, 2, 3] or x = [1 2 3] Column vectors: y = [4; 5; 6] or y = transpose([4 5 6]) or y = [4 5 6]' Indexing of vectors: 1 2 n
1 2

Accessing i-th element: x(i) Accessing the last element: x(end) Deleting the i-th element: x(i) = [ ]

: n

WW Z

Quantitative Security Analysis Axel Kind

17

Key Concepts: Operations with Vectors


Multiplication of two vectors: A*B Either inner product (dimensions must agree!) or outer product Element-wise multiplication: A.*B (dimensions must agree!) Summation of two vectors: A + B (dimensions must agree!) A + a (where a is a constant) is allowed (unlike in mathematics) Subtraction of two vectors: A - B (dimensions must agree!) A - a (where a is a constant) is also allowed

WW Z

Quantitative Security Analysis Axel Kind

18

Key Concepts: Matrices


Creation of a matrix from data: X = [1 2 3; 4 5 6; 7 8 9] Creation of a matrix by vertical concatenation of previously defined row vectors: X = [y1; y2; y3] Create a matrix by horizontal concatenation of previously defined column vectors: X = [y4 y5 y6] Special matrices nan(m,n), zeros(m,n), ones(m,n), randn(m,n), eye(n) (identity matrix)

WW Z

Quantitative Security Analysis Axel Kind

19

Key Concepts: Accessing Elements of Matrices


MATLAB uses two alternative indexing techniques for accessing the elements of a matrix, say X= [1 2 3; 4 5 6; 7 8 9]: Index
1,1 1,2 2,2 3,2 1,3 2,3 3,3

Content
1 4 7 2 5 8 3 6 9

Cartesian indexing: X(row,column)


2,1 3,1

Linear indexing: X(i)

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

Key Concepts: The Colon Operator :


Generating vectors: K = 1:6 is equivalent to K=[1 2 3 4 5 6] K = 1:0.5:4 is equivalent to K=[1 1.5 2 2.5 3 3.5 4] Accessing elements of a vector Y(1:3:end) accesses every third element of vector Y, starting from the first one Accessing elements of a matrix X(:,1) accesses the first column of matrix X (all elements in the first column) X(2,:) accesses the second row of matrix X (all elements in the second row) X(:,2:2:end) accesses every second column vector (starting from the second) of matrix X

WW Z

Quantitative Security Analysis Axel Kind

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

Quantitative Security Analysis Axel Kind

22

Exercise III (Continued)


Transform those daily prices into weekly prices and store them into a variable called weeklyPriceV.

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

Quantitative Security Analysis Axel Kind

23

Key Concepts: MATLAB Functions (I)


Elements of every MATLAB function:
Function name used to call the function. Avoid shadowing by using exist(FunctionName), e.g. exist('mean') ans = 2 Input parameters (arguments): one or more parameters separated by commas within round brackets. They can be scalars, vectors, or matrices and some of them can be optional. Output parameters: one or more variables (scalars, vectors, or matrices) help <function_name> in the command window

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

Quantitative Security Analysis Axel Kind

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.

Calculate simple monthly returns and store them into retSimpleV.

Calculate logarithmic monthly returns and store them into retLogV.

WW Z

Quantitative Security Analysis Axel Kind

25

Exercise IV (Continued)
Calculate the geometric mean of simple returns and store it in retSimpleBar.

Calculate the arithmetic mean of log returns and store it in retLogBar.

Calculate the annualized standard deviation of both simple and logarithmic returns and store them in sigmaSimpleRet and sigmaLogRet.

WW Z

Quantitative Security Analysis Axel Kind

26

Key Concepts: MATLAB Functions (II)


User-defined functions: 1) Function definition (first line): function [output1 output2] = FunctionName(input1, input2, input3) Saved as FunctionName.m (same file name as function name) either in the current directory or in a directory included in the MATLAB search paths. 2) Description: lines of text beginning with % retrievable by typing help FunctionName in the command window: Preamble (short description of functionality), Explanation of input and output parameters, Usage example, Author, date, contact information 3) List of commands: (well commented) sequence of commands to be executed with final attribution of values to output arguments.

WW Z

Quantitative Security Analysis Axel Kind

27

Key Concepts: MATLAB Functions (III)


Example of user-defined function: 1) function name 2) description function value = rmse(x,y) % % value = rmse(x,y) % % This function calculates the root mean squared error between % two vectors % % INPUT: x = N*1 vector % y = N*1 vector % % OUTPUT: value = root mean squared error (scalar) % % EXAMPLE: A = rmse([0.01 0.03 0.03 -0.01]', [0.0 0.02 0.01 -0.02]') % % AUTHOR: Axel Kind, axel.kind@unibas.ch, % value = sqrt(mean((x-y).^2)); end 3) list of commands optional
WW Z
Quantitative Security Analysis Axel Kind 28

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

Quantitative Security Analysis Axel Kind

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

Quantitative Security Analysis Axel Kind

30

Key Concepts: Text Output

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

This prints The random number is 0.9575. to the command window.

WW Z

Quantitative Security Analysis Axel Kind

31

Key Concepts: Text Output (II)


Write formatted data to file: fprintf(fid, format, A, ...) fid = fopen('WriteToFile.txt','w'); % fid is the file identifyer x=rand(1); fprintf(fid,'The random number is %1.4f.',x); fclose(fid);

WW Z

Quantitative Security Analysis Axel Kind

32

Key Concepts: Text Output (III)


fid = fopen('WriteToFile.tex','w'); x=rand(1); fprintf(fid,'The random number is %1.4f.',x); fclose(fid);

WW Z

Quantitative Security Analysis Axel Kind

33

Key Concepts: Graphical Output (I)


Creating a new figure: figure Plot a vector y against a vector x: x = [1 2 3 4 5]; y = [1 -1 0 2 1]; plot(x,y) Plot by defining the color, the marker type, and the shape of the line: plot(x,y,'r*--') Main color options: 'b' (blue), 'g' (green), 'r' (red), 'c' (cyan), 'm' (magenta), 'y' (yellow), 'k' (black), w (white) Main marker types: '.' (point), 'o' (circle), 'x' (x-mark), '+' (plus), '*' (star), 's' (square), '<' (left triangle), '>' (right triangle), etc. Main line shapes: '-' (solid), ':' (dotted), '-.' (dashdotted), '--' (dashed) Add further plots to the same figure: x = [1 2 3 4 5]; y = [1 -1 0 2 1]; z = [2 0 3 4 1]; plot(x,y,'r*--'); hold on plot(x,z,'g^-.')

WW Z

Quantitative Security Analysis Axel Kind

34

Key Concepts: Graphical Output (II)


Add labels for x axis and y axis: xlabel('time') ylabel('\gamma_{\theta}=e^{t \times \lambda}') (MATLAB recognizes and processes simple LaTex commands) Change the size of characters: xlabel('time', 'FontSize',16) ylabel('\gamma_{\theta}=e^{t \times \lambda}' , 'FontSize',16) Add a legend: legend('First Plot', 'Second Plot', 0) position in the graph

Add a title: title('This is a great figure', 'FontSize',16)

WW Z

Quantitative Security Analysis Axel Kind

35

Key Concepts: Graphical Output (III)


Change the range of the axes: axis([x_min x_max y_min y_max]) Create separate plots in one figure: subplot(1,2,1), plot(exp([1 2 3 4])), subplot(1,2,2), plot(log([1 2 3 4])) Create plots with logarithmic axes subplot(2,1,1), plot(exp([1:50])), subplot(2,1,2), semilogy(exp([1:50])) Save the graph in an appropriate format: saveas(gcf,'first_graph.jpg','jpg'); saveas(gcf,'first_graph.eps','psc2');

WW Z

Quantitative Security Analysis Axel Kind

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.

Calculate beta of stock A by using the market model regression.

Calculate alpha and beta of stock A by using the CAPM regression.

WW Z

Quantitative Security Analysis Axel Kind

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

Quantitative Security Analysis Axel Kind

39

Exercise VI (Continued)
Add a regression line to the figure.

Add the text Slope =

' at position (0.04,-0.1) of the figure

Save the figure as a .jpg file with name GreatPlot to your hard drive.

WW Z

Quantitative Security Analysis Axel Kind

40

Key Concepts: Relational Operators


Relational operators compare two variables of same dimension (scalars, vectors, or matrices). The result of any of the following statements is a logical variable (1 for true and 0 for false) of the same dimension as x and y. Equal: x == y (not x = y !) Not equal: x ~= y Smaller: x < y Smaller or equal: x <= y Larger: x > y Larger or equal: x >= y Example: x = [1 2 3]; y = [3 2 3]; x == y yields a vector [0 1 1]

WW Z

Quantitative Security Analysis Axel Kind

41

Key Concepts: if-Statement (I)


if (logical condition 1) commands; [elseif (logical condition 2) commands; else commands;] end

WW Z

Quantitative Security Analysis Axel Kind

42

Key Concepts: if-Statement (II)


Example of a game function with the if-statement: function [ ] = GambleGame() if rand > 0.95 disp('You won 1000 CHF'); else disp('I am sorry, you lost! Try another time...') end

WW Z

Quantitative Security Analysis Axel Kind

43

Key Concepts: switch-Statement (I)


switch switch_var case case_expr statement, ..., statement case {case_expr1, case_expr2, case_expr3, ...} statement, ..., statement otherwise statement, ..., statement end

WW Z

Quantitative Security Analysis Axel Kind

44

Key Concepts: switch-Statement (II)


Example of a game function with the switch-statement: val = rand > 0.95; switch val case 1 disp('You won 1000 CHF'); case 0 disp('I am sorry, you lost! Try another time...') end

WW Z

Quantitative Security Analysis Axel Kind

45

Key Concepts: Logical Operators


Logical operators: AND: & OR: | NOT: ~ Example: Relational operators and logical operators in an if-statement. What do you expect MATLAB to do after running the following code? a=3; if ((a<3) & (a>1)) | ~(a==4) disp('if-condition is satisfied') end

WW Z

Quantitative Security Analysis Axel Kind

46

Key Concepts: for-loop (I)


There is no need to spend time an repetitive and silly tasks take care of them . MATLAB will

WW Z

Quantitative Security Analysis Axel Kind

47

Key Concepts: for-loop (II)


Example of a function with a for-loop: function [ ] = Repeat(text,times) % This function prints many times on the screen a given text % INPUT: % - text = string of arbitrary size % - times = integer indicating the number of repetitions % OUTPUT: % nothing (void), simply a screen output % Axel Kind, axel.kind@unibas.ch, 15/02/2009, % Quantitative Security Analysis (21996), University of Basel % for i = 1:times disp(text); end

WW Z

Quantitative Security Analysis Axel Kind

48

Key Concepts: while-loop


Example of a function with a while-loop: function prize = GambleGameWhile(probabilityThreshold) % % This function is simply a funny game % INPUT: probabilityThreshold = probability of getting 0 CHF % OUTPUT: prize = prize won at the game % AUTHOR: Axel Kind, axel.kind@unibas.ch % prize = 0; while rand > probabilityThreshold prize = prize + 100; end disp(['You won ' num2str(prize) ' CHF !'])

WW Z

Quantitative Security Analysis Axel Kind

49

A Note on Numerical Precision


The numerical precision of MATLAB variables is 15 decimal places.
fprintf('%.15f\n',2.22222) fprintf('%.25f\n',2.22222)

This holds also for constants such as pi or e


fprintf('piMatlab = %.15f\npiTrue = 3.141592653589793\n',pi) fprintf('piMatlab = %.25f\npiTrue = 3.141592653589793238462643\n',pi) fprintf('eMatlab = %.15f\neTrue = 2.718281828459045\n',exp(1)) fprintf('eMatlab = %.25f\neTrue = 2.718281828459045235360287\n',exp(1))

WW Z

Quantitative Security Analysis Axel Kind

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

Quantitative Security Analysis Axel Kind

51

Not-So-Key Concepts (II)


Optional input parameters in a function: nargin function PlotLine(data, linewidth) % plot line with varying linewidth if nargin > 1 plot(data,'LineWidth',linewidth); else plot(data); end

WW Z

Quantitative Security Analysis Axel Kind

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

Quantitative Security Analysis Axel Kind

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

Quantitative Security Analysis Axel Kind

54

Not-So-Key Concepts

(V): Sending Emails

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

Not-So-Key Concepts (VI): Sounds and Images


function [] = RussianRoulette(nPlayer) clc, slots = 6; alive = 1; [win, winMap] = imread('dove.jpg'); [lose, loseMap] = imread('death4.jpg'); [yShot, FsShot] = wavread('shot.wav'); [yEmptyChamber, FsEmptyChamber] = wavread('emptychamber.wav'); [ySpin, FsSpin] = wavread('spin.wav'); [ySpan, FsSpan] = wavread('span.wav'); fprintf('\nThere are %1.0f players in this game.\n\n',nPlayer); for iPlayer = 1:nPlayer fprintf('Player %1.0f, it is your turn. Spin the cylinder of the revolver and shoot by pressing ''enter''!\n\n',iPlayer); pause, close if slots == 6, wavplay(ySpan, FsSpan), pause(1.0), wavplay(ySpin, FsSpin), pause(0.5+2*rand) else pause(1.0), wavplay(ySpan, FsSpan), pause(0.5+2*rand) end

WW Z

Quantitative Security Analysis Axel Kind

56

Not-So-Key Concepts (VI): Sounds and Images (Continued)


if rand >= 1/slots wavplay(yEmptyChamber, FsEmptyChamber) figure, image(win); title(sprintf('Congratulations, Player %1.0f, you are still alive!',iPlayer),'FontSize',14), axis off alive = 1; else wavplay(yShot, FsShot) figure, image(lose), title(sprintf('This is a sad moment, Player %1.0f left us!',iPlayer), FontSize',14), axis off alive = 0; end if slots == 2 | alive == 0; slots = 6; else slots = slots - 1; end end fprintf('THE GAME IS OVER! \n');

WW Z

Quantitative Security Analysis Axel Kind

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

Run from first breakpoint (red point) to second breakpoint with F5

Execute code line-by-line with F11

WW Z

Quantitative Security Analysis Axel Kind

59

Basic Programming Hints for MATLAB

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

Quantitative Security Analysis Axel Kind

60

Arithmetic Operations in MATLAB

WW Z

Quantitative Security Analysis Axel Kind

61

Basic Commands (I): Creation of Variables


The MATLAB tutorial is available on the course webpage: MatlabTutorial.m and sp_500.txt To quit a MATLAB program while it is running, press Ctrl + c Create a variable A with a value of 3: A=3 To prevent MATLAB from showing the result use ; after the command: A = 3; Create a row vector B: B = [1 2 3] Create a column vector C: C = [4; 5; 6] or C = [4 5 6]' Calculate the inner product of B and C and store it in D: D = B*C Calculate the outer product of B and C and store it in E: E = C*B
Quantitative Security Analysis Axel Kind 62

WW Z

Basic Commands (II): Matrix Manipulation


Create two 3x3 matrices (F and G): F = [1 2 3; 4 5 6; 7 8 9] G = [9 8 7; 6 5 4; 3 2 1] Transform matrix F into a matrix F_long with dimension 9x1: F_long = reshape(F,9,1) Multiply F with G and store the result in H: H = F*G Multiply F with G element-by-element and store the result in I: I = 0 F.*G Divide F through G element-by-element and store the result in L: L = F./G Set the element (1,1) of L equal to the square root of 2: L(1,1) = sqrt(2) Extract the first column of L and store it in L_1: L_1 = L(:,1)
Quantitative Security Analysis Axel Kind 63

WW Z

Basic Commands (III): Matrix Manipulation


Extract the second row of L and store in L_2: L_2 = L(2,:) Eliminate L_1 and L_2 from the workspace: clear L_1 L_2 Concatenate matrices F and G row-wise to obtain a 4x8 matrix: M_2 = [F G] Concatenate matrices F and G column-wise to obtain a 8x4 matrix: M_2 = [F; G] Create a column vector of even integers from 8 to 46: N = [8:2:46]' Create a column vector N_sub by taking only every third element of N: N_sub = N(1:3:end)
WW Z
Quantitative Security Analysis Axel Kind 64

Basic Commands (IV): Matrix Manipulation


Create a 3x3 identity matrix O: O = eye(3) Create a 2x3 matrix of ones P: P = ones(2,3) Calculate the vertical sum of the elements of P: Q = sum(P) Calculate the horizontal sum of the elements of P: Q = sum(P,2) Calculate the vertical cumulative sum of P: Q = cumsum(P,1) Calculate the horinzontal cumulative sum of P: Q = cumsum(P,2)
WW Z
Quantitative Security Analysis Axel Kind 65

Basic Commands (V): Matrix Manipulation


Generate a 3x3 matrix with standard normally distributed random numbers: R = randn(3,3) Calculate the horizontal product of R: S = prod(R,2) Sort the column vector S from largest to smallest: S = sort(S, 'descend') Calculate the vertical cumulative product R: S = cumprod(R,1) Calculate the horizontal cumulative product: S = cumprod(R,2) Flip vertically the matrix S: S = flipud(S) Flip horizontally the matrix S: S = fliplr(S)

WW Z

Quantitative Security Analysis Axel Kind

66

Basic Commands (VI): Importing and Exporting Data


Import data from the file sp_500.txt and store it in the matrix price_data: [Change the current directory to the one containing the file sp_500.txt] price_data = importdata('sp_500.txt',' '); Calculate the series of log returns and save them (together with the date) in a matrix called return data: return_data = [price_data(2:end,1) ... log(price_data(2:end,2))-log(price_data(1:end-1,2))]; Calculate the annualized average and standard deviation from daily returns on the S&P 500 and save them in a .txt file: result(1) = mean(return_data(:,2))*250 result(2) = std(return_data(:,2))*sqrt(250) save('myresults.txt','result','-ASCII')

WW Z

Quantitative Security Analysis Axel Kind

67

Basic Commands (VII): Plotting Data


Plot daily returns together with two-sigma bounds: figure plot(return_data(:,1),return_data(:,2),'-b','LineWidth',1); hold on lower_bound = mean(return_data(:,2))+2*std(return_data(:,2)); upper_bound = mean(return_data(:,2))-2*std(return_data(:,2)); plot(return_data(:,1),repmat(lower_bound,size(return_data,1),1),':r','LineWidth',2); plot(return_data(:,1),repmat(upper_bound,size(return_data,1),1),'-r','LineWidth',2); Improve the readability of the graph by describing axes, and by adding a legend and a title: ylabel('Daily S&P returns','fontSize',14); xlabel('Time','fontSize',14); datetick('x',12,'keepticks'); [legend_h,object_h,plot_h,text_strings]=legend('S&P returns','upper two-sigma bound','lower two-sigma bound',4); set(legend_h,'FontSize',14); legend(legend_h,'boxoff'); title('S&P Returns','FontSize',14);
Quantitative Security Analysis Axel Kind 68

WW Z

Basic Commands (VIII): Plotting Data


Save the graph in .jpg format and .eps format (for importing into .tex files): saveas(gcf,'sp_graph.jpg','jpg'); saveas(gcf,'sp_graph.eps','psc2'); Find the dates when S&P returns where lower than 2 standard deviations: index_sp = find(return_data(:,2) < lower_bound); datestr(return_data(index_sp,1)+365.243*1900, 1) n = size(return_data(index_sp,1),1)

WW Z

Quantitative Security Analysis Axel Kind

69

Anda mungkin juga menyukai