我正在尝试在Pine Script中制作Spearman等级相关系数脚本。我的问题是,有时它会下降到两位数的负值。该脚本是对内置的correlation()(皮尔逊系数)函数的压缩,我的斯皮尔曼的行为有所不同。所以我认为我的数学一定有问题,还是这是Spearman相关的预期行为?
这是脚本:
//@version=4
study("Spearman Rank Correlation Coefficient [ChuckBanger]", shorttitle="Spearman Correlation CB", precision=3)
length = input(title="Length", type=input.integer, defval=20)
sym1 = input(title="1st Symbol", type=input.symbol, defval="BITMEX:XBTUSD")
sym2 = input(title="2nd Symbol", type=input.symbol, defval="BITMEX:ETHUSD")
src = input(title="Source", type=input.source, defval=close)
data1 = security(sym1, timeframe.period, src)
data2 = security(sym2, timeframe.period, src)
rankit(x, n) =>
int r=0, int s=0
float rank = na
for i = 0 to n by 1
r:=1,s:=1
for j = 0 to i by 1
if (x[j] < x[i])
r := r + 1
if (x[j] == x[i])
s := s + 1
for k = i + 1 to n by 1
if (x[k] < x[i])
r := r + 1
if (x[k] == x[i])
s := s + 1
rank := r + (s - 1) * 0.5
correlationCoefficient(X, Y, n) =>
float sum_X = 0
float sum_Y = 0
float sum_XY = 0
float squareSum_X = 0
float squareSum_Y = 0
for i = 0 to n by 1
// sum of elements of array X.
sum_X := nz(sum_X) + X[i]
// sum of elements of array Y.
sum_Y := nz(sum_Y) + Y[i]
// sum of X[i] * Y[i].
sum_XY := nz(sum_XY) + X[i] * Y[i]
// sum of square of array elements.
squareSum_X := squareSum_X + X[i] * X[i]
squareSum_Y := squareSum_Y + Y[i] * Y[i]
corr = (n * sum_XY - sum_X * sum_Y) / sqrt((n *
squareSum_X - sum_X * sum_X) * (n * squareSum_Y - sum_Y * sum_Y))
corr
spearman(data1, data2, length) =>
rank_x = rankit(data1, length)
rank_y = rankit(data2, length)
correlationCoefficient(rank_x, rank_y, length)
spear = spearman(data1, data2, length)
spearCorr = sym1 == sym2 ? 1 : spear
pearsonCorr = correlation(data1, data2, length)
plot(spearCorr, title="Spearman", color=color.orange, transp=0)
plot(pearsonCorr, title="Pearson", color=color.purple, transp=0)