""" AUTHOR JONATHAN LAU""" import math """ The following is the cdf of a standard normal variable """ def f(x): return math.exp((-x**2.0)/2.0) def simp_rule(a, b, n): h = (b-a)/float(n) total = f(a) / 6.0 + f(b) / 6.0 for i in range (1, n): total = total + f(a + i*h) / 3.0 for i in range (1, n+1): total = total + 2 * f(a + (i-0.5) * h) / 3.0 return total * h def cum_distrib(x, n): total = 0.5 return total + 1/(math.sqrt(2.0 * math.pi)) * simp_rule(0.0, x, n) def cum_distrib_tol(tol, x): tolerance = float(tol) n = 4 old_int = cum_distrib(x,n) n = 2 * n new_int = cum_distrib(x,n) while abs(new_int - old_int) > tolerance: old_int = new_int n = 2* n new_int = cum_distrib(x,n) return new_int """return (n, new_int, abs(new_int - old_int) ) ==> copy this in if you want to see how many iterations it takes, and what the difference between the new and old estimates are""" """ Black Scholes Theorem""" def PutCallOptionPrice (S, K, r, q, vol, T, t): d1 = ( math.log(float(S) / K) + (r - q + (vol**2)/2) * (T - t) ) / (vol * math.sqrt(T - t)) d2 = d1 - vol * math.sqrt(T - t) C = S* math.exp(-q* (T-t)) * cum_distrib_tol(10**-12, d1) - K * math.exp(-r *(T-t)) * cum_distrib_tol(10**-12, d2) P = K* math.exp(-r* (T-t)) * cum_distrib_tol(10**-12, -d2) - S * math.exp(-q *(T-t)) * cum_distrib_tol(10**-12, -d1) return (C, P, d1, d2) print PutCallOptionPrice(60, 50, 0.01, 0.02, 0.2, 0.75, 0) print PutCallOptionPrice(20, 40, 0.02, 0.03, 0.3, 0.25, 0) print PutCallOptionPrice(42.0, 40.0, 0.05, 0.03, 0.3, 0.5, 0.0) print cum_distrib_tol(10**-12, 2)
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question