
P1: JYS
c04 JWBK378-Fletcher May 23, 2009 4:21 Printer: Yet to come
38 Financial Modelling in Python
4.5 LINEAR ALGEBRA
The Python NumPy package contains a module that covers most of what is required from
linear algebra from a financial engineering perspective. For the most part, this section provides
some examples of its use for problems common in financial engineering. This section just
touches on the capabilities of NumPy for linear algebra. The interested reader is referred to the
NumPy documentation for further detail. Readers with an interest in the development of linear
algebra routines in Python are encouraged to consult Jaan Kiusalaas’s Numerical Methods in
Engineering with Python [12].
4.5.1 Matrix Multiplication
The ordinary matrix product.
>>> from numpy import *
>>> from numpy.linalg import inv
>>> A = array([ [1, 3, 2], [1, 0, 0], [2, 1, 1]])
>>> M = matrix(A)
>>> print M*M
[[854]
[1 3 2]
[5 7 5]]
Note the use of the matrix construction function in the example above. It is this that gives the
interpretation of the operation as a matrix product. Multiplying two arrays, on the other hand,
gives the product element-wise, e.g.
>>> print A*A
[[194]
[1 0 0]
[4 1 1]]
Matrix multiplication can be performed on arrays by use of the dot function, as illustrated
below.
>>> print dot(A, A)
[[854]
[1 3 2]
[5 7 5]]
4.5.2 Matrix Inversion
Find the inverse of a square non-singular matrix.
>>> from numpy import *
>>> from ...