1 import numpy as np 2 from matplotlib.pyplot import plot 3 from matplotlib.pyplot import show 4 5 bhp = np.loadtxt('BHP.csv', delimiter=',', usecols=(6,), unpack=True) 6 7 bhp_returns = np.diff(bhp) / bhp[ : -1] 8 9 vale = np.loadtxt('VALE.csv', delimiter=',', usecols=(6,), unpack=True) 10 11 vale_returns = np.diff(vale) / vale[ : -1] 12 13 covariance = np.cov(bhp_returns, vale_returns) 14 print("Covariance", covariance) 15 16 print ("Covariance diagonal", covariance.diagonal()_ 17 print( "Covariance trace", covariance.trace()) 18 19 print (covariance/ (bhp_returns.std() * vale_returns.std())) 20 21 print ("Correlation coefficient", np.corrcoef(bhp_returns, vale_returns)) 22 23 difference = bhp - vale 24 avg = np.mean(difference) 25 dev = np.std(difference) 26 27 print ("Out of sync", np.abs(difference[-1] - avg) > 2 * dev) 28 29 t = np.arange(len(bhp_returns)) 30 plot(t, bhp_returns, lw=1) 31 plot(t, vale_returns, lw=2) 32 show()
参考资料:《Numpy学习指南》