Python for Finance: Analyze Big Financial Data

(Elle) #1

short rate over five years. The factors for t = 0 are all equal to 1; i.e., “no discounting” of


today’s cash flows. However, given a short rate of 10% and a cash flow due in five years,


the cash flow would be discounted to a value slightly above 0.6 per currency unit (i.e., to


60%). We generate the plot as follows:


In  [ 47 ]: import matplotlib.pyplot as plt
%matplotlib inline
In [ 48 ]: t = np.linspace( 0 , 5 )
for r in [0.01, 0.05, 0.1]:
plt.plot(t, discount_factor(r, t), label=‘r=%4.2f’ % r, lw=1.5)
plt.xlabel(‘years’)
plt.ylabel(‘discount factor’)
plt.grid(True)
plt.legend(loc= 0 )

For comparison, now let us look at the class-based implementation approach. We call it


short_rate since this is the central entity/object and the derivation of discount factors is


accomplished via a method call:


Figure 13-1. Discount factors for different short rates over five years

In  [ 49 ]: class short_rate(object):
”’ Class to model a constant short rate object.

                                                    Parameters
==========
name : string
name of the object
rate : float
positive, constant short rate

                                                    Methods
=======
get_discount_factors :
returns discount factors for given list/array
of dates/times (as year fractions)
”’
def __init__(self, name, rate):
self.name = name
self.rate = rate
def get_discount_factors(self, time_list):
”’ time_list : list/array-like ”’
time_list = np.array(time_list)
return np.exp(-self.rate * time_list)

To start with, define sr to be an instance of the class short_rate:


In  [ 50 ]: sr  =   short_rate(‘r’, 0.05)
In [ 51 ]: sr.name, sr.rate
Out[51]: (‘r’, 0.05)
Free download pdf