Python for Finance: Analyze Big Financial Data

(Elle) #1
                                            |       (0.5*x  +   sin(x)) dx
|
/
a

Using integrate, we can then derive the antiderivative of the integration function:


In  [ 101 ]:    int_func    =   sy.integrate(sy.sin(x)  +   0.5 *   x,  x)
In [ 102 ]: print sy.pretty(int_func)
Out[102]: 2
0.25*x - cos(x)

Equipped with the antiderivative, the numerical evaluation of the integral is only three


steps away. To numerically evaluate a SymPy expression, replace the respective symbol


with the numerical value using the method subs and call the method evalf on the new


expression:


In  [ 103 ]:    Fb  =   int_func.subs(x,    9.5).evalf()
Fa = int_func.subs(x, 0.5).evalf()

The difference between Fb and Fa then yields the exact integral value:


In  [ 104 ]:    Fb  -   Fa #    exact   value   of  integral
Out[104]: 24.3747547180867

The integral can also be solved symbolically with the symbolic integration limits:


In  [ 105 ]:    int_func_limits =   sy.integrate(sy.sin(x)  +   0.5 *   x,  (x, a,  b))
print sy.pretty(int_func_limits)
Out[105]: 2 2
- 0.25*a + 0.25*b + cos(a) - cos(b)

As before, numerical substitution — this time using a dict object for multiple


substitutions — and evaluation then yields the integral value:


In  [ 106 ]:    int_func_limits.subs({a :   0.5,    b   :   9.5}).evalf()
Out[106]: 24.3747547180868

Finally, providing quantified integration limits yields the exact value in a single step:


In  [ 107 ]:    sy.integrate(sy.sin(x)  +   0.5 *   x,  (x, 0.5,    9.5))
Out[107]: 24.3747547180867

Differentiation


The derivative of the antiderivative shall yield in general the original function. Let us


check this by applying the diff function to the symbolic antiderivative from before:


In  [ 108 ]:    int_func.diff()
Out[108]: 0.5*x + sin(x)

As with the integration example, we want to use differentiation now to derive the exact


solution of the convex minimization problem we looked at earlier. To this end, we define


the respective function symbolically as follows:


In  [ 109 ]:    f   =   (sy.sin(x)  +   0.05    *   x   **   2
+ sy.sin(y) + 0.05 * y ** 2 )

For the minimization, we need the two partial derivatives with respect to both variables, x


and y:


In  [ 110 ]:    del_x   =   sy.diff(f,  x)
del_x
Out[110]: 0.1*x + cos(x)
In [ 111 ]: del_y = sy.diff(f, y)
del_y
Free download pdf