Creating Functions

Writing the Function

In this section we show you how to write and call a function in Matlab. In particular we will write a function that calculates the value of a European put and call option using the Black-Scholes-Merton pricing formula.

  • Open Matlab and click “New” and then “Function” and write a description of what the function should do.

  • Recall the Black-Scholes-Merton pricing formula:
\[\begin{split}c &= S_{0}N(d_{1}) - Ke^{-rT}N(d_{2}) \\ p &= Ke^{-rT}N(-d_{2}) - S_{0}N(-d_{1}) \\ d_{1} &= \frac{ln{S_{0} \over K}+(r-q+\sigma^2/2)T}{\sigma\sqrt{T}} \\ d_{2} &= \frac{ln{S_{0} \over K}+(r-q-\sigma^2/2)T}{\sigma\sqrt{T}} \\ &= d_{1} - \sigma\sqrt{T}\end{split}\]
  • Where:
    • \(c\) = Call Price
    • \(p\) = Put Price
    • \(S_{0}\) = Time Zero Underlying Asset Price
    • \(K\) = Strike Price
    • \(T\) = Time to Maturity
    • \(\sigma\) = Annual Volatility
    • \(r\) = Risk Free Interest Rate
    • \(q\) = Dividend Rate / Foreign Interest Rate
  • After the blue word “function” are the output arguments. Since we want to generate the value of a put and a call, we need two output arguments: [ c, p ]

  • On the right hand side of the equals sign is the function name you will use when calling the function. Let’s call it “BSM” so that it is meaningful and easy to use.

  • Inside the parentheses is where we list the input arguments; these are the arguments that the Black-Scholes-Merton pricing formula needs to calculate the price. We can enter them as BSM( S, K, T, sigma, r, q )

  • Within the body of the function we type the equations needed to find the price of both the call and put options. Enter \(d_{1}, d_{2}\) first, then the equations for the put and call price. Be sure to give the put and call value the same name as the output variables.

  • Finally, save your function with the same name that you gave it on the first line of your code. In our case, this was “BSM”.

  • Your function should look similar to the image below:
_images/BSM.png
  • You might have noticed my use of the backslash “\” which is short hand for inverse in Matlab

Calling the Function

  • Suppose you are interested in the cost of entering into a 6 month at the money straddle position, where the underlying stock price is trading at $50 per share, has a 30% annual volatility and pays no dividend. If the risk free rate is 5%, how much would it cost you to enter this strategy?

  • In this case \(S_{0}=50, K=50, T=0.5, \sigma=0.30, r=0.05, q=0\)

  • To find both the put and call price, type: [ call, put ] = BSM( 50, 50, 0.5, 0.3, 0.05, 0 ) in the command window

  • Notice that you can name the output variables whatever you like: they don’t have to match the output names within the function. However, order matters. If we would have entered [ put, call ] we would have assigned the wrong values to the proper meaning of each word.

  • The cost of the straddle is the sum of the put and call
_images/BSM2.png