Symbolic Computation
The previous sections are mainly concerned with numerical computation. This section
now introduces symbolic computation, which can be applied beneficially in many areas of
finance. To this end, let us import SymPy, the library specifically dedicated to symbolic
computation:
In [ 82 ]: import sympy as sy
Basics
SymPy introduces new classes of objects. A fundamental class is the Symbol class:
In [ 83 ]: x = sy.Symbol(‘x’)
y = sy.Symbol(‘y’)
In [ 84 ]: type(x)
Out[84]: sympy.core.symbol.Symbol
Like NumPy, SymPy has a number of (mathematical) function definitions. For example:
In [ 85 ]: sy.sqrt(x)
Out[85]: sqrt(x)
This already illustrates a major difference. Although x has no numerical value, the square
root of x is nevertheless defined with SymPy since x is a Symbol object. In that sense,
sy.sqrt(x) can be part of arbitrary mathematical expressions. Notice that SymPy in
general automatically simplifies a given mathematical expression:
In [ 86 ]: 3 + sy.sqrt(x) - 4 ** 2
Out[86]: sqrt(x) - 13
Similarly, you can define arbitrary functions using Symbol objects. They are not to be
confused with Python functions:
In [ 87 ]: f = x ** 2 + 3 + 0.5 * x ** 2 + 3 / 2
In [ 88 ]: sy.simplify(f)
Out[88]: 1.5*x**2 + 4
SymPy provides three basic renderers for mathematical expressions:
LaTeX-based
Unicode-based
ASCII-based
When working, for example, solely in the IPython Notebook, LaTeX rendering is generally
a good (i.e., visually appealing) choice. In what follows, we stick to the simplest option,
ASCII, to illustrate that there is no handmade type setting involved:
In [ 89 ]: sy.init_printing(pretty_print=False, use_unicode=False)
In [ 90 ]: print sy.pretty(f)
Out[90]: 2
1.5*x + 4
As you can see from the output, multiple lines are used whenever needed. Also, for
example, see the following for the visual representation of the square-root function:
In [ 91 ]: print sy.pretty(sy.sqrt(x) + 0.5)
Out[91]: ___
\/ x + 0.5