Sie sind auf Seite 1von 190

INTRODUCTION

 TO    
FINANCIAL  PROGRAMMING    
Antonio  Rivela  
First  Edition  
 

 
 
 

USES  MATLAB,  EXCEL  AND  VISUAL  BASIC  


INDEX  
 

1.   QUANTITATIVE  FINANCE  AT  A  GLANCE ................................................................................. 8  

1.1.   Portfolio  Theory................................................................................................................ 8  


1.1.1.   Two-­‐Asset  Portfolio  Risk  and  Return ........................................................................................... 8  
1.1.2.   Multi  Asset  Portfolio  Risk  and  Return .......................................................................................... 9  
1.1.3.   Efficient  Frontier  and  GMVP ..................................................................................................... 13  
1.1.4.   Sharpe  Ratio  and  Optimal  Portfolio .......................................................................................... 14  
1.2.   The  Black  Scholes  Model ................................................................................................. 16  
1.2.1.   Understanding  Black  Scholes  Model .......................................................................................... 16  
1.3.   Monte  Carlo  Simulation ................................................................................................... 18  
1.3.1.   Understanding  Monte  Carlo  Methods ........................................................................................ 18  
1.3.2.   Apply  Monte  Carlo  Method  to  Compute  π .................................................................................. 18  
1.4.   Brownian  Motion ............................................................................................................ 19  
1.4.1.   Derive  Geometric  Brownian  Motion  (GBM)  Formula .................................................................. 19  
1.4.2.   Geometric  Brownian  Motion ..................................................................................................... 20  
1.4.3.   Evaluate  European  Option  Fair  Price ........................................................................................ 21  
1.5.   Variance  Reduction  Techniques ...................................................................................... 23  
1.5.1.   Common  Random  Number ....................................................................................................... 23  
1.5.2.   Antithetic  Variates ................................................................................................................... 23  
1.5.3.   Moment  Matching.................................................................................................................... 23  
1.5.4.   Stratified  Sampling .................................................................................................................. 24  
1.5.5.   Quasi-­‐Random  Sequences ......................................................................................................... 25  
1.5.6.   Applications  to  Option  Pricing .................................................................................................. 27  
1.5.6.1.   European  Call  Option ....................................................................................... 28  
1.5.6.2.   European  Down  and  Out  Barrier  Option ........................................................... 31  
1.6.   Introduction  to  correlation .............................................................................................. 36  
1.6.1.   Why  is  correlation  useful  in  finance? ......................................................................................... 36  
1.6.2.   Variance,  covariance  and  covariance  matrix ............................................................................. 37  
1.6.3.   Linear  correlation  coefficient  and  linear  correlation  matrix ....................................................... 38  
1.6.4.   Rank  coefficients...................................................................................................................... 39  
1.6.5.   Copulas ................................................................................................................................... 40  
1.6.6.   Types  of  copulas ...................................................................................................................... 41  
1.7.   Practical  implementation  of  correlation  in  financial  modeling ......................................... 43  
1.7.1.   Modeling  correlation  using  Cholesky  decomposition  of  the  correlation  matrix ............................ 43  
1.7.2.   Modeling  correlation  using  eigenvector  decomposition  of  the  correlation  matrix ........................ 44  
1.7.3.   Modeling  correlation  using  copulas .......................................................................................... 44  
1.7.4.   Data  collection  and  analysis ..................................................................................................... 44  
1.7.5.   Linear  correlation  between  S&P  500,  Euro  Stoxx  50  and  Nikkei  225  returns ............................... 48  

2
1.7.6.   Correlation  of  S&P  500  and  Euro  Stoxx  50  returns  using  copulas ................................................ 48  

2.   ADVANCED  EXCEL ................................................................................................................. 54  

2.1.   Financial  Calculations  in  Excel ......................................................................................... 54  


2.2.   Matrices  and  vectorial  calculations  in  Excel ..................................................................... 57  
2.3.   Main  Statistical  Functions  in  Excel ................................................................................... 58  

3.   APPLYING  EXCEL  TO  FINANCE .............................................................................................. 59  

3.1.   Solver ............................................................................................................................. 59  


3.1.1.   Long  Only  Constraint  (No  Short  Selling) .................................................................................... 60  
3.1.2.   130/30  Constraint ................................................................................................................... 61  
3.1.3.   Diversification  Constraint ........................................................................................................ 63  
3.1.4.   Exposure  Constraint................................................................................................................. 64  

4.   INTRODUCTION  TO  MATLAB ................................................................................................ 66  

4.1.   Matrices  as  Fundamental  Objects .................................................................................... 67  


4.2.   Matrix  Operations ........................................................................................................... 67  
4.3.   Assignment  Statements ................................................................................................... 68  
4.4.   Case  Sensitivity ............................................................................................................... 68  
4.5.   Immediate  and  Deferred  Execution ................................................................................. 69  
4.6.   Showing  Values ............................................................................................................... 70  
4.7.   Initializing  Matrices ........................................................................................................ 70  
4.8.   Making  Matrices  from  Matrices ....................................................................................... 71  
4.9.   Using  Portions  of  Matrices............................................................................................... 72  
4.10.   Text  Strings .................................................................................................................... 73  
4.11.   Matrix  and  Array  Operations ........................................................................................... 74  
4.12.   Matrix  Operations ........................................................................................................... 75  
4.13.   Array  Operations ............................................................................................................ 76  
4.14.   Using  Functions .............................................................................................................. 77  
4.15.   Logical  and  Relational  Operations  on  Matrices ................................................................ 80  
4.16.   Sorting  Matrices .............................................................................................................. 82  
4.17.   Controlling  Execution  Flow ............................................................................................. 83  
4.18.   For  Loops........................................................................................................................ 84  
4.19.   While  Loops .................................................................................................................... 84  
4.20.   If  Statements ................................................................................................................... 85  
4.21.   Nesting ........................................................................................................................... 86  
4.22.   Writing  Functions ........................................................................................................... 87  
4.23.   Comments  and  Help ........................................................................................................ 89  
4.24.   Data  Input  and  Output..................................................................................................... 89  
3
4.25.   Data  Input ....................................................................................................................... 90  
4.26.   Data  Output .................................................................................................................... 91  
4.27.   FRONTCON  FUNCTION ................................................................................................... 92  

5.   APPLYING  MATLAB  TO  FINANCE .......................................................................................... 96  

5.1.   Report  1:  Portfolio  Theory  (2  Assets) .............................................................................. 96  


5.2.   Report  2:  Portfolio  Theory  (4  Assets) ............................................................................ 113  
5.3.   Report  3:  Portfolio  Theory  (Real  Life  Constrains) .......................................................... 117  
5.4.   Report  4:  Portfolio  Theory  &  Simulation ........................................................................ 137  
5.5.   Report  5:  Simulation  (Exponential  Distribution) ............................................................ 144  
5.6.   Report  6:  Simulation  (Normal  Distribution  of  Stock  Returns)......................................... 147  
5.7.   Report  7:  Simulation  (number  PI) ................................................................................. 152  
5.8.   Report  8:  Geometric  Brownian  Motion  followed  by  stock  prices .................................... 155  

6.   INTRODUCTION  TO  VISUAL  BASIC ...................................................................................... 158  

6.1.   Creating  Your  First  Macro ............................................................................................. 158  


6.2.   Simple  User  Defined  Functions ...................................................................................... 158  
6.2.1.   Where  To  Put  The  Function  Code ............................................................................................ 159  
6.2.2.   User  Defined  Funtions  And  Calcuations ................................................................................... 160  
6.3.   Objects  and  Collections ................................................................................................. 160  
6.3.1.   Workbook  and  Worksheet  Object ............................................................................................ 161  
6.3.2.   Range  Object  and  Cells  Property ............................................................................................. 162  
6.4.   Methods  and  Properties ................................................................................................ 164  
6.4.1.   Assigning  Object  Variables  and  Using  Named  Argument .......................................................... 165  
6.5.   Modules  and  Procedures ............................................................................................... 165  
6.5.1.   Modules  and  Procedures  and  Their  Scope ................................................................................ 165  
6.5.2.   Calling  Sub  Procedures  and  Function  Procedures .................................................................... 167  
6.5.3.   Passing  Argument  by  Reference  or  by  Value ............................................................................ 168  
6.6.   Creating  and  Managing  Arrays ...................................................................................... 168  
6.6.1.   Declaring  an  Array  With  Dim  Statement ................................................................................. 169  
6.6.2.   Resize  an  Array  With  Redim  Statement ................................................................................... 170  
6.6.3.   Manage  Dynamic  Array ......................................................................................................... 170  
6.6.4.   Create  Multi-­‐Dimensional  Array ............................................................................................. 171  
6.6.5.   Find  The  Size  of    an  Array ....................................................................................................... 172  
6.6.6.   Choosing  The  Right  Return  Array  Size ..................................................................................... 173  
6.6.7.   Orienting  An  Array ................................................................................................................ 174  
6.7.   Decision  Structures  -­‐  IF  and  Select  Case ......................................................................... 176  
6.7.1.   IF  ...  Then  Statement .............................................................................................................. 176  
6.7.2.   IF  ...  Then  ...  Else ..................................................................................................................... 176  
6.7.3.   IF  ...  Then  ...  ElseIf ................................................................................................................... 177  

4
6.7.4.   Select  Case ............................................................................................................................ 177  
6.8.   Loop  Structures ............................................................................................................ 178  
6.8.1.   For  ...  Next ............................................................................................................................. 178  
6.8.2.   For  ...  Next  Loop  With  Step ..................................................................................................... 178  
6.8.3.   Do  While  ...  Loop .................................................................................................................... 179  
6.8.4.   Do  Until  ...  Loop ..................................................................................................................... 179  
6.8.5.   Do  ...  Loop  While .................................................................................................................... 180  
6.8.6.   Do  ...  Loop  Until ..................................................................................................................... 180  

7.   APPLYING  VBA  TO  FINANCE.  INTRODUCTORY  EXAMPLES ................................................ 181  

7.1.   Your  first  function  in  VBA:  Sum  A  and  B ........................................................................ 181  
7.2.   Your  second  function  in  VBA:  Conditional  IF .................................................................. 182  
7.3.   Your  third  function  in  VBA:  Loops ................................................................................. 183  
7.4.   Your  fourth  function  in  VBA:  Arrays .............................................................................. 184  
7.5.   Your  fifth  function  in  VBA:  Ranges  from  Excel  to  VBA .................................................... 186  
7.6.   Your  sixth  function  in  VBA:  Prices  to  Returns ................................................................ 187  

8.   BIBLIOGRAPHY .................................................................................................................... 190  

 
 
 
 
 
 
 
   

5
 
 
 
 
 
“Finance  is  the  art  of  passing  currency  from  hand  to  hand  until  it  finally  disappears”.  
   
Robert  W.  Sarnoff    

6
PREFACE  
 
Financial   modeling   is   undoubtedly   one   of   the   most   difficult   courses   in  
advanced  finance  and  the  well  deserved  target  for  many  recent  Nobel  prizes.    
 
I   have   devoted   most   of   my   life   to   financial   modeling,   as   a   banker   at  
Santander,   Merrill   Lynch,   Deutsche   Bank   and   UBS   in   London,   and   as   a   finance  
professor  at  ICADE  and  IE  Business  School  in  Madrid.  Modeling  is  not  a  science  but  
a  combination  of  an  art  (creativity)  and  science  (technical  skills).    
 
It  takes  many  books  to  understand  the  theoretical  foundations  of  financial  
modeling.  One  of  my  key  references  has  always  been  Financial  Modeling  by  Simon  
Benninga.   This   book   is   very   focused   on   VBA   modeling   but   it   does   not   cover  
derivatives  at  a  high  level,  and  besides,  it  does  not  use  Matlab.  I  like  Simon´s  style  a  
lot,   because,   not   only   he   teaches   things,   he   does   them   for   real.   This   book   uses  
Matlab  and  Visual  Basic  in  order  to  implement  all  the  models.  VBA  is  excellent  but  
lacks  calculation  power,  and  that´s  when  Matlab  comes  in.    
 
I  am  a  big  believer  in  “learning  by  real  practise”  education.  Real  models  are  
extremely  helpful  for  practisioners  that  just  want  to  be  able  to  put  financial  models  
together   for   accounting,   financial,   legal   issues,   asset   management,   risk   control   or  
any   other   reasons.   Once   you   see   it   in   the   computer,   its   much   easier   to   be   able   to  
cope  with  the  huge  density  of  text  books.  You  do  not  need  to  be  a  “rocket  scientist”  
to  use  these  models.  
 
Last   but   not   least   I   would   like   to   thank   to   all   my   IE   Business   School  
students.  As  Elton  John  would  say  “this  song  is  for  you”.  
 
Have  fun!  
      Antonio  Rivela  

7
1. QUANTITATIVE  FINANCE  AT  A  GLANCE  
Before   we   start   looking   at   financial   programming,   we   need   to   refresh   our  
knowledge   on   a   few   quantitative   finance   situations,   so   then   we   can   go   ahead  
understanding  the  main  foundations.  
 
 

1.1. Portfolio  Theory    


In  this  chapter  we  introduce  the  basic  mechanics  of  portfolio  calculations.  We  start  
with  a  simple  portfolio  that  contains  two  assets,  to  introduce  the  methods  to  use  
historical   price   data   to   derive   the   portfolio   return   and   risk.   We   then   discuss   the  
general  case  of  N  assets.  Furthermore,  we  discuss  the  efficient  portfolio  theory,  and  
apply  Matlab  to  optimize  the  portfolio  combination  through  maximize  the  Sharpe  
Ratio.    
 
1.1.1. Two-­‐Asset  Portfolio  Risk  and  Return  
In  this  section  we  compute  the  return  and  risk  statistics  for  two  stocks:  Walmart  
(stock  symbol  WMT)  and  Target  (TGT).    Furthermore,  we  introduce  the  formula  to  
calculate  the  expected  return  and  risk  of  the  two-­‐asset  portfolio.  
 

8
A B C D E F G

PRICE AND RETURN DATA FOR WALMART (WMT)


AND TARGET (TGT)
1 Yahoo's closing price adjusts for dividends
2 Prices Returns
3 Date WMT TGT WMT TGT
4 5-Jul-01 26.07 37.40
5 1-Aug-01 22.00 33.53 -16.97% -10.92% <-- =LN(C5/C4)
6 4-Sep-01 20.07 30.73 -9.18% -8.72% <-- =LN(C6/C5)
59 1-Feb-06 58.46 54.29 4.96% -0.46%
60 1-Mar-06 60.23 51.90 2.98% -4.50%
61 3-Apr-06 65.46 52.99 8.33% 2.08%
62 1-May-06 60.84 48.92 -7.32% -7.99%
63 1-Jun-06 67.51 48.87 10.40% -0.10%
64 3-Jul-06 67.65 49.17 0.21% 0.61%
65
66 WMT TGT
67 Monthly mean 1.59% 0.46% <-- =AVERAGE(F5:F64)
68 Monthly variance 0.0093 0.0052 <-- =VARP(F5:F64)
69 Monthly standard deviation 9.63% 7.19% <-- =STDEVP(F5:F64)
70
71 Annual mean 19.07% 5.47% <-- =12*F67
72 Annual variance 0.1114 0.0620 <-- =12*F68
73 Annual standard deviation 33.37% 24.90% <-- =SQRT(F72)
74
75 Covariance 0.0038 <-- =COVAR(E5:E64,F5:F64)
76 Correlation 0.5484 <-- =CORREL(E5:E64,F5:F64)  
The   formulas   to   calculate   the   expected   portfolio   return   and   risk   (variance)   are  
below  (where  S  is  the  volatility):  
 
𝑹𝒆𝒕𝒖𝒓𝒏 = 𝑊WMT ∗ 𝐸 𝑅WMT + 𝑊TGT ∗ 𝐸 𝑅TGT  
𝑽𝒂𝒓𝒊𝒂𝒏𝒄𝒆 = 𝑊 WMT ! ∗ 𝑆WMT ! + 𝑊TGT ! ∗ 𝑆TGT ! + 2 ∗ 𝑊WMT ∗ 𝑊TGT ∗ 𝐶𝑜𝑣(𝑅WMT, 𝑅TGT  )  
 

     

1.1.2. Multi  Asset  Portfolio  Risk  and  Return  


Now   we   generalize   the   formula   to   calculate   the   risk   and   return   of   an   N   asset  
portfolio.  We  need  to  introduce  the  concept  of  matrix.    
Use  vector/matrix  to  express  expected  return,  E(r),  variance-­‐covariance  matrix  S,  
and  weights  of  each  asset  in  this  portfolio  x.      
 
  ⎡ x1 ⎤
⎡ E (r1 ) ⎤ ⎡ σ 11 σ 21 L σ N 1 ⎤ ⎢ x ⎥
  ⎢ σ N
⎢ E (r ) ⎥ σ 22 L σ N 2 ⎥⎥ x = ⎢ 2 ⎥ ,
  E ( r ) = ⎢
2 ⎥
S = ⎢ 12
⎢ M ⎢ M⎥ ∑x i =1
⎢ M ⎥ ⎥ i =1
⎢ ⎥ ⎢ ⎥ ⎢ ⎥
⎣ E (rN ) ⎦ ⎣σ 1N σ 2 N L σ NN ⎦ ⎣ xN ⎦ 9
 
 
 
The  expected  return  of  the  portfolio  is  calculated  as:  
 
⎡ E ( r1 ) ⎤
  ⎢ ⎥
E ( r2 ) ⎥
E ( rx ) = x T ⋅ R = [ x1 x2 L xN ] ⎢
  ⎢ M ⎥
⎢ ⎥
  ⎣ E ( rN )⎦
N
  = ∑ xi E ( ri )
i =1
 
 
The  mathematical  expression  to  calculate  the  portfolio  variance:    
 
N N N
2 2 2
  σ = ∑ x σ + 2∑ ∑ xi x jσ ij
x i i
i =1 i =1 j =i +1
 
To  apply  matrix  to  calculate  variance,  we  could  express  the  formula  as:  
 
  σ x2 = x T Sx
  ⎡ σ 11 σ 21 L σ N 1 ⎤ ⎡ x1 ⎤
⎢ σ σ 22 L σ N 2 ⎥ ⎢ x2 ⎥
  = [ x1 x2 L xN ] ⎢ 12 ⎥ ⎢ ⎥
⎢ M ⎥ ⎢ M⎥
  ⎢
σ NN ⎥⎦ ⎢⎣ xN ⎥⎦
⎣σ 1N σ 2 N L
  N N
= ∑∑ xi x jσ ij
  i =1 j =1

 
In   real   life,   a   portfolio   manager   may   manage   several   portfolios,   thus   it   is   necessary  
to   evaluate   the   portfolio   pool’s   combined   risk   and   return   of   those   portfolios.   The  
combined  return  is  the  sum  of  weighted  return  of  each  portfolio.    
 
! !

𝐸 𝑃 = 𝑊𝑖 ∗ 𝐸(𝑃𝑖)                          𝑤ℎ𝑒𝑟𝑒   𝑊𝑖 = 1  
!!! !!!

10
 
Now  we  further  discuss  the  portfolio  variance  model  by  adding  new  assumptions:    
1. Each   asset   is   a   portfolio,   composed   by   several   non-­‐divisible   assets   (e.g.  
stock,  gold,  and  bond).  
2. Some   of   the   assets   share   same   non-­‐divisible   assets   (e.g.   portfolio   A   and   D  
both  include  IBM  stock).  
 
In   the   portfolio   variance  matrix  model,  there  are  2  components:  the  first  one  is  the  
weight  vector  (the  weight  of  each  asset),  and  the  second  one  is  variance-­‐covariance  
matrix.  We  could  apply  normalization  method  to  get  each  portfolio’s  weight  in  the  
pool,  and  then  formulate  the  weight  vector.  We  have  discussed  the  matrix  model  to  
calculate   portfolio´s   variance,   now   we   further   discuss   the   model   to   calculate   the  
covariance  of  two  portfolios.  
 
*IN-­‐DEPTH  DISCUSSION    
Note   that   we   could   not   consider   each   portfolio   as   an   asset,   and   apply   the   simple  
covariance  method  that  is  used  to  calculate  the  covariance  of  two  assets,  as  it  ignores  
the  covariance  between  an  asset  in  portfolio  A  and  another  asset  in  portfolio  B.      
To  calculate  the  covariance  between  two  portfolios  X  and  Y  
 
  σ xy =   Cov rx , ry = x T Sy = y T Sx
( )
      ! σ 11 σ 21 ! σ N 1 $! y1 $
# &# &
  $# σ 12 σ 22 ! σ N 2 &# y 2 &
= !# x1 x2 ! x N &%# &# &
  "
# ! &# &
# σ 1N σ 2N ! σ NN &%#" y N &
  " %
N N
  = ∑∑ xi y j σ ij
  i =1 j =1

Now  consider  a  portfolio  manager  manages  2  portfolios,  X  and  Y.  The  investment  
pool   includes   5   stocks,   A,   B,   C,   D,   and   E.   The   size   of   portfolio   X   is   1   million,   and   the  
stocks   are   A   (0.5   mil),   B   (0.3   mil),   and   C   (0.2   mil).   The   size   of   portfolio   Y   is   2  
million,   and   the   stocks  are   C   (1   mil),  D  (0.8  mil)  and  E  (0.2  mil).  To  calculate  the  
covariance  of  X  and  Y,  we  first  need  to  construct  a  5x5  variance-­‐covariance  matrix  
11
of  the  5  stocks.  Next,  we  apply  the  weight  vector  [    .5    .3    .2    0    0    ]  for  portfolio  X  
and  weight  vector  [    0    0    1    .8    .2    ]  for  Y.  The  sum  of  the  weights  of  vector  X  is  1  and  
vector   Y   is   2,   which   represents   the   total   size   of   each   portfolio.   Lastly,   we   apply   the  
matrix  formula  to  calculate  the  covariance  between  X  and  Y.    
 
   
 
 
 
 
 
 
 
 
 
 
 
   

12
1.1.3. Efficient  Frontier  and  GMVP    
A  combination  of  assets,  or  a  portfolio,  is  referred  to  be  “efficient”  if  it  has  achieved  
the   best   possible   expected   return   for   the   respective   level   of   risk   (proxy   of   the  
standard  deviation  of  the  portfolio´s  return).  Every  possible  combination  of  risky  
assets,  without  holding  any  risk-­‐free  asset,  can  be  plotted  in  risk-­‐-­‐return  space,  and  
the   collection   of   all   such   possible   portfolios   defines   a   region   in   the   space.   The  
upward   sloped   boundary   of   the   region   is   called   “efficient   frontier”.   The   efficient  
frontier   is   the   positively   sloped   portion   of   the   opportunity   set   that   offers   the  
highest  expected  return  for  a  given  level  of  risk.  The  efficient  frontier  lies  at  the  top  
of   the   opportunity   set   or   the   feasible   set.   Suppose   there   are   N   assets   having   a  
variance-­‐covariance   matrix   S.   The   Global   Minimum   Variance   Portfolio   (GMVP)   is  
the   portfolio   x   =   {x1,   x2,   .   .   .   ,   xN}   that   has   the   lowest   variance   from   among   all  
feasible  portfolios.  The  GMVP  is  located  at  the  left-­‐most  of  the  efficient  frontier,  i.e.  
the  point  that  has  the  minimum  standard  deviation.  The  envelope  portfolio  line  is  
composed   by   envelop,   but   inefficient   portfolios,   which   means   according   to   same  
risk  level,  an  investor  could  find  higher  return  combination  (e.g.  from  the  efficient  
frontier).   We   could   see   efficient   frontier,   envelope   portfolio   line   and   global  
minimum  variance  portfolio  from  Figure  3.1.    

Figure  3.1  

Proposition  1  
13
All   envelop   portfolios   solve   the   following   equation   below.   Where   c   is   risk   free   rate  
and  S-­‐1  is  the  inverse  matrix  of  the  variance-­‐covariance  matrix.  Result  x  is  a  weight  
vector  that  consists  of  each  asset’s  weight.  The  result  may  not  be  efficient.    
 
  S −1 {E ( r ) − c}
x= −1
  ∑ S {E ( r ) − c}
 
Proposition  2  
The   convex   combination   of   any   two   envelope   portfolios   is   also   an   envelope  
portfolio.    
 
Proposition  1  and  2  shows  the  method  to  compute  the  envelope  (i.e.  the  blue  curve  
in   Figure   3.1).   Frist,   we   compute   any   two   envelope   portfolios   X   and   Y.   Do   this   with  
two  risk  free  rate  Cx  and  Cy.  Second,  we  compute  the  mean  and  standard  deviation  
of   all   convex   combinations   of   X   and   Y.   Note   that   if   the   two   portfolios   are   fixed,   you  
could   change   C   to   get   different   portfolio   combination,   however,   all   the   convex  
combination   will   locate   on   the   same   curve   (could   be   either   envelop   portfolio   or  
efficient   portfolio).   We   conclude   that   the   constant   rate   C   is   irrelevant   to   determine  
the  envelope.    
 
NO  CONSTRAINTS:  Calculate  Global  Minimum  Variance  Portfolio  (GMVP)    
 
  GMVP =
{1,...,1} S −1
⎧1⎫
 
{1,...,1} S ⎪⎨M⎪⎬
−1

  ⎪1⎪
⎩ ⎭
 
The  above  calculation  will  result  a  vector  to  represent  the  weight  of  each  asset  in  
this   portfolio.   This   formula   could   be   used   to   calculate   GMVP   only   if   the   portfolio  
has   no   constraints.   If   there   are   constraints   that   affect   the   weights   of   assets,   for  
example,   the   portfolio   must   allocate   at   least   30%   to   asset   X,   or   no   short   sell  
allowed,  we  need  to  adopt  the  portfolio  variance  formula  that  we  have  discussed  
before,  minimize  the  variance  through  changing  the  weights  of  each  asset.    
1.1.4. Sharpe  Ratio  and  Optimal  Portfolio    
14
Sharpe   Ratio   is   used   to   measure   risk   adjusted   performance.   It   is   a   measure   of  
excess  return  (risk  premium)  per  unit  of  risk  (or  deviation)  of  asset.    
 
𝐸[  𝑅 − 𝑅𝑓] 𝐸[  𝑅 − 𝑅𝑓]
𝑺𝒉𝒂𝒓𝒑𝒆  𝑹𝒂𝒕𝒊𝒐 = =  
𝑆𝐼𝐺𝑀𝐴 𝑉𝐴𝑅 𝑅 − 𝑅𝑓
 
Where   R   is   the   asset   return,   Rf   is   risk   free   rate   (or   benchmark   asset   return).  
𝐸  𝑅 − 𝑅𝑓  is  the  expected  excess  return  over  the  risk  free  rate,  and  SIGMA  is  the  
asset   volatility   (i.e.   the   risk).   The   Sharpe   ratio   is   used   to   characterize   how   well   the  
return   of   an   asset   compensates   the   investor   for   the   risk   taken,   the   higher   the  
sharpe   ratio   the   better.  Sharpe   ratio   is   often   used   in   measuring   the   mutual   fund  
performance.   There   are   several   weakness   associates   with   sharpe   ratio.   The   sharpe  
ratio  tends  to  be  “inflated”  in  the  case  of  hedge  funds  with  short  records,  and  could  
not   inflect   the   real   risk   of   the   investment.   The   sharpe   ratio   is   also   difficult   to  
interpret,   for   example,   we   could   not   measure   how   much   better   is   an   investment  
with  a  0.5  sharpe  ratio  than  the  one  with  a  ratio  of  0.1.    
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
   

15
1.2. The  Black  Scholes  Model    
 
1.2.1. Understanding  Black  Scholes  Model      
Black  Scholes  Model  is  of  price  variation  over  time  of  financial  instruments  such  as  
stocks  that  can,  among  other  things,  be  used  to  determine  the  price  of  a  European  
call   option.    The   model  assumes   that  the   price   of   heavily   traded   assets   follow  
a  geometric  Brownian  motion  (to  be  discussed  in  next  section)  with  constant  drift  
and   volatility.  Many   empirical   tests   have   shown   the   Black–Scholes   price   is   “fairly  
close”  to  the  observed  prices.    
 
The  Black  Scholes  model  follows  assumptions:  
1. The  stock  price  is  log-­‐normally  distributed.  
2. The   stock   price   follows   geometric   Brownian   motion   with   constant   drift  
(expected  return)  and  volatility.    
3. The  stock  has  no  dividends  before  maturity.    
4. European  style.  Cannot  exercise  before  maturity.    
 
The  call  and  put  option  prices  are  given  by  

 
 
Where  N(  )  indicates  values  of  the  standard  normal  distribution.    
σ  is  the  standard  deviation  of  return  of  stock.    
T  is  the  time  to  maturity  of  the  option.    
X  is  the  strike  price.    
 

16
The   model   proof   is   based   on   arbitrage   between   the   stock   and   risk   free   rate.   The  
arbitrage  is  dynamic,  meaning  that  premium  is  continuously  updated,  depends  on  
the  Stock  price,  time  to  maturity,  riskness  of  stock  return  !,  and  the  dynamic  risk  
free   rate   r.   Note   that   the   exercise   price   X   is   static,   although   it   is   a   determinant  
factor  of  the  option  premium.      
 
Adjust  for  Discrete  and  Continuous  Dividends  
To   price   an   option   with   known/expected   discrete   dividends,   instead   of   using  
current   stock   price,   we   apply   the   adjusted   stock   price   in   Black   Scholes   model   to  
derive  the  option  price.    
 
𝐴𝑑𝑗𝑢𝑠𝑡𝑒𝑑  𝑃𝑟𝑖𝑐𝑒 = 𝑆𝑝𝑜𝑡  𝑃𝑟𝑖𝑐𝑒 − 𝑃𝑉  𝑜𝑓  ∑𝑑𝑖𝑣𝑖𝑑𝑒𝑛𝑑𝑠  
 
To  price  an  option  on  a  stock  that  pays  continuous  dividends  (such  as  an  option  for  
S&P   500   index),   we   need   to   apply   the   Merton   Model   (derived   from   the   Black-­‐
Scholes  Model).  For  details,  please  refer  to  Financial  Modeling  3rd  Edition  (Simon  
Benninga).          
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

17
1.3. Monte  Carlo  Simulation    
 
1.3.1. Understanding  Monte  Carlo  Methods    
Monte   Carlo   Simulation   is   a   computational   algorithm   that   relies   on   repeated  
random   sampling   to   compute   the   results.   This   simulation   is   most   suited   to  
calculation   by   a  computer  and   tends   to   be   used   when   it   is   infeasible   to   compute   an  
exact   result   with   a   deterministic   algorithm.   This   method   is   also   used   to  
complement   the   theoretical   derivations   and   to   simulate   systems   with  
many  coupled  degrees  of  freedom.    
 
In   finance,   Monte   Carlo   methods   are   used   to   value   and   analyse   complex   portfolios,  
instruments   and   investments   through   simulating   the   various   sources   of  
uncertainty   affecting   their   value,   and   then   determining   the   their   average   value  
over   the   range   of   result   outcomes.   The   advantage   of   Monte   Carlo   methods   over  
other   techniques   increases   as   the   dimensions   (sources   of   uncertainty)   of   the  
problem  increase.  
 
There  are  several  disadvantages  that  are  associated  with  such  simulation.  First  one  
is   time   consuming   and   computationally   wasteful.   If   the   mathematic   model   is  
available,  we  could  apply  the  model  to  calculate  the  result  with  few  steps.  However,  
due   to   the   accuracy,   to   simulate   an   approximate   result   may   require   millions   of  
simulations.  Another  advantage  is  that  Monte  Carlo  Simulation  is  an  approximate  
calculation,  not  exactly  equal  to  the  result  that  we  derive  from  those  models.  
 
 
1.3.2. Apply  Monte  Carlo  Method  to  Compute  π  
First   we   draw   a   square,   each   side   length   is   2,   and   the   area   is   4.   Then   we   draw   a  
circle  in  the  square  and  its  area  is  π.  Put  the  circle   1.0

and  square  in  an  Axis,  and  the  center  is  (0,0).  The  
circle  in  the  upper  right  hand  quadrant  has  area  of   0.5

π/4,  and  all  points  in  this  area,  (x,  y),  complies  with  
-1.0 -0.5 0.5 1.0
the  condition  that    0   ≤ 𝑥, 𝑦   ≤ 1.    

-0.5 18

-1.0
 
 
 
1.4. Brownian  Motion    
In   this   sub-­‐chapter,   we   derive   two   specific   mathematical   models   to   simulate   the  
stock   price   and   return   movement,   which   are   Geometric   Brownian   Motion   and  
Brownian   Motion,   respectively.     They   are   two   of   the   most   fundamental   and  
common   formats   of   Monte   Carlo   Simulation.   The   Brownian   Motion   follows   the  
assumptions  of  Black  Scholes  model,  and  is  a  part  of  the  derivation  of  Black  Scholes  
model,  thus  we  discuss  the  method  to  simulate  fair  European  call  option  price,  and  
compare  with  the  price  that  we  get  from  Black  Scholes  model.    
 
1.4.1. Derive  Geometric  Brownian  Motion  (GBM)  Formula    
GBM  model  is  one  of  the  most  basic  formats  of  Monte  Carlo  Simulation,  and  is  used  
to   simulate   the   stock   price.   Technically,   it   is   a   Markov   process:   the   stock   price  
follows   a   random   walk   and   is   consistent   with   the   efficient   market   hypothesis:   past  
price  information  is  incorporated  and  the  next  price  movement  is  independent  of  
past  price  movements.  By  knowing  this,  we  can  derive  the  formula  that  calculates  
stock  price  on  period  1  (S1),  based  on  stock  price  on  period  0  (S0):      
 
𝑆1
𝑆1 = 𝑆0 ∗ 𝐸𝑥𝑝 𝑅                        𝐴𝑠      𝑅 =  𝐿𝑛  
𝑆0
 
Here,   we   follow   the   two   assumptions   of   Black   Scholes   model:   return   is   normally  
distributed,  and  stock  price  is  log-­‐normally  distributed  (could  be  concluded  from  
the  formula  as  well).    
 
Firstly,  we  derive  the  formula  as  following:  
𝑆1 = 𝑆0 ∗ 𝐸𝑥𝑝(𝑒𝑥𝑝𝑒𝑐𝑡𝑒𝑑  𝑟𝑒𝑡𝑢𝑟𝑛 + 𝑢𝑛𝑒𝑥𝑝𝑒𝑐𝑡𝑒𝑑  𝑣𝑜𝑙𝑎𝑡𝑖𝑙𝑖𝑡𝑦)  
 
Secondly,  we  derive  the  expected  return  during  the  time  interval:  
𝑒𝑥𝑝𝑒𝑐𝑡𝑒𝑑  𝑟𝑒𝑡𝑢𝑟𝑛 =    µμ ∗ 𝛥𝑡  
µ  =  expected  return  during  the  period  

19
𝛥𝑡  =  time  interval.  
 
 
Thirdly,  we  derive  the  unexpected  volatility:    
𝑒𝑥𝑝𝑒𝑐𝑡𝑒𝑑  𝑣𝑜𝑙𝑎𝑡𝑖𝑙𝑖𝑡𝑦 =   𝑒𝑥𝑝𝑙𝑎𝑖𝑛𝑒𝑑  𝑣𝑎𝑟𝑖𝑎𝑛𝑐𝑒  

𝑒𝑥𝑝𝑒𝑐𝑡𝑒𝑑  𝑣𝑜𝑙𝑎𝑡𝑖𝑙𝑖𝑡𝑦 =   𝑠𝑖𝑔𝑚𝑎! ∗ 𝛥𝑡   = 𝑠𝑖𝑔𝑚𝑎 ∗ 𝛥𝑡    


𝑢𝑛𝑒𝑥𝑝𝑒𝑐𝑡𝑒𝑑  𝑣𝑜𝑙𝑎𝑡𝑖𝑙𝑖𝑡𝑦 = 𝑍 ∗ 𝑒𝑥𝑝𝑒𝑐𝑡𝑒𝑑  𝑣𝑜𝑙𝑎𝑡𝑙𝑖𝑡𝑦  
Where  Z  is  a  random  deviate  and  Z~N(0,1).    
 
Now  we  have  completed  the  formula:    
𝑆1 = 𝑆0 ∗ 𝐸𝑥𝑝(  µμ ∗ 𝛥𝑡 + 𝑠𝑖𝑔𝑚𝑎 ∗ 𝛥𝑡 ∗ 𝑍)  

 
 
1.4.2. Geometric  Brownian  Motion    
We   need   to   understand   that   the   Brownian   Motion   is   different   from   Geometric  
Brownian  Motion  as  it  is  used  to  simulate  periodical  stock  return.  The  stock  price  
change  (i.e.  return)  is  a  function  of  its  price  and  time.  Such  simulation  follows  the  
Ito  Process  (the  proof  of  Ito  Process  is  beyond  this  book).    
From  previous  section,  we  have  derived  
   
𝑆1 = 𝑆0 ∗ 𝐸𝑥𝑝(  µμ ∗ 𝛥𝑡 + 𝑠𝑖𝑔𝑚𝑎 ∗ 𝛥𝑡 ∗ 𝑍)  
𝑆1
ln =  µμ ∗ 𝛥𝑡 + 𝑠𝑖𝑔𝑚𝑎 ∗ 𝛥𝑡 ∗ 𝑍  
𝑆0
 
So  we  generalize  it:                          𝑑𝑥 = µμ 𝑥, 𝑡 ∗ 𝑑𝑡 + 𝑠𝑖𝑔𝑚𝑎(𝑥, 𝑡) ∗ 𝑑𝑍  

20
 
Where  z  and  t  are  same  as  before,  µμ  (x,  t),  and  sigma(x,  t)  are  the  functions  of  x  and  
t.  The  expected  return  rate  is  µμ  (x,  t)  and  variance  is  sigma2.  Ito’s  lemma  shows  that  
a  function  df(t,  x)  follows  the  Ito  ‘s  process    
 

 
 
This  function  follows  an  Ito  Process,  with  an  expected  rate  of  return:  
 
 
 
And  standard  deviation  of    
 
Now   we   derive   this   formula   by   Taylor   expansion,   and   let   x=S   (stock   price).   We  
have  
 
ð𝑓 ð𝑓 1 ð! 𝑓 ! ! ð𝑓
𝑑𝑓 = ∗ µμ ∗ 𝑆 +   + ∗ ! ð 𝑆 ∗ 𝑑𝑡 + ∗ 𝑠𝑖𝑔𝑚𝑎 ∗ 𝑆 ∗ 𝑑𝑍  
ð𝑆 ð𝑡 2 ð𝑆 ð𝑆
 
Let    f(t,  S)  =  ln  S.  Now  that  we  have  the  formula  (sigma  =  !,  interchangeable).      
 
Now  we  have  derived  the  GBM  formula  to  simulate  the  stock  return.    
 
𝑠𝑖𝑔𝑚𝑎!
𝑑𝑓 = µμ − ∗ 𝑑𝑡 + 𝑠𝑖𝑔𝑚𝑎 ∗ 𝑍 ∗ 𝑑𝑡  
2
 
 
 
1.4.3. Evaluate  European  Option  Fair  Price  
Assumes  that  one  investor  want  to  purchase  a  European  call  option  of  IBM  stock.  
The  option  contract  has  the  following  features:  the  expected  annual  return  of  IBM  

21
stock   is   10%,   stock   volatility   is   20%,   and   contract   maturity   in   1250   days.   The  
investor  wants  to  apply  GBM  model  to  explore  the  fair  price  of  this  contract.    
 
 
Step  1    
Use  GBM  model  to  simulate  1  million  stock  prices  at  30th  day.  
Step  2  
Calculate  the  payoff  of  holding  this  call  option.  Est(i)  =  ith  simulated  price.    
If  stock  price  >  strike  price,  payoff  =  Est(i)  –  strike.        
Otherwise,  payoff  =  0  
𝐹𝑎𝑖𝑟  𝑃𝑟𝑖𝑐𝑒 =  𝐸𝑥𝑝𝑒𝑐𝑡𝑒𝑑  𝑃𝑎𝑦𝑜𝑓𝑓 =   ∑ 𝑚𝑎𝑥 𝐸𝑠𝑡 𝑖 − 𝑆𝑡𝑟𝑖𝑘𝑒, 0 1,000,000  
Step  3  
Now,   compare   the   simulated   fair   price   and   the   option   price   that   we   calculate   from  
Black  Scholes  model,  we  could  conclude  that  as  the  number  of  simulations  tends  to  
infinity,  the  difference  between  the  two  prices  tends  to  zero.    
 

22
1.5. Variance  Reduction  Techniques  
 
There  are  several  variance  reduction  techniques.  I’m  going  to  focus  in  the  ones  that  
involve  direct  manipulation  of  the  random  number  set.    

1.5.1. Common  Random  Number  


All   math   softwares   have   a   function   to   generate   random   numbers   uniformly  
distributed   in   the   0   to   1.     So   to   generate   a   set   of   random   numbers   that   have   a  
normal   distribution   (0,1)   you   can   start   from   a   uniformly   distributed   set   of  
numbers  and  apply  the  inverse  of  the  normal  probability  function.    This  is  our  base  
case  scenario.  

1.5.2. Antithetic  Variates  


When  we  generate  a  random  set  of  normally  distributed  numbers  with  mean  0  and  
standard  deviation  1,  N(0,1),  chances  are  that  if  the  set  is  really  random  its  mean  is  
not   exactly   0.   So   if   I   need   100   N(0,1)   numbers   y   randomly   generate   50   and   the  
other   50   are   just   the   original   ones   with   a   negative   sing.     The   rationale   behind   is  
that   the   final   set   would   better   fit   a   normal   distribution   and   thus   reduces   the  
solution  variance.    An  additional  advantage  of  this  method  is  that  as  generate  only  
half  of  the  numbers  require  it  should  take  less  time  to  compute.    Remember  that  
the   final   objective   of   reducing   variance   is   to   reduce   simulation   number   thus  
simulation  time.  

1.5.3. Moment  Matching  


In   statistics   the   moments   of   a   discrete   set   of   numbers   are   the   parameters   of   the  
population,   the   first   moment   is   the   mean,   the   second   moment   is   the   standard  
deviation.     As   we   are   trying   to   generate   a   normal   distribution   that   is   defined   by  
two   parameters   we   are   only   going   to   work   with   the   first   two   moments.   Moment  
Matching   takes   the   same   idea   of   Antithetic   Variates   (AV)   but   take   it   a   little   bit  
further.     So   we   are   going   to   generate   the   random   set   and   then   apply   a  

23
transformation   to   force   the   set   to   have   a   mean   =   0   and   stdev   =   1.     The  
transformation  is  given  by:  

𝑧! − 𝑧
𝑧! =  
𝜎!

When  doing  AV  we  are  already  matching  the  first  moment  of  the  population,  so  one  
alternative  to  the  transformation  is  to  do  AV  first  and  then  dividing  by  the  stdev  to  
match   the   second   moment.     I   will   consider   this   alternative   separately   to  
understand  which  method  is  really  helping.  

1.5.4. Stratified  Sampling  


By   matching   the   first   to   parameters   of   a   “normal   population”   we   make   sure   that  
the  mean  and  stdev  are  as  required.    But  the  shape  of  the  distribution  me  still  be  
different   in   some   one.     One   possibility   is   to   match   further   moments   of   the  
distribution,   jet   another   is   to   stratify   the   sample.     Remember   that   we   are   first  
generating   de   uniformly   distributed   U(0,1)   numbers   and   then   applying   the   normal  
inverse,   so   instead   of   generating   the   whole   amount   of   numbers   needed   in   (0,1)  
range  we  divide  the  range  in  bins.  

Suppose  that  we  want  to  generate  100  random  U(0,1)  numbers.    What  we  can  do  is  
to   divide   the   range   in   10   smaller   ranges   (0,   0.1);   (0.1,   0.2);   ...;   (0.9,   1)   and   generate  
10   random   numbers   in   each   bin.   In   this   way   I   will   make   sure   that   all   the   (0,1)  
range  is  better  uniformly  cover.    Thus  when  applying  the  normal  transformation  I  
would  get  a  better  normal  distribution.    To  graphic  this  method  I  have  generated  
two   set   of   2000   random   U(0,1)   numbers.   The   first   one   using   just   2000   random  
numbers  in  (0,1).    For  the  second  one  I  divided  the  (0,1)  range  in  100  bins  and  I  
generated   20   random   numbers   for   each   bin.     Then   I   applied   the   normal  
transformation  to  each  set  and  graph  the  histograms  of  the  result.  

24
0.4 0.4

0.3 0.3

0.2 0.2

0.1 0.1

0 0
-­‐5 0 5 -­‐5 0 5
 
Figure  1:  Left:  random  generated  normal  distribution.    Right:  generated  using  stratified  sampling.  

As  you  can  see  the  second  set  fits  the  normal  shape  far  better.  

1.5.5. Quasi-­‐Random  Sequences  


As  the  name  already  suggest  these  methods  are  not  random.    The  main  objective  of  
Quasi-­‐Random   sequences   is   to   populate   a   given   space   or   range   in   an   even   way.    
There   are   several   algorithms   that   generate   quasi   random   sequences   I’m   going   to  
work   with   Halton   sequence   and   Sobol   Sequence.     Both   algorithms   are   already  
embedded   in   MATLAB,   so   I   not   going   into   detail   explanation   of   the   algorithms  
themselves.     What   is   important   to   understand   is   that   these   sequences   are  
deterministic,  this  is  to  say  that  each  time  that  the  generation  algorithm  is  run  the  
result   is   the   same.       These   sequences   are   not   random   at   all,   but   as   the   sequence  
generates   infinite   points,   we   can   choose   to   start   picking   numbers   at   whatever  
point  we  want.    In  this  way  we  add  some  randomness.    The  idea  behind  using  quasi  
random   sequences   is   continuing   to   work   in   the   same   direction   of   stratified  
sampling.     If   we   start   with   a   better   evenly   distributed   set   of   numbers   we   are   going  
to  get  a  better  fit  to  the  normal  distribution  that  we  are  trying  to  generate.  

To   better   understand   how   quasi   random   sequence   work   we   are   going   to   set   an  
example.   We   are   going   to   approximate   the   area   of   a   “lake”   counting   how   many  
points   of   a   2   dimension   random   set   of   numbers   lay   inside   the   polygon   that  
determines   the   lake.     I   took   this   idea   from   Mathworks.com   (MATLAB   webpage).    
The   area   of   the   polygon   shown   in   Figures   2,   3   and   4   is   1920.1.   Each   set   consists   of  
2000  points.  

25
100

90

80

70

60

50

40

30

20

10

0
0 10 20 30 40 50 60 70 80 90 100

 
Figure  2:  Scatter  plot  of  a  2  dimension  set  of  random  U(0,100)  numbers.  Points  inside  361.  Area  
proxy  =  1805.  

100

90

80

70

60

50

40

30

20

10

0
0 10 20 30 40 50 60 70 80 90 100

 
Figure  3:  Scatter  plot  of  a  2  dimension  set  of  Halton  Sequence  Numbers.  Points  inside  384.  Area  
proxy  =  1920  

26
100

90

80

70

60

50

40

30

20

10

0
0 10 20 30 40 50 60 70 80 90 100

 
Figure  4:  Scatter  plot  of  a  2  dimension  set  of  Sobol  Sequence  Numbers.  Points  inside  384.  Area  
proxy  =  1920.  
 
If   we   compare   Figure   2,   Figure   3   and   Figure   4,   we   can   see   that   in   the   first   case   the  
area   of   the   graph   is   cover   randomly   leading   to   zones   of   more   density   of   points   and  
areas  with  less  density.  While  in  Figures  3  and  4  the  points  are  evenly  distributed.    
In  Figure  4  is  easy  to  see  the  pattern  that  the  Sobol  algorithm  generates.  

1.5.6. Applications  to  Option  Pricing  


Different  method  of  generating  the  random  set  of  numbers  in  Monte  Carlo  would  
have  different  processing  times.    So  if  we  can  find  an  excellent  variance  reduction  
method   but   that   takes   very   long   to   compute   its   benefits   would   probably   be  
compensated  by  its  deficiencies.    Even  if  in  general  these  methods  are  call  variance  
reduction   methods   its   final   objective   is   to   generate   more   efficient   Monte   Carlo  
simulations,  so  we  need  a  measure  of  efficiency  that  takes  into  consideration  not  
only  the  variance  reduction  but  also  the  computing  time.  

As   measure   to   compare   the   different   methods   I’m   going   to   use   the   indicator  
proposed   by   Boyle,   Broadie   and   Glasserman   (1997)   by   which   method   1   is   better  
than  method  2  if:  

𝜎!! 𝑏! < 𝜎!! 𝑏!  

27
Where  𝑏!  and  𝑏!  are  the  mean  time  by  simulation  for  each  case,  and  𝜎!!  𝜎!!  are  the  
variances  of  the  solution  estimator.  

And  just  to  get  a  simpler  understanding  I  divided  the  indicator  each  method  by  the  
indicator  of  the  base  scenario,  to  get  a  multiple  of  improvement  with  each  method.  

As   many   all   these   methods   involve   manipulating   the   Z(0,1)   set,   then   we   cannot  
assume   that   the   standard   deviation   of   the   result   is   an   unbiased   estimator.   To  
overcome  this  problem  I  run  each  Monte  Carlo  simulation  100  times.    And  to  better  
understand  how  each  method  perform  when  increasing  the  number  of  simulations  
I  also  run  each  method  varying  the  number  of  simulations  for  each  run.      

For  example  I  configure  the  process  to  get  the  indicator  for  the  base  case  scenario  
with   normally   generated   set,   I   run   that   method   with   100   simulations   100   times,  
then  with  200  simulations  100  times,  and  so  on  till  I  got  to  1000  simulations  100  
times.  Then  I  repeat  the  same  procedure  for  each  method.  

And   finally   I   repeated   this   procedure   for   the   two   types   of   options   I’m   going   to  
value.  

1.5.6.1. European  Call  Option  


The  first  test  is  run  for  a  European  call  option  with  the  following  parameters.  

   S                =  100;      %price  of  the  underlying  


   K                =  100;      %strike  price  
   KO              =  120;      %Up  &  Out  Barrier  Limit  
   r                =  0.05;    %risk  free  rate  
   sigma        =  0.2;      %standard  deviation  
   T                =  1;          %time  to  maturity  
   div            =  0;          %continiuous  dividend  yield  
%  NSim          =  100;      %number  of  simulations  
   NSteps      =  1;          %number  of  steps  in  each  simulation  
   NVar          =  1;          %number  of  simulated  variables  
%  GenType    =  ;            %Random  Number  Algorithm  

 
The  price  of  such  an  option  calculated  with  Black-­‐Scholes  formula  is  10.451.  And  
the  results  are  graph  below.  

28
 
Graph  1:  Mean   Price   achieved   with   each   method   for   a   given   number   of   simulations   for   a   European  
Call  option.  

 
Graph  2:    Mean  Standard  Deviation  achieved  with  each  method  for  a  given  number  of  simulations  
for  a  European  Call  option.  

29
 
Graph  3:     Performance   Indicator   achieved   with   each   method   for   a   given   number   of   simulations   for  
a  European  Call  option.  
 
In   Graph   1   you   can   see   how   prices   of   the   European   call   option   tend   towards   the  
real  Black-­‐Scholes  price.    The  common  random  generator  method  is  labeled  in  blue  
as  ‘Normal’.  We  can  see  that  the  ‘normal’  and  the  ‘antithetic’  methods  oscillate  a  lot  
but   the   rest   of   the   methods   performed   very   well.   This   is   supported   by   information  
in  Graph  2  where  we  can  see  how  confidence  intervals  are  smaller  as  simulations  
increase.  Aging  the  normal  an  antithetic  methods  produce  much  larger  confidence  
intervals   than   the   rest   of   the   methods,   but   the   rest   of   the   methods   seems   to  
perform  quite  evenly.  

With  only  that  information  is  not  possible  to  make  a  conclusion  of  the  performance  
of  the  last  5  methods.      

In  Graph  3  we  can  see  the  Performance  indicator  described  in  Section  6.  Now  we  
can  clearly  see  that  the  Stratified  method  is  the  best  performing  in  the  range  from  
100   to   800   simulations   with   a   performance   multiple   of   around   80,   follow   by   the  
Moment   Matching.     But   we   can   also   see   that   its   performance   is   more   or   less  
constant  regardless  the  number  of  simulations.  This  can  be  explained  because  the  
computational   time   to   generate   each   new   number   to   the   set   is   constant,   so   the  
increase  performance  to  the  base  case  is  also  constant.  

In   the   case   of   the   quasi   random   sequences,   we   can   clearly   see   that   performance  
over  the  common  random  numbers  increased  with  the  number  of  simulations.    The  

30
explanation   may   be   hidden   in   the   sequence   generation   algorithm.     If   we   were   to  
generate   the   sequence   in   the   code   then   it   would   be   expected   to   have   a   similar  
behavior   than   the   Stratified   method.   But   the   case   is   that   the   sequence   is   not  
generated  every  run  but  it  is  already  saved  in  with  software  internal  memory.  So  
when  we  run  the  test  the  software  take  some  time  to  access  the  memory  position  
and  then  read  the  sequence,  thus  for  each  extra  simulation  the  increase  computing  
time  is  decreasing.    This  explain  the  increase  performance  with  time.  

1.5.6.2. European  Down  and  Out  Barrier  Option  


The  second  test  is  run  for  a  European  call  down  and  out  option  with  the  following  
parameters.  

   S                =  100;      %price  of  the  underlying  


   K                =  100;      %strike  price  
   B                =  85;        %Down  &  Out  Barrier  Limit  
   r                =  0.05;    %risk  free  rate  
   sigma        =  0.3;      %standard  deviation  
   T                =  0.25;    %time  to  maturity  
   div            =  0;          %continiuous  dividend  yield  
%  NSim          =  100;      %number  of  simulations  
   NSteps      =  100;      %number  of  steps  in  each  simulation  
   NVar          =  1;          %number  of  simulated  variables  
%  GenType    =  ;            %Random  Number  Algorithm  

31
The  close  form  Black-­‐Scholes  price  is  6.5.  The  results  are  graph  below.  

 
Graph  4:  Mean   Price   achieved   with   each   method   for   a   given   number   of   simulations   for   a   European  
Call  Down  and  Out  option.  
 

32
 
Graph  2:    Mean  Standard  Deviation  achieved  with  each  method  for  a  given  number  of  simulations  
for  a  European  Call  Down  and  Out  option.  

33
Graph  6:     Performance   Indicator   achieved   with   each   method   for   a   given   number   of   simulations   for  
a  European  Call  Down  and  Out  option.  
 

In  the  case  the  barrier  option  the  main  difference  in  the  valuation  algorithm  is  that  
barrier  options  are  path  dependent.    So  we  not  only  have  to  simulate  the  price  at  
time  =  T  but  also  prices  for  each  intermediate  t.    So  we  are  adding  dimensions  to  
the   simulation,   in   Monte   Carlo   each   new   dimension   add   computing   time  
exponentially.    The  time  taken  by  the  transformations  of  the  random  numbers,  lose  
importance  relative  to  time  to  compute  all  mathematical  operations  from  the  code.    
And  that’s  why  all  methods  perform  similarly.      

We  can  see  that  Halton  performs  particularly  badly,  I  can  find  no  final  explanation  
to  that  behavior,  but  I  it  must  be  related  with  the  way  the  sequence  dimensions  are  
allocated  to  Monte  Carlos  model  dimensions.    It  is  important  to  notice  than  price  
and  interval  confidence  for  Halton  performs  even  worse  than  the  common  normal  
random  generator.    So  the  Halton  method  is  the  case  base  for  this  test  run.  

Finally   we   can   still   see   that   Moment   Matching   is   the   best   performing   method   for  
this   option   type.   But   please   notice   that   if   we   take   in   consideration   both   variance  
reduction  and  time  many  of  the  methods  performed  worse  than  normal.    Even  the  
best  performing  methods  are  only  better  by  a  factor  of  between  1.5  and  2  respect  
to  the  normal  which  is  not  at  all  conclusive.  

34
   

35
1.6. Introduction  to  correlation  
 
1.6.1. Why  is  correlation  useful  in  finance?  
Correlation  is  of  incredible  importance  in  finance.  Many  of  the  most  used  financial  
theories,  such  as  the  capital  asset  pricing  model  or  the  arbitrage  pricing  theory,  use  
correlation   as   a   measure   of   dependence   between   different   financial   instruments.  
Professionals   working   in,   for   example,   asset   allocation   or   risk   management   must  
be   very   aware   of   the   correlation   between   different   financial   instruments   to  
successfully   manage   their   risk.   Common   examples   of   the   use   of   correlation   to  
manage   risk   are   portfolio   diversification   and   hedging.   By   diversifying   between  
different   assets,   portfolio   managers   try   to   reduce   non-­‐systemic   risk.   However,   it   is  
important   to   take   into   account   the   correlation   between   these   assets   to   correctly  
reduce  the  diversifiable  risk,  as  it  will  not  provide  risk  protection  when  the  assets  
are   (strongly)   positively   correlated.   Hedging   relies   on   positive   or   negative  
correlation   between   assets,   where   the   risk   will   be   reduced   by   going   long   on   an  
asset  with  negative  correlation  or  shorting  an  asset  with  positive  correlation.  
 
This   chapter   focuses   on   how   to   use   correlation   in   financial   modeling   and   more  
specifically,   how   to   generate   correlated   random   numbers.   Random   number  
generation   is   at   the   core   of   Monte   Carlo   simulation   methods,   which   have   countless  
applications   in   finance.   As   it   is   at   the   core   of   these   methods,   it   is   of   incredible  
importance   to   generate   random   numbers   that   inhibit   correct   correlation.  
Otherwise,  the  results  of  the  simulation  will  probably  be  flawed.  
This   note   will   explain   the   most   important   concepts   in   correlation   and   financial  
modeling  and  how  to  practically  generate  correlated  random  numbers.  Specifically  
the   software   package   MATLAB   will   be   used.   As   a   case   study,   the   correlation  
between  selected  equity  index  returns  is  investigated  using  copulas.  
   

36
 
1.6.2. Variance,  covariance  and  covariance  matrix  
The  variance  measures  the  width  of  a  probability  distribution  or  the  spread  of  data  
points  around  their  mean.  The  larger  the  variance  is,  the  wider  the  distribution  or  
the  spread  of  data  around  the  mean  is.  The  variance  is  defined  as  the  mean  of  the  
squared   deviations   of   all   data   points   in   a   given   data   set   from   their   mean.   The  
square  root  of  the  variance  is  called  the  standard  deviation  and  is  often  preferred  
above   the   variance   as   it   is   expressed   in   the   same   units   as   the   original   data   and  
consequently   easier   to   interpret.   Mathematically,   the   variance   of   a   random  
variable  X  can  be  expressed  as:  
 
Var 𝑋 = 𝜎!! = 𝜎 ! 𝑋 = 𝐸 𝑋 − 𝜇 !
= 𝐸 𝑋! − 𝐸 𝑋 !
 
 
The   covariance   measures   how   two   variables   change   together.   It   is   therefore   an  
indication   of   the   linear   relationship   between   the   two   variables.   A   positive  
covariance   indicates   similar   behavior,   while   a   negative   covariance   indicates  
opposite   behavior   between   the   two   variables.   The   covariance   is   defined   as   the  
mean   value   of   the   multiplication   products   of   the   deviations   between   the   data  
points   in   the   first   data   set   and   the   data   points   in   the   second   data   set   with   their  
respective   mean   values.   Mathematically,   the   covariance   between   two   jointly  
distributed  random  variables  X  and  Y  can  be  expressed  as:  
 
Cov 𝑋, 𝑌 = 𝜎!,! = 𝜎 𝑋, 𝑌 = 𝐸 𝑋 − 𝐸 𝑋 𝑌−𝐸 𝑌 = 𝐸 𝑋𝑌 − 𝐸 𝑋 𝐸 𝑌  
 
Notice   the   similarity   between   the   variance   and   covariance.   The   variance   can   be  
seen  as  the  covariance  of  a  data  set  with  itself.  
 
The   covariance   matrix,   also   known   as   the   cross   covariance   matrix,   variance-­‐
covariance  matrix  or  dispersion  matrix,  is  a  matrix  in  which  the  element  on  the  i,j  
position  is  the  covariance  between  the  ith  variable  and  jth  variable.  The  covariance  
matrix  is  consequently  a  symmetrical  matrix  of  covariances  with  the  variances  of  
the   variables   on   the   diagonal.   Mathematically,   the   covariance   matrix   for   random  
vectors  X  and  Y  can  be  expressed  as:  
37
 
!
𝜎 𝑿, 𝒀 = 𝐸 𝑿 − 𝐸 𝑿 𝒀−𝐸 𝒀 = 𝐸 𝑿𝒀! − 𝐸 𝑿 𝐸 𝒀 !  
 
𝜎!! … 𝜎!,!
𝜎 𝑿, 𝒀 = ⋮ ⋱ ⋮  
𝜎!,! … 𝜎!!
 
1.6.3. Linear  correlation  coefficient  and  linear  correlation  matrix  
The   linear   correlation   coefficient,   also   known   as   the   Pearson   product-­‐moment  
correlation   coefficient   or   simply   Pearson’s   correlation   coefficient,   measures   the  
strength   of   the   linear   relationship   between   two   variables.   The   linear   correlation  
coefficient   is   calculated   by   dividing   the   covariance   of   the   two   variables   by   the  
square   root   of   the   product   of   their   variances.   The   linear   correlation   coefficient   is  
therefore   a   normalized   covariance,   which   makes   the   strength   of   the   linear  
relationship   easier   to   interpret.   A   linear   correlation   coefficient   of   1   represents   a  
perfect   positive   linear   relationship,   a   value   of   -­‐1   indicates   perfect   negative   linear  
correlation  and  a  value  of  0  indicates  no  linear  relationship  at  all.  Illustrations  of  
high  and  low,  positive  and  negative  correlation  for  the  bivariate  standard  normal  
distribution  are  shown  in  Figure 1.  It  is,  however,  important  to  realize  that  a  linear  
correlation  coefficient  of  0  does  not  mean  that  the  two  variables  are  not  correlated.  
It   is   possible   they   inhibit   a   non-­‐linear   type   of   correlation.   Mathematically,   the  
linear   correlation   coefficient   between   two   jointly   distributed   random   variables   X  
and  Y  can  be  expressed  as:  
 
𝜎 𝑋, 𝑌
𝜌 𝑋, 𝑌 =  
𝜎! 𝑋 𝜎! 𝑌
 
The  linear  correlation  matrix  is  a  matrix  in  which  the  element  on  the  i,j  position  is  
the  linear  correlation  coefficient  between  the  ith  variable  and  jth  variable.  This  is  a  
symmetrical   matrix   with   only   1   on   the   diagonal,   as   the   linear   correlation  
coefficient  of  a  variable  with  itself  equals  1.  The  linear  correlation  matrix  is  equal  
to   the   covariance   matrix   of   the   standardized   random   vectors,   i.e.   the   original  

38
random   vectors   divided   by   their   standard   deviation.   Mathematically,   the   linear  
correlation  matrix  for  random  vectors  X  and  Y  can  be  expressed  as:  
 
𝜎 𝑿, 𝒀
𝜌 𝑿, 𝒀 =  
𝜎! 𝑿 𝜎! 𝒀
 
1 𝜌!,! …           𝜌!,!          
       
𝜌!,! 1 ⋱           ⋮
𝜌 𝑿, 𝒀 =  
⋮ ⋱ 1 𝜌!!!,!
𝜌!,! … 𝜌!,!!! 1
 

Figure  1:  Bivariate  standard  normal  distributions  with  high  (+/-­‐  0.8)  
and  low  (+/-­‐  0.2),  positive  and  negative  correlations  

 
1.6.4. Rank  coefficients  
Similarly   to   the   linear   correlation   coefficient,   rank   coefficients   are   important  
measures  of  correlation.  
In   the   case   of   non-­‐elliptical   distributions   (i.e.   no   Gaussian   or   Student’s   t-­‐
distributions),  use  of  the  linear  correlation  coefficient  is  inappropriate  and  can  be  
very   misleading.   Rank   coefficients   provide   a   good   alternative   in   this   case   to  
measure  correlation.  
 
• The   Spearman   rank   coefficient   or   Spearman’s   rho   for   the   random   vector  
(X,Y)T:  
39
𝜌 𝑋, 𝑌 = 3 ℙ 𝑋 − 𝑋 𝑌 − 𝑌′ > 0 − ℙ 𝑋 − 𝑋 𝑌 − 𝑌′ < 0 ,  

where  (X,Y)T,  (𝑋, 𝑌)T  and  (X’,Y’)T  are  independent  copies.  


 
• The  Kendall  rank  coefficient  or  Kendall’s  tau  for  the  random  vector  (X,Y)T:  
𝜏 𝑋, 𝑌 = ℙ 𝑋 − 𝑋 𝑌 − 𝑌 > 0 − ℙ 𝑋 − 𝑋 𝑌 − 𝑌 < 0 ,  

where  (𝑋, 𝑌)T  is  an  independent  copy  of  (X,Y)T.  


 
1.6.5. Copulas  
A  copula  is  a  multivariate  probability  distribution  function  defined  on  the  unit  cube  
[0,1]n,   with   uniformly   distributed   margins,   i.e.   for   which   the   marginal   probability  
distribution  of  each  variable  is  uniform.  (Embrechts  et  al.,  2003)  Sklar’s  theorem  is  
of  incredible  importance  with  regard  to  the  use  of  copulas.  
 
Sklar’s   theorem:   Let   H   be   an   n-­‐dimensional   distribution   function   with   margins  
F1,…,Fn.   Then   there   exists   an   n-­‐copula   C   such   that   for   all   x   in  ℝ! ,  𝐻 𝑥! , … , 𝑥! =
𝐶 𝐹! 𝑥! , … , 𝐹! 𝑥! .   If   F1,…,Fn   are   all   continuous,   then   C   is   unique,   otherwise   C   is  
uniquely   determined   on   Ran   F1   ×   …   ×   Ran   Fn.   Conversely,   if   C   is   an   n-­‐copula   and  
F1,…,Fn   are   distribution   functions,   then   the   function   H   defined   above   is   an   n-­‐
dimensional  distribution  function  with  margins  F1,…,Fn.  
 
From   Sklar’s   theorem   it   can   be   seen   that   the   univariate   margins   and   the  
multivariate   dependence   structure   of   a   continuous   multivariate   distribution  
function   can   be   separated.   In   other   words,   the   dependence   structure   of   a  
multivariate   distribution   function   can   be   fully   represented   by   a   copula.   An  
illustrative   example   of   the   application   of   this   theorem   is   shown   in   Figure 2.   In   this  
example   a   2-­‐dimensional   distribution   function   H(x1,x2)   is   defined   by   a   bivariate  
Gaussian   copula   C(U1,U2)   with   a   linear   correlation   coefficient   of   0.8   and   two  
univariate  margins  F1(x1)  and  F2(x2),  which  are  both  standard  normal  distributions.  
The  top  graph  in  this  figure  represents  random  numbers  selected  from  the  copula  
C.   Note   that   the   margins   are   uniform.   By   applying   an   inverse   cumulative  
distribution  function  on  these  random  numbers  (𝑋! = 𝐹!!! 𝑈!  and  𝑋! = 𝐹!!! 𝑈! ),  

40
the   random   numbers   get   scaled   back   to   the   dimensions   of   the   original   distribution  
function  H,  which  is  shown  in  the  bottom  graph.  
 

Figure  2:  Copula  

 
1.6.6. Types  of  copulas  
Source:  (SAS  Institute  Inc.,  n.d.)  
 
Elliptical  copulas  
Normal  or  Gaussian  
Copula:  𝐶!!" 𝑢 = Φ! Φ!! 𝑢! , … , Φ!! 𝑢!  
 
Student-­‐t  with  ν  degrees  of  freedom  
!
Copula:   𝐶!,! 𝑢 = 𝑡!,! 𝑡!!! 𝑢! , … , 𝑡!!! 𝑢! ,   with   𝜈 ∈ 1, ∞ ,   Σ ∈ ℝ!×! ,   tν   a  
univariate   Student’s   t-­‐distribution   with   ν   degrees   of   freedom   and   Σ   the   linear  
correlation  matrix.  
 
Archimedean  copulas  
𝐶 𝑢 = 𝜙 !! 𝜙 𝑢! + ⋯ + 𝜙 𝑢!  
Clayton  
Generator  function:  𝜙 𝑢 = 𝜃 !! 𝑢!! − 1  

41
!
!! !!
Copula:  𝐶!!" 𝑢 = 1 − 𝑛 + !
!!! 𝑢! ,  with  𝜃 > 0.  
 
Gumbel  
Generator  function:  𝜙 𝑢 = − log 𝑢 !  
!
Copula:  𝐶!!" 𝑢 = exp   − !
!!! − log 𝑢! ! !
,  with  𝜃 > 1.  

 
Frank  
!"# !!" !!
Generator  function:  𝜙 𝑢 = − log !"# !! !!
 
!
! !"# !!!! !!
Copula:  𝐶!!! 𝑢 = ! log 1 + !!!
!"# !! !! !!!
,   with  𝜃 ∈ −∞, ∞ \ 1  for  𝑛 = 2  and  

𝜃 > 0  for  𝑛 ≥ 3.  
 
Student’s   t-­‐copulas   are   interesting   as   they   are   basically   an   extension   of   the  
Gaussian   copula.   They   exhibit   more   dependence   in   the   tails,   but   include   the  
Gaussian  copula  as  a  limit  case  when  the  degree  of  freedom  tends  to  infinity.  The  
other   copula   families   represent   different   degrees   of   correlation.   The   Clayton  
copula  allows  to  model  greater  correlation  in  the  left  tails.  The  Gumbel  copula,  on  
the   other   hand,   allows   to   model   greater   correlation   in   the   right   tails.   The   Frank  
copula  is  symmetric.  (Fermanian,  2005)  
   

42
1.7. Practical   implementation   of   correlation   in   financial  
modeling  
In  this  section  a  number  of  methods  to  implement  correlation  in  financial  modeling  
will   be   introduced.   The   goal   of   this   section   is   to   understand   how   random  
correlated   numbers   can   be   created   from   a   given   correlation   matrix   C.   The   creation  
of   random   correlated   numbers   is   essential   for   financial   modeling,   as   random  
numbers  are  at  the  basis  of  Monte  Carlo  simulation.  The  implementation  of  these  
methods  will  be  illustrated  using  MATLAB.  
 
 
1.7.1. Modeling   correlation   using   Cholesky   decomposition   of   the  
correlation  matrix  
 
Random   correlated   numbers   Rc   with   a   given   correlation   matrix   C   can   be   generated  
from  uncorrelated  random  numbers  R  by  multiplying  them  with  a  matrix  U:  
𝑅! = 𝑅𝑈  
 
In  the  above  equation  U  is  a  matrix  for  which  the  following  holds:  
𝑈 ! 𝑈 = 𝐶  
 
U  can  be  found  from  the  correlation  matrix  C  by  using  a  Cholesky  decomposition  
algorithm.  
 
In  MATLAB,  the  Cholesky  decomposition  of  C  can  be  performed  using  the  function  
chol():  
𝑈 = chol 𝐶  
   

43
1.7.2. Modeling   correlation   using   eigenvector   decomposition   of  
the  correlation  matrix  
 
The   matrix   U,   mentioned   in   the   previous   section,   can   also   be   found   using   an  
eigenvector   decomposition,   or   spectral   decomposition.   First,   the   eigenvectors   Ei  
and   eigenvalues   λi   of   the   correlation   matrix   C   should   be   found.   Afterwards,   a  
matrix  V  is  defined  as:  
𝑉 = 𝐸! diag 𝜆!  
where  diag()  represents  a  diagonal  matrix  with  the  square  roots  of  the  eigenvalues  
of  C  on  the  diagonal.  
 
U  can  then  be  found  by  transposing  V:  
𝑈 = 𝑉 !  
 
In   MATLAB,   the   eigenvectors   and   eigenvalues   of   C   can   be   calculated   with   the  
function  eigs():  
𝐸! , 𝜆! = eigs 𝐶  
 
1.7.3. Modeling  correlation  using  copulas  
 
In  this  section  the  correlation  between  selected  equity  indices  is  investigated.  
 
1.7.4. Data  collection  and  analysis  
Daily   total   returns   (gross   dividends)   for   the   S&P   500,   Euro   Stoxx   50   and   Nikkei  
225   were   collected   from   Bloomberg   for   the   period   January   2,   1987   till   February  
19,  2014.  As  only  trading  days  were  considered,  the  resulting  data  series  for  each  
stock  index  contained  7079  daily  returns.  
 
The  mean  daily  return  and  standard  deviation  of  each  data  series  was  calculated  to  
observe   if   the   daily   returns   follow   a   normal   distribution.   A   graphical  
representation   of   the   historical   daily   returns   and   the   corresponding   normal  
distributions  is  shown  in  Figure 3.  The  normal  distribution  seems  to  approximate  
44
the   daily   returns   relatively   well.   Many   authors,   however,   such   as   Fergusson   &  
Platen   (2006)   suggest   that   stock   index   returns   follow   a   Student’s   t-­‐distribution  
with  relatively  fat  tails,  i.e.  with  a  small  number  of  degrees  of  freedom.  As  can  be  
seen   in   Figure 4,   the   Student’s   t-­‐distribution   seems   to   approximate   the   real   data  
better.  This  was  not  verified  in  a  more  scientific  manner,  as  this  is  not  the  objective  
of  this  paper.  

  Figure  3:  Distributions  

45
  Figure  4:  t-­‐distributions  

 
The   dataset   of   daily   stock   index   returns   was   split   up   in   six   subsets   of   equal   size,  
each   of   them   containing   some   important   financial   crises   (Table 1).   By   creating  
different  subsets,  the  validity  of  the  proposed  model  in  different  time  periods  will  
be  confirmed.  
 
Table  1:  Data  subsets  and  corresponding  financial  crises  

Subset   Time  period   Financials  crises  


1   02/01/1987  –  11/07/1991   1987  Black  Monday  
1989-­‐1991  United  States  savings  &  loan  crisis  
1990  Japanese  asset  price  bubble  collapsed  
2   12/07/1991  –  18/01/1996   Early  1990s  Swedish  banking  crisis  
Early  1990s  Finnish  banking  crisis  
Early  1990s  recession  
1992  Black  Wednesday  
1994  Economic  crisis  in  Mexico  
3   19/01/1996  –  27/07/2000   1997  Asian  financial  crisis  
1998  Russian  financial  crisis  
1998–2002  Argentine  Great  Depression  
4   28/07/2000  –  03/02/2005   Early  2000s  recession  
2001  Turkish  economic  crisis  
2001  Bursting  of  dot-­‐com  bubble  
5   04/02/2005  –  13/08/2009   2007–2008  Global  financial  crisis  
2008-­‐2011  Icelandic  financial  crisis  
6   14/08/2009  –  19/02/2014   2010  European  sovereign  debt  crisis  

46
   

47
1.7.5. Linear   correlation   between   S&P   500,   Euro   Stoxx   50   and  
Nikkei  225  returns  
 
Tail   dependence   between   stock   indexes   is   of   specific   interest.   It   is   believed   that  
stock   indexes   between   markets   become   more   correlated   in   volatile   market  
conditions.   This   is   observed   in   the   historical   data,   as   both   the   highest   and   the  
lowest  daily  return  coincide  for  all  three  stock  indexes  (Table 3).  
 
 
Table  2:  Correlation  between  selected  equity  index  returns  

Equity  indexes   Linear  correlation  


S&P  500  –  Euro  Stoxx  50   50.16%  
S&P  500  –  Nikkei  225   11.55%  
Euro  Stoxx  50  –  Nikkei  225   27.95%  

 
Table  3:  Lowest  and  highest  equity  index  returns  

Equity  index   Lowest  return   Highest  return  


S&P  500   -­‐20.47%   +11.58%  
(19/10/1987)   (13/10/2008)  
Euro  Stoxx  50   -­‐7.93%   +11.00%  
(19/10/1987)   (13/10/2008)  
Nikkei  225   -­‐14.90%   +14.15%  
(20/10/1987)   (14/10/2008)  
 
 
1.7.6. Correlation   of   S&P   500   and   Euro   Stoxx   50   returns   using  
copulas  
The   correlation   between   the   historical   index   returns   of   the   S&P   500   and   Euro  
Stoxx   50   was   measured   for   all   datasets   (complete   dataset   and   6   subsets)   by  
determining  the  corresponding  linear  correlation  matrix,  Kendall’s  tau  matrix  and  
Spearman’s   rho   matrix.   The   latter   two   are   symmetric   matrices   of   the   following  
form:  
 

48
1 𝜏
𝐾𝑒𝑛𝑑𝑎𝑙𝑙 ! 𝑠  𝑡𝑎𝑢  𝑚𝑎𝑡𝑟𝑖𝑥 =  
𝜏 1
 
1 𝜌
𝑆𝑝𝑒𝑎𝑟𝑚𝑎𝑛! 𝑠  𝑟ℎ𝑜  𝑚𝑎𝑡𝑟𝑖𝑥 =  
𝜌 1
 
where   the   Kendall   rank   coefficient   τ   and   the   Spearman   rank   coefficient   ρ   are  
measures  for  the  correlation  between  the  S&P  500  and  the  Euro  Stoxx  50.  
 
With   these   rank   coefficients,   MATLAB   can   generate   random   numbers   from   the  
desired  copula  using  the  command  copularnd.  However,  these  numbers  are  taken  
from  the  copula  and  thus  do  not  yet  represent  returns,  but  probabilities  between  0  
and   1.   To   convert   the   random   numbers   to   forecasted   returns,   a   kernel   density  
estimation   has   to   be   made   of   the   random   variables   and   the   inverse   cumulative  
distribution   function   has   to   be   evaluated.   MATLAB   can   do   both   these   steps   with  
the  command  ksdensity.  A  MATLAB  example  for  the  Gaussian  copula  is  represented  
in  Figure 4.  
 
Similar   calculations   were   done   for   the   Clayton   copula,   Frank   copula,   Gumbel  
copula  and  for  the  Student’s  t-­‐copula  with  5  degrees  of  freedom.  The  end  results  of  
these  simulations  were  forecasts  of  daily  stock  index  returns  for  the  S&P  500  and  
Euro  Stoxx  50  with  each  of  these  copulas.  The  resulting  forecasts  are  represented  
graphically  in  Figure 6.    

49
Contents
Load stock index returns (historical data)
Calculate the linear correlation and rank coefficients
Monte Carlo forecasts with Gaussian copula / S&P 500 versus Euro Stoxx 50
Plot the historical data versus the forecasted returns

% Implementing Correlation in Financial Modeling


% Nico De Coker & Antonio Rivela
% IE Business School

Load stock index returns (historical data)

% Load daily index total returns (gross dividends) for S&P 500 (column 1),
% Euro Stoxx 50 (column 2) and Nikkei 225 (column 3)
% From January 2, 1987 till February 19, 2014 (business days)
load stocks.mat
% In this example only the first 2 columns (S&P 500 and Euro Stoxx 50) will be used
stocks = stocks(:,1:2);
% Number of historical data per index
nobs = size(stocks,1);

Calculate the linear correlation and rank coefficients

% Linear correlation matrix (Pearson)


corr_stocks = corr(stocks);
% Kendall's tau coefficients
Kendall_tau_stocks = corr(stocks,'type','Kendall');
% Spearman's rho coefficients
Spearman_rho_stocks = corr(stocks,'type','Spearman');

Monte Carlo forecasts with Gaussian copula / S&P 500 versus Euro Stoxx 50

% Create random numbers following Gaussian copula


% A total of 'nobs' (number of historical data) random numbers will be created
r_Gaussian = copularnd('Gaussian',corr_stocks,nobs);
% Use a kernel density estimator and inverse cdf to transform the random
% numbers to daily total returns
X1_Gaussian = ksdensity(stocks(:,1),r_Gaussian(:,1),'function','icdf');
X2_Gaussian = ksdensity(stocks(:,2),r_Gaussian(:,2),'function','icdf');

Plot the historical data versus the forecasted returns

% Historical data
subplot(2,1,1)
scatter(stocks(:,1),stocks(:,2),'.')
axis ([-10 10 -10 10])
title('Historical data')
xlabel('S&P 500')
ylabel('Euro Stoxx 50')
% Gaussian copula
subplot(2,1,2)
scatter(X1_Gaussian,X2_Gaussian,'.')
axis ([-10 10 -10 10])
title('Gaussian copula')
xlabel('S&P 500')
ylabel('Euro Stoxx 50')

Published with MATLAB® R2013a

Figure  5:  MATLAB  example  for  the  Gaussian  copula  

  50
 
Figure  6:  Historical  daily  returns  for  the  S&P  500  and  Euro  Stoxx  50  and  forecasts  using  different  
copulas  

 
After  forecasting  daily  returns  with  different  copulas,  the  frequencies  of  coinciding  
extreme   values   of   both   the   historical   data   and   the   forecasts   were   determined.  
Coinciding   extreme   values   are   defined   here   as   values   for   which   both   stock   indexes  
have  a  return  less  than  the  mean  return  minus  3  standard  deviations  (coinciding  
extremely  low  returns)  or  greater  than  the  mean  return  plus  3  standard  deviations  
(coinciding  extremely  high  returns).  
 
Mathematically   the   frequencies   of   coinciding   extremely   low,   respectively   high,  
returns  can  be  formulated  as:  
 
!
!!! 𝑅!,! < 𝜇! − 3𝜎! ∩ 𝑅!,! < 𝜇! − 3𝜎!
!"#
𝑓 𝑅 =  
𝑛
 
!
!!! 𝑅!,! > 𝜇! + 3𝜎! ∩ 𝑅!,! > 𝜇! + 3𝜎!
!!"!
𝑓 𝑅 =  
𝑛
51
 
with  R  a  n×2  matrix  of  daily  returns  for  the  two  stock  indexes,  μ1  and  μ2  the  mean  
returns   of   the   two   stock   indexes   and   σ1   and   σ2   the   standard   deviations   of   the  
returns  of  both  stock  indexes.  
 
To  determine  which  copula  forecast  provides  the  best  fit  of  the  historical  returns,  
the   frequencies   of   extreme   values   for   the   forecasts   were   compared   with   the  
frequencies  of  extreme  values  for  the  historical  returns  (Table 4).  This  was  used  as  
a  best  fit  measure  because  in  this  paper  we  are  especially  interested  in  capturing  
the   tail   dependence.   From   f   low   and   f  high   for   the   different   forecasts,   it   is   clear   that  
the  Student’s  t-­‐copula  with  5  degrees  of  freedom  is  the  best  copula  to  capture  tail  
dependence   of   daily   returns   of   the   S&P   500   and   Euro   Stoxx   50.   The   same  
procedure   was   repeated   for   the   6   data   subsets   to   determine   if   this   conclusion   is  
valid   in   different   time   periods.   In   each   of   the   subsets,   the   Student’s   t-­‐copula   with   5  
degrees  of  freedom  performs  relatively  well  at  capturing  tail  dependence.  
 
Table  4:  Historical  frequencies  of  coinciding  extreme  
values   (mean   return   +/-­‐   3   standard   deviations)   for  
both   indices   and   forecasted   frequencies   using  
different  copulas  

Historical/Forecast   f  low   f  high  


Historical  data   0.002684   0.002119  
Gaussian   0.001271   0.000565  
Student’s  t  (ν=5)   0.002825   0.002260  
Clayton   0.004238   0.000000  
Gumbel   0.000000   0.002967  
Frank   0.000424   0.000000  
 
   

52
 
Daily   returns   of   the   S&P   500   and   Euro   Stoxx   50   are   highly   dependent.   That  
explains  why  we  need  to  research  how  to  model  highly  dependent  environments.  
Furthermore,   research   has   shown   that   the   correlation   between   these   equity  
indices   becomes   greater   in   highly   volatile   market   conditions,   such   as   crises.   This  
makes  linear  correlation  useless  to  model  the  correlation  between  the  equity  index  
returns.   Rank   coefficients,   such   as   Spearman’s   rho   and   and   Kendall’s   tau   are  
consistent  with  codependence  methodologies  (copulas).  
 
When   analyzing   the   outliers   (coinciding   extreme   values),   the   Student’s   t-­‐copula  
comes  out  as  the  best  representation  of  correlation  between  the  S&P  500  and  Euro  
Stoxx  50  returns.  
 
 

53
2. ADVANCED  EXCEL    
 

2.1. Financial  Calculations  in  Excel  


 
Perpetuity  cash  flow  
Perpetuity  cash  flow  means  the  cash  flow  never  ends.  If  the  yearly  cash  flow  is  10,  
and  discount  rate  is  2%,  the  perpetuity  cash  flow  total  amount  is  (10/2%=)  500.  
PV  of  total  cash  flow  =  annuity  cash  flow  /  interest  rate    
 
XNPV  (rate,  values,  dates)  
Returns  the  net  present  value  for  a  schedule  of  cash  flows  that  is  not  necessarily  
periodic.  To  calculate  the  net  present  value  for  a  series  of  cash  flows  that  is  
periodic,  use  the  NPV  function.  

XIRR(values,  dates,  [guess])  

Returns  the  internal  rate  of  return  for  a  schedule  of  cash  flows  that  is  not  
necessarily  periodic.  To  calculate  the  internal  rate  of  return  for  a  series  of  periodic  
cash  flows,  use  the  IRR  function.  

 
 
54
 
 
 
Use  Goal  Seek  /  SOLVER  to  calculate  loan  instalment  
   
 

 
 
Use  Table  to  conduct  Sensitivity  Analysis  
We   conduct   a   sensitivity   analysis   on   Treasury   Inflation   Protected   Securities   to  
demonstrate  the  affect  from  inflation  rate  and  discount  rate.  The  cash  flows  are  28,  
10,   10,   and   10,   in   4   years.   We   adjust   the   cash   flow   according   to   the   appropriate  
inflation  rate  in  cell  B8  to  E8.              
Note   that   we   need   to   put   the   formula   in   the   top   left   corner   of   the   table,   i.e.   B17.  
Apply   the   formula   that   =table(row   17,   column   B)   to   include   those   variables   in   row  
17  and  column  B  in  the  table  to  calculate  the  NPV  and  conduct  sensitivity  analysis.    
 
 
 
 

55
 

 
 
 
 
 
 
 

56
2.2. Matrices  and  vectorial  calculations  in  Excel  
 
Remember  to  press  CTRL+SHIFT+ENTER  when  entering  matrices  functions  in  
excel.  Otherwise  system  will  not  work.  
 
 
MMULT  
Multiplies  two  matrices.  

MINVERSE  

Inverts  one  matrix.  


 
TRANSPOSE  

Transposes  one  matrix.  


 
 
 
 
 
 

57
2.3. Main  Statistical  Functions  in  Excel  
 
These  are  the  main  statistical  functions  that  we  will  use  in  the  course.  
 
 
AVERAGE  
Average  of  a  vector  of  data  

VARP    

Population  (n)  Variance  of  a  vector  of  data  

STDEVP  

Population  (n)  Standard  Deviation  of  a  vector  of  data  

VAR    

Sample  (n-­‐1)  Variance  of  a  vector  of  data  

STDEV  

Sample  (n-­‐1)  Standard  Deviation  of  a  vector  of  data  

COVAR  

Population  (n)  Co-­‐Variance  of  a  vector  of  data  

   

58
3. APPLYING  EXCEL  TO  FINANCE  
In   this   section,   we   want   to   cover   how   Excel   can   be   used   for   portfolio  
optimization.  One  way  to  do  it,  if  you  don’t  have  constraints  (except  that  the  sum  of  
weights   must   be   equal   to   1),   is   to   apply   the   formula   we   saw   in   section   1  
(proposition   1)   to   calculate   the   weights   of   each   asset   in   the   portfolio.   The   only  
thing  you  have  to  do  is  to,  previously,  get  the  variance-­‐covariance  matrix  and  the  
average   return   matrix   for   each   asset.   Once   you   obtain   this   matrix   and   you   have  
your  risk-­‐free  rate  you  are  able  to  apply  the  formula  in  Excel,  which  will  give  you  
the  weights  of  each  asset  to  construct  the  efficient  portfolio.    
However,  it  gets  more  complicated  if  we  have  to  deal  with  constraints  while  
building  our  efficient  portfolio.  For  example,  typical  constraint  in  the  mutual  fund  
industry  is  the  impossibility  of  going  short.  When  we  have  constraints  like  this,  the  
formula  is  not  longer  valid,  but  Excel  is  still  valid  to  solve  the  problem.  The  tool  we  
need  is  SOLVER.  
 

3.1. Solver  
Solver  is  a  tool  in  Excel.  To  enable  Solver,  click  ‘Tools’  then  ‘Addins’.  Within  
the  Addin  box,  check  ‘SOLVER.xlam’  then  hit  ‘OK’.    
Solver   allows   you   to   resolve   optimization   problems   and   equations.   In  
portfolio   theory   what   we   do   to   find   the   optimal   portfolio   given   a   number   of  
constrains  is  to  maximize  the  Sharpe-­‐ratio  subject  to  those  constraints.  Solver  does  
this  optimization  problem  for  you  in  Excel.    
The   only   thing   Solver   needs   to   work   it   out   is   to   have   all   the   data   and   the  
links  between  cells.  This  means  that  you  need  the  variance-­‐covariance  matrix,  the  
average  returns  matrix,  the  risk-­‐free  rate  (“c”  in  the  examples)  and  the  cells  with:  
(i)   the   sum   of   all   the   weights;   (ii)   the   portfolio   average   return   formula;   (iii)   the  
variance   and   standard   deviation   formula;   and   (iv)   the   Sharpe-­‐ratio   formula.   All  
these  formulas  are  linked  to  the  matrix  of  weights,  that  is  the  matrix  that  Solver  is  
going  to  give  you  as  a  result  of  the  optimization  problem.  
We   are   going   to   see   4   different   examples   of   constrains   and   how   we   can  
introduce  this  constraints  in  Solver.  
 
59
 
3.1.1. Long  Only  Constraint  (No  Short  Selling)  
This   constraint,   typical   in   the   mutual   fund   industry   as   we   said   before,  
means   that   the   minimum   weight   an   asset   can   have   in   your   portfolio   is   zero.   An  
immediate   consequence   is   that   the   maximum   weight   of   any   asset   in   your   portfolio  
has   to   be   1,   because   you   only   can   go   over   1   in   one   asset   if   you   go   below   zero   in  
other  asset.    
Therefore,   the   problem   we   have   to   resolve   (Solver   has   to   resolve)   is   to  
maximize  the  Sharp-­‐ratio  subject  to  the  constraints  that:  (i)  the  sum  of  the  weights  
equal   1;   (ii)   all   weights   have   to   be   equal   or   greater   than   zero.   Let’s   see   how   to  
introduce  all  this  information  in  Solver.  
 

 
As   you   can   see,   when   you   click   on   Solver   a   box   like   the   one   in   the   image  
above  appears  and  ask  you  four  questions:  (i)  target  cell  (“Establecer  objetivo”,  in  
the  Spanish  version),  that  in  this  case  has  to  be  the  cell  where  you  have  the  Sharpe-­‐
ratio  formula  ($E$28);  (ii)  what  for  (“Para”),  that  in  this  case  is  “max”  because  we  
want   to   maximize   the   target   cell;   (iii)   changing   cells   (“cambiando   las   celdas   de  
variables”)   that   in   this   case   are   the   cells   with   the   weights   ($D$17:$D$22);   (iv)  
subject  to  (“Sujeto  a  las  restricciones”),    where  we  need  to  specify  our  constraints  
clicking   on   the   right   button   called   Add   (“Agregar”)   to   start   adding   constraints.   In  

60
this  case,  one  constraint  is  that  the  cell  that  contains  the  sum  of  the  weights  equals  
1   ($D$23=1)   and   the   other   constraint   is   that   all   weights   must   be   equal   or   above  
zero  ($D$17:$D$22>=0).  Then  you  click  on  Solve  (“Resolver”)  and  Solver  gives  you  
the  solution.  
 

Then,  you  only  need  to  click  on  Accept  (“Aceptar”)  the  solution.  
 
 
3.1.2. 130/30  Constraint  
130/30  means  that  the  weights  of  your  assets  can  go  from  -­‐30%  to  130%.    
This  is  a  typical  constraint  used  in  the  Hedge-­‐Fund  industry.    
Comparing  to  the  problem  with  the  long-­‐only  constraint  we’ve  seen  before,  
the  only  change  is  that  we  need  to  include  this  constraint  in  Solver  instead  of  the  
long-­‐only  constraint.  The  rest  is  the  same.  So,  now  the  constrain  is  that  the  weights  
($D$17:$D$22)  must  be  <=1.3  and  >=-­‐0.3.  
 
 
 
 
 
 
61
 
 
 

 
And  the  solution,  as  we  are  relaxing  our  constraints  (now  we  can  go  short  at  
least  30%),  must  be  weights  that  provide  the  portfolio  with  a  higher  Sharpe-­‐ratio.    
 

 
As  you  can  see,  the  Sharpe-­‐ratio  in  this  case  is  higher,  as  expected.  
   

62
3.1.3. Diversification  Constraint  
Sometimes  we  want  to  build  a  diversified  portfolio,  even  at  the  cost  of  obtaining  a  
lower   return,   because   we   consider   that   the   more   diversified,   the   less   risk.   This  
diversification  constraint  can  be  defined  in  many  ways.  For  example,  we  can  decide  
that  every  asset  has  to  be  in  the  portfolio  with  at  least  a  10%  weight.    
 
In  this  case,  we  are  constraining  our  portfolio  choices  more  than  with  the  long-­‐only  
constraint.  Therefore,  the  solution  should  be  a  portfolio  with  a  lower  Sharpe-­‐ratio  
than  in  the  long-­‐only  case  and  than  in  the  130/30  case.  Let’s  see  how  to  implement  
this  constrain  in  Solver  and  check  if  the  solution  implies  a  lower  Sharpe-­‐ratio.  
 
Now,   our   constrain   is   that   each   weight   for   each   asset   is   higher   than   10%   (0.1).  
Therefore   we   have   to   change   the   constrain   and   implement   a   new   one   where   all  
weights  ($D$17:$D$22)  have  to  be  equal  or  greater  than  10%.  

 
  As  expected,  Solver  gives  us  a  solution  with  a  lower  Sharpe-­‐ratio  than  in  the  
previous  cases.    

63
 
 
3.1.4. Exposure  Constraint  
  In  this  case,  we  want  to  limit  our  exposure  to  one  asset  in  order  to  avoid  a  
big  concentration  of  our  portfolio  in  one  single  asset.  For  example,  we  can  define  
this  constrain  in  a  way  that  the  weights  of  the  assets  in  the  portfolio  must  be  below  
50%.   Let’s   see   how   to   introduce   this   constrain   in   Solver   and   the   solution   that   it  
provide  us.    

64
   
As  you  can  see  the  constrain  establish  that  the  weights  ($D$17:$D$22)  must  
be   <=0.5   (50%).   If   we   click   Solve   (“Resolver”),   Solver   will   give   es   the   solution   with  
the  new  weights.    
 
 
 

   

65
4. INTRODUCTION  TO  MATLAB  
 
MATLAB   stands   for   Matrix   Laboratory.   According   to   The   Mathworks,   its  
producer,   it   is   a   "technical   computing   environment".   We   will   take   the   more  
mundane  view  that  it  is  a  programming  language.  
 
This   section   covers   much   of   the   language,   but   by   no   means   all.   We   aspire   to  
at  the  least  to  promote  a  reasonable  proficiency  in  reading  procedures  that  we  will  
write   in   the   language   but   choose   to   address   this   material   to   those   who   wish   to   use  
our  procedures  and  write  their  own  programs.  
 
Versions  of  MATLAB  are  available  for  almost  all  major  computing  platforms.  
Our   material   was   produced   and   tested   on   the   version   designed   for   the   Microsoft  
Windows   and   MAC   OS   X   environment.   The   vast   majority   of   it   should   work   with  
other  versions,  but  no  guarantees  can  be  offered.  
 
Of   particular   interest   are   the   Student   Versions   of   MATLAB.   Prices   are  
generally  below  $100.  These  systems  include  most  of  the  features  of  the  language,  
but   no   matrix   can   have   more   than   8,192   elements,   with   either   the   number   of   rows  
or   columns   limited   to   32.   For   many   applications   this   proves   to   be   of   no  
consequence.  At  the  very  least,  one  can  use  a  student  version  to  experiment  with  
the  language.  
 
The   Student   Editions   are   sold   as   books   with   disks   enclosed.   They   are  
published  by  Prentice-­‐Hall  and  can  be  ordered  through  bookstores.  
 
In   addition   to   the   MATLAB   system   itself,   Mathworks   offers   sets   of  
Toolboxes,  containing  MATLAB  functions  for  solving  a  number  of  important  types  
of  problems.  Of  particular  interest  to  us  is  the  optimization  toolbox,  which  will  be  
discussed  in  a  later  section.  

66
4.1. Matrices  as  Fundamental  Objects  
 
MATLAB  is  one  of  a  few  languages  in  which  each  variable  is  a  matrix  (broadly  
construed)   and   "knows"   how   big   it   is.   Moreover,   the   fundamental   operators   (e.g.  
addition,   multiplication)   are   programmed   to   deal   with   matrices   when   required.  
And  the  MATLAB  environment  handles  much  of  the  bothersome  housekeeping  that  
makes   all   this   possible.   Since   so   many   of   the   procedures   required   for   Macro-­‐
Investment  Analysis  involve  matrices,  MATLAB  proves  to  be  an  extremely  efficient  
language  for  both  communication  and  implementation.  
 
 

4.2. Matrix  Operations  


 
Consider  the  following  MATLAB  expression:  
 
  C  =  A  +  B            
 
If  both  A  and  B  are  scalars  (1  by  1  matrices),  C  will  be  a  scalar  equal  to  their  
sum.   If   A   and   B   are   row   vectors   of   identical   length,   C   will   be   a   row   vector   of   the  
same   length,   with   each   element   equal   to   the   sum   of   the   corresponding   elements   of  
A   and   B.   Finally,   if   A   and   B   are,   say,   {3*4}   matrices,   so   will   C,   with   each   element  
equal  to  the  sum  of  the  corresponding  elements  of  A  and  B.  
In  short  the  symbol  "+"  means  "perform  a  matrix  addition".  But  what  if  A  and  
B   are   of   incompatible   sizes?   Not   surprisingly,   MATLAB   will   complain   with   a  
statement  such  as:  
 
  ???  Error  using  ==>  +  
 
  Matrix  dimensions  must  agree.  
 
So   the   symbol   "+"   means   "perform   a   matrix   addition   if   you   can   and   let   me  
know  if  you  can't".  

67
4.3. Assignment  Statements  
 
MATLAB   uses   a   pattern   common   in   many   programming   languages   for  
assigning  the  value  of  an  expression  to  a  variable.  The  variable  name  is  placed  on  
the   left   of   an   equal   sign   and   the   expression   on   the   right.   The   expression   is  
evaluated   and   the   result   assigned   to   the   variable   name.   In   MATLAB,   there   is   no  
need  to  declare  a  variable  before  assigning  a  value  to  it.  If  a  variable  has  previously  
been  assigned  a  value,  the  new  value  overrides  the  predecessor.  
This   may   sound   obvious,   but   consider   that   the   term   "value"   now   includes  
information  concerning  the  size  of  matrix  as  well  as  its  contents.  Thus  if  A  and  B  
are  of  size  {20*30}  the  statement:  
 
  C  =  A  +  B            
 
Creates   a   variable   named   C   that   is   also   {20*30}   and   fills   it   with   the  
appropriate  values.  If  C  already  existed  and  was,  say  {20*15}  it  would  be  replaced  
with  the  required  {20*30}  matrix.  In  MATLAB,  unlike  some  languages,  there  is  no  
need   to   "pre-­‐dimension"   or   "re-­‐dimension"   variables.   It   all   happens   without   any  
explicit  action  on  the  part  of  the  user.  
 
 

4.4. Case  Sensitivity  


 
MATLAB   variable   names   are   normally   case-­‐sensitive.   Thus   variable   C   is  
different  from  variable  c.  A  variable  name  can  have  up  to  19  characters,  including  
letters,   numbers   and   underscores.   While   it   is   tempting   to   use   names   such   as  
FundReturns   it   is   safer   to   choose   instead   fund_returns   or   to   use   the   convention  
from   the   C   language   of   capitalizing   only   second   and   subsequent   words,   as   in  
fundReturns.  In  any  event,  a\Adopt  a  simple  set  of  naming  conventions  so  that  you  
won't   write   one   version   of   a   name   in   one   place   and   another   later.   If   you   do   so,   you  
may  get  lucky  (e.g.  the  system  will  complain  that  you  have  asked  for  the  value  of  an  
undefined  variable)  or  you  may  not  (e.g.  you  will  assign  the  new  value  to  a  newly-­‐
created  variable  instead  of  the  old  one  desired).  In  programming  languages  there  
68
are   always   tradeoffs.   You   don't   have   to   declare   variables   in   advance   in   MATLAB.  
This   avoids   a   great   deal   of   effort,   but   it   allows   nasty,   difficult-­‐to-­‐detect   errors   to  
creep  into  your  programs.  

4.5. Immediate  and  Deferred  Execution  


 
When   MATLAB   is   invoked,   the   user   is   presented   with   an   interactive  
environment.   Enter   a   statement,   press   the   carriage   return   ("ENTER")   and   the  
statement   is   immediately   executed.   Given   the   power   that   can   be   packed   into   one  
MATLAB   statement,   this   is   no   small   accomplishment.   However,   for   many   purposes  
it  is  desirable  to  store  a  set  of  MATLAB  statements  for  use  when  needed.  
The   simplest   form   of   this   approach   is   the   creation   of   a   script   file:   a   set   of  
commands  in  a  file  with  a  name  ending  in  .m  (e.g.  do_it.m).  Once  such  a  file  exists  
and   is   stored   on   disk   in   a   directory   that   MATLAB   knows   about   (i.e.   one   on   the  
"MATLAB  path"),  the  user  can  simply  type:  
 
  do_it  
 
at  the  prompt  in  interactive  mode.  The  statements  will  then  be  executed.  
 
Even   more   powerful   is   the   function   file;   this   is   also   a   file   with   an   .m  
extension,   but   one   that   stores   a   function.   For   example,   assume   that   the   file  
val_port.m,  stored  in  an  appropriate  directory,  contains  a  function  to  produce  the  
value   of   a   portfolio,   given   a   vector   of   holdings   and   a   vector   of   prices.   In   interactive  
mode,  one  can  then  simply  type:  
   
v  =  val_port(holdings,  prices);  
 
MATLAB  will  realize  that  it  doesn't  have  a  built-­‐in  function  named  val_port  
and   search   the   relevant   directories   for   a   file   named   val_port.m,   then   use   the  
function  contained  in  it.  
Whenever  possible,  you  should  try  to  create  "m-­‐files"  to  do  your  work,  since  
they  can  easily  be  re-­‐used.  
69
 

4.6. Showing  Values  


 
If  at  any  time  you  wish  to  see  the  contents  of  a  variable,  just  type  its  name.  
MATLAB   will   do   its   best,   although   the   result   may   take   some   space   if   the   variable   is  
a  large  matrix.  
MATLAB   likes   to   do   this   and   will   tell   you   what   it   has   produced   after   an  
assignment  statement  unless  you  request  otherwise.  Thus  if  you  type:  
  C  =  A  +  B            
 
MATLAB  will  show  you  the  value  of  C.  This  may  be  a  bit  daunting  if  C  is,  say,  
a  20  by  30  matrix.  To  surpress  this,  put  a  semicolon  at  the  end  of  any  assignment  
statement.  For  example:  
 
  C  =    A  +  B;  
 
 

4.7. Initializing  Matrices  


 
If  a  matrix  is  small  enough,  one  can  provide  initial  values  by  simply  typing  
them  in.  For  example:  
 
                       a  =  3;  
                       b  =  [  1  2  3];  
                       c  =  [  4  ;  5  ;  6];  
                       d  =  [  1  2  3  ;  4  5  6];  
 
Here,  a  is  a  scalar,  b  is  a  {1*3}  row  vector,  c  a  {3*1}  column  vector,  and  d  is  a  
{2*3}  matrix.  Thus,  typing  "d"  produces:  
 
  d  =  
           1          2          3  
           4          5          6  
 

70
The  system  for  indicating  matrix  contents  is  very  simple.  Values  separated  
by  spaces  are  to  be  on  the  same  row;  those  separated  by  semicolons  are  on  to  be  
on  separate  rows.  All  values  are  enclosed  in  square  brackets.  
 
 

4.8. Making  Matrices  from  Matrices  


 
The   general   scheme   for   initializing   matrices   can   be   extended   to   include  
matrices  as  components.  For  example:  
 
         a  =  [1  2  3];  
         b  =  [4  5  6];  
         c  =  [a  b];  
 
gives:  
       c  =  
               1          2          3          4          5          6  
While:  
 
         d  =  [a  ;  b]  
 
gives:  
 
         d  =  
               1          2          3  
               4          5          6  
 
Matrices  can  easily  be  "pasted"  together  in  this  manner  -­‐-­‐  a  process  that  is  
both   simple   and   easily   understood   by   anyone   reading   a   procedure   (including   its  
author).   Of   course,   the   sizes   of   the   matrices   must   be   compatible.   If   they   are   not,  
MATLAB  will  tell  you.  
 
   

71
4.9. Using  Portions  of  Matrices  
 
Frequently   one   wishes   to   reference   only   a   portion   of   a   matrix.   MATLAB  
provides  simple  and  powerful  ways  to  do  so.  
To   reference   a   part   of   a   matrix,   give   the   matrix   name   followed   by  
parentheses   with   expressions   indicating   the   portion   desired.   The   simplest   case  
arises   when   only   one   element   is   wanted.   For   example,   using   d   in   the   previous  
section:  
 
       d(1,2)  equals  2  
       d(2,1)  equals  4  
 
In  every  case  the  first  parenthesized  expression  indicates  the  row  (or  rows),  
while   the   second   expression   indicates   the   column   (or   columns).   If   a   matrix   is,   in  
fact,  a  vector,  a  single  expression  may  be  given  to  indicate  the  desired  element,  but  
it   is   often   wise   to   give   both   row   and   column   information   explicitly,   even   in   such  
cases.  
 
MATLAB's  real  power  comes  into  play  when  more  than  a  single  element  of  a  
matrix   is   wanted.   To   indicate   "all   the   rows"   use   a   colon   for   the   first   expression.   To  
indicate  "all  the  columns",  use  a  colon  for  the  second  expression.  Thus,  with:  
   
       d  =  
               1          2          3  
               4          5            6  
     
     d(1,:)  equals  
               1          2          3  
 
       d(:,2)  equals  
               2  
               5  
 
In  fact,  you  may  use  any  expression  in  this  manner  as  long  as  it  evaluates  to  
a  vector  of  valid  row  or  column  numbers.  For  example:  
       d(2,[2  3])  equals  
                   5          6      
72
       d(2,  [3  2])  equals  
                   6          5  
 
Variables  may  also  be  used  as  "subscripts".  Thus:  
   if  
         z  =  [2  3]  
   then  
         d(2,z)  equals  
                   5          6    
 
Particularly   useful   in   this   context   (and   others)   is   the   construct   that   uses   a  
colon  to  produce  a  string  of  consecutive  integers.  For  example:  
     the  statement:  
 
                 x  =  3:5  
 
     produces  
               x  =  
                         3          4          5  
 
Thus:  
       d(1,  1:2)  equals  
2  
1          
 
 
 
4.10. Text  Strings  
 
MATLAB  is  wonderful  with  numbers.  It  deals  with  text  but  you  can  tell  that  
its  heart  isn't  in  it.  
 
A  variable  in  MATLAB  is  one  of  two  types:  numeric  or  string.  A  string  matrix  
is  like  any  other,  except  the  elements  in  it  are  interpreted  asASCII  numbers.  Thus  
the   number   32   represents   a   space,   the   number   65   a   capital   A,   etc..   To   create   a  
string   variable,   enclose   a   string   of   characters   in   "single"   quotation   marks   (actually,  
apostrophes),  thus:  
 

73
         stg  =  'This  is  a  string';  
 
Since   a   string   variable   is   in   fact   a   row   vector   of   numbers,   it   is   possible   to  
create  a  list  of  strings  by  creating  a  matrix  in  which  each  row  is  a  separate  string.  
As  with  all  standard  matrices,  the  rows  must  be  of  the  same  length.  Thus:  
 
     the  statement  
 
             x  =  ['ab'  ;  'cd']  
 
     produces:      
             x  =  
                       ab  
                       cd  
 
     while  
             x  =  ['ab'  'cd']  
     produces:  
             x  =  
                     abcd  
     as  always.  
 
 
4.11. Matrix  and  Array  Operations  
 
The   Mathworks   uses   the   term   matrix   operation   to   refer   to   standard  
procedures  such  as  matrix  multiplication.  The  term  array  operation  is  reserved  for  
element-­‐by-­‐element  computations.  

   

74
4.12. Matrix  Operations  
 
Matrix  transposition  is  as  easy  as  adding  a  prime  (apostrophe)  to  the  name  
of  the  matrix.  Thus:  
     if:  
         x  =  
             1  2  3  
     then:  
         x'  =  
               1        
               2  
               3  
 
To   add   two   matrices   of   the   same   size,   use   the   plus   (+)   sign.   To   subtract   one  
matrix  from  another  of  the  same  size,  use  a  minus  (-­‐)  sign.  If  a  matrix  needs  to  be  
"turned  around"  to  conform,  use  its  transpose.  Thus,  if  A  is  {3*4}  and  B  is  {4*3},  the  
statement:  
 
             C  =  A  +  B  
will  get  you  the  message:  
         ???  Error  using  ==>  +  
         Matrix  dimensions  must  agree.  
 
while:  
             C  =  A  +  B'  
will  get  you  a  new  matrix.  
 
There   is   one   case   in   which   addition   or   subtraction   works   when   the  
components   are   of   different   sizes.   If   one   is   a   scalar,   it   is   added   to   or   subtracted  
from  all  the  elements  in  the  other.  
 

75
Matrix  multiplication  is  indicated  by  an  asterisk  (*),  commonly  regarded  in  
programming   languages   as   a   "times   sign".   With   one   exception   the   usual   rules  
apply:   the   inner   dimensions   of   the   two   operands   must   be   the   same.   If   they   are   not,  
you  will  be  told  so.  The  one  allowed  exception  covers  the  case  in  which  one  of  the  
components   is   a   scalar.   In   this   instance,   the   scalar   value   is   multiplied   by   every  
element  in  the  matrix,  resulting  in  a  new  matrix  of  the  same  size.  
MATLAB   provides   two   notations   for   "matrix   division"   that   provide   rapid  
solutions  to  simultaneous  equation  or  linear  regression  problems.  They  are  better  
discussed  in  the  context  of  such  problems.  
 
 

4.13. Array  Operations  


 
To   indicate   an   array   (element-­‐by-­‐element)   operation,   precede   a   standard  
operator  with  a  period  (dot).  Thus:  
 
   if  x  =  
                   1          2          3  
   and  y  =  
                   4          5          6  
   then:  
           x.*y  =  
                   4        10        18  
 
   the  "dot  product"  of  x  and  y.  
 
You   may   divide   all   the   elements   in   one   matrix   by   the   corresponding  
elements  in  another,  producing  a  matrix  of  the  same  size,  as  in:  
           C  =  A  ./  B  
 
In  each  case,  one  of  the  operands  may  be  a  scalar.  This  proves  handy  when  
you  wish  to  raise  all  the  elements  in  a  matrix  to  a  power.  For  example:  
     if  x  =  
                 1          2          3  
     then:  
           x.^2  =    

76
                 1          4          9  
 
MATLAB   array   operations   include   multiplication   (.*),   division   (./)   and  
exponentiation  (.^).  Array  addition  and  subtraction  are  not  needed  (and  in  fact  are  
not  allowed),  since  they  would  simply  duplicate  the  operations  of  matrix  addition  
and  subtraction.  
 
 

4.14. Using  Functions  


 
MATLAB   has   a   number   of   built-­‐in   functions   -­‐-­‐   many   of   which   are   very  
powerful.  Some  provide  one  (matrix)  answer;  others  provide  two  or  more.  
 
You   may   use   any   function   in   an   expression.   If   it   returns   one   answer,   that  
answer  will  be  used.  The  sum  function  provides  an  example:  
 
     if  x  =  
                 1  
                 2  
                 3  
     then  the  statement:  
 
           y  =sum(x)  +  10  
 
     will  produce:  
           y  =  
                 16    
 
Some   functions,   such   as   max   provide   more   than   one   answer.   If   such   a  
function   is   included   in   an   expression,   only   the   first   answer   will   be   used.   For  
example:  
   
           if  x  =  
                       1          4          3  
 
           the  statement:  

77
 
                       z  =  10  +  max(x)  
 
           will  produce:  
 
                       z  =    
                               14  
 
To   get   all   the   answers   from   a   function   that   provides   more   than   one,   use   a  
multiple   assignment   statement   in   which   the   variables   that   are   to   receive   the  
answers  are  listed  to  the  left  of  the  equal  sign,  enclosed  in  square  brackets,  and  the  
function  is  on  the  right.  For  example:  
   
           if  x  =  
                       1          4          3  
 
           the  statement:  
                     [y  n]  =  max(x)  
 
           will  produce:  
 
                     y  =  
                             4  
                     n  =  
                             2  
 
In   this   case,   y   is   the   maximum   value   in   x,   and   n   indicates   the   position   in  
which  it  was  found.  
 
Many  of  MATLAB's  built-­‐in  functions,  such  as  sum,  min,  max,  and  mean  have  
natural   interpretations   when   applied   to   a   vector.   If   a   matrix   is   given   as   an  
argument   to   such   a   function,   its   procedure   is   applied   separately   to   each   column,  
and  a  row  vector  of  results  returned.  Thus:  
 
         if  x  =  
                         1          2          3  
                         4          5          6  
 
         then  :  
78
 
               sum(x)  =  
                         5          7          9  
 
Some  functions  provide  no  answers  per  se.  For  example,  to  plot  a  vector  y  
against  a  vector  x,  simply  use  the  statement:  
 
         plot(x,y)  
 
which  will  produce  the  desired  cross-­‐plot.  
 
Note  that  in  this  case,  two  arguments  (the  items  in  the  parentheses  after  the  
function   name)   were   provided   as   inputs   to   the   function.   Each   function   needs   a  
specific   number   of   inputs.   However,   some   have   been   programmed   to   react  
appropriately   when   fewer   are   given.   For   example,   to   plot   y   against   (1,2,3...),   you  
can  use  the  statement:  
 
         plot(y)  
 
There   are   many   built-­‐in   functions   in   MATLAB.   Among   them,   the   following  
are  particularly  useful  for  Macro-­‐Investment  Analysis:  
 
ones  ones  matrix  
zeros  zeros  matrix  
size  size  of  a  matrix  
diag  diagonal  elements  of  a  matrix  
inv    matrix  inverse  
rand  uniformly  distributed  random  numbers  
randn    normally  distributed  random  numbers  
cumprod  cumulative  product  of  elements  
cumsum    cumulative  sum  of  elements  
max    largest  component  
min    smallest  component  
sum    sum  of  elements  

79
mean    average  or  mean  value  
median    median  value  
std    standard  deviation  
sort    sort  in  ascending  order  
find    find  indices  of  nonzero  entries  
corrcoef    correlation  coefficients  
cov    covariance  matrix  
 
Not  listed,  but  of  great  use,  are  the  many  functions  that  provide  plots  of  data  
in   either   two   or   three   dimensions,   as   well   as   a   number   of   more   specialized  
functions.   However,   this   list   should   serve   to   whet   the   Analyst's   appetite.   The   full  
list  of  functions  and  information  on  each  one  can  be  obtained  via  MATLAB's  on-­‐line  
help  system.  
 
 

4.15. Logical  and  Relational  Operations  on  Matrices  


 
MATLAB  offers  six  relational  operators:  
 
<  :  less  than  
<=  :  less  than  or  equal  to  
>  :  greater  than  
>=  :  greater  than  or  equal  to  
==  :  equal  
~=  :  not  equal  
 
Note   carefully   the   difference   between   the   double   equality   and   the   single  
equality.   Thus   A==B   should   be   read   "A   is   equal   to   B",   while   A=B   should   be   read   "A  
should   be   assigned   the   value   of   B".   The   former   is   a   logical   relation,   the   latter   an  
assignment  statement.  
 
Whenever   MATLAB   encounters   a   relational   operator,   it   produces   a   one   if  
the  expression  is  true  and  a  zero  if  the  expression  is  false.  Thus:  
     the  statement:  

80
 
               x  =  1  <  3  produces:  x=1,  while  
               x  =  1  >  3  produces:  x=0  
 
Relational   operators   can   be   used   on   matrices,   as   long   as   they   are   of   the  
same  size.  Operations  are  performed  element-­‐by-­‐element,  resulting  a  matrix  with  
ones  in  positions  for  which  the  relation  was  true  and  zeros  in  positions  for  which  
the  relation  was  false.  Thus:  
 
       if  A  =  
                   1          2  
                   3          4  
 
       and  B  =    
                   3          1  
                   2          2  
         
the  statement:  
 
                   C  =  A  >  B  
 
       produces:  
             C  =  
                   0          1  
                   1          1  
 
One   or   both   of   the   operands   connected   by   a   relational   operator   can   be   a  
scalar.  Thus:  
 
         if  A  =  
                   1          2  
                   3          4  
 
         the  statement:  
                   C  =  A  >  2  
 
         produces:  
               C  =  

81
                   0          0  
                   1          1    
 
One  may  also  use  logical  operators  of  which  there  are  three:  
 
&  :  and  
|  :  or  
~  :  not  
 
Each   works   with   matrices   on   an   element-­‐by-­‐element   basis   and   conforms   to  
the   ordinary   rules   of   logic,   treating   any   non-­‐zero   element   as   true   and   any   zero  
element  as  false.  
 
Relational   and   logical   operators   are   used   frequently   with   If   statements  
(described   below)   and   scalar   variables,   as   in   more   mundane   programming  
languages.   But   the   ability   to   use   them   with   matrices   offers   major   advantages   in  
some  Investment  applications.  
 
 

4.16. Sorting  Matrices  


 
To  sort  a  matrix  in  ascending  order,  use  the  sort  function.  If  the  argument  is  
a  vector,  the  result  will  be  a  new  vector  with  the  items  in  the  desired  order.  If  it  is  a  
matrix,   the   result   will   be   a   new   matrix   in   which   each   column   will   contain   the  
contents   of   the   corresponding   column   from   the   old   matrix,   in   ascending   order.  
Note  that  in  the  latter  case,  each  column  is,  in  effect,  sorted  separately.  Thus:  
 
     if  x  =  
                   1          5  
                   3          2  
                   2          8  
 
   the  statement:    
         
y=sort(x)  
 

82
   will  produce:  
             y  =  
                   1          2  
                   2          5  
                   3          8  
 
To   obtain   a   record   of   the   rows   from   which   each   of   the   sorted   elements  
came,  use  a  multiple  assignment  to  get  the  second  output  of  the  function.  For  the  
case  above:  
 
     the  statement:  
           [y  r]  =  sort(x)  
     would  produce  y  as  before  and    
         
     r  =  
                     1          2  
                     3          1  
                     2          3  
 
Thus  the  second  item  in  the  sorted  list  in  column  1  came  from  row  3,  etc..  
 
 

4.17. Controlling  Execution  Flow  


 
It  is  possible  to  do  a  great  deal  in  MATLAB  by  simply  executing  statements  
involving   matrix   expressions,   one   after   the   other,   However,   there   are   cases   in  
which   one   simply   must   substitute   some   non-­‐sequential   order.   To   facilitate   this,  
MATLAB  provides  three  relatively  standard  methods  for  controlling  program  flow:  
For  Loops,  While  Loops,  and  If  statements  
   

83
4.18. For  Loops  
 
The  most  common  use  of  a  For  Loop  arises  when  a  set  of  statements  is  to  be  
repeated  a  fixed  number  of  times,  as  in:  
 
     for  j=  1:n  
           .......  
     end  
 
There  are  fancier  ways  to  use  For  Loops,  but  for  our  purposes,  the  standard  
one  suffices.  
 
 

4.19. While  Loops  


 
A   While   Loop   contains   statements   to   be   executed   as   long   as   a   stated  
condition  remains  true,  as  in:  
 
     while  x  >  0.5  
           .......  
     end  
 
It  is,  of  course,  crucial  that  at  some  point  a  statement  will  be  executed  that  
will  cause  the  condition  in  the  While  statement  to  be  false.  If  this  is  not  the  case,  
you  have  created  an  infinite  loop   -­‐-­‐  one  that  will  go  merrily  on  until  you  pull  the  
plug.  
 
For   readability,   it   is   sometimes   useful   to   create   variables   for   TRUE   and  
FALSE,  then  use  them  in  a  While  Loop.  For  example:  
     
 true  =  1==1;  
     false  =  1==0;  
     .....  
     done  =  false;  
     while  not  done  
               ........  
84
     end  
 
Of   course,   somewhere   in   the   While   loop   there   should   be   a   statement   that  
will  at  some  point  set  done  equal  to  true.  
 
 

4.20. If  Statements  
 
A   If   Statement   provides   a   method   for   executing   certain   statements   if   a  
condition   is   true   and   other   statements   (or   none)   if   the   condition   is   false.   For  
example:  
         If  x  >  0.5  
                 ........  
             else  
                 .......  
         end  
In   this   case,   if   x   is   greater   than   0.5   the   first   set   of   statements   will   be  
executed;  if  not,  the  second  set  will  be  executed.  
 
A  simpler  version  omits  the  "else  section",  as  in:  
         If  x  >  0.5  
                 ........  
       end  
 
Here,  the  statements  will  be  executed  if  (but  only  if)  x  exceeds  0.5.  
 
   

85
4.21. Nesting  
 
All   three   of   these   structures   allow   nesting,   in   which   one   type   of   structure  
lies  within  another.  For  example:  
 
         for  j  =  1:n  
               for  k  =  1:n  
                   if  x(j,k)  >  0.5  
                           x(j,k)  =  1.5;  
                   end  
             end  
     end  
 
The  indentation  is  for  the  reader's  benefit,  but  highly  recommended  in  this  
and   other   situations.   MATLAB   will   pair   up   end   statements   with   preceding   for,  
while,   or   if   statements   in   a   last-­‐come-­‐first-­‐served   manner.   It   is   up   to   the  
programmer   to   ensure   that   this   will   give   the   desired   results.   Indenting   can   help,  
but  hardly  guarantees  success  on  every  occasion.  
 
While   it   is   tempting   for   those   with   experience   in   traditional   programming  
languages   to   take   the   easy   way   out,   using   For   and   While   loops   for   mathematical  
operations,   this   temptation   should   be   resisted   strenuously.   For   example,   instead  
of:  
 
   port_val  =  0;  
     for  j  =  1:n  
               port_val  =  port_val  +  (  holdings(j)  *  prices(j));  
     end  
write:  
       port_val  =  holdings*prices;  
 
The   latter   is   more   succinct,   far   clearer,   and   will   run   much   faster.   MATLAB  
performs   matrix   operations   at   blinding   speed,   but   can   be   downright   glacial   at  
times   when   loops   are   to   be   executed   a   great   many   times,   since   it   must   do   a   certain  
amount  of  translation  of  each  statement  every  time  it  is  encountered.  
 
 
86
4.22. Writing  Functions  
 
The   power   of   MATLAB   really   comes   into   play   when   you   add   your   own  
functions  to  enhance  the  language.  Once  a  function  m-­‐file  is  written,  debugged,  and  
placed   in   an   appropriate   directory,   it   is   for   all   practical   purposes   part   of   your  
version  of  MATLAB.  
 
A  function  file  starts  with  a  line  declaring  the  function,  its  arguments  and  its  
outputs.   There   follow   the   statements   required   to   produce   the   outputs   from   the  
inputs  (arguments).  That's  it.  
 
Here  is  a  simple  example:  
 
     function  y  =  port_val(holdings,prices)  
     y  =  holdings*prices;    
 
Of  course,  this  will  only  work  if  the  holdings  and  prices  vectors  or  matrices  
are   compatible   for   matrix   multiplication.   A   more   complex   version   could   examine  
the  sizes  of  these  two  matrices,  then  use  transposes,  etc.  as  required.  
 
It   is   important   to   note   that   the   argument   and   output   names   used   in   a  
function   file   are   strictly   local   variables   that   exist   only   within   the   function   itself.  
Thus  in  a  program,  one  could  write  the  statement:  
 
             v  =    port_val(h,p);  
 
The  first  matrix  in  the  argument  list  in  this  calling  statement  (here,  h)  would  
be   assigned   to   the   first   argument   in   the   function   (here,   holdings)   while   the   second  
matrix  in  the  calling  statement  (p)  would  be  assigned  to  the  second  matrix  in  the  
function   (prices).   There   is   no   need   for   the   names   to   be   the   same   in   any   respect.  
Moreover,   the   function   cannot   change   the   original   arguments   in   any   way.   It   can  
only  return  information  via  its  output.  

87
This   function   returns   only   one   output,   called   y   internally.   However,   the  
resultant   matrix   will   be   substituted   for   the   entire   argument   "call"   in   any  
expression.  
 
If   a   function   is   to   return   two   or   more   arguments,   simply   assign   them   names  
in  the  declaration  line,  as  in:  
 
     function  [total_val,  avg_val]  =  port_val(holdings,prices)  
     total_val  =  holdings*prices;  
     avg_val  =  total_val/size(holdings,2);    
 
This  can  still  be  used  as  in  the  earlier  case  if  only  the  total  value  is  desired.  
To  get  both  the  total  value  and  the  average  value  per  position,  a  program  could  use  
a  statement  such  as:  
 
     [tval  aval]  =  port_val(  h,p);  
 
Note  that  as  with  inputs,  the  correspondence  between  outputs  in  the  calling  
statement   and   the   function   itself   is   strictly   by   order.   When   the   function   has  
finished   its   work,   its   output   values   are   assigned   to   the   variables   in   the   calling  
statement.  
 
Variables   other   than   inputs   and   arguments   may   be   included   in   functions,   as  
needed.   They   are   strictly   local   to   the   function   and   have   no   existence   outside   it.  
Indeed,  a  variable  in  a  function  may  have  the  same  name  as  one  in  another  place;  
the  two  will  coexist  with  neither  bothering  the  other.  While  MATLAB  provides  for  
the  use  of  "global  variables",  their  use  is  widely  discouraged  and  will  not  be  treated  
here.  
   

88
4.23. Comments  and  Help  
 
It  is  an  excellent  idea  to  include  comments  throughout  any  m-­‐file.  To  do  so,  
use   the   percent   (%)   sign.   Everything   after   it   up   to   the   end   of   the   line   will   be  
ignored  by  MATLAB.  
 
The   first   several   lines   after   each   function   header   should   provide   a   brief  
description   of   the   function   and   its   use.   Once   the   function   has   been   placed   in   an  
appropriate  directory,  a  user  need  only  type  help  followed  by  the  function  name  to  
be   shown   all   the   initial   comment   lines   (up   to   the   first   non-­‐comment   or   totally  
blank   line).   Thus   if   there   is   a   function   named   port_val,   the   user   can   get   this  
information  by  typing:  
 
           help  port_val    
 
To   provide   even   more   assistance,   create   a   script   file   with   nothing   but  
comment  lines,  each  giving  the  name  and  a  brief  description  of  all  your  functions  
and  scripts.  If  this  were  named  mia_fun,  the  user  could  simply  type:  
 
           help  mia_fun  
 
to   get   a   list   of   your   functions,   then   type   help   function   name   to   get   more  
details  on  any  specific  function.  
 
 

4.24. Data  Input  and  Output  


 
There   are   many   ways   to   get   information   into   and   out   of   the   MATLAB  
environment.  We  will  cover  only  the  simpler  ones  here.  
   

89
4.25. Data  Input  
 
The  most  straightforward  way  to  get  information  into  MATLAB  is  to  type  it  
in  "command  mode".  For  example:  
 
     prices  =  [  12.50  37.875    12.25];  
     assets  =  ['cash    ';'bonds  '  ;  'stocks'];  
 
MATLAB   even   makes   it   easy   to   enter   matrices   in   a   more   normal   form   by  
treating  carriage  returns  as  semicolons  within  brackets.  Thus:  
 
         holdings  =  [  100  200  
                                   300  400    
                                   500  600  ]  
 
will  create  a  {3*2}  matrix,  as  desired.  
 
A   second   way   to   get   data   into   MATLAB   is   to   create   a   script   file   with   the  
required   statements,   such   as   the   one   above.   This   can   be   done   with   any   text  
processor.  Large  matrices  of  data  can  even  be  "cut  out"  of  databases,  spreadsheets,  
etc.  then  edited  to  include  the  desired  variable  names,  square  brackets  and  the  like.  
Once  the  file  or  files  are  saved  with  .m  names  they  only  have  to  be  invoked  to  bring  
the  data  into  MATLAB.  
 
Next   up   the   chain   of   complexity   is   the   use   of   a   flat   file   which   stores   data   for  
a  matrix.  Such  a  file  should  have  numeric  ascii  text  characters,  with  each  element  
in  a  row  separated  from  its  neighbor  with  a  space  and  each  row  on  a  separate  line.  
Say,   for   example,   that   you   have   stored   the   elements   of   a   matrix   in   a   file   named  
test.txt  in  a  directory  on  the  MATLAB  path.    
 
Then  the  statement:  
       load  test.txt  
 
will  create  a  matrix  named  test  containing  the  data.  
 
90
 

4.26. Data  Output  


 
A  simple  way  to  output  data  is  to  display  a  matrix.  This  can  be  accomplished  
by  either  giving  its  name  (without  a  semicolon)  in  interactive  mode.  Alternatively  
you   can   use   the   disp   function,   which   shows   values   without   the   variable   name,   as  
in:  
 
       disp(test);  
 
For  prettier  output,  MATLAB  has  various  functions  for  creating  strings  from  
numbers,  formatting  data,  etc..  Function  pmat  can  produce  small  tables  with  string  
identifiers  on  the  borders.  
 
If  you  want  to  save  almost  everything  that  appears  on  your  screen,  issue  the  
command:  
 
       diary  filename  
 
where   filename   represents   the   name   of   a   new   file   that   will   receive   the  
subsequent  output.  When  you  are  through,  issue  the  command:  
 
       diary  off  
 
Later,  at  your  leisure,  you  may  use  a  text  editor  to  extract  data,  commands,  
etc.  to  data  files,  script  or  function  files,  and  so  on.  
 
There  are,  of  course,  other  alternatives.  If  you  are  in  an  environment  (such  
as   a   Windows   system)   that   allows   material   to   be   copied   from   one   program   and  
pasted  into  another,  this  may  suffice.  
 
To  create  a  flat  file  containing  the  data  from  a  matrix  use  the  -­‐ascii  version  
of  the  save  command.  For  example:  
 
91
         save  newdata.txt  test  –ascii  
 
will  save  the  matrix  named  test  in  the  file  named  newdata.txt.  
 
Finally,  you  may  save  all  or  part  of  the  material  from  a  MATLAB  session  in  
MATLAB's  own  mat  file  format.  To  save  all  the  variables  in  a  file  named  temp.mat,  
issue  the  command:  
 
         save  temp  
 
At   some   later   session   you   may   load   all   this   information   by   simply   issuing  
the  command:  
 
         load  temp  
 
To   save   only   one   or   more   matrices   in   this   manner,   list   their   names   after   the  
file  name.  Thus:  
 
         save  temp  prices    holdings    portval  
 
would   save   only   these   three   matrices   in   file   temp.mat.   Subsequent   use   of  
the  command:  
 
         load  temp  
 
would  restore  the  three  named  matrices,  with  their  values  intact.  
There   are   more   sophisticated   ways   to   move   information   into   and   out   of  
MATLAB,  but  they  can  be  left  to  others.  
 

4.27. FRONTCON  FUNCTION  


Frontcon  is  a  function  of  Matlab  that  allows  us  to  obtain  the  mean-­‐variance  
efficient  frontier.  This  function  has  three  main  inputs:  (i)  the  1  by  N  (being  N  the  
number  of  assets)  vector  of  expected  returns  of  the  assets;  (ii)  the  N  by  N  variance-­‐

92
covariance  matrix;  (iii)  and  the  number  of  portfolios  that  you  want  to  use  to  build  
the  efficient  frontier.    
You  can  also  included  constrains  to  the  weights  as  an  input,  as  we  did  with  
Solver  in  Excel.    
In   this   case,   after   including   as   inputs   the   expected   returns,   the   variance-­‐
covariance   matrix   and   the   number   of   ports,   you   have   to   leave   a   blank   between  
brackets  and  then  introduce  as  an  argument  a  2  by  N  matrix  containing  the  lower  
and  upper  bounds  for  each  asset  of  the  portfolio  (lower  bounds  in  the  first  row  and  
upper   bounds   in   the   second   row).   In   this   example,   we   are   going   to   consider   as  
bounds  the  130/30  constraint.  
So,  once  you  have  all  data  (expected  return,  variance-­‐covariance  matrix),  the  
number  of  ports  and  the  bounds…    

 
 
…  You  are  able  to  use  the  frontcon  function  in  Matlab  which  will  give  you  as  
outputs   the   risk,   the   return   and   the   weights   of   each   of   the   portfolios   you   use   to  
build   your   efficient   frontier.   It   would   be   a   good   idea   to   end   the   function   with   a  
semi-­‐colon  to  order  Matlab  not  to  show  all  the  portfolios  (in  the  example  below  we  
are  building  our  efficient  frontier  with  1.000  portfolios).  The  function  will  look  like  
this:    
 
93
 
 
As  you  can  see,  now  you  have  in  your  workspace  the  matrix  that  contains  the  
returns,   variance   and   weights   of   the   1.000   portfolios   that   we   use   to   build   our  
efficient  frontier.    
Once  you  have  your  efficient  frontier,  you  are  able  to  find  the  portfolio  that  
maximizes  the  Sharpe-­‐ratio,  given  the  risk-­‐free  rate.  This  is  shown  in  section  5.  
 
 
 

94
95
5. APPLYING  MATLAB  TO  FINANCE  
 

5.1. Report  1:  Portfolio  Theory  (2  Assets)  


 

Portfolio  Theory  

Portfolio  return,  variance  and  covariance  calculation  

Antonio  Rivela  IE  Business  School  2011  

File:  S3S4_MIF2011.m  

Contents  

• Importing  data  
• Plotting  Data  
• Transposing  matrices  
• Choosing  parts  of  matrices  
• Calculate  the  returns  of  both  stocks  
• Calculating  variances  from  returns  
 

Importing  data  

You  use  the  Load  command  to  upload  data  to  Matlab  

%  Clear  the  screen  


clc  
%  Load  the  Prices  variable  (posted  in  Online  Campus)  
load  Prices  

96
%  Show  Prices  variable  
Prices  
Prices  =  
 
     26.0700      37.4000  
     22.0000      33.5300  
     20.0700      30.7300  
     20.0200      30.1500  
     23.3500      36.3800  
     24.7900      39.7900  
     23.0300      43.0400  
     18.0900      40.6600  
     19.1700      41.8500  
     20.2500      42.3600  
     22.7900      40.2900  
     20.5200      37.0300  
     16.5000      32.4100  
     16.2700      33.3000  
     14.9200      28.7400  
     18.0100      29.3200  
     22.4300      33.9200  
     21.7500      29.2600  
     18.4300      27.5100  
     18.8700      28.0000  
     18.6700      28.6000  
     16.3200      32.6900  
     16.5700      35.8700  
     16.1200      37.0500  
     17.9100      37.5200  
     20.4500      39.8300  

97
     20.6000      36.9100  
     22.9200      38.9800  
     24.1200      38.0500  
     25.4700      37.7400  
     25.5000      37.3100  
     30.0600      43.2700  
     33.8700      44.3400  
     33.1000      42.6900  
     34.9700      44.0800  
     36.9100      41.8800  
     39.2300      42.9900  
     37.5800      44.0400  
     34.6000      44.7000  
     34.0400      49.4100  
     37.9900      50.6800  
     40.7400      51.3800  
     42.1700      50.2300  
     43.9200      50.3600  
     51.2500      49.5700  
     46.9200      45.9900  
     49.2500      53.3000  
     52.0400      54.0000  
     55.6900      58.3100  
     48.2400      53.4500  
     47.0400      51.6400  
     50.9300      55.3700  
     52.1900      53.3100  
     55.3100      54.7600  
     55.6300      54.5400  
     58.4600      54.2900  

98
     60.2300      51.9000  
     65.4600      52.9900  
     60.8400      48.9200  
     67.5100      48.8700  
     67.6500      49.1700  
 
Plotting  Data  

Plot  the  prices  with  a  nice  format  

%  Create  figure  
figure1  =  figure('XVisual',...  
       '0x24  (TrueColor,  depth  24,  RGB  mask  0xff0000  0xff00  0x00ff)');  
%  Create  axes  
axes1  =  axes('Parent',figure1);  
box(axes1,'on');  
hold(axes1,'all');  
%  Create  xlabel  
xlabel('Monthly  Observations');  
%  Create  ylabel  
ylabel('Price');  
%  Create  title  
title('Walmart  &  Target  Prices');  
%  Create  multiple  lines  using  matrix  input  to  plot  
plot1  =  plot(Prices,'Parent',axes1);  
set(plot1(1),'DisplayName','Walmart');  
set(plot1(2),'DisplayName','Target');  
%  Create  legend  
legend1  =  legend(axes1,'show');  
set(legend1,...  

99
       'Position',[0.63782816229117   0.328846153846154   0.239856801909308  
0.192948717948718]);  

Transposing  matrices  

You  use  Transpose  or  the  '  to  transpose  

%  Transpose  the  Prices  variable  


Prices'  
%  Assign  the  Prices  variable  to  new  variable  'a'  
a=Prices'  
ans  =  
 
   Columns  1  through  15  
 
     26.0700       22.0000       20.0700       20.0200       23.3500       24.7900       23.0300      
100
18.0900       19.1700       20.2500       22.7900       20.5200       16.5000       16.2700      
14.9200  
     37.4000       33.5300       30.7300       30.1500       36.3800       39.7900       43.0400      
40.6600       41.8500       42.3600       40.2900       37.0300       32.4100       33.3000      
28.7400  
 
   Columns  16  through  30  
 
     18.0100       22.4300       21.7500       18.4300       18.8700       18.6700       16.3200      
16.5700       16.1200       17.9100       20.4500       20.6000       22.9200       24.1200      
25.4700  
     29.3200       33.9200       29.2600       27.5100       28.0000       28.6000       32.6900      
35.8700       37.0500       37.5200       39.8300       36.9100       38.9800       38.0500      
37.7400  
 
   Columns  31  through  45  
 
     25.5000       30.0600       33.8700       33.1000       34.9700       36.9100       39.2300      
37.5800       34.6000       34.0400       37.9900       40.7400       42.1700       43.9200      
51.2500  
     37.3100       43.2700       44.3400       42.6900       44.0800       41.8800       42.9900      
44.0400       44.7000       49.4100       50.6800       51.3800       50.2300       50.3600      
49.5700  
 
   Columns  46  through  60  
 
     46.9200       49.2500       52.0400       55.6900       48.2400       47.0400       50.9300      
52.1900       55.3100       55.6300       58.4600       60.2300       65.4600       60.8400      
67.5100  
     45.9900       53.3000       54.0000       58.3100       53.4500       51.6400       55.3700      

101
53.3100       54.7600       54.5400       54.2900       51.9000       52.9900       48.9200      
48.8700  
 
   Column  61  
 
     67.6500  
     49.1700  
 
 
a  =  
 
   Columns  1  through  15  
 
     26.0700       22.0000       20.0700       20.0200       23.3500       24.7900       23.0300      
18.0900       19.1700       20.2500       22.7900       20.5200       16.5000       16.2700      
14.9200  
     37.4000       33.5300       30.7300       30.1500       36.3800       39.7900       43.0400      
40.6600       41.8500       42.3600       40.2900       37.0300       32.4100       33.3000      
28.7400  
 
   Columns  16  through  30  
 
     18.0100       22.4300       21.7500       18.4300       18.8700       18.6700       16.3200      
16.5700       16.1200       17.9100       20.4500       20.6000       22.9200       24.1200      
25.4700  
     29.3200       33.9200       29.2600       27.5100       28.0000       28.6000       32.6900      
35.8700       37.0500       37.5200       39.8300       36.9100       38.9800       38.0500      
37.7400  
 
   Columns  31  through  45  

102
 
     25.5000       30.0600       33.8700       33.1000       34.9700       36.9100       39.2300      
37.5800       34.6000       34.0400       37.9900       40.7400       42.1700       43.9200      
51.2500  
     37.3100       43.2700       44.3400       42.6900       44.0800       41.8800       42.9900      
44.0400       44.7000       49.4100       50.6800       51.3800       50.2300       50.3600      
49.5700  
 
   Columns  46  through  60  
 
     46.9200       49.2500       52.0400       55.6900       48.2400       47.0400       50.9300      
52.1900       55.3100       55.6300       58.4600       60.2300       65.4600       60.8400      
67.5100  
     45.9900       53.3000       54.0000       58.3100       53.4500       51.6400       55.3700      
53.3100       54.7600       54.5400       54.2900       51.9000       52.9900       48.9200      
48.8700  
 
   Column  61  
 
     67.6500  
     49.1700  
 
Choosing  parts  of  matrices  

You  use  the  subindices  between  parenthesis  to  choose  specific  


elements  Show  the  following  elements  of  the  matrix  Prices  

P_1_2=Prices(1,2)  
P_2_1=Prices(2,1)  
P_1_1=Prices(1,1)  

103
 
%  Show  different  matrixes  extracted  from  Prices  
P_from_1_to_5_1=Prices(1:5,1)  
P_from_1_to_5_2=Prices(1:5,2)  
P_from_1_to_end_1=Prices(1:end-­‐2,1)  
P_from_1_to_7_both=Prices(1:7,1:2)  
P_from_9_to_end_both=Prices(9:end,1:2)  
P_1_2  =  
 
     37.4000  
 
 
P_2_1  =  
 
       22  
 
 
P_1_1  =  
 
     26.0700  
 
 
P_from_1_to_5_1  =  
 
     26.0700  
     22.0000  
     20.0700  
     20.0200  
     23.3500  
 

104
 
P_from_1_to_5_2  =  
 
     37.4000  
     33.5300  
     30.7300  
     30.1500  
     36.3800  
 
 
P_from_1_to_end_1  =  
 
     26.0700  
     22.0000  
     20.0700  
     20.0200  
     23.3500  
     24.7900  
     23.0300  
     18.0900  
     19.1700  
     20.2500  
     22.7900  
     20.5200  
     16.5000  
     16.2700  
     14.9200  
     18.0100  
     22.4300  
     21.7500  

105
     18.4300  
     18.8700  
     18.6700  
     16.3200  
     16.5700  
     16.1200  
     17.9100  
     20.4500  
     20.6000  
     22.9200  
     24.1200  
     25.4700  
     25.5000  
     30.0600  
     33.8700  
     33.1000  
     34.9700  
     36.9100  
     39.2300  
     37.5800  
     34.6000  
     34.0400  
     37.9900  
     40.7400  
     42.1700  
     43.9200  
     51.2500  
     46.9200  
     49.2500  
     52.0400  

106
     55.6900  
     48.2400  
     47.0400  
     50.9300  
     52.1900  
     55.3100  
     55.6300  
     58.4600  
     60.2300  
     65.4600  
     60.8400  
 
 
P_from_1_to_7_both  =  
 
     26.0700      37.4000  
     22.0000      33.5300  
     20.0700      30.7300  
     20.0200      30.1500  
     23.3500      36.3800  
     24.7900      39.7900  
     23.0300      43.0400  
 
 
P_from_9_to_end_both  =  
 
     19.1700      41.8500  
     20.2500      42.3600  
     22.7900      40.2900  
     20.5200      37.0300  

107
     16.5000      32.4100  
     16.2700      33.3000  
     14.9200      28.7400  
     18.0100      29.3200  
     22.4300      33.9200  
     21.7500      29.2600  
     18.4300      27.5100  
     18.8700      28.0000  
     18.6700      28.6000  
     16.3200      32.6900  
     16.5700      35.8700  
     16.1200      37.0500  
     17.9100      37.5200  
     20.4500      39.8300  
     20.6000      36.9100  
     22.9200      38.9800  
     24.1200      38.0500  
     25.4700      37.7400  
     25.5000      37.3100  
     30.0600      43.2700  
     33.8700      44.3400  
     33.1000      42.6900  
     34.9700      44.0800  
     36.9100      41.8800  
     39.2300      42.9900  
     37.5800      44.0400  
     34.6000      44.7000  
     34.0400      49.4100  
     37.9900      50.6800  
     40.7400      51.3800  

108
     42.1700      50.2300  
     43.9200      50.3600  
     51.2500      49.5700  
     46.9200      45.9900  
     49.2500      53.3000  
     52.0400      54.0000  
     55.6900      58.3100  
     48.2400      53.4500  
     47.0400      51.6400  
     50.9300      55.3700  
     52.1900      53.3100  
     55.3100      54.7600  
     55.6300      54.5400  
     58.4600      54.2900  
     60.2300      51.9000  
     65.4600      52.9900  
     60.8400      48.9200  
     67.5100      48.8700  
     67.6500      49.1700  
 
Calculate  the  returns  of  both  stocks  

The  dot  operator  '.'  is  key  in  order  to  perform  this  calculation  
The   dot   operator   performs   element   by   element   vector/matrix  
operations  

ret=log(Prices(2:end,1:2)./Prices(1:end-­‐1,1:2))  
ret  =  
 
     -­‐0.1697      -­‐0.1092  
109
     -­‐0.0918      -­‐0.0872  
     -­‐0.0025      -­‐0.0191  
       0.1539        0.1878  
       0.0598        0.0896  
     -­‐0.0736        0.0785  
     -­‐0.2414      -­‐0.0569  
       0.0580        0.0288  
       0.0548        0.0121  
       0.1182      -­‐0.0501  
     -­‐0.1049      -­‐0.0844  
     -­‐0.2180      -­‐0.1333  
     -­‐0.0140        0.0271  
     -­‐0.0866      -­‐0.1473  
       0.1882        0.0200  
       0.2195        0.1457  
     -­‐0.0308      -­‐0.1478  
     -­‐0.1656      -­‐0.0617  
       0.0236        0.0177  
     -­‐0.0107        0.0212  
     -­‐0.1345        0.1337  
       0.0152        0.0928  
     -­‐0.0275        0.0324  
       0.1053        0.0126  
       0.1326        0.0597  
       0.0073      -­‐0.0761  
       0.1067        0.0546  
       0.0510      -­‐0.0241  
       0.0545      -­‐0.0082  
       0.0012      -­‐0.0115  
       0.1645        0.1482  

110
       0.1193        0.0244  
     -­‐0.0230      -­‐0.0379  
       0.0550        0.0320  
       0.0540      -­‐0.0512  
       0.0610        0.0262  
     -­‐0.0430        0.0241  
     -­‐0.0826        0.0149  
     -­‐0.0163        0.1002  
       0.1098        0.0254  
       0.0699        0.0137  
       0.0345      -­‐0.0226  
       0.0407        0.0026  
       0.1543      -­‐0.0158  
     -­‐0.0883      -­‐0.0750  
       0.0485        0.1475  
       0.0551        0.0130  
       0.0678        0.0768  
     -­‐0.1436      -­‐0.0870  
     -­‐0.0252      -­‐0.0345  
       0.0795        0.0697  
       0.0244      -­‐0.0379  
       0.0581        0.0268  
       0.0058      -­‐0.0040  
       0.0496      -­‐0.0046  
       0.0298      -­‐0.0450  
       0.0833        0.0208  
     -­‐0.0732      -­‐0.0799  
       0.1040      -­‐0.0010  
       0.0021        0.0061  
 

111
Calculating  variances  from  returns  

Sample  variance  not  population  variance  (argument  needs  to  


be  one)  

var(ret)  
%  Population  variance!  was  calculated  fine  
var(ret,1)  
ans  =  
 
       0.0094        0.0053  
 
 
ans  =  
 
       0.0093        0.0052  
 

112
5.2. Report  2:  Portfolio  Theory  (4  Assets)  
 

Portfolio  Theory  

Portfolio  return,  variance  and  covariance  calculation  

Antonio  Rivela  IE  Business  School  2011  

File:  Session4_MIF2011.m  

Contents  

• Importing  data  
• Assigning  data  to  variables  
• Calculating  average  return  for  portfolio  i  
• Calculating  average  return  for  portfolio  j  
• Calculating  variance  for  portfolio  i  
• Calculating  variance  for  portfolio  j  
• Calculating  co-­‐variance  for  portfolios  
 

Importing  data  
%  Load  tha  data  posted  in  online  campus  s  
load  s  
 

Assigning  data  to  variables  

This  is  the  average  returns  vector  for  the  stocks  portfolio  

Er=[0.06  0.05  0.07  0.08]'  


 
%  This  is  the  variance-­‐covariance  matrix  
s  
%  Portfolio  i  is  comprised  by  the  following  weights  allocated  on  each  stock  
wi=[.1  .1  .1  .7]'  
%  Portfolio  j  is  comprised  by  the  following  weights  allocated  on  each  stock  
wj=[.9  .05  .05  0]'  
Er  =  

113
 
       0.0600  
       0.0500  
       0.0700  
       0.0800  
 
 
s  =  
 
       0.4000        0.0300        0.0200                  0  
       0.0300        0.2000                  0      -­‐0.0600  
       0.0200                  0        0.3000        0.0300  
                 0      -­‐0.0600        0.0300        0.1000  
 
 
wi  =  
 
       0.1000  
       0.1000  
       0.1000  
       0.7000  
 
 
wj  =  
 
       0.9000  
       0.0500  
       0.0500  
                 0  
 
Calculating  average  return  for  portfolio  i  
This  is  the  average  return  of  portfolio  i  

 
Er_i=wi'*Er  
Er_i  =  
 
       0.0740  
 
Calculating  average  return  for  portfolio  j  
This  is  the  average  return  of  portfolio  j  
114
 
Er_j=wj'*Er  
Er_j  =  
 
       0.0600  
 
Calculating  variance  for  portfolio  i  
This  is  the  variance  of  portfolio  i  

 
var_i=wi'*s*wi  
var_i  =  
 
       0.0548  
 
 

Calculating  variance  for  portfolio  j  


This  is  the  variance  of  portfolio  j  

 
var_j=wj'*s*wj  
var_j  =  
 
       0.3298  
 
 
Calculating  co-­‐variance  for  portfolios  
This  is  the  co-­‐variance  of  portfolio  i  and  portfolio  j  

 
covar_ij=wj'*s*wi  
covar_ij  =  
 
       0.0422  
115
 

116
5.3. Report  3:  Portfolio  Theory  (Real  Life  Constrains)  
Envelope  with  2  Efficient  Portfolios,  Efficient  Portfolios,  GMVP    

Antonio  Rivela  IE  Business  School  2011  

File:  MIF_Session5.m  

Contents  
• Load  the  sample  information  for  the  following  equation:  
• Calculate  stock  returns  
• Calculate  the  variance  of  the  population  
• Calculate  the  standard  deviation  of  the  population  
• Calculate  the  covariance  of  the  population  
• Calculate  the  number  of  assets  of  the  sample  
• Display  the  stocks  returns/volatilities  
• Efficient  Portfolio  A  c=1%  (short  selling  allowed)  
• Efficient  Portfolio  B  c=5%  (short  selling  allowed)  
• Covariance  between  portfolio  A  and  portfolio  B  
• Weights  from  -­‐4  to  6  
• Formulas  that  apply  to  2  portfolios  only  for  the  mean  
• Formulas  that  apply  to  2  portfolios  only  for  the  standard  deviation  
• Plot  for  2  efficient  portfolio  a,b  with  weight  w  and  weight(1-­‐w)  
• GMVP  Calculation  
• Plot  efficient  portfolio  A,  portfolio  B  and  the  GMVP  
• Efficient  Portfolio  (Short  Selling  not  allowed)  c=1%  
• Calculate  sharpe  ratio  for  all  portfolios  
• Find  max  sharpe  ratio  of  the  no-­‐short  selling  portofolios  
• GMVP  (Real  Constraints,  i.e.  long  only  no  short)  Find  min  Sigma  
• Efficient  Portfolio  (Yes  Short  Selling)  c=1%  
• Calculate  sharpe  ratio  for  all  portfolios  
• Find  max  sharpe  ratio  of  the  short  selling  portofolios  
• Class:  Exercise  1  Weights  between  -­‐0.3  and  1.3  (Hedge  Funds  130/30)  
• Calculate  sharpe  ratio  for  all  portfolios  
• Find  max  sharpe  ratio  of  the  short  selling  portofolios  
• Class:  Exercise  2  Weights  between  -­‐0.1  and  1  (10%  Diversification)  
• Calculate  sharpe  ratio  for  all  portfolios  
• Find  max  sharpe  ratio  of  the  short  selling  portofolios  
• Class:  Exercise  3  Weights  between  -­‐2  and  2  (200%  Exposure  /  LongShort)  
• Calculate  sharpe  ratio  for  all  portfolios  
• Find  max  sharpe  ratio  of  the  short  selling  portofolios  
• Plot  the  short  and  the  no-­‐short  portfolio  
• Plots  for  Class  Exercises  
   

117
Load  the  sample  information  for  the  following  equation:  

Use  the  load  command  to  load  info  for  5  stocks  

load  data5  
 
 
Calculate  stock  returns  
Use  the  '.'  operator  to  perform  element  by  element  division  on  
the  following  formula:  

 
ret=log(data5(2:end,:)./data5(1:end-­‐1,:));  
 
%  Calculate  mean  returns  
mean5=mean(ret)  
mean5  =  
 
       0.2864        0.2551        0.1976        0.0573        0.3277  
 
Calculate  the  variance  of  the  population  

Population  Variance  argument=1  Sample  Variance  


argument=0  

var5=var(ret,1)  
var5  =  
 
       0.1307        0.1834        0.0386        0.0561        0.1217  
 
Calculate  the  standard  deviation  of  the  population  

Population  Standard  Deviation  argument=1  Sample  St.  Dev  


argument=0  

std5=std(ret,1)  
std5  =  
 
       0.3616        0.4283        0.1965        0.2368        0.3489  
 
   
118
Calculate  the  covariance  of  the  population  

Variance-­‐Covariance  Matrix  

s=cov(ret,1)  
s  =  
 
       0.1307        0.0774        0.0242      -­‐0.0053        0.1142  
       0.0774        0.1834        0.0501      -­‐0.0014        0.0382  
       0.0242        0.0501        0.0386        0.0186        0.0118  
     -­‐0.0053      -­‐0.0014        0.0186        0.0561      -­‐0.0081  
       0.1142        0.0382        0.0118      -­‐0.0081        0.1217  
 
 
Calculate  the  number  of  assets  of  the  sample  
N.  Assets  of  the  sample  

n=size(ret,2)  
n  =  
 
         5  
 
 
Display  the  stocks  returns/volatilities  

Consider  the  following  5  INVESTMENT  BANK  STOCKS.  Labels  


are  useful  to  plot  data  

Labels={'JPM','MER','GS','MS','DB'};  
 
%  Keep  the  graph  static  
hold  on  
 
%  Display  a  label  in  each  point  with  the  text  command  
for  k  =  1:n  
   text(std5(k),mean5(k),Labels(k))  
end  
%  Plot  the  stocks  
 
 
%  Create  xlabel  
xlabel('Sigma');  
%  Create  ylabel  
119
ylabel('Return');  
%  Create  title  
title('Plotting  standard  deviations  vs  returns');  
 
plot(std5,mean5,'.b')  
 
hold  off  

 
 
Efficient  Portfolio  A  c=1%  (short  selling  allowed)  

By  implementing  the  following  formula  

 
c1=0.01  
weights_A=inv(s)*(mean5-­‐c1)'/sum(inv(s)*(mean5-­‐c1)')  
 
mean_a=mean5*weights_A  
var_a=weights_A'*s*weights_A  
std_a=sqrt(var_a)  
120
c1  =  
 
       0.0100  
 
 
weights_A  =  
 
     -­‐0.6922  
       0.0794  
       0.7683  
     -­‐0.0683  
       0.9128  
 
 
mean_a  =  
 
       0.2691  
 
 
var_a  =  
 
       0.0364  
 
 
std_a  =  
 
       0.1909  
 
 
Efficient  Portfolio  B  c=5%  (short  selling  allowed)  
By  implementing  the  following  formula  

 
c2=0.05  
weights_B=inv(s)*(mean5-­‐c2)'/sum(inv(s)*(mean5-­‐c2)')  
 
mean_b=mean5*weights_B  
var_b=weights_B'*s*weights_B  
std_b=sqrt(var_b)  
c2  =  
 
       0.0500  
121
 
 
weights_B  =  
 
     -­‐0.8035  
       0.0916  
       0.8467  
     -­‐0.1804  
       1.0456  
 
 
mean_b  =  
 
       0.2929  
 
 
var_b  =  
 
       0.0441  
 
 
std_b  =  
 
       0.2100  
 
Covariance  between  portfolio  A  and  portfolio  B  
cov_a_b=weights_A'*s*weights_B  
cov_a_b  =  
 
       0.0398  
 
Weights  from  -­‐4  to  6  
w=[-­‐4:.1:6]';  
 

Formulas  that  apply  to  2  portfolios  only  for  the  mean  

Formula  to  calculate  the  return  of  a  portfolio  comprised  by  2  


securities  

122
mean_c=w*mean_a+(1-­‐w)*mean_b;  
   

123
Formulas  that  apply  to  2  portfolios  only  for  the  standard  
deviation  

 
std_c=sqrt(var_a.*w.^2+var_b.*(1-­‐w).^2+2*w.*(1-­‐w)*cov_a_b);  
 

Plot  for  2  efficient  portfolio  a,b  with  weight  w  and  


weight(1-­‐w)  
hold  on  
%  Create  xlabel  
xlabel('Sigma');  
%  Create  ylabel  
ylabel('Return');  
%  Create  title  
title('Plotting  the  efficient  line  out  of  2  efficient  portfolios');  
plot(std_c,mean_c)  

 
GMVP  Calculation  

124
Formula  in  Latex  

%  Weights  of  the  GMVP  


weights_gmvp=(ones(1,n)*inv(s))/sum((ones(1,n)*inv(s)))  
 
mean_gmvp=mean5*weights_gmvp'  
var_gmvp=weights_gmvp*s*weights_gmvp'  
std_gmvp=sqrt(var_gmvp)  
weights_gmvp  =  
 
     -­‐0.3103        0.0378        0.4995        0.3162        0.4567  
 
 
mean_gmvp  =  
 
       0.1873  
 
 
var_gmvp  =  
 
       0.0249  
 
 
std_gmvp  =  
 
       0.1579  
 
Plot  efficient  portfolio  A,  portfolio  B  and  the  GMVP  
Plot  both  portfolios  

%  Create  xlabel  
xlabel('Sigma');  
%  Create  ylabel  
ylabel('Return');  
%  Create  title  
title('Plotting  2  Efficient  Portfolios  and  the  GMVP');  
 
plot(std_a,mean_a,'*g')  
text(std_a,mean_a,'Efficient  c=1%')  
plot(std_b,mean_b,'*g')  
text(std_b,mean_b,'Efficient  c=5%')  
plot(std_gmvp,mean_gmvp,'*r')  
text(std_gmvp,mean_gmvp,'Efficient  GMVP')  

125
 
hold  off  

 
Efficient  Portfolio  (Short  Selling  not  allowed)  c=1%  
NumPorts  =  2000;  
%  Find  the  efficient  frontier  with  the  frontcon  command  
[PortRisk,  PortReturn,  PortWts]  =  frontcon(mean5,s,  NumPorts,[],  [0  0  0  0  0;  
99  99  99  99  99]);  
 
Calculate  sharpe  ratio  for  all  portfolios  

 
sharpe_noshort=(PortReturn-­‐c1)./PortRisk;  
 

Find  max  sharpe  ratio  of  the  no-­‐short  selling  portofolios  


Use  the  find  command  and  the  max  function  

126
ix=find(sharpe_noshort==max(sharpe_noshort))  
 
%  This  is  called  indexing  
mean_noshort=PortReturn(ix)  
std_noshort=PortRisk(ix)  
sharpe_noshort=sharpe_noshort(ix)  
weights_noshort=PortWts(ix,:)  
ix  =  
 
     889  
 
 
mean_noshort  =  
 
       0.2425  
 
 
std_noshort  =  
 
       0.1907  
 
 
sharpe_noshort  =  
 
       1.2190  
 
 
weights_noshort  =  
 
                 0                  0        0.6552                  0        0.3448  
 
GMVP  (Real  Constraints,  i.e.  long  only  no  short)    
Find  min  Sigma  

Use  the  find  command  and  the  min  function  

ix=find(std_noshort==min(std_noshort))  
 
%  This  is  called  indexing  
mean_gmvp_noshort=PortReturn(ix)  
std_gmvp_noshort=PortRisk(ix)  
sharpe_gmvp_noshort=sharpe_noshort(ix)  
weights_gmvp_noshort=PortWts(ix,:)  
ix  =  
127
 
         1  
 
 
mean_gmvp_noshort  =  
 
       0.1743  
 
 
std_gmvp_noshort  =  
 
       0.1625  
 
 
sharpe_gmvp_noshort  =  
 
       1.2190  
 
 
weights_gmvp_noshort  =  
 
                 0                  0        0.4567        0.3476        0.1957  
 
 

Efficient  Portfolio  (Yes  Short  Selling)  c=1%  

Find  the  efficient  frontier  with  the  frontcon  command  

[PortRisk2,  PortReturn2,  PortWts2]  =  frontcon(mean5,s,  NumPorts,  [],  [-­‐1  -­‐1  


-­‐1  -­‐1  -­‐1;  1  1  1  1  1]);  
 

Calculate  sharpe  ratio  for  all  portfolios  

 
sharpe_short=(PortReturn2-­‐c1)./PortRisk2;  
 

Find  max  sharpe  ratio  of  the  short  selling  portofolios  


ix2=find(sharpe_short==max(sharpe_short))  
 
128
%  This  is  called  indexing  
mean_short=PortReturn2(ix2)  
std_short=PortRisk2(ix2)  
sharpe_short=sharpe_short(ix2)  
weights_short=PortWts2(ix2,:)  
ix2  =  
 
     384  
 
 
mean_short  =  
 
       0.2691  
 
 
std_short  =  
 
       0.1909  
 
 
sharpe_short  =  
 
       1.3572  
 
 
weights_short  =  
 
     -­‐0.6924        0.0794        0.7685      -­‐0.0686        0.9130  
 
 

Class:  Exercise  1  Weights  between  -­‐0.3  and  1.3  (Hedge  


Funds  130/30)  
%  Find  the  efficient  frontier  with  the  frontcon  command  
[PortRisk3,  PortReturn3,  PortWts3]  =  frontcon(mean5,s,  NumPorts,  [],  [-­‐0.3  
-­‐0.3  -­‐0.3  -­‐0.3  -­‐0.3;  1.3  1.3  1.3  1.3  1.3]);  
 

Calculate  sharpe  ratio  for  all  portfolios  

 
sharpe_e1=(PortReturn3-­‐c1)./PortRisk3;  
129
   

130
Find  max  sharpe  ratio  of  the  short  selling  portofolios  
ix3=find(sharpe_e1==max(sharpe_e1))  
 
%  This  is  called  indexing  
mean_e1=PortReturn3(ix3)  
std_e1=PortRisk3(ix3)  
sharpe_e1=sharpe_e1(ix3)  
weights_e1=PortWts3(ix3,:)  
ix3  =  
 
     523  
 
 
mean_e1  =  
 
       0.2543  
 
 
std_e1  =  
 
       0.1856  
 
 
sharpe_e1  =  
 
       1.3163  
 
 
weights_e1  =  
 
     -­‐0.3000      -­‐0.0107        0.7757      -­‐0.0529        0.5879  
 
 

Class:  Exercise  2  Weights  between  -­‐0.1  and  1  (10%  


Diversification)  
%  Find  the  efficient  frontier  with  the  frontcon  command  
[PortRisk4,  PortReturn4,  PortWts4]  =  frontcon(mean5,s,  NumPorts,  [],  [.1  .1  
.1  .1  .1;  1  1  1  1  1]);  
 
Calculate  sharpe  ratio  for  all  portfolios  
131
 
sharpe_e2=(PortReturn4-­‐c1)./PortRisk4;  
 
Find  max  sharpe  ratio  of  the  short  selling  portofolios  
ix4=find(sharpe_e2==max(sharpe_e2))  
 
%  This  is  called  indexing  
mean_e2=PortReturn4(ix4)  
std_e2=PortRisk4(ix4)  
sharpe_e2=sharpe_e2(ix4)  
weights_e2=PortWts4(ix4,:)  
ix4  =  
 
               1214  
 
 
mean_e2  =  
 
       0.2331  
 
 
std_e2  =  
 
       0.1989  
 
 
sharpe_e2  =  
 
       1.1217  
 
 
weights_e2  =  
 
       0.1000        0.1000        0.4318        0.1000        0.2682  
 
   

132
Class:  Exercise  3  Weights  between  -­‐2  and  2  (200%  
Exposure  /  LongShort)  
%  Find  the  efficient  frontier  with  the  frontcon  command  
[PortRisk5,  PortReturn5,  PortWts5]  =  frontcon(mean5,s,  NumPorts,  [],  [-­‐2  -­‐2  
-­‐2  -­‐2  -­‐2;  2  2  2  2  2]);  
 

Calculate  sharpe  ratio  for  all  portfolios  

 
sharpe_e3=(PortReturn5-­‐c1)./PortRisk5;  
 

Find  max  sharpe  ratio  of  the  short  selling  portofolios  


ix5=find(sharpe_e3==max(sharpe_e3))  
 
%  This  is  called  indexing  
mean_e3=PortReturn5(ix5)  
std_e3=PortRisk5(ix5)  
sharpe_e3=sharpe_e3(ix5)  
weights_e3=PortWts5(ix5,:)  
ix5  =  
 
     209  
 
 
mean_e3  =  
 
       0.2691  
 
 
std_e3  =  
 
       0.1909  
 
 
sharpe_e3  =  
 
       1.3572  
 
 
133
weights_e3  =  
 
     -­‐0.6924        0.0794        0.7685      -­‐0.0685        0.9130  
 
Plot  the  short  and  the  no-­‐short  portfolio  
%  Create  plot  
plot(PortRisk,PortReturn,'-­‐b','DisplayName','Frontier  no  short  selling');  
hold  on  
%  Create  plot  
plot(PortRisk2,PortReturn2,'-­‐g','DisplayName','Frontier  short  selling');  
 
 
 
%  Plot  the  portfolio  no  short  with  the  best  sharpe  ratio  
 
%  Create  xlabel  
xlabel('Sigma');  
%  Create  ylabel  
ylabel('Return');  
%  Create  title  
title('Plotting  Efficient  Frontiers  and  the  Best  Sharpe  Ratios');  
 
plot(std_noshort,mean_noshort,'or')  
text(std_noshort,mean_noshort,'Best  Sharpe  Ratio  No  Short')  
 
plot(std_gmvp_noshort,mean_gmvp_noshort,'or')  
text(std_gmvp_noshort,mean_gmvp_noshort,'GMVP  No  Short')  
 
%  Plot  the  portfolio  short  with  the  best  sharpe  ratio  
plot(std_short,mean_short,'or')  
text(std_short,mean_short,'Best  Sharpe  Ratio  Long/Short')  
 
 
hold  off  

134
 
Plots  for  Class  Exercises  
%  Create  plot  Exercise  1  
%  plot(PortRisk3,PortReturn3,'-­‐r','DisplayName','Frontier  130/30');  
 
 
plot(PortRisk2,PortReturn2,'-­‐g','DisplayName','Frontier  short  selling');  
%  Create  xlabel  
xlabel('Sigma');  
%  Create  ylabel  
ylabel('Return');  
%  Create  title  
title('Plotting  Class  Exercises  Portfolios  vs  Ideal  Frontier');  
 
hold  on  
 
%  Create  plot  Exercise  2  
%  plot(PortRisk4,PortReturn4,'-­‐y','DisplayName','Frontier  10%  
Diversification');  
%  Create  plot  Exercise  3  
%  plot(PortRisk5,PortReturn5,'-­‐b','DisplayName','Frontier  200%  
Exposure');  
135
 
 
%  Plot  the  portfolio  Exercise  1:  130/30  
plot(std_e1,mean_e1,'or')  
text(std_e1,mean_e1,'Best  Sharpe  Ratio  130/30')  
%  Plot  the  portfolio  Exercise  2:  10%  Diversification  
plot(std_e2,mean_e2,'or')  
text(std_e2,mean_e2,'Best  Sharpe  Ratio  10%  Diversification')  
%  Plot  the  portfolio  Exercise  3:  200%  Exposure  
plot(std_e3,mean_e3,'or')  
text(std_e3,mean_e3,'Best  Sharpe  Ratio  200%  Exposure')  

   

136
5.4. Report  4:  Portfolio  Theory  &  Simulation  
 

Portfolio  Theory  &  Introduction  to  Simulation  

Efficient  Portfolios  with/without  shortselling  

Antonio  Rivela  IE  Business  School  2011  

File:  MIF_session6.m  

Contents  
• Introducing  data  for    and  S  
• Simulation  with  No  Short  Sales  Allowed  
• Simulation  with  Short  Sales  Allowed  
• Frontcon  command  to  build  efficient  frontiers  with  no  shortselling  
• Frontcon  command  to  build  Efficient  curve  for  portfolios  where  short  
sales  are  allowed  
 
Introducing  data  for    and  S  
Assign  data  to  variables  

ExpReturn=[.08  .09  .10  .11];  


 
ExpCovariance=      [0.10   0.03   -­‐0.08   0.05;  
                                   0.03   0.20    0.02   0.03;  
                                 -­‐0.08   0.02    0.30   0.20;  
                                   0.05   0.03    0.20   0.90];  
%  N.  of    portfolios  for  calculation  of  the  efficient  curve  
NumPorts=1000;  
%  N.  of    portfolios  for  calculation  of  the  simulation  
NumSims=1000;  
 
   

137
Simulation  with  No  Short  Sales  Allowed  

We  simulate  the  weights  of  each  portfolio  to  follow  a  uniform  


distribution  that  takes  values  from  0  to  1  i.e.  we  are  long  only  

rand('state',  0)  
Weights  =rand(NumSims,4);  
 
%  Check  5  portfolios  to  see  if  the  are  fine  
%  They  are  not  fine  we  need  to  normalise  to  1  
Weights(1:5,:)  
 
Total  =  sum(Weights,  2);          %  Add  the  weights  
Total  =  Total(:,ones(4,1));    %  Make  size-­‐compatible  matrix  
Weights  =  Weights./Total;        %  Normalize  so  sum  =  1  
 
%  Check  5  portfolios  to  see  if  the  are  fine.  Now  they  are  fine  
Weights(1:5,:)  
 
[PortRisk2,  PortReturn2]  =  portstats(ExpReturn,  ExpCovariance,Weights);  
 
%  Keep  graphic  static  -­‐>  Add  graphics  on  top  every  time  
hold  on  
%  Create  xlabel  
xlabel('Sigma');  
%  Create  ylabel  
ylabel('Return');  
%  Create  title  
title('Random  portfolios  where  short  sales  are  not  allowed');  
plot  (PortRisk2,  PortReturn2,  '.r')  
ans  =  
 
       0.9501        0.1568        0.9862        0.0810  
       0.2311        0.4164        0.8853        0.3015  
       0.6068        0.0940        0.4048        0.1800  
       0.4860        0.4499        0.6271        0.7162  
       0.8913        0.8692        0.3855        0.7903  
 
   

138
ans  =  
 
       0.4370        0.0721        0.4536        0.0372  
       0.1260        0.2270        0.4826        0.1644  
       0.4720        0.0731        0.3149        0.1400  
       0.2132        0.1974        0.2752        0.3142  
       0.3036        0.2960        0.1313        0.2691  
 

 
Simulation  with  Short  Sales  Allowed  

Then  we  simulate  the  weights  of  each  portfolio  to  follow  a  
uniform  distribution  that  takes  values  from  -­‐1  to  1,  i.e.  we  can  
short  (-­‐1)  stocks  

Weights3  =(-­‐1)+(1+1)*rand(NumSims,4);  
Weights3(:,4)=1-­‐Weights3(:,1)-­‐Weights3(:,2)-­‐Weights3(:,3);  
 
%  Check  5  portfolios  to  see  if  the  are  fine  
Weights3(1:5,:)  
 
[PortRisk3,  PortReturn3]  =  portstats(ExpReturn,  ExpCovariance,Weights3);  

139
 
%  Create  xlabel  
xlabel('Sigma');  
%  Create  ylabel  
ylabel('Return');  
%  Create  title  
title('Random  portfolios  where  short  sales  are  allowed');  
plot  (PortRisk3,  PortReturn3,  '.y')  
ans  =  
 
     -­‐0.0127        0.0968      -­‐0.4569        1.3728  
     -­‐0.1748        0.7280        0.8070      -­‐0.3602  
       0.9605      -­‐0.0869      -­‐0.9880        1.1144  
       0.0939        0.4252        0.0770        0.4039  
       0.3561      -­‐0.3411      -­‐0.5691        1.5540  
 

 
   

140
Frontcon  command  to  build  efficient  frontiers  with  no  
shortselling  
%  Risk  free  rate  
r=0.02;  
 
%  Calculating  the  efficient  line  
[PortRisk,  PortReturn,  PortWts]  =  frontcon(ExpReturn,ExpCovariance,  
NumPorts,  [],  [0  0  0  0;1  1  1  1]);  
 
%  Calculating  the  sharpe  ratio  
Sharpe=  (PortReturn-­‐r)./PortRisk;  
 
%  This  is  the  max  sharpe  ratio  achievable  in  the  data  
max(Sharpe)  
 
%  This  is  the  index  that  corresponds  to  the  max  sharpe  ratio  
ix=find(Sharpe==max(Sharpe))  
 
%  Risk,  return  and  weights  for  the  best  sharpe  ratio  portfolio  you  can  
%  produce  with  no  shortselling  in  the  efficient  frontier  
PortRisk(ix)  
PortReturn(ix)  
PortWts(ix,:)  
 
%  Plotting  the  efficient  curve  
%  Create  xlabel  
xlabel('Sigma');  
%  Create  ylabel  
ylabel('Return');  
%  Create  title  
title('Efficient  curve  for  portfolios  where  short  sales  are  not  allowed');  
 
plot(PortRisk,PortReturn,'b+-­‐','LineWidth',2)  
ans  =  
 
       0.3313  
 
 
 
ix  =  
 
       22  
 
 
141
ans  =  
 
       0.2030  
 
 
ans  =  
 
       0.0872  
 
 
ans  =  
 
       0.5910        0.0943        0.3147                  0  
 

142
Frontcon  command  to  build  Efficient  curve  for  portfolios  
where  short  sales  are  allowed  
Calculating  the  efficient  line  

[PortRisk,  PortReturn,  PortWts]  =  frontcon(ExpReturn,ExpCovariance,  


NumPorts,  [],  [-­‐1  -­‐1  -­‐1  -­‐1;1  1  1  1]);  
 
%  Create  xlabel  
xlabel('Sigma');  
%  Create  ylabel  
ylabel('Return');  
%  Create  title  
title('Efficient  curve  for  portfolios  where  short  sales  are  allowed');  
plot(PortRisk,PortReturn,'m*-­‐','LineWidth',4)  

   

143
5.5. Report  5:  Simulation  (Exponential  Distribution)  
 

Contents  

• Shoot  random  time  to  defaults  that  follow  Exp  Dist.  


• Unique  exponential  parameter  is  50  (average  time  to  
default)  
• Check  wheter  condition  <  5  years  is  fulfilled  
• Check  with  Classic  Statistics  
• Question  3:  Find  the  average  
• Question  4:  Find  the  standard  deviation  
• Plot  a  histogram  
 
%   This  function  will  simulate  IBM  bond  defaults  -­‐>  Exp(Average  
Time=50y)  
 
%   Antonio  Rivela  @  Nov  2011  
%   IE  Business  School  
%   Financial  Math  Programming  
 

Shoot  random  time  to  defaults  that  follow  Exp  Dist.  

Vector  will  be  comprised  by  n  simulations  n  is  the  number  of  
simulations.  Need  a  huge  number  to  guarantee  defaults  

n=1000000  
n  =  
 
         1000000  
 
Unique  exponential  parameter  is  50  (average  time  to  
default)  

Generate  a  vector  comprised  by  n  elements  

time_exp=exprnd(50,n,1);  
   
144
Check  wheter  condition  <  5  years  is  fulfilled  

Then  divide  by  total  number  of  simulations  to  obtain  a  


frequency=prob  

prob_lower_than_5=sum((time_exp<5))/n  
prob_lower_than_5  =  
 
       0.0952  
 
Check  with  Classic  Statistics  
Normal  Curve  -­‐>  Cumulative  F(x)  

prob_lower_than_5_F=expcdf(5,50)  
prob_lower_than_5_F  =  
 
       0.0952  
 
Question  3:  Find  the  average  
average_dist=mean(time_exp)  
average_dist  =  
 
     49.9240  
 
Question  4:  Find  the  standard  deviation  
standard_deviation_dist=std(time_exp,1)  
standard_deviation_dist  =  
 
     49.9075  
   

145
Plot  a  histogram  

Looks  like  the  density  function  of  the  exponential  

t  =  0:1:500;  
hist(time_exp,t)  
 
output=histc(time_exp,t);  
output/n;  

   

146
5.6. Report   6:   Simulation   (Normal   Distribution   of   Stock  
Returns)  
 

Contents  
• Shoot  random  returns  that  follow  Normal  Dist.  
• Normal  parameters  are  7%  and  20%  
• Check  wheter  condition  <  -­‐50%  is  fulfilled  
• Check  wheter  condition  >  10%  is  fulfilled  
• Check  with  Classic  Statistics  
• Plot  a  histogram  
 
%   This  function  will  simulate  IBM  stock  returns  -­‐>  Normal  (7%,20%)  
 
%   Antonio  Rivela  @  Nov  2011  
%   IE  Business  School  
%   Financial  Math  Programming  
 

Shoot  random  returns  that  follow  Normal  Dist.  

Vector  will  be  comprised  by  n  simulations  n  is  the  number  of  
simulations  

n=1000000  
n  =  
 
         1000000  
 
 
Normal  parameters  are  7%  and  20%  
Generate  a  vector  comprised  by  n  elements  

return_normal=normrnd(0.07,.2,n,1);  

147
Check  wheter  condition  <  -­‐50%  is  fulfilled  

Then  divide  by  total  number  of  simulations  to  obtain  a  


frequency=prob  

prob_lower_than_50=sum((return_normal<-­‐.5))/n  
prob_lower_than_50  =  
 
       0.0022  
 
 

Check  wheter  condition  >  10%  is  fulfilled  

Then  divide  by  total  number  of  simulations  to  obtain  a  


frequency=prob  

prob_higher_than_10=sum((return_normal>.1))/n  
prob_higher_than_10  =  
 
       0.4410  
 
 

Check  with  Classic  Statistics  


Normal  Curve  -­‐>  Cumulative  F(x)  

prob_lower_than_50_F=normcdf(-­‐.5,.07,.2)  
prob_higher_than_10_F=1-­‐normcdf(.1,.07,.2)  
prob_lower_than_50_F  =  
 
       0.0022  
 
 
prob_higher_than_10_F  =  
 
       0.4404  
 
   

148
Plot  a  histogram  

...  

x  =  -­‐1:0.1:1  
 
hist(return_normal,x)  
 
output=histc(return_normal,x)  
output/n  
x  =  
 
   Columns  1  through  15  
 
     -­‐1.0000      -­‐0.9000      -­‐0.8000      -­‐0.7000      -­‐0.6000      -­‐0.5000      -­‐0.4000      -­‐0.3000      
-­‐0.2000      -­‐0.1000                  0        0.1000        0.2000        0.3000        0.4000  
 
   Columns  16  through  21  
 
       0.5000        0.6000        0.7000        0.8000        0.9000        1.0000  
 
 
output  =  
 
                     1  
                     6  
                   54  
                 359  
               1807  
               7163  
             22563  
             56134  
           109280  
           165655  
           195942  
           182342  
           133052  
             76226  
             33592  
             11718  
               3249  
                 727  
                 116  
                   14  
                     0  
149
 
 
ans  =  
 
       0.0000  
       0.0000  
       0.0001  
       0.0004  
       0.0018  
       0.0072  
       0.0226  
       0.0561  
       0.1093  
       0.1657  
       0.1959  
       0.1823  
       0.1331  
       0.0762  
       0.0336  
       0.0117  
       0.0032  
       0.0007  
       0.0001  
       0.0000  
                 0  
 

150
 

 
 

   

151
5.7. Report  7:  Simulation  (number  PI)  
 

Contents  
• Shoot  random  points  x  &  y  that  follow  Uniform  Continuous  Dist.  
• Check  wheter  coordinates  are  inscribed  within  the  circle  
• The  number  of  inside  points  are  
• The  ratio  is  
• Calculates  PI  by  multiplying  inside  points*4  /  Total  Number  
Simulations  
• Plots  a  scatter  in  Matlab  
 
The  function  
%   This  function  will  simulate  PI  
 
%   Antonio  Rivela  @  Nov  2011  
%   IE  Business  School  
%   Financial  Math  Programming  
 
Shoot  random  points  x  &  y  that  follow  Uniform  
Continuous  Dist.  

Vector  will  be  comprised  by  n  simulations  n  is  the  number  of  
simulations  Uniform  parameters  are  0  and  1  

x=unifrnd(0,1,n,1);  
y=unifrnd(0,1,n,1);  
 
Check  wheter  coordinates  are  inscribed  within  the  circle  
Make  sure  you  use  the  dot  operator  for  vector  component^2  

z=x.^2+y.^2;  
 
%  Output  vector  will  contain  0  (outside)  and  1  (inside)  
output=(z<=1);  
 
%  This  is  a  mask  that  makes  outside  points  dissapear  by  muktiplying  by  0  
%  And  keeps  inside  points  by  multiplying  by  1  
x=x.*output;  
152
y=y.*output;  
 
 
The  number  of  inside  points  are  
inside_points=sum(output)  
inside_points  =  
 
           785490  
 
 
The  ratio  is  
ratio=sum(output)/n  
ratio  =  
 
       0.7855  
 
 
Calculates  PI  by  multiplying  inside  points*4  /  Total  
Number  Simulations  
pi2=sum(output)*4/n  
pi2  =  
 
       3.1420  
 
   

153
Plots  a  scatter  in  Matlab  

Scatter  not  plot!  

scatter(x,y)  

   

154
5.8. Report   8:   Geometric   Brownian   Motion   followed   by  
stock  prices  
 

Contents  
• Input  parameters  for  the  GBM  model  
• Initial  Stock  Price  
• Maturity  
• Risk  Free  Rate  
• Volatility  
• Number  of  simulations  
• Number  of  time  steps  
• Calculating  the  volatility  component  
• Calculating  the  drift  component  
• Drift  for  the  Brownian  Motion  (not  the  GBM)  
• Producing  random  numbers  
• Assigning  initial  value  of  the  stock  to  the  matrix  
• Producing  the  values  for  stock  prices  
• Plotting  paths  for  stock  prices  
 
 
The  function  
%  Geometric  Brownian  Motion  
%  Antonio  Rivela  
%  IE  Business  School  @  Feb  2010  
%  File:  geometric_brownian_motion.m  
 

Input  parameters  for  the  GBM  model  

Initial  Stock  Price  


S=100;  %spot  price  
 

Maturity  
T=1;  %maturity  
 

155
Risk  Free  Rate  
r=0.05;  %interest  rate  
 

Volatility  
sigma=0.25;  %volatility  
 

Number  of  simulations  


NSimulations=100000;  %no  of  monte  carlo  simulations  
 
Number  of  time  steps  
NSteps=100;  %no  of  time  steps  
dt=T/(NSteps-­‐1);  
 

Calculating  the  volatility  component  


vsqrdt=sigma*dt^0.5;  
 

Calculating  the  drift  component  


drift=(r-­‐(sigma^2)/2)*dt;  
 
Drift  for  the  Brownian  Motion  (not  the  GBM)  
%  drift=r*dt;    This  is  not  executed.  Just  for  your  reference.  

Producing  random  numbers  


x=randn(NSimulations,NSteps);  
 
Smat=zeros(NSimulations,NSteps);  
 
156
Assigning  initial  value  of  the  stock  to  the  matrix  
Smat(:,1)=S;  
 

Producing  the  values  for  stock  prices  


for  i=2:NSteps,  
  Smat(:,i)=Smat(:,i-­‐1).*exp(drift+vsqrdt*x(:,i));  
end  
 

Plotting  one  path  for  stock  prices  


plot(Smat(1,:))  

   

157
 

6. INTRODUCTION  TO  VISUAL  BASIC  


 

6.1. Creating  Your  First  Macro        


     
In   this   section,   we   will   show   you   how   to   create   your   first   macro   (VBA  
program).       We   will   use   the   world   classic   "Hello   World!"   example.     To   create   the  
example,  please  follow  the  following  steps:  
 
 
1.     Open   Visual   Basic   Editor   by   go   to   Tools...Macro...Visual   Basic   Editor   or   just  
simply  press  the  [Alt]  and  [F11]  keys  at  the  same  time.  
   
 
2.  In  the  Insert   menu  on  top  of  the  Visual  Basic  Editor,  select  Module  to  open  the  
Module  window  (code  window).  
 
3.    In  the  Module  window,  type  the  following:  
 
 
Sub  showMessage()  
       MsgBox  "Hello  World!"  
End  Sub  
 
 
4.  Click  the  Run     button,,  press  [F5],  or  go  to  Run..Run   Sub/UserForm  to  run  the  
program  
 
5.    The  message  box  pops  up  with  the  "Hello  World!"  greeting.  
 
 
Now  you  are  a  VBA  programmer!  
 
 

6.2. Simple  User  Defined  Functions  


 
A  User  Defined  Function  (or  UDF)  is  a  Function  procedure  that  typically  (but  not  
necessarily)   accepts   some   inputs   and   returns   a   result.   A   UDF   can   only   return   a  
value   to   the   cell(s)   whence   it   was   called   -­‐-­‐   it   must   not   modify   the   contents   or  
formatting  of  any  cell  and  must  not  modify  the  operating  environment  of  Excel.  If  
you   attempt   to   change   anything,   the   function   will   terminate   immediately   and  

158
return  a  #VALUE  error  to  the  calling  cell.  In  Excel  97  and  2000,  a  UDF  cannot  use  
the   Find   method   of   a   Range   object,   even   though   that   method   does   not   change  
anything   in   Excel.   This   was   fixed   with   Excel   2002.  The   following   is   an   example   of   a  
simple  UDF  that  calculates  the  area  of  a  rectangle:  
 
Function  RectangleArea(Height  As  Double,  Width  As  Double)  As  Double  
       RectangleArea  =  Height  *  Width  
End  Function  
 
This   function   takes   as   inputs   two   Double   type   variables,   Height   and   Width,   and  
returns   a   Double   as   its   result.   Once   you   have   defined   the   UDF   in   a   code   module,  
you   can   call   it   from   a   worksheet   cell   with   a   formula  
like:    =RectangleArea(A1,B1)    where   A1   and   B1   contain   the   Height   and   Width   of  
the   rectangle.      Because   functions   take   inputs   and   return   a   value,   they   are   not  
displayed  in  the  list  of  procedures  in  the  Macros  dialog.  
 
 
 
6.2.1. Where  To  Put  The  Function  Code  
 
The   code   for   a   UDF   should   be   placed   in   a   standard   code   module,   not   one   of   the  
Sheet  modules  and  not  in  the  ThisWorkbook  module.  In  the  VBA  editor,  go  to  the  
Insert   menu   and   choose   Module.   This   will   insert   a   new   code   module   into   the  
project.    
 
 
A  module  can  contain  any  number  functions,  so  you  can  put  many  functions  into  a  
single   code   module.   You   can   change   the   name   of   a   module   from   Module1   to  
something   more   meaningful   by   pressing   the   F4   key   to   display   the   Properties  
window  and  changing  the  Name  property  to  whatever  you  want.  
 
You  can  call  a  function  from  the  same  workbook  by  using  just  the  function  name.  
For   example:    =RectangleArea(12,34)    It   is   possible,   but   strongly   recommended  
against,  to  have  two  functions  with  the  same  name  is  two  separate  code  modules  
within  the  same  workbook.  You  would  call  them  using  the  module  name  from  cells  
with  formulas  like:    
 
 =Module1.MyFunction(123)  =Module2.MyFunction(123)      
 
 
 Doing  this  will  lead  only  to  confusion,  so  just  because  it  is  possible  doesn't  mean  
you  should  do  it.  Don't  do  it.      Do  not  give  the  same  name  to  both  a  module  and  a  
function  (regardless  of  whether  that  module  contains  that  function).  Doing  so  will  
cause  an  untrappable  error.    
 
   You   can   call   a   UDF   that   is   contained   in   another   (open)   workbook   by   using   the  
workbook  name  in  the  formula.    
 
159
 
For  example,  
 
     ='MyBook.xls'!RectangleArea(A1,A2)      
 
will   call   the   function   RectangleArea   defined   in   the   workbook   MyBook.xls.   If   a  
function  is  defined  in  an  Add-­‐In  (either  an  XLA  or  an  Automation  Add-­‐In;  
 
 The  function  name  alone  is  sufficient  for  calling  a  function  in  an  Add-­‐In.  
 
 
6.2.2. User  Defined  Funtions  And  Calcuations  
 
As   a   general   rule,   you   should   pass   into   the   function   all   the   values   it   needs   to  
properly  calculate  the  result.  That  means  that  your  UDF  should  not  make  explicit  
refences   to   other   cells.   If   you   reference   other   cells   directly   from   within   the  
function,   Excel   may   not   recalculate   the   function   when   that   cell   is   changed.   For  
example,  a  poorly  written  UDF  is  as  follows:  
 
Public  Function  BadRectangleArea(Height  As  Double)  As  Double  
       BadRectangleArea  =  Height  *  Range("A1").Value  
End  Function  
 
In   this   function,   the   Width   is   assumed   to   be   in   cell   A1.   The   problem   here   is   that  
Excel   doesn't   know   that   this   function   depends   on   cell   A1   and   therefore   will   not  
recalculate  the  formula  when  A1  is  changed.  Thus,  the  cell  calling  the  function  call  
will  not  contain  the  correct  result  when  cell  A1  is  changed.  You  can  force  Excel  to  
recalculate   a   UDF   whenever   any   calculation   is   made   by   adding   the  
line    Application.Volatile  True    as  the  first  line  in  the  function.  For  example,  
 
Function  BadRectangleArea(Height  As  Double)  As  Double  
       Application.Volatile  True  
       BadRectangleArea  =  Height  *  Range("A1").Value  
End  Function  
 
This   has   the   drawback,   however,   that   the   function   is   recalculated   even   if   it   doesn't  
need  to  be  recalculated,  which  can  cause  a  performance  problem.  In  general,  you  
shouldn't  use  Application.Volatile  but  instead  design  your  UDF  to  accept  as  inputs  
everything  it  needs  to  properly  caclulate  the  result.  
 
 
 

6.3. Objects  and  Collections          


     
Objects  are  the  fundamental  building  blocks  of  Visual  Basic.     An  object  is  a  special  
type   of   variable   that   contains   both   data   and   codes.     A   collection   is   a   group   of  
160
objects   of   the   same   class.     The   most   used   Excel   objects   in   VBA   programming   are  
Workbook,  Worksheet,  Sheet,  and  Range.  
 
Workbooks   is   a   collection   of   all   Workbook   objects.     Worksheets   is   a   collection   of  
Worksheet  objects.  
 
The   Workbook   object   represents   a   workbook,   the   Worksheet   object   represents   a  
worksheet,  the  Sheet  object  represents  a  worksheet  or  chartsheet,  and  the  Range  
object  represents  a  range  of  cells.  
 
The  following  figure  shows  all  the  objects  mentioned.    The  workbook  (Excel  file)  is  
currently   Book3.xls.     The   current   worksheet   is   Sheet1   as   the   Sheet   Tab  
indicated.    Two  ranges  are  selected,  range  B2  and  B7:B11.  
 
 
 
6.3.1. Workbook  and  Worksheet  Object  
 
A  workbook  is  the  same  as  an  Excel  file.    The  Workbook  collection  contains  all  the  
workbooks  that  are  currently  opened.     Inside  of  a  workbook  contains  at  least  one  
worksheet.      In  VBA,  a  worksheet  can  be  referenced  as  followed:  
 
Worksheets("Sheet1")  
 
Worksheets("Sheet1")  is  the  worksheet  that  named  "Sheet1."  
Another  way  to  refer  to  a  worksheet  is  to  use  number  index  like  the  following:  
 
Worksheets(1)  
 
The  above  refers  to  the  first  worksheet  in  the  collection.      
 
*   Note   that   Worksheets(1)   is   not   necessary   the   same   sheet   as  
Worksheets("Sheet1").  
 
Sheets  is  a  collection  of  worksheets  and  chart  sheets  (if  present).     A  sheet  can  be  
indexed  just  like  a  worksheet.    Sheets(1)  is  the  first  sheet  in  the  workbook.  
 
To   refer   sheets   (or   other   objects)   with   the   same   name,   you   have   to   qualify   the  
object.    For  example:  
 
Workbooks("Book1").Worksheets("Sheet1")  
Workbooks("Book2").Worksheets("Sheet1")  
 
If  the  object  is  not  qualified,  the  active  or  the  current  object  (for  example  workbook  
or  worksheet)  is  used.    
 
The   sheet   tab   on   the   buttom   the   spreadsheet   (worksheet)   shows   which   sheet   is  
active.     As  the  figure  below  shows,  the  active  sheet  is  "Sheet1"  (show  in  bold  font  
161
and  white  background).    
     
 
*  You  can  change  the  color  of  the  sheet  tabs  by  right  click  the  tab,  choose  Tab  Color,  
then  select  the  color  for  the  tab.  
 
The   sub   routine   below   shows   the   name   of   each   sheet   in   the   current   opened  
workbook.     You   can   use   For   Each...Next   loop   to   loop   throgh   the   Worksheets  
collection.      
 
Sub  ShowWorkSheets()  
       Dim  mySheet  As  Worksheet  
         
       For  Each  mySheet  In  Worksheets  
               MsgBox  mySheet.Name  
       Next  mySheet  
 
End  Sub  
 
 
 
6.3.2. Range  Object  and  Cells  Property  
 
Range   represents   a   cell,   a   row,   a   column,   a   selection   of   cells   containing   one   or  
more  contiguous  blocks  of  cells,  or  a  3-­‐D  range.     We  will  show  you  some  examples  
on  how  Range  object  can  be  used.  

The  following  example  places  text  "AB"  in  range  A1:B5,  on  Sheet2.  

Worksheets("Sheet2").Range("A1:B5")  =  "AB"  
 
 
Note   that,   Worksheets.Range("A1",   "B5")   =   "AB"   will   yield   the   same   result   as   the  
above  example.  
 
The  following  place  "AAA"  on  cell  A1,  A3,  and  A5  on  Sheet2.  
 
Worksheets("Sheet2").Range("A1,  A3,  A5")  =  "AAA"  
 
 
Range  object  has  a  Cells  property.     This  property  is  used  in  every  VBA  projects  on  
this   website   (very  important).     The   Cells   property   takes   one   or   two   indexes   as   its  
parameters.      
 
For  example,    
 
Cells(index)  or  Cells(row,  column)  

162
 
where  row  is  the  row  index  and  column  is  the  column  index.  
 
The  following  three  statements  are  interchangable:  
 
ActiveSheet.Range.Cells(1,1)  
Range.Cells(1,1)    
Cells(1,1)  
 
The  following  returns  the  same  outcome:  
 
Range("A1")  =  123        and        Cells(1,1)  =  123  
 
The   following   puts   "XYZ"   on   Cells(1,12)   or   Range("L1")   assume   cell   A1   is   the  
current  cell:  
 
Cells(12)  =  "XYZ"  
 
The  following  puts  "XYZ"  on  cell  C3:  
 
Range("B1:F5").cells(12)  =  "ZYZ"  
 
 
*   The   small   gray   number   on   each   of   the   cells   is   just   for   reference   purpose   only.  
They  are  used  to  show  how  the  cells  are  indexed  within  the  range.  
 
Here  is  a  sub  routine  that  prints  the  corresponding  row  and  column  index  from  A1  
to  E5.  
 
Sub  CellsExample()  
     For  i  =  1  To  5  
               For  j  =  1  To  5  
                       Cells(i,  j)  =  "Row  "  &  i  &  "      Col  "  &  j  
               Next  j  
     Next  i  
End  Sub  
 
 
Range   object   has   an   Offset   property   that   can   be   very   handy   when   one   wants   to  
move   the   active   cell   around.     The   following   examples   demostrate   how   the   Offset  
property  can  be  implemented  (assume  the  current  cell  before  the  move  is  E5):  
 
ActiveCell.Offset(1,0)  =  1                                              Place  a  "1"  one  row  under  E5  (on  E6)  
 
ActiveCell.Offset(0,1)  =  1                                               Place  a  "1"  one  column  to  the  right  of  E5  (on  
F5)  
 
ActiveCell.Offset(0,-­‐3)  =  1                                            Place  a  "1"  three  columns  to  the  left  of  E5  (on  
B5)  
163
 
 
 
6.4. Methods  and  Properties  
 
Each  object  contains  its  own  methods  and  properties.  
 
A   Property   represents   a   built-­‐in   or   user-­‐defined   characteristic   of   the   object.     A  
method   is   an   action   that   you   perform   with   an   object.     Below   are   examples   of   a  
method  and  a  property  for  the  Workbook  Object:  
 
Workbooks.Close    
Close  method  close  the  active  workbook  
 
Workbooks.Count  
Count  property  returns  the  number  of  workbooks  that  are  currently  opened  
 
Some   objects   have   default   properties.   For   example,   Range's   default   property   is  
Value.    
The  following  yields  the  same  outcome.      
 
Range("A1")  =  1        and          Range("A1").Value  =  1  
 
Here  are  examples  on  how  to  set  and  to  get  a  Range  property  value:  
The  following  sets  the  value  of  range  A1  or  Cells(1,1)     as  "2005".     It  actually  prints  
"2005"  on  A1.  
 
Range("A1").Value  =  2005  
 
The  following  gets  the  value  from  range  A1  or  Cells(1,1).  
 
X  =  Range("A1").Value  
 
Method   can   be   used   with   or   without   argument(s).     The   following   two   examples  
demostrate  this  behavior.  
 
Methods  That  Take  No  Arguments:  
 
Worksheets("Sheet").Column("A:B").AutoFit                                              
                                             
Methods  That  Take  Arguments:  
 
Worksheets("Sheet1").Range("A1:A10").Sort  _  
Worksheets("Sheet1").Range("A1")      
                                         
Worksheets("Sheet1").Range("A1")  is  the  Key  (or  column)  to  sort  by.  
 
 
164
 
 
6.4.1. Assigning  Object  Variables  and  Using  Named  Argument  
 
Sometime   a   method   takes   more   than   one   argument.     For   example,   the   Open  
method  for  the  Workbook    
object,   takes   12   arguments.     To   open   a   workbook   with   password   protection,   you  
would  need  to  write  the  following  code:  
 
Workbooks.Open  "Book1.xls",  ,  ,  ,"pswd"  
 
Since   this   method   takes   so   many   arguments,   it   is   easy   to   misplace   the   password  
argument.    To  overcome  this  potential  problem,  one  can  use  named  arguments  like  
the  following  example:  
 
Workbook.Open  fileName:="Book1.xls",  password:="pswd"  
 
You  can  also  assign  an  object  to  an  object  variable  using  the  Set  Statement.  
 
For  example:  
 
Dim  myRange  as  Range  
Set  myRange  =  Range("A1:A10")  
 
 
 

6.5. Modules  and  Procedures  


 
6.5.1. Modules  and  Procedures  and  Their  Scope  
 
A  module  is  a  container  for  procedures  as  shown  in  our  prior  examples.     A  
procedure   is   a   unit   of   code   enclosed   either   between   the   Sub   and   End   Sub  
statement  or  between  the  Function  and  End  Function  statements.        
 
The   following   sub   procedure   (or   sub   routine)   print   the   current   date   and   time   on  
cell  C1:  
 
Sub  ShowTime()  
       Range("C1")  =  Now()  
End  Sub  
 
The  following  function  sum  up  two  numbers:  
 
Function  sumNo(x,  y)  
165
         sumNo  =  x  +  y  
End  Function  
 
Procedures   in   Visual   Basic   can   have   either   private   or   public   scope.     A   procedure  
with  private  scope  is  only  accessible  to  the  other  procedures  in  the  same  module;  a  
procedure  with  public  scope  is  accessible  to  all  procedures  in  in  every  module  in  
the   workbook   in   which   the   procedure   is   declared,   and   in   all   workbooks   that  
contain  a  reference  to  that  workbook.    By  default,  procedures  has  public  scope.  
 
Here  are  examples  of  defining  the  scope  for  procedure.      
 
Public  Sub  ShowTime()  
       Range("C1")  =  Now()  
End  Sub  
 
Private  Sub  ShowTime()  
       Range("C1")  =  Now()  
End  Sub  
 
 
 
   

166
6.5.2. Calling  Sub  Procedures  and  Function  Procedures  
 
There  are  two  ways  to  call  a  sub  procedure.     The  following  example  shows  
how  a  sub  procedure  can  be  called  by  other  sub  procedures.      
 
Sub  z(a)  
       MsgBox  a  
End  Sub  
 
Sub  x()  
       Call  z("ABC")  
End  Sub  
 
Sub  y()  
       z  "ABC"  
End  Sub  
 
Sub  z  procedure  takes  an  argument  (a)  and  display  the  argument  value  ("ABC")  in  
a  message  box.    Running  either  Sub  x  or  Sub  y  will  yield  the  same  result.  
 
The  following  example  calls  a  function  procedure  from  a  sub  procedure.  
 
Sub  ShowSum()  
         msgbox  sumNo(3,5)  
End  Sub  
 
Function  sumNo(x,  y)  
         sumNo  =  x  +  y  
End  Function  
 
The   ShowSum   sub   procedure   calls   the   sumNo   function   and   returns   an   "8"   in   a  
message  box.  
 
If  there  are  procedures  with  duplicate  names  in  different  modules,  you  must  need  
to   include   a   module   qualifier   before   the   procedure   name   when   calling   the  
procedure.      
 
For  example:  
 
Module1.ShowSum  
 
 
 
   

167
6.5.3. Passing  Argument  by  Reference  or  by  Value    
 
If   you   pass   an   argument   by   reference   when   calling   a   procedure,   the  
procedure  access  to  the  actual  variable  in  memory.    As  a  result,  the  variable's  value  
can   be   changed   by   the   procedure.     Passing   by   reference   is   the   default   in   VBA.     If  
you   do   not   explicitly   specify   to   pass   an   argurment   by   value,   VBA   will   pass   it   by  
reference.    The  following  two  statements  yield  the  same  outcome.      
 
Sub  AddNo(ByRef  x  as  integer)  
Sub  AddNo(x  as  integer)  
 
Here   is   an   example   to   show   the   by   reference   behavior.     The   sub   procedure,  
TestPassing   1   calls   AddNo1   by   reference   and   display   "60"   (50   +   10)   on   the  
message  box.  
 
Sub  TestPassing1()  
       Dim  y  As  Integer  
       y  =  50  
       AddNo1  y  
       MsgBox  y  
End  Sub  
 
Sub  AddNo1(ByRef  x  As  Integer)  
       x  =  x  +  10  
End  Sub  
 
 
The   following   example   shows   the   by   value   behavior.     The   sub   procedure,  
TestPassing  2  calls  AddNo2  by  value  and  display  "50"  on  the  message  box.  
 
Sub  TestPassing2()  
       Dim  y  As  Integer  
       y  =  50  
       AddNo2  y  
       MsgBox  y  
End  Sub  
 
Sub  AddNo2(ByVal  x  As  Integer)  
       x  =  x  +  10  
End  Sub  
 
 

6.6. Creating  and  Managing  Arrays        


 
An   array   is   a   set   of   sequentially   indexed   elements   having   the   same   intrinsic  
data   type.   Each   element   of   an   array   has   a   unique   identifying   index   number.  
168
Changes  made  to  one  element  of  an  array  don't  affect  the  other  elements.      
 
 
     
6.6.1. Declaring  an  Array  With  Dim  Statement  
 
 
Before   signing   values   to   an   array,   the   array   needs   to   be   created.     You   can  
declare  the  array  by  using  the  Dim  statement.  
 
For   example,   to   declare   a   one-­‐dimensional   array   with   5   elements,   type   the  
following:  
 
                       Dim  Arr(4)  
 
The  element’s  index  of  the  array  starts  from  0  unless  Option  Base  1  is  specified  in  
the  public  area  (area  outside  of  the  sub  procedure).     If  Option  Base  1  is  specified,  
the  index  will  start  from  1.  
 
The   following   example   assigns   values   to   the   array   and   displays   all   values   in   a  
message  box  :  
 
                 Option  Base  1  
                       Sub  assignArray(  )  
                                   Dim  Arr(5)    
 
                                   Arr(1)  =  “Jan”  
                                   Arr(2)  =  “Feb”  
                                             Arr(3)  =  “Mar”  
                                             Arr(4)  =  “Apr”  
                                   Arr(5)  =  “May”  
 
                                 Msgbox  Arr(1)  &  "-­‐"  &  Arr(2)  &  "-­‐"  &  Arr(3)  &  "-­‐"  &  Arr(4)  &  "-­‐"  &  Arr(5)  
                         
End  Sub  
 
 
                 
 
*  The  number  inside  the  array,  i.e.  Arr(1),  is  the  index.     One  (1)  is  the  index  of  the  
first  element  in  the  
   array.  
 
 
   

169
6.6.2. Resize  an  Array  With  Redim  Statement  
 
The   ReDim   statement   is   used   to   size   or   resize   a   dynamic   array   that   has  
already  been  formally  declared.  
 
For  example,  if  you  have  already  declared  an  array  with  an  element  value  of  
5  and  decided  to  change  the  number  of  the  element  to  6,  you  can  do  the  following  
to  resize  the  array:  
 
                       Redim  Arr(6)  
 
We  incorporate  it  into  our  last  example:  
 
                 Option  Base  1  
                 Sub  assignArray(  )  
                                   'Dim  Arr(5)    
                                   Redim  Arr(6)  
 
                                   Arr(1)  =  “Jan”  
                                   Arr(2)  =  “Feb”  
                                   Arr(3)  =  “Mar”  
                                   Arr(4)  =  “Apr”  
                                   Arr(5)  =  “May”  
                                   Arr(6)  =  “Jun”  
 
                                   Msgbox  Arr(1)  &  "-­‐"  &  Arr(2)  &  "-­‐"  &  Arr(3)  &  "-­‐"  &  Arr(4)  &  "-­‐"  &  Arr(5)  
                       End  Sub    
 
Note  that  the  Dim   Arr(5)  statement  is  commoned  out,  because  leaving  this  
original  statement  in  the  sub  will  causing  a  compile  error.  
 
 
 
6.6.3. Manage  Dynamic  Array  
 
A  word  of  caution  in  using  the  Redim   Statement  to  resize  an  array  -­‐  resize  
the   array   can   erase   the   elements   in   it.     In   the   following   example,   all   the   values  
assigned  prior  to  resize  the  array  are  erased.     Only  the  value  assigned  to  the  array  
after  resize  remains.    
 
                 Option  Base  1  
                       Sub  assignArray(  )                                      
                                   Redim  Arr(5)  
 
                                   Arr(1)  =  “Jan”  
                                   Arr(2)  =  “Feb”  
                                   Arr(3)  =  “Mar”  
170
                                   Arr(4)  =  “Apr”  
                                   Arr(5)  =  “May”  
 
                                   Redim  Arr(6)  
 
                                   Arr(6)  =  “Jun”  
 
                                    Msgbox   Arr(1)   &   "-­‐"   &   Arr(2)   &   "-­‐"   &   Arr(3)   &   "-­‐"   &   Arr(4)   &   "-­‐"   &   Arr(5)  
&  "-­‐"  &  Arr(6)  
                       End  Sub  
 
 
    By   replace   the   Redim   Arr(6)   with   Redim   Preserve   Arr(6),   all   values   will  
remain.    For  example:  
 
                   Option  Base  1  
                   Sub  assignArray(  )  
                                   Redim  Arr(5)  
 
                                   Arr(1)  =  “Jan”  
                                   Arr(2)  =  “Feb”  
                                   Arr(3)  =  “Mar”  
                                   Arr(4)  =  “Apr”  
                                   Arr(5)  =  “May”  
 
                                   Redim  Preserve  Arr(6)  
 
                                   Arr(6)  =  “Jun”  
 
                                    Msgbox   Arr(1)   &   "-­‐"   &   Arr(2)   &   "-­‐"   &   Arr(3)   &   "-­‐"   &   Arr(4)   &   "-­‐"   &   Arr(5)  
&  "-­‐"  &  Arr(6)  
                       End  Sub  
 
 
 
6.6.4. Create  Multi-­‐Dimensional  Array  
 
An  array  can  also  store  multiple  dimensional  data.     To  simplify  our  tutorial,  
example   on   a   two-­‐dimensional   array   is   used.     Assume   you   have   data   of   a   local  
store's  yearly  sale  in  the  following  table  and  you  want  to  store  the  data  in  a  two-­‐
dimensional  array:  
 
                                                         Year  2003          Year  2004  
                     CD  Sale                        1,000                      1,500  
                 DVD  Sale                      1,200                        2,000  
 
First  we  create  the  array  as  follow:  
 
171
                               Dim  Arr(2,2)  
 
Then  we  assign  the  values  into  the  array.     We  treat  the  first  dimension  as  the  year  
and  the  second  dimension  as  the  product  sale:  
 
                       arr(1,1)  =  1000  
                       arr(1,2)  =  1200  
                       arr(2,1)  =  1500  
                       arr(2,2)  =  2000  
 
We  now  display  the  values  of  the  array  with  a  message  box:  
 
Msgbox  "Sale  of  CD  in  2003  is  "  &  arr(1,1)  &  vbCrLf     &  "Sale  of  CD  in  2004  is  "  _&  
arr(2,1)     &   vbCrLf     &   "Sale   of   DVD   in   2003   is   "   &   arr(1,2)   &   vbCrLf  _  &   "Sale   of   DVD  
in  2004  is  "  &  arr(2,2)    
 
The  complete  precedure  is  as  followed:  
                         
                 Option  Base  1  
                       Sub  multDimArray(  )                          
                                   Dim  Arr(2,2)  
 
                                   arr(1,1)  =  1000  
                                   arr(1,2)  =  1200  
                                   arr(2,1)  =  1500  
                                   arr(2,2)  =  2000    
 
Msgbox  "Sale  of  CD  in  2003  is  "  &  arr(1,1)  &  vbCrLf     &  "Sale  of  CD  in  2004  is  "  _&  
arr(2,1)  &  vbCrLf     &  "Sale  of  DVD  in  2003  is  "  &  arr(1,2)  &  vbCrLf  _&  "Sale  of  DVD  
in  2004  is  "  &  arr(2,2)    
 
                       End  Sub  
 
                     
 
*  vbCrLf  stands  for  VB  Carriage  Return  Line  Feed.     It  puts  a  return  and  a  new  line  
as  shown  in  the  message  box  above.    The  underscore  "_"  on  the  back  of  the  first  line  
of  the  message  box  means    
   "continue  to  the  next  line"  
 
 
6.6.5. Find  The  Size  of    an  Array  
 
The  largest  available  subscript  for  the  indicated  dimension  of  an  array  can  
be  obtained  by  using  the  Ubound  function.    In  our  one-­‐dimensional  array  example,  
Ubound(arr)  is  5.  
   
In  our  two-­‐dimensional  array  example  above,  there  are  two  upper  bound  figures  -­‐  
172
both  are  2.      
UBound  returns  the  following  values  for  an  array  with  these  dimensions*:  
 
                 Dim  A(1  To  100,  0  To  3,  -­‐3  To  4)  
 
                 Statement                          Return  Value    
                 UBound(A,  1)                                                  100                                        
                 UBound(A,  2)                                                        3    
                 UBound(A,  3)                                                        4    
 
*  Example  taken  from  Excel  VBA  Help  section.  
 
The  UBound  function  is  used  with  the  LBound  function  to  determine  the  size  of  an  
array.  Use  the  LBound  function  to  find  the  lower  limit  of  an  array  dimension.  
 
                 Statement                          Return  Value    
                 LBound(A,  1)                                                        1                                        
                 LBound(A,  2)                                                        0    
                 LBound(A,  3)                                                      -­‐3    
 
To  get  the  size  of  an  array,  use  the  following  formula:  
 
               UBound(Arr)  -­‐  LBound(Arr)  +  1  
 
For  example:    
 
               Ubound(A,1)  -­‐  LBound(A,1)  +  1    
               =  100  -­‐  1  +  1    
               =  100  
 
               Ubound(A,2)  -­‐  LBound(A,2)  +  1    
               =  3  -­‐  0  +  1    
               =  4  
 
               Ubound(A,3)  -­‐  LBound(A,3)  +  1    
               =  4  -­‐  (-­‐3)  +  1    
               =  8  
 
 
 
6.6.6. Choosing  The  Right  Return  Array  Size  
 
At   its   simplest,   the   size   of   the   returned   array   can   be   mandated   by   the   function   and  
require  that  the  user  use  an  array  that  size  in  order  to  get  all  the  results.    
 
The   Excel   function   LINEST   function   works   this   way.   You   must   array-­‐enter   that  
function  into  a  range  of  cells  that  is  5  rows  tall  and  2  columns  wide.  If  you  enter  it  
into   a   larger   range,   Excel   fills   out   the   unused   elements   of   the   range   with   #N/A  
173
errors.  If  you  enter  it  into  a  smaller  range,  you  will  not  get  all  the  values  created  by  
LINEST.  
 
To  mandate  the  size  of  the  returned  array,  simply  declare  the  array  to  that  size  and  
setting  the  result  of  the  function  to  that  array.  For  example,  
 
       Function  Test()  As  Variant  
               Dim  V()  As  Variant  
               Dim  N  As  Long  
               Dim  R  As  Long  
               Dim  C  As  Long  
               ReDim  V(1  To  3,  1  To  4)  
               For  R  =  1  To  3  
                       For  C  =  1  To  4  
                               N  =  N  +  1  
                               V(R,  C)  =  N  
                       Next  C  
               Next  R  
               Test  =  V  
       End  Function  
 
This  function  simply  returns  an  array  with  3  rows  and  4  columns  that  contains  the  
integers  from  1  to  12.    
 
Returning   such   a   fixed-­‐size   array   can   be   useful   if   the   number   of   results   does   not  
vary  with  the  number  and/or  values  of  the  inputs  to  the  function.  However,  this  is  
usually  not  the  case.  
 
In  the  majority  of  circumstances,  if  your  UDF  is  going  to  return  an  array,  that  array  
will  vary  in  size  and  the  size  will  depend  on  any  one  or  more  of  three  things:  the  
size  of  the  range  into  which  the  UDF  was  entered,  the  number  of  elements  passed  
into   the   function,   and,   of   course,   the   nature   and   function   of   the   UDF   itself.   The  
Application.Caller  object,  when  used  in  a  UDF  called  from  a  worksheet  range,  is  a  
Range  reference  to  the  range  from  which  your  UDF  was  called.  
 
 
6.6.7. Orienting  An  Array  
 
If   your   UDF   creates   a   1-­‐dimensional   array   as   its   result,   it   can   orient   the   array   as  
either  a  row  vector  or  a  column  vector  so  that  is  will  be  properly  displayed  in  the  
worksheet   cells   without   requiring   the   user   to   wrap   your   UDF   result   in   a  
TRANSPOSE  function.    
 
If  the  function  was  called  from  a  row  vector  of  cells  (e.g.,  A1:E1),  it  does  not  need  to  
be  transposed.  If  the  function  was  called  from  a  column  vector  of  cells  (e.g.,  A1:A5),  
the   array   needs   to   be   transposed.   The   code   below   looks   at  
Application.Caller.Rows.Count   and   if   this   is   greater   than   1,   it   tranposes   the   array  
before   returning   it   to   the   caller.   Note   that   this   should   be   done   only   with   single-­‐
174
dimensional  arrays  and  only  when  the  UDF  is  being  called  from  a  worksheet  range.  
Therefore,   you   should   first   test   Application.Caller   with   IsObject   and   then   test  
Application.Caller.Rows.Count  and  Application.Caller.Columns.Count  to  test  if  it  is  
being  called  from  a  row  or  column  vector.    
 
For  example,    
 
 
       Function  Test(NN  As  Long)  
               Dim  Result()  As  Long  
               Dim  N  As  Long  
               ReDim  Result(1  To  NN)  
               For  N  =  1  To  NN  
                       Result(N)  =  N  
               Next  N  
               If  Application.Caller.Rows.Count  >  1  Then  
                       Test  =  Application.Transpose(Result)  
               Else  
                       Test  =  Result  
               End  If  
       End  Function  
 
You  can,  of  course,  forego  this  and  return  the  array  as-­‐is  and  leave  it  up  to  the  user  
to  use  the  TRANSPOSE  function  to  properly  orient  the  array.    

175
6.7. Decision  Structures  -­‐  IF  and  Select  Case  
 
6.7.1. IF  ...  Then  Statement  
 
The  IF  ...  Then  is  a  single  condition  and  run  a  single  statement  or  a  block  of  
statement.  
 
Example,  the  following  statement  set  variable  Status  to  "Adult"  if  the  statement  is  
true:  
 
               If  Age  >=  18  Then  Status  =  "Adult"  
 
You  can  also  use  multiple-­‐line  block  in  the  If  statement  as  followed:  
 
               If  Ago  >=  18  Then    
                       Status  =  "Adult"  
                       Vote  =  "Yes"  
               End  If  
 
Note   that   in   the   multiple-­‐line   block   case,   End   If   statement   is   needed,   where   the  
single-­‐line  case  does  not.  
 
 
 
 
6.7.2. IF  ...  Then  ...  Else  
 
The  If  ...  Then  ...  Else  statement  is  used  to  define  two  blocks  of  conditions   -­‐  
true  and  false.  
 
Example:  
         
         If  Age  >=22  Then  
               Drink  =  "Yes"  
       Else  
               Drink  =  "No"  
       End  If  
 
Again,  note  that  End  If  statement  is  needed  in  this  case  as  well  since  there  is  more  
than  one  block  of  statements.  
 
 
 
 
176
6.7.3. IF  ...  Then  ...  ElseIf  
 
The   IF   ...   Then   ...   ElseIf   is  used  to  test  additional  conditions  without  using  
new  If  ...  Then  statements.  
 
For  Example:  
 
     If  Age  >=  18  and  Age  <  22  Then  
               Msgbox  "You  can  vote"  
       ElseIf  Age  >=22  and  Age  <  62  Then  
               Msgbox  "You  can  drink  and  vote"  
       ElseIf  Age  >=62  Then  
               Msgbox  "You  are  eligible  to  apply  for  Social  Security  Benefit"  
       Else  
               Msgbox  "You  cannot  drink  or  vote"  
       End  If  
 
Note  that  the  last  condition  under  Else  is,  implicitly,  Age  <  18.  
 
 
 
6.7.4. Select  Case  
 
Select   Case  statement  is  an  alternative  to  the  ElseIf  statement.    This  method  
is  more  efficient  and  readable  in  coding  the  the  If  ...  Then  ...  ElseIf  statment.      
 
Example:  
 
       Select  Case  Grade  
               Case  Is  >=  90  
                       LetterGrade  =  "A"  
               Case  Is  >=  80  
                       LetterGrade  =  "B"  
               Case  Is  >=  70  
                       LetterGrade  =  "C"  
               Case  Is  >=  60  
                       LetterGrade  =  "D"  
               Case  Else  
                       LetterGrade  =  "Sorry"  
       End  Select  
 
 
   

177
 
6.8. Loop  Structures  
 
6.8.1. For  ...  Next    
 
Use  For   ...   Next  loop  if  the  number  of  loops  is  already  defined  and  known.    A  
For   ...   Next  loop  uses  a  counter  variable  that  increases  or  decreases  in  value  during  
each   iteration   of   the   loop.     This   loop   structure   is   being   used   the   most   for   our  
examples  on  this  site.      
 
Here  is  an  example  of  the  For  ...  Next  loop:  
 
       For  i  =  1  to  10  
               Cells(i,  1)  =  i  
       Next  i  
 
         
 
In   this   example,   i   is   the   counter   variable   from   1   to   10.     The   looping   process   will  
send  value  to  the  first  column  of  the  active  sheet  and  print  i  (which  is  1  to  10)  to  
row  1  to  10  of  that  column.  
 
Note  that  the  counter  variable,  by  default,  increases  by  an  increment  of  1.  
 
 
 
 
6.8.2. For  ...  Next  Loop  With  Step  
 
You   can   use   the   Step   Keyword   to   sepcify   a   different   increment   for   the  
counter  variable.      
 
For  example:  
 
       For  i  =  1  to  10  Step  2  
               Cells(i,  1)  =  i  
       Next  i  
 
This  looping  process  will  print  values  with  an  increment  of  2  on  row  1,  3,  5,  7  and  9  
on  column  one.  
       
 
You  can  also  have  decrement  in  the  loop  by  assign  a  negative  value  afte  the  Step  
keyword.      

178
 
For  example:  
 
       For  i  =  10  to  1  Step  -­‐2  
               Cells(i,  1)  =  i  
       Next  i  
 
This   looping   process   will   print   values   with   an   increment   of   -­‐2   starts   from   10   on  
row    10,  8,  6,  4  and  2  on  column  one.  
 
 
6.8.3. Do  While  ...  Loop  
 
You   can   use   the   Do   While   ...   Loop   to   test   a   condition   at   the   start   of   the  
loop.     It   will   run   the   loop   as   long   as   the   condition   is   ture   and   stops   when   the  
condition  becomes  false.    For  Example:  
 
     i  =  1  
       Do  While  i  =<  10  
               Cells(i,  1)  =  i  
               i  =  i  +  1  
       Loop  
 
This   looping   process   yields   the   same   result   as   in   the   For   ...   Next   structures  
example.  
 
One  thing  to  be  caution  is  that  sometimes  the  loop  might  be  a  infinite  loop.     And  it  
happens   when   the   condition   never   beomes   false.     In   such   case,   you   can   stop   the  
loop  by  press  [ESC]  or  [CTRL]  +  [BREAK].  
 
 
 
 
6.8.4. Do  Until  ...  Loop    
 
You  can  test  the  condition  at  the  beginning  of  the  loop  and  then  run  the  loop  until  
the  test  condition  becomes  true.  
 
Example:  
 
       i  =  1  
       Do  Until  i  =  11  
               Cells(i,  1)  =  i  
               i  =  i  +  1          
       Loop  
 
179
This   looping   process   yields   the   same   result   as   in   the   For   ...   Next   structures  
example.  
 
 
 
 
6.8.5. Do  ...  Loop  While    
 
When  you  want  to  make  sure  that  the  loop  will  run  at  least  once,  you  can  put  the  
test   at   the   end   of   loop.     The   loop   will   stop   when   the   condition   becomes  
false.      (compare  this  loop  structure  to  the  Do  ...  While  Loop.)  
 
For  Example:  
         
     i  =  1  
       Do    
               Cells(i,  1)  =  i  
               i    =  i  +  1  
       Loop  While  i  <  11  
     
This   looping   process   yields   the   same   result   as   in   the   For   ...   Next   structures  
example.                  
 
 
 
6.8.6. Do  ...  Loop  Until  
 
This  loop  structure,  like  the  Do  ...  Loop  While,  makes  sure  that  the  loop  will  run  at  
least   once,   you   can   put   the   test   at   the   end   of   loop.     The   loop   will   stop   when   the  
condition  becomes  true.      (compare  this  loop  structure  to  the  Do  ...  Until  Loop.)  
 
For  Example:  
         
     i  =  1  
       Do    
               Cells(i,  1)  =  i  
               i    =  i  +  1  
       Loop  Until  i  =  11  
     
This   looping   process   yields   the   same   result   as   in   the   For   ...   Next   structures  
example.          
 
 
 
 
 
180
 
7. Applying  VBA  to  Finance.  Introductory  Examples  
 

7.1. Your  first  function  in  VBA:  Sum  A  and  B  


 
This  function  sums  2  real  numbers.  
 
___________________________________________________________________  
 
'  This  function  adds  up  a  and  b  
Function  sum_ab(a  As  Double,  b  As  Double)  As  Double  
 
sum_ab  =  a  +  b  
 
End  Function  

 
 

181
7.2. Your  second  function  in  VBA:  Conditional  IF  
 
This  function  sums  or  multiplies  2  real  numbers  depending  upon  variable  c.  
 
___________________________________________________________________  
 
'  This  function  adds  up  a  and  b  if  option=1  
'  This  function  multiplies  a  by  b  if  option=2  
Function  multiple_operation(a  As  Double,  b  As  Double,  c  As  Integer)  As  Double  
 
If  (c  =  1)  Then  multiple_operation  =  a  +  b  
If  (c  =  2)  Then  multiple_operation  =  a  *  b  
 
End  Function  
___________________________________________________________________  
 
 
 
 

182
7.3. Your  third  function  in  VBA:  Loops  
 
This  function  sums  up  all  integers  from  1  to  n.  
 
___________________________________________________________________  
 
'  This  function  adds  all  numbers  from  1  to  n  
Function  sum_up_to(n  As  Integer)  As  Integer  
 
temp1  =  0  
 
For  i  =  1  To  n  Step  1  
temp1  =  temp1  +  i  
Next  i  
 
sum_up_to  =  temp1  
 
End  Function  
 
___________________________________________________________________  
 
 

183
7.4. Your  fourth  function  in  VBA:  Arrays  
 
This   function   helps   you   understand   how   to   create,   dimensionate,   and   assign   values   to  
matrices.  
___________________________________________________________________  
 
'  Sum  the  values  in  a  known  matrix  
Function  sum_array_elements()  
 
Dim  a(4,  3)  
sum_array_elements  =  UBound(a,  2)      
 
'  Assigning  values  to  array  elements  
 
For  i  =  1  To  UBound(a,  1)  
       For  j  =  1  To  UBound(a,  2)  
       a(i,  j)  =  10  
       Next  j  
Next  i  
 
'  Adding  Up  array  elements  
 
temp  =  0  
 
For  i  =  1  To  UBound(a,  1)  
       For  j  =  1  To  UBound(a,  2)  
       temp  =  temp  +  a(i,  j)  
       Next  j  
Next  i  
 
sum_array_elements  =  temp  
 
End  Function  
___________________________________________________________________  
 
 
 

184
 

185
7.5. Your  fifth  function  in  VBA:  Ranges  from  Excel  to  VBA  
 
This  function  is  able  to  capture  a  range  of  data  from  EXCEL  environment  and  use  it  
for  the  sake  of  computing  whatever  we  need  within  VBA  environment.  
 
___________________________________________________________________  
 
'  Sum  the  values  in  a  unknown  matrix  /  excel  range  
Function  test1(rng1  As  Range)  
 
Dim  mat  As  Variant  
mat  =  rng1  
 
max1  =  UBound(mat,  1)  
max2  =  UBound(mat,  2)  
 
For  i  =  1  To  max1  
       For  j  =  1  To  max2  
               mat(i,  j)  =  mat(i,  j)  +  1  
       Next  j  
Next  i  
 
test1  =  mat  
 
End  Function  
___________________________________________________________________  
 
 
 

186
7.6. Your  sixth  function  in  VBA:  Prices  to  Returns  
 
This   function   uses   last   section   knowledge   in   order   to   produce   a   returns   vector   out  
of  a  prices  vector  captured  from  EXCEL  environment.  
 
___________________________________________________________________  
 
'  Price  data  available  in  Excel  “price”  range.  Calculate  the  return  
Function  calreturn(range1  As  Range)  
 
Dim  r1  As  Variant  
Dim  r2  As  Variant  
 
r1  =  range1  
 
max1  =  UBound(r1,  1)        'get  the  number  of  rows  
max2  =  UBound(r1,  2)        'get  the  number  of  columns  
 
ReDim  r2(1  To  max1,  1  To  max2)  
 
'  assign  the  return  to  a  matrix  
For  j  =  1  To  max2  
       For  i  =  1  To  max1  -­‐  1  
               r2(i,  j)  =  Log(r1(i  +  1,  j)  /  r1(i,  j))  
       Next  i  
Next  j  
 
calreturn  =  r2  
 
End  Function  
___________________________________________________________________  
 
OUTPUT  OF  THE  VBA  FUNCTION  IN  EXCEL  
 

  Prices     Returns  
Date   WMT   TGT     WMT   TGT  

187
05-­‐jul-­‐01   26,07   37,40        
01-­‐ago-­‐01   22,00   33,53     -­‐0,16974   -­‐0,10923  
04-­‐sep-­‐01   20,07   30,73     -­‐0,09182   -­‐0,0872  
01-­‐oct-­‐01   20,02   30,15     -­‐0,00249   -­‐0,01905  
01-­‐nov-­‐01   23,35   36,38     0,153865   0,187834  
03-­‐dic-­‐01   24,79   39,79     0,059843   0,089596  
02-­‐ene-­‐02   23,03   43,04     -­‐0,07364   0,078514  
04-­‐feb-­‐02   18,09   40,66     -­‐0,24144   -­‐0,05689  
01-­‐mar-­‐02   19,17   41,85     0,057987   0,028847  
01-­‐abr-­‐02   20,25   42,36     0,054808   0,012113  
01-­‐may-­‐02   22,79   40,29     0,118167   -­‐0,0501  
03-­‐jun-­‐02   20,52   37,03     -­‐0,10492   -­‐0,08437  
01-­‐jul-­‐02   16,50   32,41     -­‐0,21804   -­‐0,13326  
01-­‐ago-­‐02   16,27   33,30     -­‐0,01404   0,02709  
03-­‐sep-­‐02   14,92   28,74     -­‐0,08662   -­‐0,14727  
01-­‐oct-­‐02   18,01   29,32     0,188225   0,01998  
01-­‐nov-­‐02   22,43   33,92     0,219472   0,145735  
02-­‐dic-­‐02   21,75   29,26     -­‐0,03079   -­‐0,14778  
02-­‐ene-­‐03   18,43   27,51     -­‐0,16563   -­‐0,06167  
03-­‐feb-­‐03   18,87   28,00     0,023594   0,017655  
03-­‐mar-­‐03   18,67   28,60     -­‐0,01066   0,021202  
01-­‐abr-­‐03   16,32   32,69     -­‐0,13453   0,133663  
01-­‐may-­‐03   16,57   35,87     0,015202   0,092832  
02-­‐jun-­‐03   16,12   37,05     -­‐0,02753   0,032367  
01-­‐jul-­‐03   17,91   37,52     0,105298   0,012606  
01-­‐ago-­‐03   20,45   39,83     0,132624   0,059746  
02-­‐sep-­‐03   20,60   36,91     0,007308   -­‐0,07614  
01-­‐oct-­‐03   22,92   38,98     0,106719   0,054566  
03-­‐nov-­‐03   24,12   38,05     0,051031   -­‐0,02415  
01-­‐dic-­‐03   25,47   37,74     0,05446   -­‐0,00818  
02-­‐ene-­‐04   25,50   37,31     0,001177   -­‐0,01146  
02-­‐feb-­‐04   30,06   43,27     0,164517   0,148198  
01-­‐mar-­‐04   33,87   44,34     0,119334   0,024428  
01-­‐abr-­‐04   33,10   42,69     -­‐0,023   -­‐0,03792  
03-­‐may-­‐04   34,97   44,08     0,054957   0,032041  
01-­‐jun-­‐04   36,91   41,88     0,053992   -­‐0,0512  
01-­‐jul-­‐04   39,23   42,99     0,060959   0,026159  
02-­‐ago-­‐04   37,58   44,04     -­‐0,04297   0,024131  
01-­‐sep-­‐04   34,60   44,70     -­‐0,08262   0,014875  
01-­‐oct-­‐04   34,04   49,41     -­‐0,01632   0,100179  
01-­‐nov-­‐04   37,99   50,68     0,109787   0,025379  
01-­‐dic-­‐04   40,74   51,38     0,069887   0,013718  
03-­‐ene-­‐05   42,17   50,23     0,034499   -­‐0,02264  
01-­‐feb-­‐05   43,92   50,36     0,040661   0,002585  
01-­‐mar-­‐05   51,25   49,57     0,154346   -­‐0,01581  
01-­‐abr-­‐05   46,92   45,99     -­‐0,08827   -­‐0,07496  
02-­‐may-­‐05   49,25   53,30     0,048465   0,147512  
01-­‐jun-­‐05   52,04   54,00     0,055103   0,013048  
01-­‐jul-­‐05   55,69   58,31     0,067788   0,07679  
01-­‐ago-­‐05   48,24   53,45     -­‐0,14361   -­‐0,08703  
01-­‐sep-­‐05   47,04   51,64     -­‐0,02519   -­‐0,03445  
03-­‐oct-­‐05   50,93   55,37     0,079454   0,069741  
01-­‐nov-­‐05   52,19   53,31     0,024439   -­‐0,03791  
01-­‐dic-­‐05   55,31   54,76     0,058063   0,026836  
188
03-­‐ene-­‐06   55,63   54,54     0,005769   -­‐0,00403  
01-­‐feb-­‐06   58,46   54,29     0,04962   -­‐0,00459  
01-­‐mar-­‐06   60,23   51,90     0,029828   -­‐0,04502  
03-­‐abr-­‐06   65,46   52,99     0,083269   0,020784  
01-­‐may-­‐06   60,84   48,92     -­‐0,07319   -­‐0,07992  
01-­‐jun-­‐06   67,51   48,87     0,104028   -­‐0,00102  
 
03-­‐jul-­‐06   67,65   49,17     0,002072   0,00612  
 
 
 

189
8. Bibliography  
 
Hull,   J.   (2008).   Options,   Futures,   and   Other   Derivate   Securities   (8th   Edition).  
Englewood  Cliffs,  N.J.:  Prentice-­‐Hall.  

Boyle,   P.,   Broadie,   M.   and   Glasserman,   P.   (1997).   Monte   Carlo   methods   for  
security  pricing.  Journal  of  Economic  Dynamics  and  Control  21,  1267-­‐2321.  

Black,   F.   and   Scholes,   M.   (1973).  The  Pricing  of  Options  and  Corporate  Liabilities.  
Journal  of  Political  Economy  81,  637-­‐654.  

Leclecrcq,   V.   Monte   Carlo   Simulation   using   MATLAB.   Online   webinar,  


www.mathworks.com  

190

Das könnte Ihnen auch gefallen