Python for Finance: Analyze Big Financial Data

(Elle) #1

Graphical User Interfaces


For the majority of computer users, as compared to developers or data scientists, a


graphical user interface (GUI) is what they are used to. Such a GUI does not only bring


along visual appeal and simplicity; it also allows us to guide and control user interaction


much better than alternative approaches like interactive scripting, or use of a command


line interface or shell. In what follows, we build on the examples of the previous section


and build simple GUIs for our short rate and cash flow series classes.


To build the GUIs we use the traits library, documentation of which you can find at


http://code.enthought.com/projects/traits/docs/html/index.html. traits is generally used


for rapid GUI building on top of existing classes and only seldom for more complex


applications. In what follows, we will reimplement the two example classes from before,


taking into account that we want to use a GUI for interacting with instances of the


respective classes.


Short Rate Class with GUI


To start, we need to import the traits.api sublibrary:


In  [ 72 ]: import numpy as np
import traits.api as trapi

For the definition of our new short_rate class, we use the HasTraits class to inherit


from. Also note in the following class definition that traits has its own data types, which


are generally closely intertwined with visual elements of a GUI — to put it differently,


traits knows which graphical elements (e.g., for a text field) to use to build a GUI


(semi)automatically:


In  [ 73 ]: class short_rate(trapi.HasTraits):
name = trapi.Str
rate = trapi.Float
time_list = trapi.Array(dtype=np.float, shape=( 5 ,))
def get_discount_factors(self):
return np.exp(-self.rate * self.time_list)

Instantiation of such a traits-based class is done as usual:


In  [ 74 ]: sr  =   short_rate()

However, via a call of the method configure_traits (inherited from HasTraits) a GUI is


automatically generated, and we can use this GUI to input values for the attributes of the


new object sr:


In  [ 75 ]: sr.configure_traits()

Figure 13-4 shows such a simple GUI, which in this case is still empty (i.e., no input


values have been put in the different fields). Note that the lower five fields all belong to


“Time list” — this layout is generated by default.


Figure 13-5 shows the same simple GUI, this time however with values in every single


field. Pushing the OK button assigns the values from the input fields to the respective


attributes of the object.

Free download pdf