[pshaiCmd] Z-Score

0 176 Views No Comments 3 months ago
  • Handy custom command for transforming any data series into more normalized type: Z-score

    More information: https://www.investopedia.com/terms/z/zscore.asp


    local close = ClosePrices()
    local zscore = CC_Z_Score(close, 30, 10)
    Plot(0, 'zscore', zscore, LineOptions(Red, Spiked, Solid, 1, 0, LeftAxis, '', true, false))
    PlotHorizontalLine(0, 'z-zero', Gray, 0, Dashed, LeftAxis)
    if CrossOver(zscore, 0) then
        PlotVerticalLine(0, '', Purple, Time(), Dashed)
    elseif CrossUnder(zscore, 0) then
        PlotVerticalLine(0, '', Cyan, Time(), Dashed)
    • This topic was modified 3 months ago by pshai.
    HaasScript Code
    DefineCommand('Z_Score', 'Calculates and outputs the Z-score for a data series.')
    local series = DefineParameter(ListNumberType, 'series', 'Input data series', true, ClosePrices())
    local length = DefineParameter(NumberType, 'length', 'Calculation period length', true, 30, 'Number, Input')
    local opt_length = DefineParameter(NumberType, 'opt_length', 'Optimization length. Use this to cut the amount of data for your needs. Helps optimize backtest speed.', false, 0, 'Number, Input')
    local short
    local s_1
    local s_avg
    local s_diff
    local s_sd
    local x
    local ret = {}
    local len = opt_length > 0 and opt_length or #series - length
    for i=len, 1, -1 do
        short = Grab(series, i, length)
        s_1 = ArrayGet(short, 1)
        s_avg = Average(short)
        s_diff = s_1 - s_avg
        s_sd = Sd(short)
        x = s_diff / s_sd
        ret = ArrayUnshift(ret, x)
    DefineOutput(ListDynamicType, ret, 'Z-Score values for input data series', 'Plot')
Login or Register to Comment

Unlock your crypto trading potential

Create a free account and enjoy everything we have to offer.

Join for Free