Out[42]: Guido
Henry
Lilli
Sandra
Zorro
In principle, we have replicated a call of the function sorted, which takes as input a list
object and returns as output a list object:
In [ 43 ]: type(sorted(name_list))
Out[43]: list
In [ 44 ]: for name in sorted(name_list):
print name
Out[44]: Guido
Henry
Lilli
Sandra
Zorro
Our approach, however, works on a completely new type of object — namely, a
sorted_list:
In [ 45 ]: type(sorted_name_list)
Out[45]: __main__.sorted_list
This concludes the rather concise introduction into selected concepts of object orientation
in Python. In the following discussion, these concepts are illustrated by introductory
financial use cases. In addition, Part III makes extensive use of object-oriented
programming to implement a derivatives analytics library.
Simple Short Rate Class
One of the most fundamental concepts in finance is discounting. Since it is so
fundamental, it might justify the definition of a discounting class. In a constant short rate
world with continuous discounting, the factor to discount a future cash flow due at date t >
0 to the present t = 0 is defined by .
Consider first the following function definition, which returns the discount factor for a
given future date and a value for the constant short rate. Note that a NumPy universal
function is used in the function definition for the exponential function to allow for
vectorization:
In [ 46 ]: import numpy as np
def discount_factor(r, t):
”’ Function to calculate a discount factor.
Parameters
==========
r : float
positive, constant short rate
t : float, array of floats
future date(s), in fraction of years;
e.g. 0.5 means half a year from now
Returns
=======
df : float
discount factor
”’
df = np.exp(-r * t)
# use of NumPy universal function for vectorization
return df
Figure 13-1 illustrates how the discount factors behave for different values for the constant