Python for Finance: Analyze Big Financial Data

(Elle) #1

We can not go into details here, but SymPy also provides many other useful mathematical


functions — for example, when it comes to numerically evaluating . The following


shows the first 40 characters of the string representation of up to the 400,000th digit:


In  [ 92 ]: pi_str  =   str(sy.N(sy.pi,  400000 ))
pi_str[: 40 ]
Out[92]: ‘3.14159265358979323846264338327950288419’

And here are the last 40 digits of the first 400,000:


In  [ 93 ]: pi_str[- 40 :]
Out[93]: ‘8245672736856312185020980470362464176198’

You can also look up your birthday if you wish; however, there is no guarantee of a hit:


In  [ 94 ]: pi_str.find(‘111272’)
Out[94]: 366713

Equations


A strength of SymPy is solving equations, e.g., of the form x


2

–   1   =   0:

In  [ 95 ]: sy.solve(x  **   2  -    1 )
Out[95]: [-1, 1]

In general, SymPy presumes that you are looking for a solution to the equation obtained by


equating the given expression to zero. Therefore, equations like x


2

–   1   =   3   might   have    to

be reformulated to get the desired result:


In  [ 96 ]: sy.solve(x  **   2  -    1  -    3 )
Out[96]: [-2, 2]

Of course, SymPy can cope with more complex expressions, like x


3

+ 0.5x


2

–   1   =   0:

In  [ 97 ]: sy.solve(x  **   3  +   0.5 *   x   **   2  -    1 )
Out[97]: [0.858094329496553, -0.679047164748276 - 0.839206763026694*I,
-0.679047164748276 + 0.839206763026694*I]

However, there is obviously no guarantee of a solution, either from a mathematical point


of view (i.e., the existence of a solution) or from an algorithmic point of view (i.e., an


implementation).


SymPy works similarly with functions exhibiting more than one input parameter, and to this


end also with complex numbers. As a simple example take the equation x


2

+ y


2

= 0:


In  [ 98 ]: sy.solve(x  **   2  +   y   **   2 )
Out[98]: [{x: -I*y}, {x: I*y}]

Integration


Another strength of SymPy is integration and differentiation. In what follows, we revisit the


example function used for numerical- and simulation-based integration and derive now


both a symbolic and a numerically exact solution. We need symbols for the integration


limits:


In  [ 99 ]: a,  b   =   sy.symbols(‘a   b’)

Having defined the new symbols, we can “pretty print” the symbolic integral:


In  [ 100 ]:    print sy.pretty(sy.Integral(sy.sin(x)   +   0.5 *   x,  (x, a,  b)))
Out[100]: b
/
|
Free download pdf