Python for Finance: Analyze Big Financial Data

(Elle) #1
In  [ 55 ]: for i in range( 2 ,  5 ):
print l[i] ** 2
Out[55]: 6.25
1.0
2.25

LOOPING OVER LISTS

In Python you can loop over arbitrary list objects, no matter what the content of the object is. This often avoids

the introduction of a counter.

Python also provides the typical (conditional) control elements if, elif, and else. Their


use is comparable in other languages:


In  [ 56 ]: for i in range( 1 ,  10 ):
if i % 2 == 0 : # % is for modulo
print “%d is even” % i
elif i % 3 == 0 :
print “%d is multiple of 3” % i
else:
print “%d is odd” % i
Out[56]: 1 is odd
2 is even
3 is multiple of 3
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is multiple of 3

Similarly, while provides another means to control the flow:


In  [ 57 ]: total   =    0
while total < 100 :
total += 1
print total
Out[57]: 100

A specialty of Python is so-called list comprehensions. Instead of looping over existing


list objects, this approach generates list objects via loops in a rather compact fashion:


In  [ 58 ]: m   =   [i  **   2   for i in range( 5 )]
m
Out[58]: [0, 1, 4, 9, 16]

In a certain sense, this already provides a first means to generate “something like”


vectorized code in that loops are rather more implicit than explicit (vectorization of code


is discussed in more detail later in this chapter).


Excursion: Functional Programming


Python provides a number of tools for functional programming support as well — i.e., the


application of a function to a whole set of inputs (in our case list objects). Among these


tools are filter, map, and reduce. However, we need a function definition first. To start


with something really simple, consider a function f that returns the square of the input x:


In  [ 59 ]: def f(x):
return x ** 2
f( 2 )
Out[59]: 4

Of course, functions can be arbitrarily complex, with multiple input/parameter objects and


even multiple outputs, (return objects). However, consider the following function:


In  [ 60 ]: def even(x):
return x % 2 == 0
even( 3 )
Free download pdf