카테고리 없음

"Black-Scholes" in Multiple Languages

steloflute 2015. 4. 11. 23:42

http://www.espenhaug.com/black_scholes.html

 

 

home

 

"Black-Scholes" in Multiple Languages

January 2008: After studying the literature (something many of the famous academics themselves obviously not have done properly) it is obvious that we option traders never have used the Black-Scholes-Merton formula in practice.( see also article in Frobes ) Only if you use close to continuous time delta hedging to remove close to all the risk all the time you are actually using the Black-Scholes (or the Black-Scholes-Merton) version of the option formula. The only problem this is impossible in practice.

If you remove most risk by hedging options with options, get immune for blow up risk by the way you construct your option portfolio then you are using the traders formula/method that was discovered before Black-Scholes-Merton by a series of traders and researchers, the first contribution form Bachelier 1900 and the last by Thorp 1969, so this is why we think it should be called the Bachelier-Thorp formula. In practice you can remove risk with discrete delta hedging (known long before Black-Scholes and Merton), but you can not remove enough risk to argue for risk-neutral valuation (and this is the main argument of Black-Scholes-Merton). See Chapter 2 in my book Derivatives Models on Models for a detailed discussion on how to hedge options in practice.

 

 

You naturally know the so called "Black-Scholes-Merton" option formula, that actualy not is the Black-Scholes-Merton formula (BSM was a theoretical hedging argument related to risk-neutral valuation), 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 30 languages):

 

Objective-C/iPhone, F#, Autoit, Fortress, Lua, APL, SAS, Mathcad, J, MEL, Postscript, VB.NET, Clean, Ruby, Lisp, 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, GNU, gnuplot...

 

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 too 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

 

Check also out Wenhua Wang excellent Java Option Pricer of first edtion of my book!

 

 

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

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;



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))).


Black-Scholes in LISP

By Robert Brown

 

I started with your C version. Once my Lisp code was producing the same
output, I added a few type declarations and did some speed tests. My
benchmark computes

BlackScholes('p', 100.0, 110.0, 10.0, 0.10, .07)

one million times.

Here are my timing results. I compiled the C version with "gcc -O2" and the
Lisp version for maximum speed -- no type checking at run time.

C version: 1.69 seconds
Lisp version: 1.12 seconds

As you can see, Common Lisp is competitive with C and OCaml in terms of
execution speed. The Common Lisp code is attached below.

(declaim (optimize (debug 0) (safety 0) (speed 3)))

(defmacro poly-eval (x coeffs)
"For COEFFS list (a0 a1 a2 ...) produce an expression that evaluates the
polynomial a0 + a1*x + a2*x^2 + ..."
(if (endp (rest coeffs))
(first coeffs)
`(+ (* ,x (poly-eval ,x ,(rest coeffs))) ,(first coeffs))))

(deftype probability () '(double-float 0.0d0 1.0d0))

(deftype nonnegative-double-float ()
'(double-float 0.0d0 #.most-positive-double-float))

(declaim (ftype (function (double-float) probability) cnd))

(defun cnd (x)
(declare (type double-float x))
(let* ((l (abs x))
(k (/ (+ 1.0d0 (* 0.2316419d0 l))))
(w (- 1.0d0 (* (/ (sqrt (* 2.0d0 pi)))
(exp (/ (* (- l) l) 2.0d0))
(poly-eval k (0.0d0 0.31938153d0 -0.356563782d0
1.781477937d0 -1.821255978d0
1.330274429d0))))))
(declare (type double-float l k w))
(if (< x 0.0d0)
(- 1.0d0 w)
w)))

(defun black-scholes (call/put price strike time r vol)
(declare (type nonnegative-double-float price strike time r vol))
(let* ((d1 (/ (+ (log (/ price strike)) (* (+ r (/ (* vol vol) 2.0d0))
time))
(* vol (sqrt time))))
(d2 (- d1 (* vol (sqrt time)))))
(declare (type double-float d1 d2))
(ecase call/put
(:call (- (* price (cnd d1))
(* strike (exp (- (* r time))) (cnd d2))))
(:put (- (* strike (exp (- (* r time))) (cnd (- d2)))
(* price (cnd (- d1))))))))

 


Black-Scholes in Ruby

># by Michael Neumann, Germany
# one-to-one translation from Python example

# Cumulative normal distribution
def cnd(x)
a1, a2, a3, a4, a5 = 0.31938153, -0.356563782, 1.781477937, -1.821255978, 1.330274429
l = x.abs
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*(k**3) + a4*(k**4) + a5*(k**5))
w = 1.0 - w if x < 0
return w
end

def BlackScholes(callPutFlag, s, x, t, r, v)
d1 = (Math.log(s/x)+(r+v*v/2.0)*t)/(v*Math.sqrt(t))
d2 = d1-v*Math.sqrt(t)
if callPutFlag == 'c'
s*cnd(d1)-x*Math.exp(-r*t)*cnd(d2)
else
x*Math.exp(-r*t)*cnd(-d2)-s*cnd(-d1)
end
end



Black-Scholes in Clean

By Isaac Gouy

module BlackScholes
import StdReal

/* Clean
   http://www.cs.kun.nl/~clean/
   Pure functional language, performance similar to C
*/

Start = black_scholes Put 100.0 95.0 7.0 0.05 0.47


::Option = Call | Put

// The Black and Scholes (1973) Stock option formula
black_scholes o s x t r v 
   = option_value o
      where
      option_value Call = s * n(d1) - x * exp(~r*t) * n(d2)
      option_value Put  = x * exp(~r*t) * n(~d2) - s * n(~d1)
      d1 = (ln(s/x) + (r+v*v/2.0)*t)/(v * sqrt t)
      d2 = d1 - v * sqrt t

// The cumulative normal distribution function
n x 
   | x < 0.0   = 1.0 - w
   | otherwise = w
      where
      w = 1.0 - 1.0 / sqrt(2.0*Pi) * exp(~l*l/2.0) * poly
      k = 1.0 / (1.0 + 0.2316419 * l)
      l = abs x
      poly = A1*k +  A2*k*k +  A3 * k^3.0 +  A4 * k^4.0 +  A5 * k^5.0


Pi :== 3.141592653589793238462643
A1 :== 0.31938153
A2 :== -0.356563782
A3 :== 1.781477937
A4 :== -1.821255978
A5 :== 1.330274429


Black-Scholes in VB.NET

By Marco Sturlese,

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

Public Function BlackScholes(ByVal CallPutFlag As String, ByVal S As Double,
ByVal X _

As Double, ByVal T As Double, ByVal r As Double, ByVal v As Double) As
Double

Dim d1 As Double, d2 As Double

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

d2 = d1 - v * Math.Sqrt(T)

If CallPutFlag = "c" Then

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

ElseIf CallPutFlag = "p" Then

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

End If

End Function

'// The cumulative normal distribution function

Public Function CND(ByVal 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 = Math.Abs(X)

K = 1 / (1 + 0.2316419 * L)

CND = 1 - 1 / Math.Sqrt(2 * Math.PI) * Math.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 Postscript Language

By Dr. Jose Gomes,

%!
% Black-Scholes formula in Postscript.
% Started from code at http://www.espenhaug.com/black_scholes.html

/E  2.718281828459045  def
/PI 3.141592653589793238462643 def

% The cumulative normal distribution function 

/CND {
    /CND_X exch def

    /CND_a1 0.31938153 def
    /CND_a2 -0.356563782 def
    /CND_a3 1.781477937 def
    /CND_a4 -1.821255978 def
    /CND_a5 1.330274429 def
    /CND_L CND_X abs def
    /CND_K 0.2316419 CND_L mul 1 add 1 exch div def

    CND_K 5 exp CND_a5 mul
    CND_K 4 exp CND_a4 mul
    add
    CND_K 3 exp CND_a3 mul
    add
    CND_a2 CND_K CND_K mul mul
    add
    CND_a1 CND_K mul
    add

    E 0 CND_L sub CND_L mul 2 div exp
    mul

    0 1 sub 2 PI mul sqrt div
    mul

    1 add

    CND_X 0 lt {1 exch sub} if
} def

% The Black and Scholes (1973) Stock option formula

/BlackScholes {
    /v exch def
    /r exch def
    /T exch def
    /X exch def
    /S exch def
    /CallPutFlag exch def

    /d1
        v v mul 2 div r add T mul
     S X div ln
        add
        T sqrt v mul
        div
    def

    /d2
        d1
        T sqrt v mul
        sub
    def

    (c) CallPutFlag eq
    {
        d1 CND S mul
        d2 CND
        E 0 r sub T mul exp
        mul
        X
        mul
        sub
    } if

    (p) CallPutFlag eq
    {
        0 d2 sub CND
        E 0 r sub T mul exp
        mul X mul
        0 d1 sub CND S mul
        sub
    } if
} def

% Example of use

/S 60 def
/X 65 def
/T 0.25 def
/r 0.08 def
/v 0.30 def
/call (c) S X T r v BlackScholes def
/put  (p) S X T r v BlackScholes def

/Fixed findfont 20 scalefont setfont
newpath
100 220 moveto (   S=) show S    100 string cvs show
100 200 moveto (   X=) show X    100 string cvs show
100 180 moveto (   T=) show T    100 string cvs show
100 160 moveto (   r=) show r 100 mul 100 string cvs show (%) show
100 140 moveto (   v=) show v 100 mul 100 string cvs show (%) show
100 120 moveto (call=) show call 100 string cvs show
100 100 moveto (put =) show put  100 string cvs show

showpage

Black-Scholes in MEL

By James D. Polk,

MEL; Maya's Embedded Language. Maya is a 3D animation
program used in animated feature films and special
effects,..."Dinosaur", etc.... And now also for options!

 

global float $PI;
          $PI = 3.141592653589793238462643;


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


global proc float BlackScholes(string $CallPutFlag, float $S, float $X, float $T, float $r, float $v)
{
     float $d1, $d2;
     float $val;

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

     if($CallPutFlag == "call")
     {
          $val = $S * CumNormDist($d1) - $X * exp(-$r * $T) * CumNormDist($d2) ;
          return($val);
     }
     else
     if($CallPutFlag == "put")
     {
          $val = $X * exp(-$r * $T) * CumNormDist(-$d2) - $S * CumNormDist(-$d1);
          return($val);
     }
}



// --------------------------------------------------
// The cumulative normal distribution function
// --------------------------------------------------

global proc float CumNormDist( float $X )
{
     global float $PI;
     float $L, $K, $w ;

     float $a1 =  0.31938153,  $a2 = -0.356563782, $a3 = 1.781477937;
     float $a4 = -1.821255978, $a5 =  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-Scholes on TI-89 calculator

By Warren Severin,

1) This has been developed on a TI-89 calculator. It should work on many TI-8x models with minor tweaking.
2) This program assumes that the TI statistics and list editor application is installed, which should apply to most people. If you don't have it, download it from http://education.ti.com .

Black-Scholes in J

By Eugene McDonell,

I wrote an article on Black-Scholes for the British publication Vector, 19.3, January 2003. I have a regular column there called "At Play With J", that deals in things having to do with J, a language developed by the late Ken Iverson and Roger Hui, as a successor to Ken's APL. My article is online at :

http://www.jsoftware.com/papers/play193.htm

Here is a way to implement it in J:

***************************************************
BS =: monad define 
'S X T r v' =. y.
d =. ((ln S dv X) + T * r (+,-) hlf sqr v) dv (v * sqrt T)
diff (S , X * exp - r * T) * cnd d
)

BS is used for either call or put. A call uses a positive v, and a put uses a negative v. I learned this device from Arthur Whitney, but I could have learned it from Espen Haug: see his Wilmott paper "A Look in the Antimatter Mirror" for a discussion of the useful symmetries of put and call that permit this. The phrase (+,-) uses a J feature that generalizes the customary mathematical notation (f+g) x, meaning (f(x))+(g(x)). Thus r (+,-) hlf sqr v gives a two-element vector: (r+hlf sqr v),(r-hlf sqr v). This allows the two items d1 and d2 to be replaced by the two-element list d. The function diff is used to subtract the second item from the first.

The erf and cnd functions appear in Abramowitz and Stegun "Handbook of Mathematical Functions" in the sections shown, and were written in J by Ewart Shaw (J.E.H.Shaw  [Ewart Shaw] Department of Statistics,  University of Warwick 

erf =: monad define           NB. A&S 7.1.21 (rightmost)
((2 * y.) dv (sqrt pi)) * (exp - y. ^ 2) * (1  H. 1.5) y. ^2
)

This erf uses J's hypergeometric function, symbolized by " H. ", and thus doesn't need a list of coefficients.

cnd =: monad define           NB. A&S 26.2.29 (solved for P)
(1 + erf y. * sqrt 0.5) dv 2
)

J uses symbols for many functions, instead of names. These are the names and the equivalent J symbols of the ones used above:

diff =: -/   NB. difference           diff 39 13 is 26
dv   =: %    NB. divided by           39 dv 3 is 13
exp  =: ^    NB. exponential          exp 1 is 2.71828
hlf  =: -:   NB. half                 hlf 39 is 19.5
ln   =: ^.   NB. natural logarithm    ln 2.71828 is 0.999999
pi   =: 1p1  NB. pi                   pi is 3.14159
sqr  =: *:   NB. square               sqr 13 is 169
sqrt =: %:   NB. square root          sqrt 169 is 13

Here are examples of put and call uses of BS:

   yc                   NB. call argument
60 65 0.25 0.08 0.3
   yp                   NB. put argument
60 65 0.25 0.08 _0.3
   BS yc                NB. call result
2.13337
   BS yp                NB. put result
_5.84628
****************************************************


Black-Scholes in Mathcad v11

By Stuart Bruff,

It's written in Mathcad v11 (although it should work in v6 to v13).  There is real equivalent of a text source code, as you just type the equations in, using a palette for such things as the square root operator (although there are keyboard shortcuts for most common operators, such as integrals and derivatives). See also http://www.mathcad.com

 

Black-Scholes in SAS

By Fabrice Douglas Rouah,

* For SAS Release 6.12 or higher;


data BS;
input S X r v T;
d1 = (log(S/X) + (r+v**2/2)*T)/v/sqrt(T);
d2 = d1 - v*sqrt(T);
C = S*cdf('Normal',d1) - X*exp(-r*T)*cdf('Normal',d2);
P = X*exp(-r*T)*cdf('Normal',-d2) - S*cdf('Normal',-d1);
label
S = 'Spot Price'
X = 'Strike Price'
r = 'Risk Free Rate'
v = 'Volatility'
T = 'Time Periods'
C = 'BS Call Price'
P = 'BS Put Price' ;

* Input as many input values as needed;

cards;
120 95 0.08 0.2 3
120 100 0.08 0.2 3
120 110 0.08 0.2 3
120 120 0.08 0.2 3
;
proc print label;
var S X r v T C P;
run;

Black-Scholes in APL

By Nick Lobachevsky,

APL has the undeserved reputation of being unreadable code.  Usually, it has a lot more to do with the program author than the language itself. The code is written in a "dyalect" called Dyalog APL. www.dyalog.com


Black-Scholes in Lua

By Thomas Munro,

-- "Lua is a powerful light-weight programming language designed for
-- extending applications. Lua is also frequently used as a general-purpose,
-- stand-alone language. Lua is free software." - from http://www.lua.org
--
-- Black-Scholes option formula put into Lua by Thomas Munro, London, 2007.

-- Cumulative normal distribution.
function cnd(x)
-- taylor series coefficients
local a1, a2, a3, a4, a5 = 0.31938153, -0.356563782, 1.781477937,
-1.821255978, 1.330274429
local l = math.abs(x)
local k = 1.0 / (1.0 + 0.2316419 * l)
local w = 1.0 - 1.0 / math.sqrt(2 * 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 then w = 1.0 - w end
return w
end

-- The Black-Scholes option valuation function (1973).
-- is_call: true for call, false for put
-- s: current price
-- x: strike price
-- t: time
-- r: interest rate
-- v: volatility
function black_scholes(is_call, s, x, t, r, v)
local d1 = (math.log(s / x) + (r + v * v / 2.0) * t) / (v * math.sqrt(t))
local d2 = d1 - v * math.sqrt(t)
if is_call then
return s * cnd(d1) - x * math.exp(-r * t) * cnd(d2)
else
return x * math.exp(-r * t) * cnd(-d2) - s * cnd(-d1)
end
end

 


Black-Scholes in Fortress

By Thomas Munro

(*
* The Black-Scholes formula expressed in the unfinished language Fortress.
* Thomas Munro, London 2007.
*
* From Wikipedia: Fortress "is intended to be a successor to Fortran, with
* improvements including Unicode support and concrete syntax that is similar
* to mathematical notation. The language is not designed to be similar to
* Fortran. Syntactically, it most resembles Scala, Standard ML, and Haskell."
*)

 


Black-Scholes in AutoIt

By Russell Lazarus

AutoIt is a freeware Windows automation language which is particularly adept at manipulation of GUI windows and controls. AutoIt scripts can be 'compiled' with a run-time interpreter that allows users to run on most Windows platforms without requiring software installation.

For more information, visit the AutoIt web sit at: http://www.autoitscript.com.

;BlackScholes stock option function
Func _BlackScholes()
    Local $CallPutFlag, $S, $w, $T, $r, $v,$d1 = (Log($S / $w) + ($r + $v ^ 2 / 2) * $T) / ($v * Sqrt($T)), $d2 = $d1 - $v * Sqrt($T)
    If $CallPutFlag = "c" Then
        Local $callval = ($S * _CND($d1) - $w * Exp(-$r * $T) * _CND($d2))
    ElseIf $CallPutFlag = "p" Then
        Local $putval = ($w * Exp(-$r * $T) * _CND(-$d2) - $S * _CND(-$d1))
    EndIf
EndFunc   ;==>_BlackScholes

;The cumulative normal distribution function
Func _CND($w)
    Const $a1 = 0.31938153, $a2 = -0.356563782, $a3 = 1.781477937, $a4 = -1.821255978, $a5 = 1.330274429, $Pi = 3.14159265
    $w1 = $w
    $L = Abs($w)
    $K = 1 / (1 + 0.2316419 * $L)
    $w = 1 - 1 / Sqrt(2 * $Pi) * Exp(-$L * $L / 2) * ($a1 * $K + $a2 * $K ^ 2 + $a3 * $K ^ 3 + $a4 * $K ^ 4 + $a5 * $K ^ 5)

    If $w1 < 0 Then
        $w = 1 - $w
    EndIf
    Return $w


Black-Scholes in GNU

By Dave Prashant

/*
Prashant Dave Ph.D. prashant dot dave at alumni dot purdue dot edu
Black Scholes Option Pricing Formula Written in bc.
Details on bc are available at http://www.gnu.org/software/bc

This code is based on the C++ code written by Dr. Espen Gaarder Haug

Usage:
bc -l < bs_bc.txt
*/
define cnd (x) {
a1 = 0.31938153;
a2 = -0.356563782;
a3 = 1.781477937;
a4 = -1.821255978;
a5 = 1.330274429;
if (x > 0 ) l = x else l = -x;
k = 1.0 / (1.0 + 0.2316419 * l);
pi = 4*a(1);
w = 1.0 - 1.0 / sqrt(2 * pi) * e(-l *l / 2) * (a1 * k + a2 * k *k + a3 * (k^3) + a4 * (k^4) + a5 * (k^5));
if (x < 0 ){
w= 1.0 - w;
}
return w;
}

define blackscholes (f, s, x, t, r, v) {
d1=(l(s/x)+(r+v*v/2)*t)/(v*sqrt(t));
d2=d1-v*sqrt(t);
if (f == 0) {
return s *cnd(d1)-x * e(-r*t)*cnd(d2);
} else {
return x * e(-r * t) * cnd(-d2) - s * cnd(-d1);
}
}
/* First argument is 0 for call and nonzero for put */

blackscholes(0, 60, 65, .25, .08, .30);

 

EndFunc   ;==>_CND


Black-Scholes in gnuplot

By Dave Prashant


# Prashant Dave, Ph.D. [prashant dot dave at alumni dot purdue dot edu]
#
# GNUPlot Code Implementation of Black Scholes
# Usage: gnuplot black_scholes.gnu
#
d1 (S, X, T, r, v) = (log(S*1.0/X*1.0)+(r+v*v/2.0)*T)/(v*sqrt(T));
d2 (S, X, T, r, v) = (log(S*1.0/X*1.0)+(r-v*v/2.0)*T)/(v*sqrt(T));
BlackScholes(CallPutFlag, S, X, T, r, v) = (CallPutFlag eq "c") ? (S *norm(d1(S,X,T,r,v))-X * exp(-r*T)*norm(d2(S,X,T,r,v))) : (X * exp(-r * T) * norm(-d2(S,X,T,r,v)) - S * norm(-d1(S,X,T,r,v)));
print BlackScholes("c", 60, 65, 0.25, 0.08, 0.30);
#


Black-Scholes in F#

F# is a functional programming language for the .NET Framework. It combines the succinct, expressive, and compositional style of functional programming with the runtime, libraries, interoperability, and object model of .NET.

By Michael de la Maza

#light
 
// This code was transliterated from the OCAML code
// located here http://www.espenhaug.com/black_scholes.html
 
let pow x n = exp (n * log(x) ) 
 
let cnd 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 call_put_flag 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)
   let res = ref 0.0
   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
 
 
Example usage::
 
> black_scholes 'c' 60.0 65.0 0.25 0.08 0.3;;
val it : float = 2.133371862
> black_scholes 'p' 60.0 65.0 0.25 0.08 0.3;;
val it : float = 5.846285627

 

 


Black-Scholes in  Objective-C/iPhone

By Paul J. Sholtz

Objective-C is the programming language used for iPhones. With this code as inspiration to thet started I hope we will see a lot of great option software fro iPhones.

HEADER FILE/DECLARATION:

-(double)BlackSholes:(char)CallPutFlag: (double)S: (double)X: (double)T: (double)r: (double)v;
-(double)CND:(double)X;

IMPLEMENTATION:

#ifndef Pi 
#define Pi 3.141592653589793238462643 
#endif 

-(double)BlackSholes:(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 *[self CND:d1]-X * exp(-r*T)*[self CND:d2];	if(CallPutFlag == 'p')
		return X * exp(-r * T) * [self CND:-d2] - S * [self CND:-d1];
	
	// error flag; 
	[NSException raise:@"Call/Put Error" format:@"Option must be either a call or put"];
}
-(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;
}

INVOCATION (LOGGING ANSWER TO CONSOLE):
(models a call option, equity price 50, strike price 45, time to expiry 1/3 of a year, 8% risk free rate and 30% volatility)

	char flag = 'p';
	double S = 50.0;
	double X = 45.0;
	double T = 1./3.;
	double r = 0.08;
	double v = 0.3;
	
	double option_value = [self BlackSholes:flag :S :X :T :r :v];
NSLog(@"option value: %f",option_value);								


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

Haug, E. G. and Taleb, N.N. (2008): "Why We Have Never Used the Black-Scholes-Merton formula"

Haug, E. G. (2007): "Derivatives Models on Models" Wiley Publishing, see Chapter 2 in particular

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. 2007: 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 )

 
 

Copyright Espen Haug 1998- 2009 all rights reserved, Feel free to use the code on this page as long as you clearly refer to the programmers.