Hold many numbers in one array and do maths on all of them at once, without writing a loop.
A numpy array holds many numbers and does maths on all of them at once. Multiply an array of prices by a share count and every price gets multiplied, with no loop.
In this lesson I build arrays of prices, run arithmetic straight on them, show that a plain list does something else entirely, and turn prices into returns in one line.
Step 1. Maths on a whole row of prices
np.array() turns a list into an array. From then on, the operators work on every element.
import numpy as npprices = np.array([185.40, 187.20, 184.90]) # three closesprint(prices) # -> [185.4 187.2 184.9]print(type(prices)) # -> <class 'numpy.ndarray'>print(prices.shape) # -> (3,) <- 3 numbers, in one dimension
[185.4 187.2 184.9]
<class 'numpy.ndarray'>
(3,)
shape is a tuple, so (3,) means one row of three. Multiply by a number and each price is multiplied:
value = prices *10# 10 shares held on each of the three daysprint(value) # -> [1854. 1872. 1849.]
[1854. 1872. 1849.]
Two arrays of the same shape combine position by position: the first with the first, the second with the second.
aapl = np.array([185.40, 187.20, 184.90])msft = np.array([410.00, 408.50, 415.20])print(aapl + msft) # -> [595.4 595.7 600.1] <- one share of each, per dayprint(msft - aapl) # -> [224.6 221.3 230.3]
[595.4 595.7 600.1]
[224.6 221.3 230.3]
Step 2. A list does not do this
The same two expressions on a list mean something else. * repeats the list and + joins two lists end to end.
[1, 2] * 2 gives four items. np.array([1, 2]) * 2 gives two items, each doubled. To double every number in a list you write a loop. To double every number in an array you write * 2.
Step 3. Prices to returns in one line
Slicing an array works the way it did on lists in Lesson 5. closes[1:] is every price from the second onwards, and closes[:-1] is every price except the last.
Every element of an array shares one dtype. np.array([1, 2]).dtype is int64 and np.array([185.4, 187.2]).dtype is float64. Mix an integer into a float array and it becomes a float.