2 people like it.

Black Scholes Option Pricing

The code shows simple implementation of blackscholes algorithm.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
24: 
25: 
26: 
27: 
28: 
29: 
30: 
31: 
32: 
type Style = Call | Put
  
let cnd x =
   let pow x n = exp (n * log(x) ) 
   let a1 =  0.31938153
   let a2 = -0.356563782
   let a3 =  1.781477937
   let a4 = -1.821255978
   let a5 =  1.330274429
   let pi = 4.0 * atan 1.0
   let l  = abs(x)
   let k  = 1.0 / (1.0 + 0.2316419 * l)
   let w  = ref (1.0-1.0/sqrt(2.0*pi)*exp(-l*l/2.0)*(a1*k+a2*k*k+a3*(pow k 3.0)+a4*(pow k 4.0)+a5*(pow k 5.0)))
   if (x < 0.0) then  w := 1.0 - !w
   !w
 
// call_put_flag: 'c' if call option; otherwise put option
// s: stock price
// x: strike price of option
// t: time to expiration in years
// r: risk free interest rate
// v: volatility
let black_scholes style s x t r v =
        let d1=(log(s / x) + (r+v*v/2.0)*t)/(v*sqrt(t))
        let d2=d1-v*sqrt(t)
        match style with
         | Call -> s*cnd(d1)-x*exp(-r*t)*cnd(d2)
         | Put -> x*exp(-r*t)*cnd(-d2)-s*cnd(-d1)
 
 
// Example usage::
// black_scholes Call 60.0 65.0 0.25 0.08 0.3;;
union case Style.Call: Style
union case Style.Put: Style
val cnd : x:float -> float

Full name: Script.cnd
val x : float
val pow : (float -> float -> float)
val n : float
val exp : value:'T -> 'T (requires member Exp)

Full name: Microsoft.FSharp.Core.Operators.exp
val log : value:'T -> 'T (requires member Log)

Full name: Microsoft.FSharp.Core.Operators.log
val a1 : float
val a2 : float
val a3 : float
val a4 : float
val a5 : float
val pi : float
val atan : value:'T -> 'T (requires member Atan)

Full name: Microsoft.FSharp.Core.Operators.atan
val l : float
val abs : value:'T -> 'T (requires member Abs)

Full name: Microsoft.FSharp.Core.Operators.abs
val k : float
val w : float ref
Multiple items
val ref : value:'T -> 'T ref

Full name: Microsoft.FSharp.Core.Operators.ref

--------------------
type 'T ref = Ref<'T>

Full name: Microsoft.FSharp.Core.ref<_>
val sqrt : value:'T -> 'U (requires member Sqrt)

Full name: Microsoft.FSharp.Core.Operators.sqrt
val black_scholes : style:Style -> s:float -> x:float -> t:float -> r:float -> v:float -> float

Full name: Script.black_scholes
val style : Style
val s : float
val t : float
val r : float
val v : float
val d1 : float
val d2 : float

More information

Link:http://fssnip.net/3I
Posted:5 years ago
Author:Kishor Aher
Tags: finance