Linear Correlation Coefficient W/ MAs and Significance Tests
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © jsalemfinancial

//@version=5
indicator("Linear Correlation Coefficient")
partner = math.log(nz(request.security(input.symbol(defval="QQQ", title="Security"), timeframe.period, close)))
len = input.int(defval=31, title="Period", minval=16)

cc(sec1, sec2, len) => // Correlation Coefficent function, credit @balipour for structure.
    sec1_sum = 0.0, sec2_sum = 0.0
    for i=0 to (len-1)
        sec1_sum := sec1_sum + nz(sec1[i])
        sec2_sum := sec2_sum + nz(sec2[i])
        
    sec1_mean = sec1_sum / len
    sec2_mean = sec2_sum / len
    
    sum12=0.0, sum1=0.0, sum2=0.0
    for i=0  to (len-1)
        sum12 := sum12 +    (nz(sec1[i]) - sec1_mean) * (nz(sec2[i]) - sec2_mean)
        sum1  := sum1  + math.pow(nz(sec1[i]) - sec1_mean, 2)
        sum2  := sum2  + math.pow(nz(sec2[i]) - sec2_mean, 2)
        
    sum12 / math.sqrt(sum1 * sum2)
    
coeff = cc(math.log(close), partner, len)

t_score = coeff*math.sqrt(len-2)/math.sqrt(1-math.pow(coeff, 2)) //Hypothesis: H_0: p = 0. Use sample of size > 30 as it is two-tail.

zelen_severo_consts = array.new_float(6) //array for the taylor approximation coefficients.

array.set(zelen_severo_consts, 0, 0.2316419), array.set(zelen_severo_consts, 1, 0.319381530), array.set(zelen_severo_consts, 2, -0.356563782)
array.set(zelen_severo_consts, 3, 1.781477937), array.set(zelen_severo_consts, 4, -1.821255978), array.set(zelen_severo_consts, 5,  1.330274429)

zsc(index) =>
    array.get(zelen_severo_consts, index)

PI = 3.1415926535
E = 2.7182818284

T = 1/(1 + zsc(0)*t_score)

p_normal_cdf = 1 - ((math.pow(E, -math.pow(t_score, 2)/2)/(math.sqrt(2*PI))) * 
     (zsc(1)*T + zsc(2)*math.pow(T,2) + zsc(3)*math.pow(T,3) + zsc(4)*math.pow(T,4) + zsc(5)*math.pow(T,5))) + math.pow(10, -5)

bar_color = if p_normal_cdf < 0.05 or p_normal_cdf > 0.95
    color.yellow
else
    color.olive

band1 = hline(0.5, color=color.gray)
band2 = hline(0.7, color=color.gray)
band3 = hline(-0.5, color=color.gray)
band4 = hline(-0.7, color=color.gray)
fill(band1, band2, color=color.rgb(0, 150, 0, 90))
fill(band3, band4, color=color.rgb(150, 95, 0, 90))

hline(0, color=color.gray, linestyle=hline.style_solid)
plot(coeff, color=bar_color, linewidth=3, style=plot.style_histogram)
plot(ta.sma(coeff, input.int(defval=50, title="SMA Long")), color=color.blue)
plot(ta.sma(coeff, input.int(defval=9, title="SMA Short")), color=color.red)