Python for Finance: Analyze Big Financial Data

(Elle) #1

Vectorization with NumPy


NumPy provides a powerful multidimensional array class, called ndarray, as well as a


comprehensive set of functions and methods to manipulate arrays and implement


(complex) operations on such objects. From a more general point of view, there are two


major benefits of using NumPy:


Syntax


NumPy generally allows implementations that are more compact than pure Python and


that are often easier to read and maintain.


Speed


The majority of NumPy code is implemented in C or Fortran, which makes NumPy,


when used in the right way, faster than pure Python.


The generally more compact syntax stems from the fact that NumPy brings powerful


vectorization and broadcasting capabilities to Python. This is similar to having vector


notation in mathematics for large vectors or matrices. For example, assume that we have a


vector with the first 100 natural numbers, 1, ..., 100:


Scalar multiplication of this vector is written compactly as:


Let’s see if we can do this with Python list objects, for example:


In  [ 22 ]: v   =   range( 1 ,   6 )
print v
Out[22]: [1, 2, 3, 4, 5]
Free download pdf