University of Cyprus Public Business Administration Department Introductory Course to Matlab with Financial Case Studies PPrreeppaarreedd b
9numbered in square brackets (e.g. [2] is the Matlab online help facilities; see the section with the references). Additionally, if a figure or a tab
99dzep)z(Nxz∫∞−−=22121 represents the cumulative normal distribution function with mean zero and unity standard deviation (the Matlab build in funct
100 a function) named as “options_data.txt” in which the columns should contain S, X, T, s, r, d. The data values are given below: },,,,,,,,{S120115
101 8.1.2 BSM Derivatives From the same script as above, call a function with the name: BBSSMMddeerriivvaattiivveess that returns the partial derivat
102 8.1.3 BSM Plots and Surfaces Make the following plots: • Two subplot figures, one for call options with T=0.15 and s=0.20, and one for put optio
103 for simp. It is known that such equation has no analytic solution, so to solve it someone has to implement a numerical root-finding algorithm. T
104 arguments precede the optional ones (the optional are “dv”, “maxNumIter” and “tol”). Use as inputs the initial data from the loaded txt file (wi
105 the ones that you have initially used (these are the random values) to price calls and puts with the BSM. Note that the implied volatility of cal
106 stable convergence but with extremely slow rate. Typical values of a range between 0.01 and 0.15 depending on the faced problem. Specificall
107 Specifically, )x(''f for a function with n variables is: ∂∂∂∂∂∂∂∂∂∂∂∂∂∂∂∂∂∂∂∂∂∂=2222122222212212212212nnnnnx
108 To implement the previous algorithms, the user should be in a position to find the gradient vector and the Hessian matrix. Although it is better
10 Figure[2] 1: The Matlab desktop The above is termed as the Matlab Desktop (graphical user interfaces) and contains tools for managing files, vari
109 2212121212124h)hx,hx(f)hx,hx(f)hx,hx(f)hx,hx(fxx)x(f −+−+−−−−+++≈∂∂∂ 122212xx)x(fxx)x(f∂∂∂≡∂∂∂ 22121212122242222h)hxx(f)hxx(f)hxx(f)hxx(fx)x(f
110 • Call a function with the name: GGrraaddDDeesscceenntt that implements the gradient descent algorithm for minimizing the aforementioned functio
111 • Call a function with the name: NNeewwttoonn that implements the Newton descent algorithm for minimizing the aforementioned function. The calli
112 8.3 Portfolio Optimization Many times, a researcher needs to create a portfolio of securities that for a desire level of return/profit, it bears
113 =nnnnnnsssssssssOLMMMMLL212222111211 with )r,rcov(sjiij= . Additionally, for the portfolio optimization problem, it is required t
114 ReWT= 1=ITNW and for the case of the three assets in an analytic form: BCCBACCAABBACCBBAAwswwswwswwswswswmini222222222+++++ s.t. R)r(Ew)r(
115 Since this equals zero, we add it to the objective function that we want to minimize without affecting the results. Finally, we minimize the quad
116 ==150100050...rrrEeCBA ==280090170090210150170150250222...sssssssssOCCBCABC?BAACAB? Write a sc
117 change slightly the NNeewwttoonn function so that its calling syntax becomes: “[MinPoints] = NNeewwttoonnPPoorrtt(fun, x, r, V,
118 References [1] Ela Pekalska, Marjolein van der Glas, (2001), “Introduction to MATLAB”, Pattern Recognition Group, Faculty of Applied Sciences, D
11window text. For more information, click the Help button in the Preferences dialog box [2]. Additionally, two more windows that can be seen in Fi
12 Select one or more lines and right-click to copy and re-use the command with the command window, to evaluate it or to create an m-file Figure 3:
13 Figure 4: A basic calculation The Matlab displays the results into a variable named as aannss. This is a default variable name that is used by t
14The square brackets “[ ]” indicate the definition of the vector. Also, the space between the vector numbers separates the vector’s elements. The co
15Type also the following: “x=[(2^2+1)^2-15/4*6.1, 1.23e-2]” and after pressing [Enter] you get the Matlab’s result (Figure 7) Figure 7: A 2-e
16• “*” and “/” follow by working from left to right: (e.g. 2*8/4 = 16/4 = 4) • “+” and “-” follow last, from left to right: (e.g. 6-7+2= -1+2 = 1)
17operations like 1/0. Matlab as a calculator includes a variety of build-in mathematical functions like: trigonometric, exponential, complex, roundi
18List of Useful Commands: wwhhoo Lists current variables located in the workspace. wwhhooss A long form of wwhhoo. It lists all the variables i
1Table of Contents 1. Introduction...3 1.1 Learning Matlab...
19ffoorrmmaatt lloonngg ee Floating-point format with 15 digits. ffoorrmmaatt lloonngg gg Best of fixed or floating-point format with 15 digits
20 “s = 0.65321” Blank spaces around the “=”, “+”, and “-“operators are optional, but they improve readability. Command Line Editing
21current directory or on the search path (the search path is a default list of paths that include all folders with Matlab build in functions and too
22It’s like a text editor (e.g. MS Word) suitable for writing executable Matlab code. Notice that reserved words (e.g. wwhhiillee, iiff, eellssee, ee
23Type also: “hheellpp eellffuunn” to view the help results concerning the build-in elementary functions exhibited in Table 1 (notice also t
24 Figure[2] 11: Matlab’s help browser To become familiar with the Matlab’s accompanied toolboxes, navigate in the contexts, open up the droppin
25Second Section 2. Manipulating Vectors and Matrices A matrix or an array is the basic element on which Matlab can operate. A 1-by-1 matrix forms
26functions element-wise. The lleennggtthh of the above vector is obtained via the following command: Matlab’s command: >> length(y) Matlab’s
27Matlab’s command: >> c1=5+b Matlab’s response: c1 = 7 6 7 Comments: An element-by-element addition of vector bb with 5. Matlab’
28parts of vectors (afterwards, with matrices, the colon can be used to view a certain part of a matrix). For instance, the following commands produc
23.2 Creating 3D Graphs...59 3.2.1 Creation of 3D Line Plots ...
292.1.2 Column Vectors Column vectors are created via the use of semi-colon “;” instead of commas and spaces. Operations with column vectors are simi
302.1.3 Transporting Vectors To perform operation with column and row vectors of similar length, it is first needed to transpose the vectors in order
31Matlab’s command: >> Z=[], Z=1:3, Z=[], length(Z) Matlab’s response: Z = [] Z = 1 2 3 Z = [] ans = 0 Comments:
32 The inner product is defined as the linear combination: ∑==tiiiuwu~w~1 The following depicts some examples with inner products. Matlab’s comman
33The dot product in Matlab is performed via the “.*” symbol. By the use of dot product we can get the inner product. This is explained in the follow
34Matlab’s command: >> d_div1=-3:1.5:3, d_div2=1:5 >> d_div2./d_div2, d_div1./d_div2, d_div2./5 Matlab’s response: d_div1 = -3.0000
35and a Not-a-Number, NNaaNN,, is returned in the vector. In the third case, the inverse of each vector element is required, but Matlab returns an er
36Comments: Examples of dot power. The second or the forth power of a certain vector can be defined either with the dot power or the dot product oper
37Matlab’s response: ans = 1 x = 1.0000 2.8000 4.6000 6.4000 8.2000 10.0000 x = 1.2589 1.5136 1.8197 2.1878 2.
38It is obvious that the above matrix can be decomposed to either 2 row vectors of 41× dimensions or to 4 column vectors of 12X. So, row and column
3First Section 1. Introduction This handout demonstrates a comprehensive introduction to the basic utilities of a high technical programming langua
39A2 = 1.0000 1.7500 2.5000 3.2500 4.0000 1.0000 2.0000 3.0000 4.0000 5.0000 1.0000 1.7500 2.5000 3.2500
40 It is the same idea with the transpose of a row vector to a column one and vise versa. The transpose of an nm×matrix is an mn×one that is found if
41in the workspace; use the wwhhoo function to view the variables that you have saved in the workspace or view them from the workspace browser): M
42position (2,1) is taken to be the second (2), the (3,1) the third and finally the (m, n) element is the last one (n*m). View the following example
43In addition, there are special cases where the step is defined to be a different integer number other than 1. Some paradigms follow: Matlab’s comm
442.2.2 Matrix Basic Manipulations Subtraction and multiplication with a scalar are similar as with the vector case. Matrix dimensions (ssiizzee) mus
45 Matlab’s command: >> clear; U=[-1 2 1; 0 -2 3]; V=[1:3; 5 2 4]; >> U.^2, U.*V, (1./V).^2.*U, U.^U Matlab’s response: ans = 1
46 111××××=nnmmCAC Let’s define the “A” and “B” matrices: =×242322211413121142aaaaaaaaA , =×424132312221121124bbbbbbbbB Like
47Col = 13 4 5 1 ans = 39 -310 297 314 Comments: Matrix-vector and matrix-matrix products. 2.1.5 Special Cases of Mat
48 ans = 0.9501 0.6068 0.2311 0.4860 ans = 0 0 Comments: Examples with matrices build-in functions. 2.1.5 Additional Useful
4Matlab features a family of add-on application-specific solutions called toolboxes. A toolbox is a comprehensive collection of Matlab functions (M-f
49 nmnmnnmmmmbxa...xaxabxa...xaxabxa...xaxa=+++=+++=+++221122122212111212111M The solution of the above system can be expressed as: bAx1−= given
50To see that these two procedures lead to different results, elaborate on the following example (search online help to see the use of the command: p
51Third Section 3. Plots and Graphs (2D and 3D) It is quite easy to create a plot or a graph by using the variables or parameters that have alrea
52Matlab’s response: 0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5-8-6-4-20246 0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5-15-10-505101520 Comments: Plot of a function. The us
53 Figure[2] 10: The figure window This figure window has tools that look like a photo editor (e.g. Microsoft® Photo Editor). You can select objects
54to mark each plotted point with a symbol. To do this, the user should call the plot function as: “pplloott(X,Y, '???')” where “?
55View the following examples to digest the plot facilities. Matlab’s command: >> plot(x, y, 'md: '); figure; plot(x, y, 'r*-
560 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5-15-10-505101520 Comments: Experimenting with various functions and facilities related with the plots. The last ppll
57Matlab’s response: 0 2 4 6-20-1001020Subplot 10 2 4 600.20.40.60.81Subplot 20 0.5 100.20.40.60.810 10 20 30-2-1012Subplot 50 2 4 6-20-1001020Subplo
58where “PropertyName” relates with an element of the plot and “PropertyValue” is defined by the user. Some useful properties concern the following:
5It is better to use this handout in direct use with the Matlab. It will be more beneficial if while reading these notes you sit in front of a PC and
593.2 Creating 3D Graphs Matlab offers fancy 3-dimensional line plots and surface graphs. 3.2.1 Creation of 3D Line Plots There is the function: p
60functional expression, z=f(x,y), is evaluated. Usually, we evaluate the z behavior in a certain area of the (x,y)-plane in which z has some interes
61Matlab’s command: >> clear; x=-2:1:2; y=-4:1:4; [X,Y]=meshgrid(x,y) >> plot(X,Y, 'rh'); axis([-3 3 -5 5]); xlabel('x-axi
62rectangular domain. The subsequent 2D plot of XX and YY shows how the grid is sampled. Now, we should evaluate the ZZ at each pair of the grid an
63-2-1.5-1-0.500.511.52-4-2024-6-4-20246xyz Comments: Creating the 3D mesh and a 3D surface. The function is not smooth because the dense of the xx a
64Matlab’s response: -2-1.5-1-0.500.511.52-4-2024-8-6-4-202468xPeaksyZ -2-1.5-1-0.500.511.52-4-2024-8-6-4-202468xPeaksyZ Comments: Creating the 3D
65To find what other useful commands can be accompanied the mmeesshh and ssuurrff commands, use the online help. 3.2.2.1 Examination of a Function’
66Comments: Creating the contour plot of the peaks function. Viewing this plot, it is easy to identify the critical points of the function. There is
67Comments: Locating the maximum of the peak function via an exhaustive search. “Fmax=mmaaxx(max(Z))” stores in Fmmaaxx the maximum value of the ZZ m
68Fourth Section 4. Control Flow A collection of commands that include repetition of a conditional code segment is termed as control flow structu
61.2 Basic Definitions Before moving to the introduction of issues specific to Matlab, some very basic definitions on computers and programming shou
69example and for the case of a scalar: 0 | 1, 1 | 0, and 1 | 1 is 1 (TRUE) while 0 | 0 is 0 (FALSE). • “~A” is a matrix whose elements are 1&apos
70 d = 1 Comments: Logical and relational operations. aa is 1 because the statement evaluated is TRUE since xx is 2 and greater than 1. bb is FA
71matrix, returning a row vector of 1's and 0's. The second one, aallll, becomes TRUE if all elements of a vector are nonzero. For vectors,
724.2.1 The iiff Statement The iiff statement evaluates a logical expression and executes a group of statements when the expression is TRUE. The opti
73Although is possible to run these examples via the command window, it is better to use the Matlab Editor/Debugger to write a script instead. Real
744.3.1. The ffoorr Loop The ffoorr loop repeats a group of statements a fixed, predetermined number of times. A matching eenndd delineates the state
75 4.3.3. Nested Conditional and Loop Expressions All conditional and loop statements can be combined in any way that is desirable. If for example a
76Statement Comment bbrreeaakk Terminates the execution of a ffoorr or wwhhiillee loop. Statements in the loop that appear after the bbrreeaakk st
77Fifth Section 5. m-files: Scripts and Functions Up to this point, all commands passed to Matlab, were done through the command window. But when
78the theoretical price of a call option contract according to various options pricing models. Options pricing models like the Black and Scholes, the
7• m-file is a file that contains Matlab’s language code. m-files can be functions that accept arguments and produce output, or they can be scripts
79error); you have to return to the Editor to debug the error, re-save the function and try to run it again. If you debug your function or add somet
80 (Figure copied from [2]) Matlab function names have the same constraints as variable names. The name must begin with a letter, which may be fol
81 “ffuunnccttiioonn [] = pprriinntt__rreessuullttss (x)” The variables that you pass to the function do not need to have the same name as those
82 5.1.1.4 The Body Text The function body contains all the Matlab code that performs computations and assigns values to output arguments. The statem
83script that calls various options pricing function in order to price a call option and compare the pricing accuracy of each model). Unlike functio
84 Try to see what this script does. After executing the script, figure out what is the difference between the command ddiisspp and the ffpprriinnttf
85Sixth Section 6. Cells and Structures Structures are collections of different kinds of data organized by named fields. Cell arrays are a specia
86To create a cell array use the command: cceellll. For example if we want AA to be a 3-by-3 cell array, then you should use the following syntax:
87 “A = [3x3 double] 'Anne Smith' [] [3.0000+ 7.0000i] [1x21 double]
88The only difference between the cceellll command and the cell and content indexing is that by using cceellll you pre-allocating the cell’s dimens
8• Every build in or user made function has a calling syntax that is unique for each function. In Matlab, to call a function you type the function’s
89 [1x21 double] [5] ” So, if “{ }” are used after a cell array then Matlab returns the array’s contents but if “( )” are used instead, t
90 Building structure arrays using assignment statements You can build a simple 1-by-1 structure array by assigning data to individual fields. Matlab
91individual field contents when you type the array name. Instead, it shows a summary of the kind of information the structure contains. You can also
92 patient(1)=ssttrruucctt('name', 'John Doe', 'billing', 127.00, 'test', ...
93 “structure_name(index_of_entry).field_name( ) ” For example type: “patient(2).test(2:end,1:end-1)” in the command window to get: “ans
94Seventh Section 7. Entering and Saving Data Files Matlab can be used to both load a file of data from an external source and to save to your P
95should have the same number of elements (of course the advance user can handle via certain methodology missing values and text in an ASCII file). T
96 Figure 16: Excel®’s Save As window The data will be saved in a file with the name: “random_number_data.txt” that can be loaded in Matlab. If by m
97name variable_name has components like: NaN or Inf, then these are saved as text and not numbers in the saved txt file. Concerning the options in
98Eighth Section 8. Case Studies In the following sub-section, some very useful examples with functions and scripts are illustrated. Read, impleme
Commentaires sur ces manuels