Python for Finance: Analyze Big Financial Data

(Elle) #1

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


We immediately notice the role indentation plays in Python. There are multiple levels of


indentation to indicate code blocks, here mainly “caused” by control structure elements


(e.g., if or else) or loops (e.g., the for loop).


Control structure elements are explained in Chapter 4, but the basic working of the


function should be clear even if you are not yet used to Python syntax. Table A-1 lists a


number of heavily used Python operators. Whenever there is a question mark in the


description column of Table A-1, the operation returns a Boolean object (i.e., True or


False).


Table A-1. Selected Python operators


Symbol Description

+

Addition
Free download pdf