[pshaiCmd] Z-Score

stable
By pshai in Oscillators Published October 2020 👁 1,720 views 💬 0 comments

Description

Handy custom command for transforming any data series into more normalized type: Z-score More information: https://www.investopedia.com/terms/z/zscore.asp Example:
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)
end
HaasScript
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)
end


DefineOutput(ListDynamicType, ret, 'Z-Score values for input data series', 'Plot')

0 Comments

Sign in to leave a comment.

No comments yet. Be the first!