PythonTrading – 3 – Learning Numpy

For financial trading I need to learn how to use Numpy and Pandas.

 

Numpy stands for an extension module for “efficient operations and arrays of homogeneous data”.

 

I am getting a little bit frightened when I read that. First I need to import Numpy and afterwards I can use it to convert Python lists to an Numpy array.

 

Actually I can also create multi dimensional arrays.

np.zeros can be used to get an array of floating type variables that have the value 0.

This is also possible for multidimensional arrays, for example np.zeros ((16,16)) would create 16 arrays with 10 floating type zero items.

Numpy offers a function called linspace, it can be used to divide a value into x spaces of the same size (evenly spaced).

np.random.rand can be used to create a collection of random numbers that have a value between 0 and 1. In our case we are going to use 11 rows with 3 colums.

There are additional functions to create random numbers, for example np.random.randint would create one or more random integers. In our case we create 300 values for a dice.

After we have created a random array for integer variables, we can get the maximum or minimum value or the index of those values – we just need to use the appropriate functions.

It is possible to do basic math operations with those arrays, for example to get the squared value you could just multiply the array with itself.

If you would use something like added_array=some_array+1.2 you would add the value 1.2 to each element in the array.

 

And np.sqrt(some_array) would calculate the square root for each element in the array.

 

Accessing elements in the array works like we already know it from lists. We just use the index…

Numpy arrays can be modified by so called broadcasts. Basically that means that it is possible to replace parts of the array with a value that overwrites the original values.

If the original values of the source array should not be modified, we need to use array.copy()

To access an item in a matrix, we can use different ways. The first one is to put the index values into square braces, the second one is to use comma separated values and we can also use a colon to define ranges.

 

For example a colon without values would define a whole array, the value before the colon is the starting index and the value behind the colon is the finishing index.

There is also something called conditional selection. With Numpy it is possible to get a subset of an array based on a condition. For example we can get all the values that are greater than 12 or less than 16 with a short notation.