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

//@version=5
indicator(title="gZScore", shorttitle="gZScore", overlay=false, precision=2)

//252 days in one year
length = input(252, title="Length on timeframe daily")

source = input(close, title="Source")
color_score = input.color(color.white, "Z-Score")
color_average = input.color(color.white, "Average")
//Z-score is a standardized measure of displacement from the mean; z = (x –  x̄) /s̄. 
//Standardization allows the displacement to be compared between different sources, even if their values are significantly different.

//mean over last day
if timeframe.period == '5'
    length := 1440/5
//mean over last week
if timeframe.period == '30'
    length := (1440/30)*5
//mean over last month
if timeframe.period == '240'
    length := (1440/240)*4
//mean over last year
if timeframe.period == 'D'
    length := length
//mean over last 3 year
if timeframe.period == 'W'
    length := 52 * 3
//mean over last 5 year
if timeframe.period == 'M'
    length := 12 * 5


mean=ta.sma(source,length)
float deviation=ta.stdev(source,length)
float displacement=source-mean
float zscore=displacement/deviation


zmean=ta.sma(zscore,length)

//Plots
plot(zscore,color=color_score,title="Z-Score", linewidth = 2)
plot(zmean,title="Z-Score Average", color = color_average, linewidth = 1)

plot(0, title = 'ZScore 0' ) //mean
plot(1, color = color.yellow, title = 'ZScore 1')
plot(-1, color = color.yellow, title = 'ZScore -1')
plot(-2, color = color.orange, title = 'ZScore -2')
plot(2, color = color.orange, title = 'ZScore 2')
plot(-3, color = color.red, title = 'ZScore -3')
plot(3, color = color.red, title = 'ZScore 3')
plot(-5, color = color.red, linewidth = 2, title = 'ZScore -5')
plot(5, color = color.red, linewidth = 2, title = 'ZScore 5')