Skip to content

Instantly share code, notes, and snippets.

@7sharp9
Created March 11, 2012 16:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 7sharp9/2016927 to your computer and use it in GitHub Desktop.
Save 7sharp9/2016927 to your computer and use it in GitHub Desktop.
F# Black-Scholes
public class Options
{
public enum Style
{
Call,
Put
}
public static double BlackScholes(Style callPut, double s, double x, double t, double r, double v)
{
double d1 = 0.0;
double d2 = 0.0;
double result = 0.0;
d1 = (Math.Log(s/x) + (r + v*v/2.0)*t)/(v*Math.Sqrt(t));
d2 = d1 - v*Math.Sqrt(t);
switch (callPut)
{
case Style.Call:
result = s*Cnd(d1) - x*Math.Exp(-r*t)*Cnd(d2);
break;
case Style.Put:
result = x*Math.Exp(-r*t)*Cnd(-d2) - s*Cnd(-d1);
break;
}
return result;
}
private static double Cnd(double x)
{
double l = 0.0;
double k = 0.0;
double w = 0.0;
const double a1 = 0.31938153;
const double a2 = -0.356563782;
const double a3 = 1.781477937;
const double a4 = -1.821255978;
const double a5 = 1.330274429;
l = Math.Abs(x);
k = 1.0/(1.0 + 0.2316419*l);
w = 1.0 - 1.0/Math.Sqrt(2*Math.PI)*
Math.Exp(-l*l/2.0)* (a1*k + a2*k*k + a3*
Math.Pow(k, 3.0) + a4*Math.Pow(k, 4.0) + a5*Math.Pow(k, 5.0));
if (x < 0)
{
return 1.0 - w;
}
return w;
}
}
module options
open System
type Style = Call | Put
let cnd x =
let a1 = 0.31938153
let a2 = -0.356563782
let a3 = 1.781477937
let a4 = -1.821255978
let a5 = 1.330274429
let l = abs x
let k = 1.0 / (1.0 + 0.2316419 * l)
let w = (1.0-1.0 / sqrt(2.0 * Math.PI) *
exp(-l * l / 2.0) * (a1 * k+a2 * k * k+a3 *
(pown k 3)+a4 * (pown k 4)+a5 * (pown k 5)))
if x < 0.0 then 1.0 - w
else w
let blackscholes 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment