Return Abnormality Score [SpiritualHealer117]
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © spiritualhealer117

//@version=5
indicator("Return Abnormality Score [SpiritualHealer117]")
import spiritualhealer117/Statistical_Tool_Pack/3 as statistics

sr_len = input.int(14, "Short Run Length", group="Input")
lr_len = input.int(300,"Long Run Length", group ="Input")
src = input.source(close,"Source", group="Input")

significance_level = input.float(0.2,"Significance Level", group="Indicator Settings")
smo = input.string("Smoothed", "Mode",["Smoothed","Unsmoothed"],group="Indicator Settings")

clr1 = input.color(#4caf50,"Bull Color", group="Style")
clr2 = input.color(#f8bbd0,"Bear Color", group="Style")
outlier_transp = input.int(60, "Default Outlier Transparency", group = "Style")
norm_transp = input.int(100, "Normal Transparency", group = "Style")

ret = (src-src[1])/src[1]
mu = ta.ema(ret,lr_len)
sigma = ta.stdev(ret,lr_len)
mu_sr = ta.ema(ret,sr_len)
sigma_sr = ta.stdev(ret,sr_len)

lr_price_abnormality = statistics.normcdf(x=ret,mu=mu,sigma=sigma)*(ret>0?1:-1)
sr_price_abnormality = statistics.normcdf(x=ret,mu=mu_sr,sigma=sigma_sr)*(ret>0?1:-1)
lr_smoothed_abnormality = ta.swma(lr_price_abnormality)
sr_smoothed_abnormality = ta.swma(sr_price_abnormality)

lr_abnormality = smo=="Smoothed"?lr_smoothed_abnormality:lr_price_abnormality
sr_abnormality = smo=="Smoothed"?sr_smoothed_abnormality:sr_price_abnormality

cond1 = lr_abnormality > 1-significance_level or sr_abnormality > 1 - significance_level
cond2 = lr_abnormality < significance_level-1 or sr_abnormality < significance_level - 1
indic_clr = color.new(sr_abnormality>lr_abnormality?clr1:clr2,(cond1 or cond2)?100-norm_transp:100-outlier_transp)
l1=plot(smo=="Smoothed"?lr_smoothed_abnormality:lr_price_abnormality, color=indic_clr, style=plot.style_columns)
hline(1-significance_level)
hline(significance_level-1)