天天看點

python怎麼計算相關系數_Python三種方法計算皮爾遜相關系數

1、皮爾遜相關系數在統計學中,皮爾遜相關系數( Pearson correlation coefficient),又稱皮爾遜積矩相關系數(Pearson product-moment correlation coefficient,簡稱 PPMCC或PCCs)。用于衡量兩個變量X和Y之間的線性相關相關關系,值域在-1與1之間。

python怎麼計算相關系數_Python三種方法計算皮爾遜相關系數

2、根據公式手寫

import numpy as np

import pandas as pdfrom math import *

def multipl(a,b):

sumofab=0.0

for i in range(len(a)):

temp=a[i]*b[i]

sumofab+=temp

return sumofab

def cal_pccs(x,y):

n=len(x)

#求和

sum1=sum(x)

sum2=sum(y)

#求乘積之和

sumofxy=multipl(x,y)

#求平方和

sumofx2 = sum([pow(i,2) for i in x])

sumofy2 = sum([pow(j,2) for j in y])

num=sumofxy-(float(sum1)*float(sum2)/n)

#計算皮爾遜相關系數

den=sqrt((sumofx2-float(sum1**2)/n)*(sumofy2-float(sum2**2)/n))

return num/den

pct_chg = pd.Series({'000001.SZ':-1.7391, '000002.SZ':0.6250,'000004.SZ':1.1378,'002600.SZ':0.0000,'000010.SZ':-1.0013})

vol = pd.Series({'000001.SZ':249326.31,'000002.SZ':338224.97,'000004.SZ':211876.00,'000010.SZ':222782.00,'002600.SZ':342096.76})

print(cal_pccs(pct_chg, vol))

3、talib的函數

import talib as ta

import pandas as pdpct_chg = pd.Series({'000001.SZ':-1.7391, '000002.SZ':0.6250,'000004.SZ':1.1378,'002600.SZ':0.0000,'000010.SZ':-1.0013})

vol = pd.Series({'000001.SZ':249326.31,'000002.SZ':338224.97,'000004.SZ':211876.00,'000010.SZ':222782.00,'002600.SZ':342096.76})

print(ta.CORREL(pct_chg,vol,5)[-1])

4、numpy的函數

import numpy as np

import pandas as pd

pct_chg = pd.Series({'000001.SZ':-1.7391, '000002.SZ':0.6250,'000004.SZ':1.1378,'002600.SZ':0.0000,'000010.SZ':-1.0013})

vol = pd.Series({'000001.SZ':249326.31,'000002.SZ':338224.97,'000004.SZ':211876.00,'000010.SZ':222782.00,'002600.SZ':342096.76})

pccs = np.corrcoef(pct_chg, vol)

print(pccs[0][1])

5、scipy的函數

import numpy as np

import pandas as pd

from scipy.stats import pearsonr

pct_chg = pd.Series({'000001.SZ':-1.7391, '000002.SZ':0.6250,'000004.SZ':1.1378,'002600.SZ':0.0000,'000010.SZ':-1.0013})

vol = pd.Series({'000001.SZ':249326.31,'000002.SZ':338224.97,'000004.SZ':211876.00,'000010.SZ':222782.00,'002600.SZ':342096.76})

pccs = pearsonr(pct_chg, vol)

print(pccs[0])

- END -

轉載:感謝您對張偉江個人部落格網站平台的認可,以及對我們原創作品以及文章的青睐,非常歡迎各位朋友分享到個人站長或者朋友圈,但轉載請說明文章出處“來源張偉江個人部落格”。