short_rate from the previous section:
In [ 77 ]: sr.rate
Out[77]: 0.05
In [ 78 ]: sr.time_list
Out[78]: array([ 0. , 0.5, 1. , 1.5, 2. ])
In [ 79 ]: sr.get_discount_factors()
Out[79]: array([ 1. , 0.97530991, 0.95122942, 0.92774349, 0.90483742])
Updating of Values
So far, the new short_rate class using traits allows us to input data for initializing
attributes of an instance of the class. However, a GUI usually is also used to present
results. You would generally want to avoid providing input data via a GUI and then
making the user access the results via interactive scripting. To this end, we need another
sublibrary, traitsui.api:
In [ 80 ]: import traits.api as trapi
import traitsui.api as trui
This sublibrary allows us to generate different views on the same class/object. It also
provides more options for, e.g., labeling and formatting. The key in the following class
definition is what happens when the Update button is pushed. In this case, the private
method _update_fired is called, which updates the list object containing the discount
factors. This updated list is then displayed in the GUI window. A prerequisite for this is
that all input parameters have been made available by the user:
In [ 81 ]: class short_rate(trapi.HasTraits):
name = trapi.Str
rate = trapi.Float
time_list = trapi.Array(dtype=np.float, shape=( 1 , 5 ))
disc_list = trapi.Array(dtype=np.float, shape=( 1 , 5 ))
update = trapi.Button
def _update_fired(self):
self.disc_list = np.exp(-self.rate * self.time_list)
v = trui.View(trui.Group(trui.Item(name = ‘name’),
trui.Item(name=‘rate’),
trui.Item(name=‘time_list’,
label=‘Insert Time List Here’),
trui.Item(‘update’, show_label=False),
trui.Item(name=‘disc_list’,
label=‘Press Update for Factors’),
show_border=True, label=‘Calculate Discount Factors’),
buttons = [trui.OKButton, trui.CancelButton],
resizable = True)
Again, instantiation and configuration are achieved as before:
In [ 82 ]: sr = short_rate()
In [ 83 ]: sr.configure_traits()
Figure 13-6 shows the new, enhanced GUI, which is still empty. You see the new
elements, like the Update button and the output fields for the discount factors.