Variance Windows
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © pkchari

//@version=5
indicator("Variance windows", overlay=true)
span1 = input(20, title="ShortTerm Analysis span", tooltip="Period for short-term variance estimation")
span2 = input(50, title="LongTerm Analysis span", tooltip="Period for Long-term variance estimation")
emaSize = input(55, title = "ZLEMA Size", tooltip = "Length of Zero-lag EMA used as the centerline")
errorBar = input(2.0, "Num Std Deviations", tooltip="How many standard deviations wide should the windows be")

// NOTE : for Error Bars, you can essentially treat it like a normal distribution z-score
// +/- 1 sigma = 68% chance that price will stay within this range
// +/- 2 sigma = 95% chance ...
// +/- 3 sigma = 99.7% chance ...
// For fractional standard deviations, you can do things like
// +/- 0.5 sigma = 38.3% chance of price staying within these windows
// +/- 1.5 sigma = 86.6% chance of staying of in the windowed range
// +/- 1.644444 sigma = 90% chance
// +/- 1.15 sigma = 75% chance
// +/- 0.675 sigma = 50% chance

// Yeah, I know, SMA is more pedantically correct for this computation of variance,
// but using EMA is giving some slightly better results in terms of readability of the chart.
sma1 = ta.ema(close, span1) * ta.ema(close, span1)
sma2 = ta.ema(close * close, span1)
shortSigma = math.sqrt(sma2 - sma1)

sma1b = ta.ema(close, span2) * ta.ema(close, span2)
sma2b = ta.ema(close * close, span2)
longSigma = math.sqrt(sma2b - sma1b)

emaData = close + (close - close[(emaSize - 1)*0.5])
followCurve = ta.ema(emaData, emaSize)

plot(followCurve + errorBar*shortSigma, title="+2Sigma(short)", color=color.green, linewidth=1, editable=true)
plot(followCurve - errorBar*shortSigma, title="-2Sigma(short)", color=color.blue, linewidth=1, editable=true)
plot(followCurve + errorBar*longSigma, title="+2Sigma(long)", color=color.teal, linewidth=2, editable=true)
plot(followCurve - errorBar*longSigma, title="-2Sigma(long)", color=color.purple, linewidth=2, editable=true)
// Another option -- plot variances (standard deviation, really) as percentages (in this case, turn overlay=false)
// plot(100 * errorBar * shortSigma / math.sqrt(sma1), title="Short Term Sigma", color=color.green, linewidth=1, editable=true)
// plot(100 * errorBar * longSigma / math.sqrt(sma1b), title="Long Term Sigma", color=color.blue, linewidth=2, editable=true)
