Black-Scholes in Multiple Languages

You naturally know the Black-Scholes-Merton Nobel Prize formula, but in how many languages? Just like me I guess you speak Norwegian, French, Russian, English, Swedish and Danish, but what about really interesting languages like (now in more than 29 languages):

Prolog, PL/SQL, LyME, ColdFusion, K, C#, HP48,
Transact SQL, O'Caml, Rebol, Real Basic, Icon, Squeak,
Haskell, JAVA , JavaScript, VBA, C++, Perl,
Maple, Mathematica, Matlab, S-Plus, 
IDL, Pascal, Python, Fortran, Scheme, PHP

If you have implemented Black-Scholes in another language I would be happy to get a copy of your source code to put it on this page!

(in that case try to use the same symbols and the setup as below)


 


In the different implementations below we will use the symbols:

S= Stock price

X=Strike price

T=Years to maturity

r= Risk-free rate

v=Volatility


Black-Scholes Directly in a Excel Sheet ("keep it simple stupid")

If you are afraid of programing languages you can start with doing Black-Scholes directly in an Excel sheet, just type in what you see below. If you are using the Norwegian or French version of Excel you have to do some translation yourself:

Are you to lazy to type in what you see above, okay download me here


Black-Scholes in Visual Basic

By Espen Gaarder Haug

Visual Basic: easy to program but quite slow!

'// The Black and Scholes (1973) Stock option formula
Public Function BlackScholes(CallPutFlag As String, S As Double, X _
As Double, T As Double, r As Double, v As Double) As Double

Dim
d1 As Double, d2 As Double

d1 = (Log(S / X) + (r + v ^ 2 / 2) * T) / (v * Sqr(T))
d2 = d1 - v * Sqr(T)
If CallPutFlag = "c" Then
BlackScholes = S * CND(d1) - X * Exp(-r * T) * CND(d2)
ElseIf CallPutFlag = "p" Then
BlackScholes = X * Exp(-r * T) * CND(-d2) - S * CND(-d1)
End If
End Function

'// The cumulative normal distribution function
Public Function CND(X As Double) As Double

Dim
L As Double, K As Double
Const
a1 = 0.31938153: Const a2 = -0.356563782: Const a3 = 1.781477937:
Const a4 = -1.821255978: Const a5 = 1.330274429

L = Abs(X)
K = 1 / (1 + 0.2316419 * L)
CND = 1 - 1 / Sqr(2 * Application.Pi()) * Exp(-L ^ 2 / 2) * (a1 * K + a2 * K ^ 2 + a3 * K ^ 3 + a4 * K ^ 4 + a5 * K ^ 5)

If X < 0 Then
CND = 1 - CND
End If
End Function


Black-Scholes in

By Espen Gaarder Haug

C++: a bit harder than most other languages but very fast and powerful. After my opinion the Rolls Royce computer language for mathematical models where you need speed (for closed form solutions like Blacks-Scholes you are naturally doing fine in almost any language, but when it comes to large scale Monte Carlo C++ is really a plus).

#ifndef Pi
#define Pi 3.141592653589793238462643
#endif

// The Black and Scholes (1973) Stock option formula
double BlackScholes(char CallPutFlag, double S, double X, double T, double r, double v)
{
double d1, d2;


d1=(log(S/X)+(r+v*v/2)*T)/(v*sqrt(T));
d2=d1-v*sqrt(T);

if(CallPutFlag == 'c')
return S *CND(d1)-X * exp(-r*T)*CND(d2);
else if(CallPutFlag == 'p')
return X * exp(-r * T) * CND(-d2) - S * CND(-d1);
}

// The cumulative normal distribution function
double CND( double X )
{

double L, K, w ;

double const a1 = 0.31938153, a2 = -0.356563782, a3 = 1.781477937;
double const a4 = -1.821255978, a5 = 1.330274429;

L = fabs(X);
K = 1.0 / (1.0 + 0.2316419 * L);
w = 1.0 - 1.0 / sqrt(2 * Pi) * exp(-L *L / 2) * (a1 * K + a2 * K *K + a3 * pow(K,3) + a4 * pow(K,4) + a5 * pow(K,5));

if (X < 0 ){
w= 1.0 - w;
}
return w;
}


Black-Scholes in JAVA

By Espen Gaarder Haug

Easy to program, can be used to build JAVA applets or large standalone systems.

Much faster than Java Script and VBA but still slower than C/C++

 

// The Black and Scholes (1973) Stock option formula

public double BlackScholes(char CallPutFlag, double S, double X, double T, double r, double v)
{
double d1, d2;

d1=(Math.log(S/X)+(r+v*v/2)*T)/(v*Math.sqrt(T));
d2=d1-v*Math.sqrt(T);

if (CallPutFlag=='c')
{
return S*CND(d1)-X*Math.exp(-r*T)*CND(d2);
}
else
{
return X*Math.exp(-r*T)*CND(-d2)-S*CND(-d1);
}
}

// The cumulative normal distribution function
public double CND(double X)
{
double L, K, w ;
double a1 = 0.31938153, a2 = -0.356563782, a3 = 1.781477937, a4 = -1.821255978, a5 = 1.330274429;

L = Math.abs(X);
K = 1.0 / (1.0 + 0.2316419 * L);
w = 1.0 - 1.0 / Math.sqrt(2.0 * Math.PI) * Math.exp(-L *L / 2) * (a1 * K + a2 * K *K + a3
* Math.pow(K,3) + a4 * Math.pow(K,4) + a5 * Math.pow(K,5));

if (X < 0.0)
{
w= 1.0 - w;
}
return w;
}

Black-Scholes JAVA Applet


Black-Scholes in Java Script

By Espen Gaarder Haug  (thanks to Kurt Hess at University of Waikato for finding a bug in my code)

Easy to program, can be used directly on the web, but quite slow!

/* The Black and Scholes (1973) Stock option formula */

function BlackScholes(PutCallFlag, S, X, T, r, v) {

var d1, d2;
d1 = (Math.log(S / X) + (r + v * v / 2.0) * T) / (v * Math.sqrt(T));
d2 = d1 - v * Math.sqrt(T);


if (PutCallFlag== "c")
return S * CND(d1)-X * Math.exp(-r * T) * CND(d2);
else
return X * Math.exp(-r * T) * CND(-d2) - S * CND(-d1);

}

/* The cummulative Normal distribution function: */

function CND(x){

var a1, a2, a3, a4 ,a5, k ;

a1 = 0.31938153, a2 =-0.356563782, a3 = 1.781477937, a4= -1.821255978 , a5= 1.330274429;

if(x<0.0)
return 1-CND(-x);
else
k = 1.0 / (1.0 + 0.2316419 * x);
return 1.0 - Math.exp(-x * x / 2.0)/ Math.sqrt(2*Math.PI) * k
* (a1 + k * (-0.356563782 + k * (1.781477937 + k * (-1.821255978 + k * 1.330274429)))) ;

}




Black-Scholes in Perl 

By Jerome V. Braun

Perl is the "Swiss Army chainsaw" of languages that naturally also can be used for Black-Scholes:

=head2 BlackScholes

Routine to implement the Black and Scholes (1973) option pricing formula.

# usage
$price = GBlackScholes($call_put_flag, $S, $X, $T, $r, $b, $v);

Here C<$call_put_flag> is either 'c' or 'p' for a call or put respectively,

=cut

sub BlackScholes {
my ($call_put_flag, $S, $X, $T, $r, $v) = @_;

# calculate some auxiliary values
my $d1 = ( log($S/$X) + ($r+$v**2/2)*$T ) / ( $v * $T**0.5 );
my $d2 = $d1 - $v * $T**0.5;

if ($call_put_flag eq 'c') {
return $S * &CND($d1) - $X * exp( -$r * $T ) * &CND($d2);
}
else { # ($call_put_flag eq 'p')
return $X * exp( -$r * $T ) * &CND(-$d2) - $S * &CND(-$d1);
}

}

=head2 CND

Approximate the cumulative normal distribution. That is, the value
of the integral of the standard normal density from minus infinity
to C<$x>.

# usage
$p = &CND($x);

=cut

sub CND {
my $x = shift;

# the percentile under consideration

my $Pi = 3.141592653589793238;

# Taylor series coefficients
my ($a1, $a2, $a3, $a4, $a5) = (0.319381530, -0.356563782, 1.781477937, -1.821255978, 1.330274429);

# use symmetry to perform the calculation to the right of 0
my $L = abs($x);

my $k = 1/( 1 + 0.2316419*$L);

my $CND = 1 - 1/(2*$Pi)**0.5 * exp(-$L**2/2)
* ($a1*$k + $a2*$k**2 + $a3*$k**3 + $a4*$k**4 + $a5*$k**5);

# then return the appropriate value
return ($x >= 0) ? $CND : 1-$CND;

}

 


Black-Scholes in Maple

By Espen Gaarder Haug

Easy to program, nice for testing and understanding option models, but quite slow.

>with(stats);
[anova, describe, fit, importdata, random, statevalf, statplots, transform]

The cummulative Normal distribution function:
> CND := proc(d)
> statevalf[cdf,normald](d);
> end:

The Balck-Scholes (1973) stock call option formula.
> BlackScholesCall:=proc(S,X,T,r,v)
> local d1,d2;
> d1:=(ln(S/X)+(r+v^2/2)*T)/(v*sqrt(T));
> d2:=d1-v*sqrt(T);
> S*CND(d1)-X*exp(-r*T)*CND(d2);
> end:

The Balck-Scholes (1973) stock put option formula.
> BlackScholesPut:=proc(S,X,T,r,v)
> local d1,d2;
> d1:=(ln(S/X)+(r+v^2/2)*T)/(v*sqrt(T));
> d2:=d1-v*sqrt(T);
> X*exp(-r*T)*CND(-d2)-S*CND(-d1);
> end:


Black-Scholes in Mathematica

By Espen Gaarder Haug

Easy to program, nice for testing and understanding option models. Mathematica 3.0 was quite slow, but Mathematica 4.0 is pretty fast (Mathematica 4.0 on a 266MHz Power Mac G3 beat MATLAB 5.2 on a 300MHz Pentium II system by an average factor of 4.3. MacWorld 10-99). What will then happen if you put Mathematica 4.0 on a Mac G4, oh my God. (thanks to Wolfram and Steve Jobs life is worth living).

The cummulative Normal distribution function:

cnd[z_] := (1 + Erf[z/Sqrt[2]])/2;

The Balck-Scholes (1973) stock option formula:

d1[S_,X_,T_,r_,v_]=(Log[S/X]+(r+v*v/2)*T)/(v*Sqrt[T]);

d2[S_,X_,T_,r_,v_]= (Log[S/X]+(r-v*v/2)*T)/(v*Sqrt[T]);

BlackScholesCall[S_,X_,T_,r_,v_]=
S*cnd[d1[S,X,T,r,v]]-X*Exp[-r*T]*cnd[d2[S,X,T,r,v]];

BlackScholesPut[S_,X_,T_,r_,v_]=
X*Exp[-r*T]*cnd[-d2[S,X,T,r,v]]-S*cnd[-d1[S,X,T,r,v]];



Black-Scholes in Matlab

By Espen Gaarder Haug

If you have a background from Engineering you probably know Matlab. Easy to program, nice for proto modelling, quite fast but still slow compared with JAVA and C/C++. (The code below should be saved as a Matlab M file):

%Black and Scholes in Matlab

function BlackScholes(CP,S,X,T,r,v)

d1=(log(S/X)+(r+v^2/2)*T)/(v*sqrt(T));
d2=d1-v*sqrt(T);
if CP=='c'
S*normcdf(d1)-X*exp(-r*T)*normcdf(d2)
else
X*exp(-r*T)*normcdf(-d2)-S*normcdf(-d1)
end


Black-Scholes in S-PLUS

By Trygve Nilsen, University of Bergen Norway and Gene D. Felber, Talus Solutions Inc

S-Plus is the favorite tool for many people working with mathematical statistics. S-Plus is also a great tool for modeling financial derivatives . The code below will also run under the free software R

call.value <- function(S,X,t,r,v)
{
d1 <- (log(S/X)+(r+0.5*v^2)*t)/(v*sqrt(t))
d2 <- d1-v*sqrt(t)
S*pnorm(d1)-X*exp(-r*t)*pnorm(d2)
}

put.value  <- function(S,X,t,r,v)
{
d1 <- (log(S/X)+(r+0.5*v^2)*t)/(v*sqrt(t))
d2 <- d1-v*sqrt(t)
X*exp(-r*t)*pnorm(-d2)-S*pnorm(-d1)
}

Important: S-PLUS  has a built-in internal functions for "T" and "call". Assigning a value to these in a function creates a conflict and the formula will return an incorrect value.


Black-Scholes in IDL

By Goran Gasparovic, The Johns Hopkins University, Baltimore, Maryland (U.S.A.)

IDL; the Interactive Data Language (available from www.rsinc.com, very expensive but useful software).

The basic routines are bs2 and cnd2. However, most IDL routines are made

so they can handle whole arrays of data at once, so routines bs and cnd

are extensions to include that features. They first check whether input

variable is a number or array (either strike price, or time) and then

react correspondingly, using basic routines to preform calculation.
pro bs,c,p,s,x,r,t,v

;	c=call price

;	p=put price

;	s=strike price

;	r=interest rate

;	t=time in years

;	v=volatility
	x1=double(x)

	t1=double(t)

	ss=0

	if ((size(x))(0) eq 1) then begin

		ss=(size(x))(1)

		t1=dblarr(ss)+t

	end

	if ((size(t))(0) eq 1) then begin

		ss=(size(t))(1)

		x1=dblarr(ss)+x

	end
	if ss eq 0 then begin

		bs2,c,p,s,x1,r,t1,v

	endif else begin

		c=dblarr(ss)

		p=dblarr(ss)

		for i=0,ss-1 do begin

			bs2,c1,p1,s,x1(i),r,t1(i),v

			c(i)=c1

			p(i)=p1

		end

	endelse
end
pro bs2,c,p,s,x,r,t,v

	d1 = (alog(s/x) + (r+v^2/2.d0)*t) / (v*sqrt(t))

	d2 = d1-v*sqrt(t)
	c = s*cnd(d1) - x*exp(-r*t)*cnd(d2)

	p = x*exp(-r*t)*cnd(-d2) - s*cnd(-d1)

end

	

function cnd2,x
	a1 = double(0.31938153)

	a2 = double(-0.356563782)

	a3 = double(1.781477937)

	a4 = double(-1.821255978)

	a5 = double(1.330274429)
	l=abs(double(x))

	k=1.0 / (1.0 + 0.2316419 * L)

	w = 1.0 - 1.0 / sqrt(2 * !dPi) * exp(-L *L / 2) * $

		(a1*K + a2*K^2 + a3*K^3 + $

		a4*K^4 + a5*K^5)

	if (x lt 0) then w = 1.d0 - w
	return,w
end
function cnd,x
	if ((size(x))(0) eq 0) then begin 

		return,cnd2(x) 

	endif $

	else begin

		s=(size(x))(1)

		r=dblarr(s)

		for i=0,s-1 do r(i)=cnd2(x(i))

		return,r

	endelse
end

Black-Scholes in Delphi/Pascal

By Desmond Nolan, Advanced Business Continuity Systems, Inc.
Pascal provides speed and power approaching C/C++. While not as popular,

it is often considered an easier and safer programming language to use,

especially by new developers. Delphi is Inprises (a.k.a. Borland) Pascal

based development environment for Microsoft Windows applications.
{Black and Scholes (1973) Stock options}

function BlackScholes(CallPutFlag : string; S, X, T, r, v : Double) :

Double;

var

  d1, d2 : Double;

begin

  Result := 0;

  d1 := (LN(S / X) + (r + Power(v, 2) / 2) * T) / (v * SqRt(T));

  d2 := d1 - v * SqRt(T);

  if CallPutFlag = 'c' then

    Result := S * CND(d1) - X * Exp(-r * T) * CND(d2)

  else

    if CallPutFlag = 'p' then

      Result := X * Exp(-r * T) * CND(-d2) - S * CND(-d1);

end;
{The cumulative normal distribution function}

function CND(X : Double) : Double;

var

  L, K : Double;

const

  a1 = 0.31938153;   a2 = -0.356563782;  a3 = 1.781477937;

  a4 = -1.821255978; a5 = 1.330274429;

begin

  L := Abs(X);

  K := 1 / (1 + 0.2316419 * L);

  Result := 1 - 1 / SqRt(2 * Pi) * Exp(-Power(L, 2) / 2)

            * (a1 * K + a2 * Power(K, 2) + a3 * Power(K, 3)

            + a4 * Power(K, 4) + a5 * Power(K, 5));

  if X < 0 then

    Result := (1 - Result)

end;

Black-Scholes in ython
Andy Smith gives you the million dollar formula in Python


Python is an interpreted, interactive, object-oriented programming

language. It incorporates modules, exceptions, dynamic typing, very high

level dynamic data types, and classes. It has interfaces to many system calls

and libraries, as well as to various window systems, and is extensible in C or C++.

It is also usable as an extension language for applications that need a programmable

interface. Finally, Python is portable: it runs on many brands of UNIX, on

the Mac, and on PCs under MS-DOS, Windows, Windows NT, and OS/2.
from math import *
# Cumulative normal distribution

def CND(X):

    (a1,a2,a3,a4,a5) = (0.31938153, -0.356563782, 1.781477937, 

     -1.821255978, 1.330274429)
    L = abs(X)

    K = 1.0 / (1.0 + 0.2316419 * L)

    w = 1.0 - 1.0 / sqrt(2*pi)*exp(-L*L/2.) * (a1*K + a2*K*K + a3*pow(K,3) +

    a4*pow(K,4) + a5*pow(K,5))
    if X<0:

        w = 1.0-w

    return w
# Black Sholes Function

def BlackSholes(CallPutFlag,S,X,T,r,v):

    d1 = (log(S/X)+(r+v*v/2.)*T)/(v*sqrt(T))

    d2 = d1-v*sqrt(T)
    if CallPutFlag=='c':

        return S*CND(d1)-X*exp(-r*T)*CND(d2)

    else:

        return X*exp(-r*T)*CND(-d2)-S*CND(-d1)

Black-Scholes in Fortran

Almost simultaneously Lance McKinzie and John Matovu sent me the Black-Scholes formula in Fortran:
! The Black and Scholes (1973) Stock option formula

	Real*8 Function BlackScholes(CallPutFlag, S, X, T, r, v)

      character*1 CallPutFlag

      real*8 S,X,T,r,v

	real*8 d1, d2

	d1 = (Log(S / X) + (r + v**2. / 2.) * T) / (v * Sqrt(T))

	d2 = d1 - v * Sqrt(T)

	If (CallPutFlag.eq.'c') Then

		BlackScholes = S * CND(d1) - X * Exp(-r * T) * CND(d2)

	ElseIf( CallPutFlag.eq.'p') Then

		BlackScholes = X * Exp(-r * T) * CND(-d2) - S * CND(-d1)

	End If

	Return

End
! The cumulative normal distribution function

	Real*8 Function CND(X)

	PARAMETER (DPI=3.141592653589793238D0)

	real*8 X

	real*8 L, K

	real*8 a1,a2,a3,a4,a5

	a1 = 0.31938153

	a2 = -0.356563782

	a3 = 1.781477937

	a4 = -1.821255978

	a5 = 1.330274429

	L = Abs(X)

	K = 1. / (1. + 0.2316419 * L)

	CND = 1. -1./Sqrt(2. * DPI) * Exp(-L**2. / 2.) * 

	1	(a1 * K + a2 * K**2. + a3 * K**3. + a4 * K**4. + a5 * K**5.)

	If (X.lt.0.) Then

		CND = 1. - CND

	End If

	Return

End

Black-Scholes in Scheme

By Howard Ding

"Scheme is a statically scoped and properly tail-recursive dialect of

the Lisp programming language invented by Guy Lewis Steele Jr. and

Gerald Jay Sussman. It was designed to have an exceptionally clear and

simple semantics and few different ways to form expressions. A wide

variety of programming paradigms, including imperative, functional, and

message passing styles, find convenient expression in Scheme."

(From the Revised(5) Report on the Algorithmic Language Scheme)


;Black-Scholes model

;Usage (black-scholes-price type s x t r v)

;type = 'call or 'put

;s=stock price, x=strike price, t=time to expiration(years)

;r=interest rate (decimal), v=volatility(decimal)
(define pi (* 4 (atan 1)))
(define (horner x coeffs)

  (if (null? coeffs)

      0

      (+ (car coeffs)

         (* x

            (horner x (cdr coeffs))))))
(define (square x) (* x x))
(define cnd-coeffs '(0

                     0.319381530

                     -0.356563782

                     1.781477937

                     -1.821255978

                     1.330274429))
(define (cumulative-normal-dist x)

  (if (< x 0)

      (- 1 (cumulative-normal-dist (- x)))

      (let ((k (/ 1

                  (+ 1 (* x

                          0.2316419))))) 

        (- 1 

           (* (/ 1 (sqrt (* 2 pi)))

              (exp (- (/ (square x) 2)))

              (horner k cnd-coeffs))))))

(define (black-scholes-price type s x t r v)

  (let* ((d1 (/ (+ (log (/ s x))

                   (* t

                      (+ r

                         (/ (square v) 2))))

                (* v (sqrt t))))

         (d2 (- d1 (* v (sqrt t)))))

    (cond ((eq? type 'call)

           (- (* s (cumulative-normal-dist d1))

              (* x

                 (exp (- (* r t)))

                 (cumulative-normal-dist d2))))

          ((eq? type 'put)

           (- (* x

                 (exp (- (* r t)))

                 (cumulative-normal-dist (- d2)))

              (* s

                 (cumulative-normal-dist (- d1)))))

          (else (error "Must be called with type 'call or 'put")))))

Black-Scholes in php

By Franiatte Xavier
 is a server-side, cross-platform, HTML embedded scripting language. It is also very

useful for making option models available on the web.
function CND ($x) {

$Pi = 3.141592653589793238;

$a1 = 0.319381530;

$a2 = -0.356563782;

$a3 = 1.781477937;

$a4 = -1.821255978;

$a5 = 1.330274429;

$L = abs($x);

$k = 1 / ( 1 + 0.2316419 * $L);

$p = 1 - 1 /  pow(2 * $Pi, 0.5) * exp( -pow($L, 2) / 2 ) * ($a1 * $k + $a2 * pow($k, 2)

     + $a3 * pow($k, 3) + $a4 * pow($k, 4) + $a5 * pow($k, 5) );

if ($x >= 0) { 

return $p;

} else {

return 1-$p;

}

}
function BlackScholes ($call_put_flag, $S, $X, $T, $r, $v) 

 {

$d1 = ( log($S / $X) + ($r + pow($v, 2) / 2) * $T ) / ( $v * pow($T, 0.5) );

$d2 = $d1 - $v * pow($T, 0.5);

if ($call_put_flag == 'c') {

return $S * CND($d1) - $X * exp( -$r * $T ) * CND($d2);

} else { 

return $X * exp( -$r * $T ) * CND(-$d2) - $S * CND(-$d1);

}

To test out how this code works go to Xavier's php option calculator.



Black-Scholes in Haskell

By Karl M. Syring from Germany


{-
The Black and Scholes (1973) Stock option formula in Haskell.
Haskell a polymorphically typed, lazy, purely functional programming language.
http://www.haskell.org/aboutHaskell.html
-}
blackscholesCall = blackscholes True
blackscholesPut = blackscholes False
blackscholes :: Bool -> Double -> Double -> Double -> Double -> Double -> Double
blackscholes  iscall s x t r v  
	| iscall == True = call
	| otherwise = put
		where
			call = s * normcdf d1 - x*exp (-r*t) * normcdf d2
			put  = x * exp (-r*t) * normcdf (-d2) - s * normcdf (-d1)
			d1 = ( log(s/x) + (r+v*v/2)*t )/(v*sqrt t)
			d2 = d1 - v*sqrt t
normcdf x  
	| x < 0 = 1 - w
	| otherwise = w
		where
			w = 1.0 - 1.0 / sqrt (2.0 * pi) * exp(-l*l / 2.0) * poly k
			k = 1.0 / (1.0 + 0.2316419 * l)
			l = abs x
			poly = horner coeff 
			coeff = [0.0,0.31938153,-0.356563782,1.781477937,-1.821255978,1.330274429] 
			
horner coeff base  = foldr1 multAdd  coeff
	where
		multAdd x y = y*base + x

Black-Scholes in Icon

By Bill Trost
     
Icon developed by the University of Arizona

procedure BlackSholes(CallPutFlag, S, X, T, r, v)
	d1 := (log(S/X) + (r + v * v / 2.) * T) / (v * sqrt(T))
	d2 := d1 - v * sqrt(T)
	if CallPutFlag == "c" then
		return S * CND(d1) - X * exp(-r * T) * CND(d2)
	return X * exp(-r * T) * CND(-d2) - S * CND(-d1)
end

procedure CND(X)
	a := [0.31938153, -0.356563782, 1.781477937, -1.821255978, 1.330274429]
	L := abs(X)
	K := 1 / (1 + 0.2316419 * L)
	w := 1.0 - 1.0 / sqrt(2.*&pi) * exp(-L * L / 2.) * (a[1] * K + a[2] * K * K + a[3] * K ^ 3 +
		a[4] * K ^ 4 + a[5] * K ^ 5)
	return if X < 0 then 1 - w else w
end



Black-Scholes in Squeak Smalltalk By Bill Trost

'From Squeak2.8 of 13 June 2000 [latest update: #2359] on 10 June 2001 at 7:40:05 pm'!

Object subclass: #BlackScholes
    instanceVariableNames: ''
    classVariableNames: ''
    poolDictionaries: ''
    category: 'Unclassified'!

"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!

BlackScholes class
    instanceVariableNames: ''!

!BlackScholes class methodsFor: 'computing' stamp: 'WRT 6/10/2001 19:39'!

isCall: isCall S: s X: x T: t r: r v: v
    "example usage:
        BlackScholes isCall: true S: 27.9 X: 30 T: 6.0 / 365 r: 1.05333 v: 0.75
    "
    |d1 d2|
    d1 := v * v / 2.0 + r * t + (s / x) ln / (v * t sqrt).
    d2 := d1 - (v * t sqrt).
    ^isCall
        ifTrue: [s * (self CND: d1) - (x * (r negated * t) exp * (self CND: d2))]
        ifFalse: [x * (r negated * t) * (self CND: d2 negated) - (s * (self CND: d1 negated))]! !

 

!BlackScholes class methodsFor: 'private' stamp: 'WRT 6/10/2001 16:53'!

CND: x
    | l k a w |
    a := #(0.31938153 -0.356563782 1.781477937 -1.821255978 1.330274429).
    l := x abs.
    k := 1.0 / (0.2316419 * l + 1).
    w := 1.0 - (1.0 / (2 * Float pi) sqrt * (l negated * l / 2) exp *
        ((1 to: 5)
            inject: 0
            into: [:sum :each |
                (a at: each) * (k raisedToInteger: each) + sum])).
    ^x negative
        ifTrue: [1 - w]
        ifFalse: [w]! !


Black-Scholes in REALbasic

By Espen Gaarder Haug

Very easy to program, with the push of a button the code can be compiled to Pc or Mac. Everything naturally looks ugly on a PC (even the machine), the result on a Mac Carbon X is just amazing! fast and fancy! Even better you can easily port your VBA code into a blistering fast and fancy application.

Simple Example: Black-Scholes in Carbon (For Mac X freeks only) Download here

First define a constant PI (under Constants)
  
Pi=3.14159265358979
  
Function GBlackScholes(CallPutFlag as string, S as double, X as double, T as double, r as double, v as doube)  As Double
  
Dim d1 As Double, d2 As Double
  d1 = (Log(S / X) + (r+ v * v  / 2.0) * T) / (v * Sqrt(T))
  d2 = d1 - v * Sqrt(T)
    
  If CallPutFlag = "c" Then
    return S * CND(d1) - X * Exp(-r * T) * CND(d2)
  Else
    return  X*Exp(-r * T) * CND(-d2) - S * CND(-d1)
  End If
End Function
  
Function CND(x as double) As Double 
  Dim L As Double, K As Double, w As double
    
  Const a1 = 0.31938153
  Const a2 = -0.356563782
  Const a3 = 1.781477937
  Const a4 = -1.821255978 
  Const a5 = 1.330274429 
    
  L = Abs(x)
  K = 1.0 / (1.0 + 0.2316419 * L)
  w= 1.0 - 1.0 / Sqrt(2.0 * Pi) * Exp(-L * L / 2.0) * (a1 * K + a2 * K*K + a3 * Pow(K, 3) + a4 * Pow(K , 4) + a5 * Pow(K, 5))
    
  If x < 0.0 Then
    w= 1.0  - w
  end if
  return w
  
End Function


Black-Scholes in By Matt Licholai

According to George F. Colony,

Another software technology will come along and kill off the Web, just as Web killed News, Gopher, et al. And that judgment day will arrive very soon -- in the next two to three years, not 25 years from now.

What will replace it? X Internet!

Don't worry we will give you some Black-Scholes REBOL code so you can survive judgment day.

REBOL is an interesting and expressive programming language well suited for internet and cross-platform use. REBOL Home Distributed Network Applications for the X Internet.

There is much more information about the language at their web site ( http://www.rebol.com/. The entire REBOL run-time (including the graphics package) fits on one floppy disk (get it from http://www.rebol.com/download.html )

Purpose: {Provide a Rebol function for computing the Black-Scholes (1973) formula for determining an European style Option Price.}

cum-normal-dist: func [
{Calculate the cumulative normal distribution using a fifth order polynomial approximation.}
x [number!]
/local
K L a a1 a2 a3 a4 a5 w1 w
][
L: abs x

set [a a1 a2 a3 a4 a5] [0.2316419 0.31938153 (- 0.356563782) 1.781477937 (- 1.821255978) 1.330274429]

K: 1 / (1 + (a * L))

w1: (K * a1) + (a2 * (K ** 2)) + (a3 * (K ** 3)) + (a4 * (K ** 4)) + (a5 * (K ** 5))
w: 1 - ((w1 / square-root (2 * pi)) * exp (- (L * L) / 2))

if negative? x [return 1 - w]
return w
]

 

black-scholes: func [
{Calculate the Black Scholes (1973) stock option pricing formula}
s [money!] "actual stock price"
x [money!] "strike price"
t [number!] "years to maturity"
r [number!] "risk free interest rate"
v [number!] "volatility"
/call "call option (default)"
/put "put option"
/local
d1 d2
][
d1: (log-e (s / x) + ((r + ((v ** 2) / 2)) * T)) / ( v * square-root t)
d2: d1 - ( v * square-root t)

either (not put) [
(s * cum-normal-dist d1) - ((x * exp (- r * t)) * cum-normal-dist d2)
][
((x * exp (- r * t)) * cum-normal-dist negate d2) - (s * cum-normal-dist - d1)
]
]


Black-Scholes in O'Caml


By Andrey A. Kolessa, OILspace inc. Moscow Office

Here is the implementation of Black-Scholes in O'Caml language. This is a very powerful and extremely fast language.

It's a programmers dream language!

(* 
   Objective Caml is a fast modern type-inferring functional programming language 
   descended from the ML (Meta Language) family.
   O'Caml is as fast as C/C++ 
   http://www.ocaml.org/
*)


let pow x n = exp ((float_of_int n) *. log(x) ) ;;
(* The cumulative normal distribution function *)
let cnd x =
   let a1 = 0.31938153 and a2= -0.356563782 and a3=1.781477937 and a4= -1.821255978 and a5=1.330274429 in
   let pi = 4.0 *. atan 1.0 in
   let l  = abs_float(x) in
   let k  = 1.0 /. (1.0 +. 0.2316419 *. l) in
   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)+.a4*.(pow k 4)+.a5*.(pow k 5))) in
   if (x < 0.0) then  w := 1.0 -. !w ;
!w
(* The Black and Scholes (1973) Stock option formula *)
let black_scholes call_put_flag s x t r v = 
   let d1=(log(s /. x) +. (r+.v*.v/.2.0)*.t)/.(v*.sqrt(t)) in
   let d2=d1-.v*.sqrt(t) in
   let res = ref 0.0 in
   if (call_put_flag == 'c') then
      res := s*.cnd(d1)-.x*.exp(-.r*.t)*.cnd(d2)
   else
      res := x*.exp(-.r*.t)*.cnd(-.d2)-.s*.cnd(-.d1);
!res


Black-Scholes in Transact SQL By Nazy Norouzy

Thanks for providing all those Black Schole calculations in different
languages. Very useful! I was needed one in SQL so I used one of your
examples and converted it to Transact SQL.

--Black Scholes Function:
create Function BlackScholes(@CallPutFlag varchar(100), @S float, @X float, @T
float, @r float, @v float) 
returns float
as
begin
declare @d1 float
declare @d2 float
declare @BS float
set @d1 = (Log(@S / @X) + (@r + power(@v,2) / 2) * @T) / (@v * Sqrt(@T))
set @d2 = @d1 - @v * Sqrt(@T)
If @CallPutFlag = 'c'
begin
	set @BS = @S * dbo.CND(@d1) - @X * Exp(-@r * @T) * dbo.CND(@d2)
end 
else
    If @CallPutFlag = 'p'
    begin
	set @BS = @X * Exp(-@r * @T) * dbo.CND(-@d2) - @S * dbo.CND(-@d1)
    End 
return @BS
End
------------------------------------------
-- The cumulative normal distribution function:
create Function CND(@X float) 
returns float
as 
begin
declare @L float
declare @K float
declare @a1 float
declare @a2 float
declare @a3 float
declare @a4 float
declare @a5 float
set @a1 = 0.31938153
set @a2 = -0.356563782
set @a3 = 1.781477937
set @a4 = -1.821255978
set @a5 = 1.330274429
set @L = Abs(@X)
set @K = 1 / (1 + 0.2316419 * @L)
declare @CND1 float
set @CND1 = 1 - 1 / Sqrt(2 * Pi()) * Exp(-power(@L,2) / 2) * (@a1 * @K + @a2 *
power(@K,2) + @a3 * power(@K,3) + @a4 * power(@K,4) + @a5 * power(@K,5))
If @X < 0 
begin
	set @CND1 = 1 - @CND1
End
return @CND1
End 


Black-Scholes in HP48 RPN By Matt Willis

Before becoming a financial engineer I used to be a real engineer, so I naturally implemented BS on my calculator, using the reverse-polish notation (aka RPN).

<< -> S X r v T
<< S X / LN r v
SQ 2 / + T * + v T
SQRT * / DUP v T SQRT * -
-> d1 d2
<< S 1 0 1 d1 UTPN - * X r T * NEG EXP *
1 0 1 d2 UTPN - * - "C" ->TAG
X r T * NEG EXP * 1 0 1 d2 NEG UTPN - *
S 1 0 1 d1 NEG UTPN - * - "P" ->TAG
>>
>>

'BlackScholes' STO

Note:
"SQRT" is a single character representing the "square root symbol"
"<<", ">>" and "->" are all single symbols

It computes both call and put values, leaving tagged names on the stack.


Black-Scholes in C#
By Robert Derby


using System;



namespace BlackScholes
{
	/// <summary>
	/// Summary description for BlackSholes.
	/// </summary>
	public class BlackSholes
	{
		public BlackSholes()
		{
			//
			// TODO: Add constructor logic here
			//
		}
		/* The Black and Scholes (1973) Stock option formula
		 * C# Implementation
		 * uses the C# Math.PI field rather than a constant as in the C++ implementaion
		 * the value of Pi is 3.14159265358979323846
		*/
		public double BlackScholes(string CallPutFlag, double S, double X, 
			double T, double r, double v)
		{
			double d1 = 0.0;
			double d2 = 0.0;
			double dBlackScholes = 0.0;
			
			d1 = (Math.Log(S / X) + (r + v * v / 2.0) * T) / (v * Math.Sqrt(T));
			d2 = d1 - v * Math.Sqrt(T);
			if (CallPutFlag == "c")
			{				
				dBlackScholes = S * CND(d1) - X * Math.Exp(-r * T) * CND(d2);
			}
			else if (CallPutFlag == "p") 
			{
				dBlackScholes = X * Math.Exp(-r * T) * CND(-d2) - S * CND(-d1);				
			}
			return dBlackScholes;
		}
		public double CND(double X)
		{
			double L = 0.0;
			double K = 0.0;
			double dCND = 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);
			dCND = 1.0 - 1.0 / Math.Sqrt(2 * Convert.ToDouble(Math.PI.ToString())) * 
				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 - dCND;
			}
			else
			{
				return dCND;
			}
		}
	}
}



Black-Scholes in K 
By Tom Messmore, Germany
 

// Black Scholes European Call & Put in k

// Tom Messmore  tom.messmore@zurich.com



.pi      : 3.14159265358979323846              // .pi

.cnd:    {t:%1+.2316419*_abs x   // .cnd[0.5]  // cumulative (std.) normal distribution function

          s:t*.31938153+t*-.356563782+t*1.781477937+t*-1.821255978+1.330274429*t 

          _abs(-x>0)+(%_sqrt 2*.pi)*(_exp -.5*x*x)*s}  // Abramowitz & Stegun 26.2.17 (from stat.k)

.bsfast: {[x;s;v;t;r;opt]                  // example call is .bsfast[100.;90;.30;90.%365;.03;0] 

  if[~opt _lin (0 1); : `"bad opt" ]       // opt 0=EurCall 1=EurPut 

  if[t < 0.; : `"bad time to expiration"]  // t is in years; must be non-negative

  h:(_log[s%x]+(r+(v*(v%2.)))*t)%(v*t^.5); // for subsequent calcs of Eur Put Pr and Eur Call Pr

 :[opt;:(-s*.cnd[-h])+(+x*(_exp(-r*t)))*.cnd[((v*t^.5)-h)];:(s*.cnd[h])+(-x*(_exp(-r*t)))*.cnd[h+(-v*t^.5)]]}


// Description of k language
// Copied from http://www.kx.com/a/k/overview.txt
// k was developed by Arthur Whitney of KX Systems (www.kx.com)
//
// k is a system for programming computers.
//
// it is designed for experts to produce integrated
// high-performance applications as fast as possible.
//
// k is high level and fast.
// k is a scripting language and a systems language.
// k is small and k application code is small.
// k runs on and hides different os's and architectures.
// maximally connected. minimally dependent.
//
// includes:
// programming language, gui, text i/o, binary i/o,
// dynamic loading, run-time application generator,
// high-speed flat file data extractor, sybase bcp extractor, odbc,
// file mapping, database management subsystem, persistent object store,
// transaction logging, excel/vb connection, pure java kclient class,
// synchronous(pull) and asynchronous(push) client server primitives.
//
// all major k applications use many of these features.
//
// k has persistent store for arbitrary objects.
// k can load object code routines written in other languages.
// k can be called remotely or in-process from excel, vb, c and java.
// k interacts well with vb(excel) and java because of a
// one-to-one mapping of self-describing primitive datatypes.


Black-Scholes in ColdFusion

By Alex


For more information on ColdFusion (a web language) go to http://www.macromedia.com

<cfscript>
function BlackScholes (call_put_flag,S,X,T,r,v) {
var d1 = ( log(S / X) + (r + (v^2) / 2) * T ) / ( v * (T^0.5) );
var d2 = d1 - v * (T^0.5);

if (call_put_flag eq 'c')
return S * CND(d1) - X * exp( -r * T ) * CND(d2);
else
return X * exp( -r * T ) * CND(-d2) - S * CND(-d1);
}

function CND (x) {
// The cumulative normal distribution function
var Pi = 3.141592653589793238;
var a1 = 0.31938153;
var a2 = -0.356563782;
var a3 = 1.781477937;
var a4 = -1.821255978;
var a5 = 1.330274429;
var L = abs(x);
var k = 1 / ( 1 + 0.2316419 * L);
var p = 1 - 1 / ((2 * Pi)^0.5) * exp( -(L^2) / 2 ) * (a1 * k + a2 * (k^2) + a3 * (k^3) + a4 * (k^4) + a5 * (k^5) );

if (x gte 0)
return p;
else
return 1-p;

}
</cfscript>


<CFSET CallPutFlag = 'c'>
<CFSET S='49.25'>
<CFSET X='50.00'>
<CFSET T='0.1'>
<CFSET r='0.35'>
<CFSET v='0.30'>
<cfoutput>
#BlackScholes(CallPutFlag,S,X,T,r,v)#
</cfoutput>


Black-Scholes in LyME

By Donsyah Yudistira

I myself am a big fan of Black Scholes Option Pricing Formula. The beauty of the derivation has encouraged many people, including you and me, to write it in a few languages as seen in your page.

A few weeks ago, my lovely wife bought me a Sony Clie PDA. Not long after that, I was browsing the net to look for the best application to calculate Black Scholes Option. I have boarded myself into LyME from Calerga (http://www.calerga.com/). LyME is a port of LME ("Lightweight Math Engine", the heart of SysQuake) to Palm OS handheld devices. This freeware software amazes me very much as it is as powerful as Mathematica, Matlab, Maple, and other mathematical software and the best thing is that you can bring it anywhere in a compact device.

Without further due, here is a small script in LyME for European Black Scholes Option:

function m=bs(cp,s,x,t,r,v)
d1=(log(s/x)+(r+v*v/2)*t)/(v*sqrt(t));
d2=d1-v*sqrt(t);

if cp=='c'
    m=s*cdf('normal',d1)-x*exp(-r*t)*cdf('normal',d2);
elseif cp=='p'
    m=x*exp(-r*t)*cdf('normal',-d2)-s*cdf('normal',-d1);
end


NEW Black-Scholes in PL/SQL

By Fernardo Casteras, Bunos Aires, Argentina

Electrical engineer Fernardo Casteras gives us the Black-Scholes formula written in PL/SQL. PL/SQL is the programming languague used to write stored procedures in ORACLE relational databases and front-end tools, a widely used enviroment in corporations.

CREATE OR REPLACE FUNCTION BLACKSCHOLES ( CALLPUTFLAG IN VARCHAR2,
S IN NUMBER,
X IN NUMBER,
T IN NUMBER,
R IN NUMBER,
V IN NUMBER ) RETURN NUMBER
IS
--
D1 NUMBER;
D2 NUMBER;
PI NUMBER := 3.141592653589793238462643;
RESULT NUMBER;
--
FUNCTION CND ( X NUMBER ) RETURN NUMBER
IS
--
L NUMBER;
K NUMBER;
A1 NUMBER := 0.31938153;
A2 NUMBER := -0.356563782;
A3 NUMBER := 1.781477937;
A4 NUMBER := -1.821255978;
A5 NUMBER := 1.330274429;
RESULT NUMBER;
--
BEGIN
--
L := ABS(X);
K := 1 / (1 + 0.2316419 * L);
RESULT := 1 - 1 / SQRT(2 * PI) * EXP(-POWER(L, 2) / 2)
* (A1 * K + A2 * POWER(K, 2) + A3 * POWER(K, 3)
+ A4 * POWER(K, 4) + A5 * POWER(K, 5));
IF ( X < 0 ) THEN
RESULT := (1 - RESULT);
END IF;
--
RETURN RESULT;
--
END CND;
--
BEGIN
--
RESULT := 0;
D1 := (LN(S / X) + (R + POWER(V, 2) / 2) * T) / (V * SQRT(T));
D2 := D1 - V * SQRT(T);
IF ( CALLPUTFLAG = 'C' ) THEN
RESULT := S * CND(D1) - X * EXP(-R * T) * CND(D2);
ELSIF ( CALLPUTFLAG = 'P' ) THEN
RESULT := X * EXP(-R * T) * CND(-D2) - S * CND(-D1);
END IF;
--
RETURN RESULT;
--
END;


NEW Black-Scholes in Prolog

By Lou Odette, MA USA

I tested it in Arity Prolog, but it should work in any standard Prolog.

% black_scholes(+Type,+Spot,+Strike,+Expiry,+RiskFreeRate,+Volatily,-Price)

% call case
black_scholes(call,S,X,T,R,V,Price) :-
D1 is (ln(S/X) + (R+V*V/2)*T)/(V*sqrt(T)),
D2 is D1 - (V*sqrt(T)),
cumulative_normal(D1,CND1),
cumulative_normal(D2,CND2),
Price is S*CND1 - X*exp(-R*T)*CND2.

% put case
black_scholes(put,S,X,T,R,V,Price) :-
D1 is (ln(S/X) + (R+V*V/2)*T)/V*sqrt(T),
D2 is D1 - V*sqrt(T),
cumulative_normal(-D1,CND1),
cumulative_normal(-D2,CND2),
Price is X*exp(-R*T)*CND2 - S*CND1.

% Cumulative Normal Distribution
cumulative_normal(X,CND) :-
X < 0,
A1 is 0.31938153,
A2 is -0.356563782,
A3 is 1.781477937,
A4 is -1.821255978,
A5 is 1.330274429,
L is abs(X),
K is 1.0/(1.0 + (0.2316419 * L)),
CND is (1.0/sqrt(2*pi))*exp(-L*L/2)*(A1*K + A2*K*K + A3*(K^3) + A4*(K^4) + A5*(K^5)),!.

cumulative_normal(X,CND) :-
A1 is 0.31938153,
A2 is -0.356563782,
A3 is 1.781477937,
A4 is -1.821255978,
A5 is 1.330274429,
L is abs(X),
K is 1.0/(1.0 + (0.2316419 * L)),
CND is 1.0 - (1.0/(sqrt(2*pi))*exp(-L*L/2)*(A1*K + A2*K*K + A3*(K^3) + A4*(K^4) + A5*(K^5))).


Time to go to the top of a mountain or out on the sea. However if you are like me I guess you still would like to value some options. All you need is a Palm + Quicksheet + downloading my Black-Scholes Quicksheet.(zip file). For Cash-or-nothing options download here.

Black-Scholes in Apple Script ? Anybody that want's to contribute?


Feel free to use the code abow as long as you refer to the programers.

For a detailed description of the Black-Scholes-Merton formula see:

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

Merton, R. C. (1973): "Theory of Rational Option Pricing," Bell Journal of Economics and Management Science, 4, 141-144

For a description of many different option pricing formulas see: Haug, E. G. 1997: The Complete Guide to Option Pricing Formulas, McGraw-Hill New York


If you hate computers and computer languages don't give up it's still hope! What about taking Black-Scholes in your head instead? If the option is about at-the-money-forward and it is a short time to maturity then you can use the following approximation: call = put = StockPrice * 0.4 * volatility * Sqrt( Time )



 
Back to my home page.