Python for Finance: Analyze Big Financial Data

(Elle) #1
In  [ 98 ]: a.std()     #   standard    deviation
Out[98]: 0.70710678118654757
In [ 99 ]: a.cumsum() # running cumulative sum
Out[99]: array([ 0. , 0.5, 1.5, 3. , 5. ])

Another major feature is the (vectorized) mathematical operations defined on ndarray


objects:


In  [ 100 ]:    a   *    2
Out[100]: array([ 0., 1., 2., 3., 4.])
In [ 101 ]: a ** 2
Out[101]: array([ 0. , 0.25, 1. , 2.25, 4. ])
In [ 102 ]: np.sqrt(a)
Out[102]: array([ 0. , 0.70710678, 1. , 1.22474487, 1.41421356
])

The transition to more than one dimension is seamless, and all features presented so far


carry over to the more general cases. In particular, the indexing system is made consistent


across all dimensions:


In  [ 103 ]:    b   =   np.array([a,    a   *    2 ])
b
Out[103]: array([[ 0. , 0.5, 1. , 1.5, 2. ],
[ 0. , 1. , 2. , 3. , 4. ]])
In [ 104 ]: b[ 0 ] # first row
Out[104]: array([ 0. , 0.5, 1. , 1.5, 2. ])
In [ 105 ]: b[ 0 , 2 ] # third element of first row
Out[105]: 1.0
In [ 106 ]: b.sum()
Out[106]: 15.0

In contrast to our list object-based approach to constructing arrays, the numpy.ndarray


class knows axes explicitly. Selecting either rows or columns from a matrix is essentially


the same:


In  [ 107 ]:    b.sum(axis= 0 )
# sum along axis 0, i.e. column-wise sum
Out[107]: array([ 0. , 1.5, 3. , 4.5, 6. ])
In [ 108 ]: b.sum(axis= 1 )
# sum along axis 1, i.e. row-wise sum
Out[108]: array([ 5., 10.])

There are a number of ways to initialize (instantiate) a numpy.ndarray object. One is as


presented before, via np.array. However, this assumes that all elements of the array are


already available. In contrast, one would maybe like to have the numpy.ndarray objects


instantiated first to populate them later with results generated during the execution of


code. To this end, we can use the following functions:


In  [ 109 ]:    c   =   np.zeros(( 2 ,   3 ,     4 ),   dtype=‘i’,  order=‘C’)      #   also:   np.ones()
c
Out[109]: array([[[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]],

                                                                    [[0,    0,  0,  0],
[0, 0, 0, 0],
[0, 0, 0, 0]]], dtype=int32)
In [ 110 ]: d = np.ones_like(c, dtype=‘f16’, order=‘C’) # also: np.zeros_like()
d
Out[110]: array([[[ 1.0, 1.0, 1.0, 1.0],
[ 1.0, 1.0, 1.0, 1.0],
[ 1.0, 1.0, 1.0, 1.0]],
Free download pdf