<!--一个博主专栏付费入口结束-->
<link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/ck_htmledit_views-d284373521.css">
<div id="content_views" class="markdown_views prism-tomorrow-night">
<!-- flowchart 箭头图标 勿删 -->
<svg xmlns="http://www.w3.org/2000/svg" style="display: none;">
<path stroke-linecap="round" d="M5,0 0,2.5 5,5z" id="raphael-marker-block" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></path>
</svg>
<h1><a name="t0"></a><a id="NumPy_0"></a>NumPy</h1>
文章目录
NumPy数组对象
-
NumPy中的ndarray是一个多维数组对象,该对象由两部分组成
- 实际的数据
- 描述这些数据的元数据
-
举例
def sum(n): #range返回的是range对象(在python3中,不返回list对象) a = list(range(n)) b = list(range(n)) c = [] for i in range(len(a)): a[i] = i ** 2 b[i] = i ** 3 c.append(a[i] + b[i]) return c
import numpy as np
def sumNp(n):
a = np.arange(n) 2
b = np.arange(n) 3
c = a + b
return c
print(sumNp(5))
print(sum(5))
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
-
数组创建函数
import numpy as np print(np.arange(5).shape) print(np.array( [[1,2],[2,1]]) ) print(np.zeros( 10 ) ) print(np.zeros( (3,6) ) ) print(np.empty( (2,3,4) ))
- 1
- 2
- 3
- 4
- 5
- 6
NumPy数据类型
-
自定义数据类型
#自定义数据类型 import numpy as np t = np.dtype([("name",np.str_,40),("items",np.int32),("price",np.float64)]) arr = np.array([("The meaning of life DVD",10,29.7),("I an your father",20,32.1)],dtype=t) print(arr[0])
- 1
- 2
- 3
- 4
- 5
NumPy数组运算
-
运算
import numpy as np arr = np.array([[1,2,3],[4,5,6]]) print(arr*arr) print(arr+arr) print(arr-arr) print(1/arr) array = [1,2,3,4] print(array[::-1]) #步长
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
NumPy索引和切片
-
切片
import numpy as np arr = np.arange(24).reshape(2,3,4) print(arr[:,:,-1]) print(arr[:,:,-1]) print() print(arr[:,::-1])#两个冒号表示步长 #全部反转 print(arr[::-1,::-1,::-1])
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
-
布尔型索引
names = np.array(["Bob","Joe","Will","Bob","Will","Joe","Joe"]) data = np.random.randn(7,4) print(data) print(names=="Bob") print(data[names=="Bob"])
- 1
- 2
- 3
- 4
- 5
-
花式索引
arr = np.arange(32).reshape((8,4)) print(arr[1]) print(arr[[1,2],[2,3]]) print(arr.T) #将数组反转
- 1
- 2
- 3
- 4
-
改变维度
#改变数组的维度 #增加维度 b = np.arange(24).reshape(2,3,4) print(b) #降低维度 print(b.flatten()) #改变维度 b.shape = (6,4) print(b) b.resize((2,12)) print(b) #反转数组 print(b.transpose())
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
NumPy数组组合
-
数组的组合
#数组组合 #水平组合 a = np.arange(9).reshape(3,3) print(a) b = a * 2 print(b) print(np.hstack((a,b))) print(np.concatenate((a,b),axis=1)) #竖直组合 print(np.vstack((a,b))) print(np.concatenate((a,b),axis=0)) #print(np.dstack((a,b)))
a1 = np.arange(0,2)
b1 = a1 * 2;
#竖直组合
print(np.column_stack((a1,b1)))
#水平组合
print(np.row_stack((a1,b1)))#分割
a = np.arange(9).reshape(3,3)
print(np.hsplit(a,3))
print(np.split(a,3,1))
print(np.vsplit(a,3))
print(np.split(a,3,0))c = np.arange(27).reshape(3,3,3)
print(c)
print(np.dsplit(c,3))- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
NumPy数组的属性
-
数组属性
#数组的属性 b = np.arange(24).reshape(2,12) print(b.ndim) #维度(几维数组) print(b.size) #数组元素总个数 print(b.itemsize) #在内存中占的字节数 print(b.nbytes) #字节总和
#复数的属性
b = np.array([1+1j,2+2j])
print(b.real)
print(b.imag)
print(b.flat[1])#获取展开为一维数组之后的指定下标值
b.flat[0]=1
b.flat[1]=2
print(b)- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
NumPy数组的转换
-
数组转换
b = np.array([1+1j,2+2j]) print(b) print(b.tostring()) print(b.tolist()) print(np.fromstring('20:42:52',sep=":",dtype=int)) print(b.astype(int)) print(b.astype(complex))
- 1
- 2
- 3
- 4
- 5
- 6
- 7
NumPy通用函数
-
一元ufunc
-
示例
arr = np.arange(10) print(np.sqrt(arr)) #开根号 print(np.exp(arr)) #指数
x = np.random.randn(8)
y = np.random.randn(8)
print(np.maximum(x,y)) #元素级最大值
arr = np.random.randn(7) * 5
print(arr)print(np.modf(arr)) #将整数和分数分离成两个数组
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
-
-
二元ufunc
NumPy数据处理
-
向量化的处理
points = np.arange(-5,5,0.01) #print(points) xs,ys = np.meshgrid(points,points) #两个一维数组,第一个决定宽度,第二个决定高度 # 比如 np.meshgrid([1,2],[3,4]) # 高度和宽度都是2,所以在xs中: # xs: [[1,2] ys:[[3,3 # [1,2]] 4,4]] import matplotlib.pyplot as plt z = np.sqrt(xs ** 2 + ys ** 2) plt.imshow(z,cmap=plt.cm.gray) plt.colorbar() plt.title("image for sql(xs ** 2 + ys ** 2)") plt.show()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
结果:
-
将条件逻辑表达式为数组运算
#where函数 arr1 = [1,2,3,4,5] arr2 = [6,7,8,9,10] cond = [True,True,False,True,True] arr3 = np.where(cond,arr1,arr2) print(arr3)
arr4 = np.random.randn(4,4)
print(arr4)
np.where(arr4>0,2,-2)- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
-
-
数学与统计方法
print(arr.mean()) #算术平均数。零长度的数组的mean为NaN print(arr.sum()) #求和 print(arr.std()) #标准差 print(arr.var()) #方法 print(arr.max()) #最大值 print(arr.min()) #最小值 print(arr.argmax()) #最大值的下标 print(arr.argmin()) #最小值的下标
bools = np.array([False,True,False,False])
print(bools.any()) #是否存在非零元素
print(bools.all()) #是否全部为0
# arr.sort(1) #按照某一行排序
arr.sort()
print(arr) #从小到大排序value = np.array([1,2,3,4,5,6])
print(np.in1d(value,[2,3,6])) #判断是否存在在第一个表中。返回的是一个布尔数组- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
NumPy线性代数
-
常用的numpy.linalg函数
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-x27G3cUS-1571620181708)(线性代数.JPG)]
arr = np.arange(16).reshape(4,4) 矩阵的对角线(一维数组) print(np.diag(arr)) # 矩阵乘法 print(arr) print("*") print(arr.T) print(np.dot(arr,arr.T))
print(np.trace(arr))
print(np.linalg.det(arr))
#计算矩阵的逆
arr = np.array([1,1,1,1]).reshape(2,2)
print(arr)
print(np.linalg.inv(arr))
print(np.dot(arr,np.linalg.inv(arr)))- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
NumPy随机数
- 产生随机数
- 示例
import random position = 0 walk = [position] steps = 1000 for i in range(steps): step = 1 if random.randint(0,1) else -1 position += step walk.append(position) print(walk)
nstep = 1000
draws = np.random.randint(0,2,size = nstep)
steps = np.where(draws>0,1,-1)
walk = steps.cumsum() #所有元素的累计和
print(steps)
print(walk)- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
NumPy例子
-
数据(csv)文件
AAPL 28-01-2011 344.17 344.4 333.53 336.1 21144800 AAPL 31-01-2011 335.8 340.04 334.3 339.32 13473000 AAPL 01-02-2011 341.3 345.65 340.98 345.03 15236800 AAPL 02-02-2011 344.45 345.25 343.55 344.32 9242600 AAPL 03-02-2011 343.8 344.24 338.55 343.44 14064100 AAPL 04-02-2011 343.61 346.7 343.51 346.5 11494200 AAPL 07-02-2011 347.89 353.25 347.64 351.88 17322100 AAPL 08-02-2011 353.68 355.52 352.15 355.2 13608500 AAPL 09-02-2011 355.19 359 354.87 358.16 17240800 AAPL 10-02-2011 357.39 360 348 354.54 33162400 AAPL 11-02-2011 354.75 357.8 353.54 356.85 13127500 AAPL 14-02-2011 356.79 359.48 356.71 359.18 11086200 AAPL 15-02-2011 359.19 359.97 357.55 359.9 10149000 AAPL 16-02-2011 360.8 364.9 360.5 363.13 17184100 AAPL 17-02-2011 357.1 360.27 356.52 358.3 18949000 AAPL 18-02-2011 358.21 359.5 349.52 350.56 29144500 AAPL 22-02-2011 342.05 345.4 337.72 338.61 31162200 AAPL 23-02-2011 338.77 344.64 338.61 342.62 23994700 AAPL 24-02-2011 344.02 345.15 338.37 342.88 17853500 AAPL 25-02-2011 345.29 348.43 344.8 348.16 13572000 AAPL 28-02-2011 351.21 355.05 351.12 353.21 14395400 AAPL 01-03-2011 355.47 355.72 347.68 349.31 16290300 AAPL 02-03-2011 349.96 354.35 348.4 352.12 21521000 AAPL 03-03-2011 357.2 359.79 355.92 359.56 17885200 AAPL 04-03-2011 360.07 360.29 357.75 360 16188000 AAPL 07-03-2011 361.11 361.67 351.31 355.36 19504300 AAPL 08-03-2011 354.91 357.4 352.25 355.76 12718000 AAPL 09-03-2011 354.69 354.76 350.6 352.47 16192700 AAPL 10-03-2011 349.69 349.77 344.9 346.67 18138800 AAPL 11-03-2011 345.4 352.32 345 351.99 16824200
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
-
代码
# 利用NumPy进行历史股价分析 import sys # 读入文件 第6,7列 :股票的收盘价和成交数量。 c,v = np.loadtxt("data.csv",delimiter=",",usecols=(5,6),unpack=True) # 计算加权平均价格(价格*频数)/总频数 vmap = np.average(c,weights=v) print("加权平均价格:",vmap) #算术平均值 print("算术平均价格:",np.mean(c)) # 时间加权平均价格 t = np.arange(len(c)) tmap = np.average(c,weights=t) print("时间加权平均价格:",tmap) # 寻找最大值和最小值:最高价和最低价 h,l = np.loadtxt("data.csv",delimiter=",",usecols=(3,4),unpack=True) print("最高价格:",np.max(h)) print("最低价格:",np.min(l)) print("最高价和最低价平均值:",(np.max(h)+np.min(h))/2) # 波动性:最高价的最大值-最高价的最小值(或最低价的最大值-最低价的最小值) print("最高价波动性:",np.ptp(h)) print("最低价波动性:",np.ptp(l)) print("中位数:",np.median(c)) print("方差:",np.var(c)) #print(np.diff(c)) #后一个值减去前一个值 #股票收益率:收益的标准差 returns = np.diff(c)/c[:-1] print("收益的标准差",np.std(returns)) logreturns = np.diff( np.log(c) )
posretindices = np.where(returns>0)
annual_volatility = np.std(logreturns)/np.mean(logreturns)
annual_volatility = annual_volatility / np.sqrt(1./252.)
print(annual_volatility)#日期分析:
# from datetime import datetime
#
# def datestr2num(s):
# return datetime.strptime(s, “%d-%m-%Y”).date().weekday()
#
# dates, close = np.loadtxt(‘data.csv’, delimiter=",", usecols=(1,6),converters={1: datestr2num}, unpack=True)#from datetime
import datetime# Monday 0
# Tuesday 1
# Wednesday 2
# Thursday 3
# Friday 4
# Saturday 5
# Sunday 6
def datestr2num(s):
#将字符转换成字符串
return datetime.datetime.strptime(s.decode(‘ascii’), “%d-%m-%Y”).date().weekday()dates, close=np.loadtxt(‘data.csv’, delimiter=’,’, usecols=(1,5),
converters={1: datestr2num}, unpack=True)
print(“Dates =”, dates)averages = np.zeros(5)
for i in range(5):
indices = np.where(dates i) #返回 i 所在的下标 。
prices = np.take(close,indices) # 返回 下标 所对应的 值 。
avg = np.mean(prices) # 求平均值
print(“Day”,i,“prices”,prices,“Average”,avg)
averages[i] = avg
top = np.max(averages)
botton = np.min(averages)
print(“最高:”,top)
print(“最低:”,botton)
#周汇总
def datestr2num(s):
return datetime.datetime.strptime(s.decode(“ascii”),"%d-%m-%Y").date().weekday()
dates,open,high,low,close = np.loadtxt(‘data.csv’,delimiter=",",
usecols=(1,2,3,4,5),
converters={1:datestr2num},
unpack=True)
close = close[:16]
dates = dates[:16]
#get first Monday
first_monday = np.ravel(np.where(dates 0 ))[0] # 将元组变成数组,也能够降维last_friday = np.ravel(np.where(dates == 4 ))[-1] # 将元组变成数组,也能够降维
# 从第一个周一到最后一个周五的下标
week_indices = np.arange(first_monday,last_friday+1)week_indices = np.split(week_indices, 3) #切成三分
print(week_indices)
def summarize(a,o,h,l,c):
monday_open = o[a[0]] # 一周的开盘价
week_high = np.max( np.take(h,a) ) #一周的最高价
week_low = np.min( np.take(l,a) ) #一周的最低价
friday_close = c[a[-1]] #一周的收盘价
return (“APPL”,monday_open,week_high,week_low,friday_close)#将arr数组的每一个元素经过func函数变换形成的一个新数组
week_summary = np.apply_along_axis(summarize,1,week_indices,open,high,low,close)
print(week_summary)
np.savetxt(‘weeksummary.csv’,week_summary,delimiter=",",fmt="%s")#真实波动幅度均值
h , l, c = np.loadtxt(‘data.csv’,delimiter="," ,usecols=(3,4,5), unpack=True)
N = 20
h = h[-N:]
l = l[-N:]
previousclose = c[-N-1:-1]truerange = np.maximum(h-l,h-previousclose,previousclose-l)
atr = np.zeros(N)
atr[0] = np.mean(truerange)
for i in range(1,N):
atr[i] = (N-1)*atr[i-1] + truerange[i]
atr[i] /= N
print(atr)#简单移动平均线
from matplotlib.pyplot import plot
from matplotlib.pyplot import show
N = 5
weights = np.ones(N) / N
c = np.loadtxt(‘data.csv’, delimiter=",",usecols=(5,),unpack=True)
# ‘full’ 默认值,返回每一个卷积值,长度是N+M-1,在卷积的边缘处,信号不重叠,存在边际效应。
# ‘same’ 返回的数组长度为max(M, N),边际效应依旧存在。
# ‘valid’ 返回的数组长度为max(M,N)-min(M,N)+1,此时返回的是完全重叠的点。边缘的点无效。
#sma1 = np.convolve(weights,c,mode=“same”)
# sma1 = np.convolve(weights,c,mode=“full”)[N-1:-N+1]
# print(sma1)
#sma = np.convolve(weights,c,mode=“same”)
sma = np.convolve(weights,c,mode=“valid”)
#print(sma1)
#print(sma3)
t = np.arange(N-1,len(c))
#plot(t,c[N-1:],lw=1.0)
#plot(t,sma,lw=2.0)
#show()#指数移动平均线
c = np.loadtxt(‘data.csv’, delimiter=",",usecols=(5,),unpack=True)
t = np.arange(N-1,len(c))
weights = np.exp(np.linspace(-1.,0.,N))
weights /= weights.sum()
ema = np.convolve(weights,c)[N-1:-N+1]
#plot(t,c[N-1:],lw = 1.0)
#plot(t, ema, lw = 2.0)
#show()#布林带
N = 5
weights = np.ones(N) / N
c = np.loadtxt(‘data.csv’,delimiter=",",usecols=(5,),unpack=True)
sma = np.convolve(weights,c)[N-1:-N+1]
deviation = []
for i in range(N-1,len(c)):
if i + N < len(c):
dev = c[i:i+N]
else:
dev = c[-N:]
averages = np.zeros(N)
averages.fill(sma[i - N - 1])
dev = dev - averages
dev = dev ** 2
dev = np.sqrt(np.mean(dev))
deviation.append(dev)
deviation = 2 * np.array(deviation)
upperBB = sma + deviation
lowerBB = sma - deviationc_slice = c[N-1:]
between_bands = np.where((c_slice < upperBB) & (c_slice > lowerBB))
between_bands = len(np.ravel(between_bands))
t = np.arange(N-1,len(c))
plot(t,c_slice,lw=1.0)
plot(t,sma,lw=2.0)
plot(t,upperBB,lw=3.0)
plot(t,lowerBB,lw=4.0)
show()- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
- 130
- 131
- 132
- 133
- 134
- 135
- 136
- 137
- 138
- 139
- 140
- 141
- 142
- 143
- 144
- 145
- 146
- 147
- 148
- 149
- 150
- 151
- 152
- 153
- 154
- 155
- 156
- 157
- 158
- 159
- 160
- 161
- 162
- 163
- 164
- 165
- 166
- 167
- 168
- 169
- 170
- 171
- 172
- 173
- 174
- 175
- 176
- 177
- 178
- 179
- 180
- 181
-
简单移动平均线
-
指数移动平均线
-
哥布林带
</div> <link href="https://csdnimg.cn/release/phoenix/mdeditor/markdown_views-b6c3c6d139.css" rel="stylesheet"> </div>