Python for Finance: Analyze Big Financial Data

(Elle) #1
Figure 9-15. Example function with integral area

Numerical Integration


The integrate sublibrary contains a selection of functions to numerically integrate a


given mathematical function given upper and lower integration limits. Examples are


fixed_quad for fixed Gaussian quadrature, quad for adaptive quadrature, and romberg for


Romberg integration:


In  [ 75 ]: sci.fixed_quad(f,   a,  b)[ 0 ]
Out[75]: 24.366995967084588
In [ 76 ]: sci.quad(f, a, b)[ 0 ]
Out[76]: 24.374754718086752
In [ 77 ]: sci.romberg(f, a, b)
Out[77]: 24.374754718086713

There are also a number of integration functions that take as input list or ndarray objects


with function values and input values. Examples in this regard are trapz, using the


trapezoidal rule, and simps, implementing Simpson’s rule:


In  [ 78 ]: xi  =   np.linspace(0.5,    9.5,     25 )
In [ 79 ]: sci.trapz(f(xi), xi)
Out[79]: 24.352733271544516
In [ 80 ]: sci.simps(f(xi), xi)
Out[80]: 24.374964184550748

Integration by Simulation


The valuation of options and derivatives by Monte Carlo simulation (cf. Chapter 10) rests


on the insight that you can evaluate an integral by simulation. To this end, draw I random


values of x between the integral limits and evaluate the integration function at every


random value of x. Sum up all the function values and take the average to arrive at an


average function value over the integration interval. Multiply this value by the length of


the integration interval to derive an estimate for the integral value.


The following code shows how the Monte Carlo estimated integral value converges to the


real one when one increases the number of random draws. The estimator is already quite


close for really small numbers of random draws:

Free download pdf