Variance
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © moot-al-cabal

//@version=4
study(title="Variance", shorttitle="Variance")
LR = "Logarithmic Returns"
PR = "Price"
HP = input(PR,"Variance mode", options=[LR,PR])
logr = log(close/close[1])*100
src = if HP == LR
    logr
else if HP == PR
    close
else
    na
source = src
lookback =input(20, "Variance Lookback")
annual = 30

mean = sma(source, lookback)
s = array.new_float(0)
for i = 0 to lookback-1 
    array.push(s,pow(source[i]-mean,2))
sum = array.sum(s)

variance = sum/(lookback-1)
stdev = sqrt(variance)
emaperiod = 20
ema1 = ema(variance, emaperiod)
//plot(variance)

source2 = variance
lookback2 = input(20, minval=1, title="Variance filter lookback")
length22 = input(14, minval=1, title="EMA length")
stdv = stdev(source2, lookback2)
ma = sma(source2, lookback2)
zsc = (source2 - ma) / stdv
ema = ema(zsc, length22)
v=if zsc > 2

    color.red

else if zsc < -2

    color.green

else

    color.white
colorema = if zsc > ema 
    color.green
else if zsc < ema
    color.red
else
    na
plot(ema, color=colorema)
plot(zsc, color=v, title="Variance")
transporange = color.new(color.orange, 70)
transpyellow = color.new(color.yellow, 70)
transppurp = color.new(color.purple, 50)
transpblue = color.new(color.blue, 50)
hline(0, color=color.gray, linestyle=hline.style_dotted)
hline(1, color=transppurp, linestyle=hline.style_dashed)
hline(-1, color=transpblue, linestyle=hline.style_dashed)
hline(2, color=transporange, linestyle=hline.style_solid)
hline(-2, color=transpyellow, linestyle=hline.style_solid)
hline(3, color=color.red, linestyle=hline.style_solid)
hline(-3, color=color.green, linestyle=hline.style_solid)





