2008/07/13

Black-Scholes Equation in Python


Photo by Martinlu, "Math"

やっぱ金融学んでるんだったら、オプションの理論価格ぐらい自分で出さないといけないよねー
ってわけで、あっちの方面では超がつくほど有名なBlack-Sholes Equotionをノリで実装してみました。特にこれといって特別なことはしてないですし、もう既にどっかの誰かがやってそうですが、こんくらい自分でやんないと。

#!/usr/bin/env python
#-*- coding:utf-8 -*-

import math

A1 = 0.319381530
A2 = -0.35653782
A3 = 1.781477937
A4 = -1.821255978
A5 = 1.330274429
RSQRT2PI = 0.3989422804
GAMMA = 0.2316419

def Black_Scholes_Call(S,K,T,R,V):
d1,d2 = _getD1D2(S,K,T,R,V)
ret = S*_normalDist(d1)-K*math.exp(-R*T)*_normalDist(d2)
return ret

def Black_Scholes_Put(S,K,T,R,V):
d1,d2 = _getD1D2(S,K,T,R,V)
ret = -S*_normalDist(-d1)+K*math.exp(-R*T)*_normalDist(-d2)
return ret

def _getD1D2(S,K,T,R,V):
vSqrtT = V*math.sqrt(T)
d1 = (math.log(float(S)/K)+(R+0.5*V*V)*T)/(vSqrtT)
d2 = d1 - vSqrtT
return (d1,d2)

def _normalDist(x):
if x >= 0:
k = 1.0/(1.0 + GAMMA*x)
cnd = RSQRT2PI*math.exp(-0.5*x*x)*(k *(A1+ k*(A2+ k*(A3 + k*(A4 + k*A5)))))
ret = 1.0 - cnd
return ret
else:
return 1.0 - _normalDist(-x)

ちなみに累積正規分布関数のところは5次の項まで近似した関数を使ってます。

0 件のコメント: