際際滷

際際滷Share a Scribd company logo
VBA
                         Q2 2012
                                   Vincent JEANNIN  ESGF 4IFM




    vinzjeannin@hotmail.com         ESGF 4IFM Q2 2012
1
ESGF 4IFM Q2 2012
Summary of the session

   Introduction: from BASIC to VBA
   Think Algorithmic First: 
   First VBA Program: a formula




                                      vinzjeannin@hotmail.com
   Alternatives to  estimation
   Formula using Excel References
   Advanced Formula: CRR




                                           2
Introduction: from BASIC to VBA
             Beginner's All-purpose Symbolic Instruction Code

                   Created in 1964 by students for students




                                                                              ESGF 4IFM Q2 2012
                   Spread because free

                   Succeed because easy and base to most of languages




                                                                              vinzjeannin@hotmail.com
    If youre old enough to know what is a 80-386 or to have played with an
    Apple II you may have heard of: Applesoft BASIC, GW BASIC, QBASIC

             BASIC extended to event driven programming: Visual BASIC
               The flow of the program is determined by events: sensor
               outputs, user actions (mouse clicks, key presses)

             Visual BASIC integrated in Microsoft Office: VBA
               Visual BASIC for Applications enables building user defined         3
               functions, automating processes,
Think Algorithmic First: 




                                                                      ESGF 4IFM Q2 2012
       Lets approximate pi




                                                                      vinzjeannin@hotmail.com
       Think first about How to regardless of any programming




       Draw a chart of the program then the translation is easier




                                                                           4
Lets pick 2 random numbers

Using a uniform distribution




                                                                 ESGF 4IFM Q2 2012
                                                                 vinzjeannin@hotmail.com
How do you determine if (x,y) is inside or outside the circle?
                                                                      5
Right Triangle properties




                                         ESGF 4IFM Q2 2012
                                         vinzjeannin@hotmail.com
 諮$ 2 = 基 2 + $ 2
                                              6
Repeat                                    Repeat


                  Generate x and y




                                                   ESGF 4IFM Q2 2012
               Calculate the hypotenuse




                                                   vinzjeannin@hotmail.com
   Is the hypotenuse shorter than the radius?



         Yes                          No



     Count

                                                        7
Surface of the square: 1
                                      
               Surface of the circle:
                                     4
                                        
               Surface of the rest: 1 
                                        4




                                                                       ESGF 4IFM Q2 2012
                                                                       vinzjeannin@hotmail.com
Lets make i trials, count the n points inside the circle

Randomisation has been done uniformly                                       8
                                                             
Proportions will be respected                        
                                                           2
First VBA Program: a formula
      VBA can be sued to create custom Excel Functions




                                                         ESGF 4IFM Q2 2012
      Display the Visual Basic Editor




                                                         vinzjeannin@hotmail.com
      Right Click on your file and insert a module




                                                              9
Lets call our function EstmPi

         What are the arguments?




                                                                 ESGF 4IFM Q2 2012
               Only one argument

               The number of simulations to make

               Lets call the variable Simu




                                                                 vinzjeannin@hotmail.com
                     Compulsory to define the type of variable

                            String: Text

                            Integer: Natural Number

                            Double: 64-bits number

                            Boolean: True/False                  10

What type is Simu?
Basic structure of the function




                                                          ESGF 4IFM Q2 2012
Used in Excel




                                                          vinzjeannin@hotmail.com
=EstmPi(100)

Result will be the value stored in the variable Result




Time to be reminded the algorithmic fundamentals of our
program and learn the corresponding BASIC functions
                                                          11
Repeat                                    Repeat


                                    Generate x and y




                                                                     ESGF 4IFM Q2 2012
   For To Next                 Calculate the hypotenuse
         or
Do While/Until Loop




                                                                     vinzjeannin@hotmail.com
                       Is the hypotenuse shorter than the radius?

                                 If Then Else End If
                           Yes                            No



                         Count

                                                                     12
For To Next
Full syntax
          For counter = start To end [Step step]
          [statements]




                                                                  ESGF 4IFM Q2 2012
          Next [counter]



The program will repeat instructions a specified number of time




                                                                  vinzjeannin@hotmail.com
Step is optional and by default 1




                         For i = 1 To Variable
              Example      Variable2= Variable2+1
                         Next i
                                                                  13
Do While/Until Loop
Full syntax

          Do [{While | Until} condition]
          [statements]




                                                                              ESGF 4IFM Q2 2012
          Loop


The program will repeat instructions while or until a condition is met




                                                                              vinzjeannin@hotmail.com
                         Do {While | Until} Variable<>0
              Example    Variable= Variable-1
                         Loop

Careful to potentially endless loop


What if in the Do While case Variable is negative at the start of the loop?
                                                                              14
If Then Else End If
Full syntax
          If condition Then
             statements




                                                                           ESGF 4IFM Q2 2012
          [Else]
             [statements]
          End If
The program will launch instructions if condition is met




                                                                           vinzjeannin@hotmail.com
Else statements are optional

        The program will lunch instructions if condition is not met if
        Else is specified
        The program wont do anything if condition is not met if Else is
        not specified
                           If Variable > 0 Then
                              Variable2=1
                              Variable3=-1                                 15
              Example
                           Else
                              Variable= Variable+1
                           End If
Repeat                                   Repeat


                                    Generate x and y




                                                                         ESGF 4IFM Q2 2012
   For To Next                 Calculate the hypotenuse
         or
Do While/Until Loop

                       Is the hypotenuse shorter than the radius?




                                                                         vinzjeannin@hotmail.com
                                 If Then Else End If
                           Yes                            No



                         Count
 For i=1 to Simu                      If Hypo<=Radius then
                                        VariableCount= VariableCount+1
 Next i                               End If                             16
   Could have use Do Until Variable=Simu. Loop
   But manual increment needed of Variable
Reminder: basic structure of the function




                                                     ESGF 4IFM Q2 2012
We know we have to use For/Next and If/Then/End If




                                                     vinzjeannin@hotmail.com
What do we miss?

         Random number: Rnd command



We Should have everything


                                                     17
Looping to numbers of simulations

Generate 2 random variables




                                                                  ESGF 4IFM Q2 2012
Calculate the length of the hypotenuse

Is the hypotenuse inside the circle?




                                                                  vinzjeannin@hotmail.com
        Yes: count it

        No: Dont count it

Simulation finished, percentage of points inside the circle

The square area being 1, knowing the radius, you can extract Pi


           3.14159                                              18

        From how many simulations the estimation is correct?
  3.14159




                                                                         ESGF 4IFM Q2 2012
                                                                         vinzjeannin@hotmail.com
Test in Excel =EstmPi (xxx) for a few different numbers of simulations
                                                                         19
Why for a same number of simulations your results are different?
From how many simulations the estimation is correct?
Alternatives to  estimation
   Reminder of our function




                               ESGF 4IFM Q2 2012
                               vinzjeannin@hotmail.com
                               20
Lets use Do While / Loop

Dont forget to fix the initial value of the variable

Dont forget to increment the variable (beware the endless loop)




                                                                   ESGF 4IFM Q2 2012
                                                                   vinzjeannin@hotmail.com
                                                                   21
Lets use Do Until/ Loop

Dont forget to fix the initial value of the variable

Dont forget to increment the variable (beware the endless loop)




                                                                   ESGF 4IFM Q2 2012
                                                                   vinzjeannin@hotmail.com
                                                                   22
What you CAN do but what you MUST NOT do




                                           ESGF 4IFM Q2 2012
                                           vinzjeannin@hotmail.com
                                           23
   Bad algorithmic method
Before going into detail of how to use the
     GoTo statement it is important to be aware
     that the use of the GoTo statement is generally
     considered to be bad programming practice.
     John Walkenbach




                                                                    ESGF 4IFM Q2 2012
The program has been led into a corner and some way of getting to
another section of code is needed




                                                                    vinzjeannin@hotmail.com
          Bad programming indeed

          Most of the time avoidable if program written carefully

          Avoiding GoTo statement make the code easier to debug
          and maintain



                                                                    24
Spaghetti code
vinzjeannin@hotmail.com   ESGF 4IFM Q2 2012
25
Formula using Excel References
    Lets build a formula pricing a Black & Scholes Call option




                                                                  ESGF 4IFM Q2 2012
    5 or 6 arguments

          Time to maturity Or Start Date  End Date




                                                                  vinzjeannin@hotmail.com
          S

          r

          K

          

                                                                  26
ESGF 4IFM Q2 2012
                                                           vinzjeannin@hotmail.com
Easy, no reason to have and loops or conditional tests


Problem Thee Standard Normal Cumulative distribution
is not available in VBA (and its not an analytic linear
formula so cant recreate it)                              27
Basic structure




                                              ESGF 4IFM Q2 2012
Time to maturity, d1 and d2 easy to compute




                                              vinzjeannin@hotmail.com
How to compute N(D1) and N(D2)?

                                              28
In Excel, it would be NORMSDIST function



Excel formula can be used in VBA with the following




                                                                ESGF 4IFM Q2 2012
                                                                vinzjeannin@hotmail.com
Final part of the formula can then be written




                                  Use it in Excel

                                   =CallBS(D4,D8,D9,D5,D6,D7)
                                                                29
Full Formula




     vinzjeannin@hotmail.com   ESGF 4IFM Q2 2012
30
Advanced Formula: CRR
    Lets build a formula pricing a CRR Call option




                                                                  ESGF 4IFM Q2 2012
    Challenges


             Build a tree with a variable number of nodes




                                                                  vinzjeannin@hotmail.com
             Enables American or European type

    7 or 8 arguments

        Time to maturity Or Start Date  End Date           

        S                                                   n
                                                                  31
        r                                                   A/E

        K
Program steps




                                                        ESGF 4IFM Q2 2012
       Build the tree for the price of the underlying




                                                        vinzjeannin@hotmail.com
       Calculate the price of the option at maturity


       Do the backward induction


                Differentiate American & European


                                                        32
ESGF 4IFM Q2 2012
                                                vinzjeannin@hotmail.com
How many nodes do you have at any given step?



                      +1
                                                33

                     Asymmetric matrix
2 dimension variable

      Must be defined and re dimensioned




                                           ESGF 4IFM Q2 2012
                                           vinzjeannin@hotmail.com
Use Dim and ReDim
                                           34
   Why +1?

    Matrix wont be fully filled
Compute T, u, d & p

        
                   1                       
=              = =         
                                     =
                                         ≒ 




                                                   ESGF 4IFM Q2 2012
                                                   vinzjeannin@hotmail.com
  Allocate S to the first node




                                                   35
Our first double loop




                                                               ESGF 4IFM Q2 2012
                                                               vinzjeannin@hotmail.com
                                                     Times
                                                     current
                                                     step+1




                                                               36

                         Times the number of steps
One For/Next inside the other




                                ESGF 4IFM Q2 2012
                                vinzjeannin@hotmail.com
Construct the tree




                                37
Lets check
       Introduction to Subs

       Display results in Excel




                                  ESGF 4IFM Q2 2012
                                  vinzjeannin@hotmail.com
                                  38
Tree seems properly built




                                  ESGF 4IFM Q2 2012
                                  vinzjeannin@hotmail.com
Back to our function


Time for the backward induction
                                  39
Same principle


      Two loops one inside the other




                                                     ESGF 4IFM Q2 2012
                                                     vinzjeannin@hotmail.com
      Negative Step on the columns


      Backward induction


Specific case on the last node

      Specific case ITM or OTM

Specific cases American or European                  40

             A few if structures inside the other?
Structure




Yes Early exercise or not?




                                   vinzjeannin@hotmail.com   ESGF 4IFM Q2 2012
                              41
vinzjeannin@hotmail.com   ESGF 4IFM Q2 2012
42
Final (Initial) Node


Same process




                                               ESGF 4IFM Q2 2012
         Compare intrinsic to binomial value




                                               vinzjeannin@hotmail.com
                                               43
1/3
                                                         Were finished!




           vinzjeannin@hotmail.com   ESGF 4IFM Q2 2012
      44
3/3




           vinzjeannin@hotmail.com   ESGF 4IFM Q2 2012
      45
2/3




           vinzjeannin@hotmail.com   ESGF 4IFM Q2 2012
      46
Use it in Excel




     vinzjeannin@hotmail.com   ESGF 4IFM Q2 2012
47
Conclusion




                           ESGF 4IFM Q2 2012
        Functions & Subs


        If Then Else




                           vinzjeannin@hotmail.com
        For Next


        Do Loop




                           48

More Related Content

VBA for Finance

  • 1. VBA Q2 2012 Vincent JEANNIN ESGF 4IFM vinzjeannin@hotmail.com ESGF 4IFM Q2 2012 1
  • 2. ESGF 4IFM Q2 2012 Summary of the session Introduction: from BASIC to VBA Think Algorithmic First: First VBA Program: a formula vinzjeannin@hotmail.com Alternatives to estimation Formula using Excel References Advanced Formula: CRR 2
  • 3. Introduction: from BASIC to VBA Beginner's All-purpose Symbolic Instruction Code Created in 1964 by students for students ESGF 4IFM Q2 2012 Spread because free Succeed because easy and base to most of languages vinzjeannin@hotmail.com If youre old enough to know what is a 80-386 or to have played with an Apple II you may have heard of: Applesoft BASIC, GW BASIC, QBASIC BASIC extended to event driven programming: Visual BASIC The flow of the program is determined by events: sensor outputs, user actions (mouse clicks, key presses) Visual BASIC integrated in Microsoft Office: VBA Visual BASIC for Applications enables building user defined 3 functions, automating processes,
  • 4. Think Algorithmic First: ESGF 4IFM Q2 2012 Lets approximate pi vinzjeannin@hotmail.com Think first about How to regardless of any programming Draw a chart of the program then the translation is easier 4
  • 5. Lets pick 2 random numbers Using a uniform distribution ESGF 4IFM Q2 2012 vinzjeannin@hotmail.com How do you determine if (x,y) is inside or outside the circle? 5
  • 6. Right Triangle properties ESGF 4IFM Q2 2012 vinzjeannin@hotmail.com 諮$ 2 = 基 2 + $ 2 6
  • 7. Repeat Repeat Generate x and y ESGF 4IFM Q2 2012 Calculate the hypotenuse vinzjeannin@hotmail.com Is the hypotenuse shorter than the radius? Yes No Count 7
  • 8. Surface of the square: 1 Surface of the circle: 4 Surface of the rest: 1 4 ESGF 4IFM Q2 2012 vinzjeannin@hotmail.com Lets make i trials, count the n points inside the circle Randomisation has been done uniformly 8 Proportions will be respected 2
  • 9. First VBA Program: a formula VBA can be sued to create custom Excel Functions ESGF 4IFM Q2 2012 Display the Visual Basic Editor vinzjeannin@hotmail.com Right Click on your file and insert a module 9
  • 10. Lets call our function EstmPi What are the arguments? ESGF 4IFM Q2 2012 Only one argument The number of simulations to make Lets call the variable Simu vinzjeannin@hotmail.com Compulsory to define the type of variable String: Text Integer: Natural Number Double: 64-bits number Boolean: True/False 10 What type is Simu?
  • 11. Basic structure of the function ESGF 4IFM Q2 2012 Used in Excel vinzjeannin@hotmail.com =EstmPi(100) Result will be the value stored in the variable Result Time to be reminded the algorithmic fundamentals of our program and learn the corresponding BASIC functions 11
  • 12. Repeat Repeat Generate x and y ESGF 4IFM Q2 2012 For To Next Calculate the hypotenuse or Do While/Until Loop vinzjeannin@hotmail.com Is the hypotenuse shorter than the radius? If Then Else End If Yes No Count 12
  • 13. For To Next Full syntax For counter = start To end [Step step] [statements] ESGF 4IFM Q2 2012 Next [counter] The program will repeat instructions a specified number of time vinzjeannin@hotmail.com Step is optional and by default 1 For i = 1 To Variable Example Variable2= Variable2+1 Next i 13
  • 14. Do While/Until Loop Full syntax Do [{While | Until} condition] [statements] ESGF 4IFM Q2 2012 Loop The program will repeat instructions while or until a condition is met vinzjeannin@hotmail.com Do {While | Until} Variable<>0 Example Variable= Variable-1 Loop Careful to potentially endless loop What if in the Do While case Variable is negative at the start of the loop? 14
  • 15. If Then Else End If Full syntax If condition Then statements ESGF 4IFM Q2 2012 [Else] [statements] End If The program will launch instructions if condition is met vinzjeannin@hotmail.com Else statements are optional The program will lunch instructions if condition is not met if Else is specified The program wont do anything if condition is not met if Else is not specified If Variable > 0 Then Variable2=1 Variable3=-1 15 Example Else Variable= Variable+1 End If
  • 16. Repeat Repeat Generate x and y ESGF 4IFM Q2 2012 For To Next Calculate the hypotenuse or Do While/Until Loop Is the hypotenuse shorter than the radius? vinzjeannin@hotmail.com If Then Else End If Yes No Count For i=1 to Simu If Hypo<=Radius then VariableCount= VariableCount+1 Next i End If 16 Could have use Do Until Variable=Simu. Loop But manual increment needed of Variable
  • 17. Reminder: basic structure of the function ESGF 4IFM Q2 2012 We know we have to use For/Next and If/Then/End If vinzjeannin@hotmail.com What do we miss? Random number: Rnd command We Should have everything 17
  • 18. Looping to numbers of simulations Generate 2 random variables ESGF 4IFM Q2 2012 Calculate the length of the hypotenuse Is the hypotenuse inside the circle? vinzjeannin@hotmail.com Yes: count it No: Dont count it Simulation finished, percentage of points inside the circle The square area being 1, knowing the radius, you can extract Pi 3.14159 18 From how many simulations the estimation is correct?
  • 19. 3.14159 ESGF 4IFM Q2 2012 vinzjeannin@hotmail.com Test in Excel =EstmPi (xxx) for a few different numbers of simulations 19 Why for a same number of simulations your results are different? From how many simulations the estimation is correct?
  • 20. Alternatives to estimation Reminder of our function ESGF 4IFM Q2 2012 vinzjeannin@hotmail.com 20
  • 21. Lets use Do While / Loop Dont forget to fix the initial value of the variable Dont forget to increment the variable (beware the endless loop) ESGF 4IFM Q2 2012 vinzjeannin@hotmail.com 21
  • 22. Lets use Do Until/ Loop Dont forget to fix the initial value of the variable Dont forget to increment the variable (beware the endless loop) ESGF 4IFM Q2 2012 vinzjeannin@hotmail.com 22
  • 23. What you CAN do but what you MUST NOT do ESGF 4IFM Q2 2012 vinzjeannin@hotmail.com 23 Bad algorithmic method
  • 24. Before going into detail of how to use the GoTo statement it is important to be aware that the use of the GoTo statement is generally considered to be bad programming practice. John Walkenbach ESGF 4IFM Q2 2012 The program has been led into a corner and some way of getting to another section of code is needed vinzjeannin@hotmail.com Bad programming indeed Most of the time avoidable if program written carefully Avoiding GoTo statement make the code easier to debug and maintain 24 Spaghetti code
  • 25. vinzjeannin@hotmail.com ESGF 4IFM Q2 2012 25
  • 26. Formula using Excel References Lets build a formula pricing a Black & Scholes Call option ESGF 4IFM Q2 2012 5 or 6 arguments Time to maturity Or Start Date End Date vinzjeannin@hotmail.com S r K 26
  • 27. ESGF 4IFM Q2 2012 vinzjeannin@hotmail.com Easy, no reason to have and loops or conditional tests Problem Thee Standard Normal Cumulative distribution is not available in VBA (and its not an analytic linear formula so cant recreate it) 27
  • 28. Basic structure ESGF 4IFM Q2 2012 Time to maturity, d1 and d2 easy to compute vinzjeannin@hotmail.com How to compute N(D1) and N(D2)? 28
  • 29. In Excel, it would be NORMSDIST function Excel formula can be used in VBA with the following ESGF 4IFM Q2 2012 vinzjeannin@hotmail.com Final part of the formula can then be written Use it in Excel =CallBS(D4,D8,D9,D5,D6,D7) 29
  • 30. Full Formula vinzjeannin@hotmail.com ESGF 4IFM Q2 2012 30
  • 31. Advanced Formula: CRR Lets build a formula pricing a CRR Call option ESGF 4IFM Q2 2012 Challenges Build a tree with a variable number of nodes vinzjeannin@hotmail.com Enables American or European type 7 or 8 arguments Time to maturity Or Start Date End Date S n 31 r A/E K
  • 32. Program steps ESGF 4IFM Q2 2012 Build the tree for the price of the underlying vinzjeannin@hotmail.com Calculate the price of the option at maturity Do the backward induction Differentiate American & European 32
  • 33. ESGF 4IFM Q2 2012 vinzjeannin@hotmail.com How many nodes do you have at any given step? +1 33 Asymmetric matrix
  • 34. 2 dimension variable Must be defined and re dimensioned ESGF 4IFM Q2 2012 vinzjeannin@hotmail.com Use Dim and ReDim 34 Why +1? Matrix wont be fully filled
  • 35. Compute T, u, d & p 1 = = = = ≒ ESGF 4IFM Q2 2012 vinzjeannin@hotmail.com Allocate S to the first node 35
  • 36. Our first double loop ESGF 4IFM Q2 2012 vinzjeannin@hotmail.com Times current step+1 36 Times the number of steps
  • 37. One For/Next inside the other ESGF 4IFM Q2 2012 vinzjeannin@hotmail.com Construct the tree 37
  • 38. Lets check Introduction to Subs Display results in Excel ESGF 4IFM Q2 2012 vinzjeannin@hotmail.com 38
  • 39. Tree seems properly built ESGF 4IFM Q2 2012 vinzjeannin@hotmail.com Back to our function Time for the backward induction 39
  • 40. Same principle Two loops one inside the other ESGF 4IFM Q2 2012 vinzjeannin@hotmail.com Negative Step on the columns Backward induction Specific case on the last node Specific case ITM or OTM Specific cases American or European 40 A few if structures inside the other?
  • 41. Structure Yes Early exercise or not? vinzjeannin@hotmail.com ESGF 4IFM Q2 2012 41
  • 42. vinzjeannin@hotmail.com ESGF 4IFM Q2 2012 42
  • 43. Final (Initial) Node Same process ESGF 4IFM Q2 2012 Compare intrinsic to binomial value vinzjeannin@hotmail.com 43
  • 44. 1/3 Were finished! vinzjeannin@hotmail.com ESGF 4IFM Q2 2012 44
  • 45. 3/3 vinzjeannin@hotmail.com ESGF 4IFM Q2 2012 45
  • 46. 2/3 vinzjeannin@hotmail.com ESGF 4IFM Q2 2012 46
  • 47. Use it in Excel vinzjeannin@hotmail.com ESGF 4IFM Q2 2012 47
  • 48. Conclusion ESGF 4IFM Q2 2012 Functions & Subs If Then Else vinzjeannin@hotmail.com For Next Do Loop 48