NumPy 数组
行情很少只算一个数。十天的收盘价是一列数,两年的日收益也是一列数。Python 列表能把它们装起来,但金融计算里更常用 NumPy 的数组:同一个运算作用在整列上。
本章只处理这一列数本身。收益率放到下一章。
学完后,应能说出数组的类型和长度,用下标和切片取出其中一段,并对整列做加减乘除。
安装
python -m pip install numpy
从列表做成数组
import numpy as np
prices = np.array([10.0, 10.5, 10.2, 11.0])
print(prices)
print(type(prices))
print(prices.dtype)
print(prices.shape)
print(prices.ndim)
print(len(prices))
输出:
[10. 10.5 10.2 11. ]
<class 'numpy.ndarray'>
float64
(4,)
1
4
ndarray 是 NumPy 的数组。dtype 是元素类型,这里写成带小数点的数,所以是 float64。shape 是形状,(4,) 表示一维、四个数。ndim 是维数,一列价格是 1。len 仍是元素个数。
整数数组和小数数组不要混着理解。np.array([10, 11, 12]) 的类型是整数,除法的结果仍会变成小数,但一开始就写价格时,用 10.0 这种写法更清楚。
下标和切片
下标从 0 开始,负数从末尾数。
print(prices[0])
print(prices[-1])
print(prices[1:3])
10.0
11.0
[10.5 10.2]
prices[1:3] 含起点、不含终点,所以是下标 1 和 2,也就是 10.5 和 10.2。这和 Python 列表的切片规则相同。
常用的几段:
| 写法 | 取到什么 |
|---|---|
prices[0] |
第一个 |
prices[-1] |
最后一个 |
prices[1:] |
从第二个一直到末尾 |
prices[:-1] |
从开头直到倒数第二个 |
prices[:2] |
前两个 |
下一章算相邻两天的收益,用的就是 prices[1:] 和 prices[:-1]。
整列运算
print(prices + 1)
print(prices * 2)
[11. 11.5 11.2 12. ]
[20. 21. 20.4 22. ]
加 1、乘 2,作用在每一个价格上,不必写 for。两个等长数组也可以逐个位置相加、相减、相乘、相除。长度不同时,NumPy 会报错,除非其中一边只有一个数。
列表相加和数组相加
a = [1, 2, 3]
b = [10, 20, 30]
print(a + b)
print(np.array(a) + np.array(b))
[1, 2, 3, 10, 20, 30]
[11 22 33]
列表的 + 把两段接成一段。数组的 + 把同一位置的数加起来。价格、收益、权重,要用第二种。
课堂练习
- 造一个含五个收盘价的数组,打印
dtype、shape和最后一个价格。 - 打印去掉第一天之后的价格,再打印去掉最后一天之后的价格,核对两段的长度是否相同。
- 把每个价格乘以 1.1,打印结果。
例子见 examples/fintech/numpy_array.py。