NumPy (or Numpy) is a Linear Algebra Library for Python, the reason it is so important for Finance with Python is that almost all of the libraries in the PyData Ecosystem rely on NumPy as one of their main building blocks. Plus we will use it to generate data for our analysis examples later on!
Numpy is also incredibly fast, as it has bindings to C libraries. For more info on why you would want to use Arrays instead of lists, check out this great StackOverflow post.
We will only learn the basics of NumPy, to get started we need to install it!
It is highly recommended you install Python using the Anaconda distribution to make sure all underlying dependencies (such as Linear Algebra libraries) all sync up with the use of a conda install. If you have Anaconda, install NumPy by going to your terminal or command prompt and typing:
conda install numpy
If you do not have Anaconda and can not install it, please refer to Numpy's official documentation on various installation instructions.
In [1]:
import numpy as np
Numpy has many built-in functions and capabilities. We won't cover them all but instead we will focus on some of the most important aspects of Numpy: vectors,arrays,matrices, and number generation. Let's start by discussing arrays.
NumPy arrays are the main way we will use Numpy throughout the course. Numpy arrays essentially come in two flavors: vectors and matrices. Vectors are strictly 1-d arrays and matrices are 2-d (but you should note a matrix can still have only one row or one column).
Let's begin our introduction by exploring how to create NumPy arrays.
We can create an array by directly converting a list or list of lists:
In [2]:
my_list = [1,2,3]
my_list
Out[2]:
In [3]:
np.array(my_list)
Out[3]:
In [4]:
my_matrix = [[1,2,3],[4,5,6],[7,8,9]]
my_matrix
Out[4]:
In [5]:
np.array(my_matrix)
Out[5]:
In [12]:
np.arange(0,10)
Out[12]:
In [23]:
np.arange(0,11,2)
Out[23]:
In [24]:
np.zeros(3)
Out[24]:
In [13]:
np.zeros((5,5,5))
Out[13]:
In [27]:
np.ones(3)
Out[27]:
In [28]:
np.ones((3,3))
Out[28]:
In [18]:
np.linspace(0,10,10)
Out[18]:
In [19]:
np.linspace(0,10,50)
Out[19]:
In [20]:
np.eye(8)
Out[20]:
In [28]:
np.random.rand(2)
Out[28]:
In [34]:
np.random.rand(5,5)
Out[34]:
In [48]:
np.random.randn(2)
Out[48]:
In [35]:
np.random.randn(5,5)
Out[35]:
In [36]:
np.random.randint(1,100)
Out[36]:
In [37]:
np.random.randint(1,100,3)
Out[37]:
In [51]:
arr = np.arange(30)
ranarr = np.random.randint(0,50,10)
In [40]:
arr
Out[40]:
In [49]:
ranarr
Out[49]:
In [53]:
arr.reshape(3,10)
Out[53]:
In [54]:
ranarr
Out[54]:
In [55]:
ranarr.max()
Out[55]:
In [56]:
ranarr.argmax()
Out[56]:
In [58]:
ranarr.min()
Out[58]:
In [59]:
ranarr.argmin()
Out[59]:
In [60]:
# Vector
arr.shape
Out[60]:
In [62]:
# Notice the two sets of brackets
arr.reshape(1,30)
Out[62]:
In [63]:
arr.reshape(1,30).shape
Out[63]:
In [64]:
arr.reshape(30,1)
Out[64]:
In [65]:
arr.reshape(30,1).shape
Out[65]:
In [66]:
arr.dtype
Out[66]: