[DMcL] Nadaraya-Watson Kernel
betaDescription
I like it on 6h or 12h timeframe
HaasScript
-- original script by jdehorty on tradingview
-- Author: DMcL
EnableHighSpeedUpdates(true)
DefineCommand('Nadaraya_Watson_Kernel', 'Signals long or short when kernel changes bullish/bearish')
-- Parameters
local alpha = DefineParameter(NumberType, 'Alpha', 'NQK Alpha', true, 2)
local h = DefineParameter(NumberType, 'Lookback Window', 'Lookback Window', true, 44)
local r = DefineParameter(NumberType, 'Relative Weighting', 'Relative Weighting', true, 6)
local x_0 = DefineParameter(NumberType, "Start Regression at Bar", "Start Regression at Bar", true, 44)
-- Data
local close = ClosePrices()
local high = HighPrices()
local ohlc = OHLCPrices()
local low = LowPrices()
local smoothColors = Input("Smooth Colors", false)
local lag = Input("Lag", 2)
-- Kernel function
local function kernel_regression (_src, _alpha, _r, _h)
local _currentWeight = 0
local _cumulativeWeight = 0
for i = 1, _alpha + x_0 do
local y = _src[i]
local w = Pow( 1 + (Pow(i, 2) / (Pow(_h, 2) * 2 * _r )), -_r)
_currentWeight = _currentWeight + (y*w)
_cumulativeWeight = _cumulativeWeight + w
end
return _currentWeight / _cumulativeWeight
end
-- Estimations
local yhat1 = kernel_regression(ohlc, alpha, r, h)
local yhat2 = kernel_regression(ohlc, alpha, r, h - lag)
-- Rates of Change
local wasBearish = yhat1[3] > yhat1[2]
local wasBullish = yhat1[3] < yhat1[2]
local isBearish = yhat1[2] > yhat1[1]
local isBullish = yhat1[2] < yhat1[1]
local isBearishChange = isBearish and wasBullish
local isBullishChange = isBullish and wasBearish
-- Crossovers
local isBullishCross = CrossOver(yhat2[1], yhat1[1])
local isBearishCross = CrossUnder(yhat2[1], yhat1[1])
local isBullishSmooth = yhat2[1] > yhat1[1]
local isBearishSmooth = yhat2[1] < yhat1[1]
-- // Alert Variables
local alertBullish = smoothColors and isBullishCross or isBullishChange
local alertBearish = smoothColors and isBearishCross or isBearishChange
-- Plot
local guid = Load("guid",NewGuid())
local green = Load('green', false)
local red = Load('red', false)
if alertBullish then
green = true
red = false
guid = NewGuid()
Save("guid",guid)
end
if alertBearish then
green = false
red = true
guid = NewGuid()
Save("guid",guid)
end
Save('green', green)
Save('red', red)
if green == true then
Plot(0, "Bullish Rational Quadratic Kernel Estimate", yhat1, {color=Green, id=guid, width=3})
end
if red == true then
Plot(0, "Bearish Rational Quadratic Kernel Estimate", yhat1, {color=Red, id=guid, width=3})
end
-- signal
local signal = SignalNone
if alertBullish then
signal = SignalLong
PlotShape(0, ShapeTriangleUp, DarkGreen, 5, false)
end
if alertBearish then
signal = SignalShort
PlotShape(0, ShapeTriangleDown, Red, 5, true)
end
DefineOutput(EnumType, signal)
1 Comment
Sign in to leave a comment.
thnx .Good job