【Python数据分析—NumPy】4.NumPy便捷函数

4.NumPy便捷函数



1、相关性(np.cov()、diagonal()、trace()、np.abs())

  使用2个示例数据集提供收盘价数据,其中包含收盘价的最小值。 第一家公司是BHP Billiton(BHP),其主要业务是石油、金属和钻石的开采。第二家公司是Vale(VALE),也是一家金属开采业的公司。这两家公司有部分业务是重合的,可以对它们的股票进行相关性分析。

import numpy as np
from matplotlib.pyplot import plot
from matplotlib.pyplot import show

bhp = np.loadtxt("BHP.csv", delimiter=",", usecols=(6,), unpack=True)
bhp_returns = np.diff(bhp) / bhp[:-1]

vale = np.loadtxt("VALE.csv", delimiter=",", usecols=(6,), unpack=True)
vale_returns = np.diff(vale) / vale[:-1]

# 协方差描述的是两个变量共同变化的趋势,其实就是归一化前的相关系数。使用cov函数计算股票收益率的协方差矩阵
covariance = np.cov(bhp_returns, vale_returns)
print("Covariance(协方差矩阵):", covariance)

# 使用diagonal函数查看对角线上的元素
a = covariance.diagonal()
print("Covariance Diagonal(角线上的元素):", a)
# 使用trace函数计算矩阵的迹,即对角线上元素之和
b = covariance.trace()
print("Covariance Trace(矩阵的迹):", b)

# 两个向量的相关系数被定义为协方差除以各自标准差的乘积
c = covariance / (np.std(bhp_returns) * np.std(vale_returns))
print("两个向量的相关系数:", c)

# 使用corrcoef函数计算相关系数(相关系数矩阵)
d = np.corrcoef(bhp_returns, vale_returns)
# 相关系数矩阵关于对角线对称,表示BHP与VALE的相关系数等于VALE和BHP的相关系数。
print("Correlation coefficient(相关系数矩阵):", d)

# 判断两只股票的价格走势是否同步:如果它们的差值偏离了平均差值2倍于标准差的距离,则认为这两只股票走势不同步
# 若判断为不同步,可以进行股票交易,等待它们重新回到同步的状态。计算这两只股票收盘价的差值,以判断是否同步
differnce = bhp - vale
avg = np.mean(differnce)
dev = np.std(differnce)

e = np.abs(differnce[-1] - avg) > 2*dev # np.abs()函数计算数组各元素的绝对值
print("Out of sync:",e)

t = np.arange(len(bhp_returns))
plot(t, bhp_returns, lw=1)
plot(t, vale_returns, lw=2)
show()

2、多项式(np.polyfit()、np.polyval()、np.roots()、np.polyder())

  在微积分里有泰勒展开的概念,是用一个无穷级数来表示一个可微的函数。实际上,任何可微的(从而也是连续的)函数都可以用一个N次多项式来估计,而比N次幂更高阶的部分为无穷小量可忽略不计。

# NumPy中的ployfit函数可以用多项式去拟合一系列数据点,无论这些数据点是否来自连续函数都适用
import numpy as np
from matplotlib.pyplot import plot
from matplotlib.pyplot import show

bhp = np.loadtxt("BHP.csv", delimiter=",", usecols=(6,), unpack=True)
vale = np.loadtxt("VALE.csv", delimiter=",", usecols=(6,), unpack=True)

t = np.arange(len(bhp))
poly = np.polyfit(t, bhp-vale, 5)  # 用一个三次多项式去拟合两只股票收盘价的差价
print("Polynomial fit(拟合的结果为多项式的系数):", poly)

# 推断下一个值
a = np.polyval(poly, t[-1]+1)
print("Next value(推断下一个值):", a)

# 使用roots()函数找出拟合的多项式函数值为0的点
b = np.roots(poly)
print("Roots(求0点):", b)

# 使用polyder函数对多项式函数求导(多项式函数的导函数系数)
der = np.polyder(poly)
print("Derivative(多项式函数的导函数系数):", der)

# 极值可能是函数的最大值或最小值,这些极值点位于函数的导数为0的位置
ext = np.roots(der)
print("Extremas(极值点):", ext)

# 复核结果(使用polyval计算多项式函数的值)
vals = np.polyval(poly, t)
print("最大值点", np.argmax(vals))
print("最小值点", np.argmin(vals))

plot(t, bhp - vale)
plot(t, vals)
show()
#在拟合前对数据进行平滑处理
import numpy as np
from matplotlib.pyplot import plot
from matplotlib.pyplot import show

bhp = np.loadtxt("BHP.csv", delimiter=",", usecols=(6,), unpack=True)
vale = np.loadtxt("VALE.csv", delimiter=",", usecols=(6,), unpack=True)
c = bhp-vale

N = 3
weights = np.ones(N) / N

sma = np.convolve(weights, c)[N-1:-N+1]


t = np.arange(len(sma))
poly = np.polyfit(t, sma, 5)  # 用一个三次多项式去拟合两只股票收盘价的差价
print("Polynomial fit(拟合的结果为多项式的系数):", poly)


# 使用polyder函数对多项式函数求导(多项式函数的导函数系数)
der = np.polyder(poly)
print("Derivative(多项式函数的导函数系数):", der)

# 极值可能是函数的最大值或最小值,这些极值点位于函数的导数为0的位置
ext = np.roots(der)
print("Extremas(极值点):", ext)

# 复核结果(使用polyval计算多项式函数的值)
vals = np.polyval(poly, t)
print("最大值点", np.argmax(vals))
print("最小值点", np.argmin(vals))

plot(t, sma)
plot(t, vals)
show()

3、净额成交量(np.sign()、np.piecewise()、np.array_equal())

  成交量(volume)是投资中一个非常重要的变量,它可以表示价格波动的大小。OBV(On-Balance Volume,净额成交量或叫能量潮指标)是最简单的股价指标之一,它可以由当日收盘价、前一天的收盘价以及当日成交量计算得出。需要在成交量前面乘上一个由收盘价变化决定的正负号。

# 把BHP数据分别加载到收盘价和成交量的数组中
import numpy as np

c, v = np.loadtxt("BHP.csv", delimiter=",", usecols=(6, 7), unpack=True)

# diff()函数计算数组中两个连续元素的差值,并返回一个这些差值组成的数组
change = np.diff(c)
print("Change", change)
print(len(c))
print(len(change))

# 1.sign函数可以返回数组中每个元素的正负符号,数组元素为负时返回-1,为 正时返回1,否则返回0。
signs = np.sign(change)
print("Signs:", signs)
# 2.piecewise函数来获取数组元素的正负。可以分段给定取值,使用合适的返回值和对应的条件调用该函数
pieces = np.piecewise(change, [change < 0, change > 0], [-1, 1])
print("Pieces:", pieces)

# 检查两次的输出是否一致
equal = np.array_equal(signs, pieces)  # 检查两个数组是否具有相同的形状和元素
print("Arrays equal?", equal)

# OBV值的计算依赖于前一日的收盘价,所以在例子中无法计算首日的OBV值
obv = v[1:] * signs
print("On Balance volume:", obv)

4、数据平滑(np.hanning()、np.polysub()、np.isreal()、np.select()、np.trim_zeros())

import numpy as np
from matplotlib.pyplot import plot
from matplotlib.pyplot import show

N = 8  # 调用hanning()函数计算权重,生成一个长度为N的窗口
weights1 = np.hanning(N)  # 余弦窗函数窗
weights2 = np.hamming(N)  # 汉明窗
weights3 = np.blackman(N)  # 布莱克曼窗
weights4 = np.bartlett(N)  # 巴特利特窗
weights5 = np.kaiser(N, 3)  # 凯泽窗
print("Weights1", weights1)
print("Weights2", weights2)
print("Weights3", weights3)
print("Weights4", weights4)
print("Weights5", weights5)

# 使用convolve()函数计算BHP和VALE的股票收益率,以归一化处理后的weights作为参数
bhp = np.loadtxt('BHP.csv', delimiter=',', usecols=(6,), unpack=True)
bhp_returns = np.diff(bhp) / bhp[: -1]
smooth_bhp1 = np.convolve(weights1/weights1.sum(), bhp_returns)[N-1:-N+1]
smooth_bhp2 = np.convolve(weights2/weights2.sum(), bhp_returns)[N-1:-N+1]
smooth_bhp3 = np.convolve(weights3/weights3.sum(), bhp_returns)[N-1:-N+1]
smooth_bhp4 = np.convolve(weights4/weights4.sum(), bhp_returns)[N-1:-N+1]
smooth_bhp5 = np.convolve(weights5/weights5.sum(), bhp_returns)[N-1:-N+1]

vale = np.loadtxt('VALE.csv', delimiter=',', usecols=(6,), unpack=True)
vale_returns = np.diff(vale) / vale[: -1]
smooth_vale1 = np.convolve(weights1/weights1.sum(), vale_returns)[N-1:-N+1]
smooth_vale2 = np.convolve(weights2/weights2.sum(), vale_returns)[N-1:-N+1]
smooth_vale3 = np.convolve(weights3/weights3.sum(), vale_returns)[N-1:-N+1]
smooth_vale4 = np.convolve(weights4/weights4.sum(), vale_returns)[N-1:-N+1]
smooth_vale5 = np.convolve(weights5/weights5.sum(), vale_returns)[N-1:-N+1]

# 使用多项式拟合平滑后的数据
K = 5
t = np.arange(N - 1, len(bhp_returns))

poly_bhp1 = np.polyfit(t, smooth_bhp1, K)
poly_bhp2 = np.polyfit(t, smooth_bhp2, K)
poly_bhp3 = np.polyfit(t, smooth_bhp3, K)
poly_bhp4 = np.polyfit(t, smooth_bhp4, K)
poly_bhp5 = np.polyfit(t, smooth_bhp5, K)

poly_vale1 = np.polyfit(t, smooth_vale1, K)
poly_vale2 = np.polyfit(t, smooth_vale2, K)
poly_vale3 = np.polyfit(t, smooth_vale3, K)
poly_vale4 = np.polyfit(t, smooth_vale4, K)
poly_vale5 = np.polyfit(t, smooth_vale5, K)

# 解出两个多项式何时取值相等,即在哪些地方存在交叉点。
# 等价于先对两个多项式函数作差,然后对所得的多项式函数求根。使用polysub()函数对多项式作差
poly_sub1 = np.polysub(poly_bhp1, poly_vale1)
xpoints1 = np.roots(poly_sub1)
print("Intersection points1", xpoints1)

poly_sub2 = np.polysub(poly_bhp2, poly_vale2)
xpoints2 = np.roots(poly_sub2)
print("Intersection points2", xpoints2)

poly_sub3 = np.polysub(poly_bhp3, poly_vale3)
xpoints3 = np.roots(poly_sub3)
print("Intersection points3", xpoints3)

poly_sub4 = np.polysub(poly_bhp4, poly_vale5)
xpoints4 = np.roots(poly_sub4)
print("Intersection points4", xpoints4)

poly_sub5 = np.polysub(poly_bhp5, poly_vale5)
xpoints5 = np.roots(poly_sub5)
print("Intersection points5", xpoints5)

# 结果中的复数不利于后续处理,要用isreal()函数来判断数组元素是否为实数
reals1 = np.isreal(xpoints1)
print("Real1 number?", reals1)
reals2 = np.isreal(xpoints2)
print("Real2 number?", reals2)
reals3 = np.isreal(xpoints3)
print("Real3 number?", reals3)
reals4 = np.isreal(xpoints4)
print("Real4 number?", reals4)
reals5 = np.isreal(xpoints5)
print("Real5 number?", reals5)

# select函数可以根据一组给定的条件,从一组元素中挑选出符合条件的元素并返回数组
# 得到的实数交叉点
xpoints1 = np.select([reals1], [xpoints1])
xpoints1 = xpoints1.real    # np.real()实部
print("Real1 intersection points", xpoints1)

xpoints2 = np.select([reals2], [xpoints2])
xpoints2 = xpoints2.real
print("Real2 intersection points", xpoints2)

xpoints3 = np.select([reals3], [xpoints3])
xpoints3 = xpoints3.real
print("Real3 intersection points", xpoints3)

xpoints4 = np.select([reals4], [xpoints4])
xpoints4 = xpoints4.real
print("Real4 intersection points", xpoints4)

xpoints5 = np.select([reals5], [xpoints5])
xpoints5 = xpoints5.real
print("Real5 intersection points", xpoints5)

# 去掉其中为0的元素:trim_zeros()函数可以去掉一维数组中开头和末尾为0的元素
print("Sans1 0s", np.trim_zeros(xpoints1))
print("Sans2 0s", np.trim_zeros(xpoints2))
print("Sans3 0s", np.trim_zeros(xpoints3))
print("Sans4 0s", np.trim_zeros(xpoints4))
print("Sans5 0s", np.trim_zeros(xpoints5))


# 图中的细线为股票收益率,粗线为平滑处理后的结果。图中折线的交叉点可能就是股价趋势的转折点
plot(t, bhp_returns[N-1:], lw=1.0)
plot(t, smooth_bhp1, lw=2.0)
plot(t, smooth_bhp2, lw=2.0)
plot(t, smooth_bhp3, lw=2.0)
plot(t, smooth_bhp4, lw=2.0)
plot(t, smooth_bhp5, lw=2.0)

plot(t, vale_returns[N-1:], lw=1.0)
plot(t, smooth_vale1, lw=2.0)
plot(t, smooth_vale2, lw=2.0)
plot(t, smooth_vale3, lw=2.0)
plot(t, smooth_vale4, lw=2.0)
plot(t, smooth_vale5, lw=2.0)
show()

小结

  使用np.corrcoef()函数计算了两只股票收益率的相关性,diagonal()和trace()函数分别可以给出矩阵的对角线元素和矩阵的迹。使用np.polyfit()函数拟合一系列数据点,用np.polyval()函数计算多项式函数的取值,np.roots()函数求解多项式的根,以及np.polyder()函数求解多项式函数的导函数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

机器视觉小学徒

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值