Valuation Algorithm
z = np.random.standard_normal(I) # pseudorandom numbers
ST = S0 np.exp((r - 0.5 sigma * 2 ) T + sigma np.sqrt(T) z)
index values at maturity
hT = np.maximum(ST - K, 0 ) # inner values at maturity
C0 = np.exp(-r T) np.sum(hT) / I # Monte Carlo estimator
Result Output
print “Value of the European Call Option %5.3f” % C0
Although the first version is perfectly executable by the Python interpreter, the second
version for sure is more readable for both the programmer and any others who may try to
understand it.
Some special rules apply to functions and classes when it comes to formatting. In general,
there are supposed to be two blank lines before any new function (method) definition as
well as any new class definition. With functions, indentation also comes into play. In
general, indentation is achieved through spaces and not through tabulators. As a general
rule, take four spaces per level of indentation.
[ 84 ]
Consider now Example A-3.
Example A-3. A Python function with multiple indentations
Function to check prime characteristic of integer
is_prime_no_doc.py
def is_prime(I):
if type(I) != int:
raise TypeError(“Input has not the right type.”)
if I <= 3 :
raise ValueError(“Number too small.”)
else:
if I % 2 == 0 :
print “Number is even, therefore not prime.”
else:
end = int(I / 2.) + 1
for i in range( 3 , end, 2 ):
if I % i == 0 :
print “Number is not prime, it is divided by %d.” % i
break
if i >= end - 2 :
print “Number is prime.”