Library · Pine Script v5 · Library

KernelFunctions

by artificial-intelligence-edge· code credited to jdehorty

KernelFunctions is a Pine Script v5 library that exports kernel weight functions for Nadaraya-Watson style estimation.

View on GitHub

GitHub stars75on the repository
Pine versionv5runs as is
Lines of code87
Settings0inputs
LicenceMIT
Last update2 days ago26 Oct 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new library, select all of the template text and paste. Press Save and give it a name.
  4. 4Publish or import itA library draws nothing. Publish it from the editor, then import its functions in your own scripts.

Source Code

87 lines of Pine Script v5 from ports/pinescript/libraries/KernelFunctions.pine, published under MIT. Keep the author's credit and licence lines when you reuse it.

KernelFunctions.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © jdehorty
// @version=5

// @description This library provides non-repainting kernel functions for Nadaraya-Watson estimator implementations. This allows for easy substition/comparison of different kernel functions for one another in indicators. Furthermore, kernels can easily be combined with other kernels to create newer, more customized kernels.
library("KernelFunctions", true)

// @function Rational Quadratic Kernel - An infinite sum of Gaussian Kernels of different length scales.
// @param _src <float series> The source series.
// @param _lookback <simple int> The number of bars used for the estimation. This is a sliding value that represents the most recent historical bars.
// @param _relativeWeight <simple float> Relative weighting of time frames. Smaller values resut in a more stretched out curve and larger values will result in a more wiggly curve. As this value approaches zero, the longer time frames will exert more influence on the estimation. As this value approaches infinity, the behavior of the Rational Quadratic Kernel will become identical to the Gaussian kernel.
// @param _startAtBar <simple int> Bar index on which to start regression. The first bars of a chart are often highly volatile, and omission of these initial bars often leads to a better overall fit.
// @returns yhat <float series> The estimated values according to the Rational Quadratic Kernel.
export rationalQuadratic(series float _src, simple int _lookback, simple float _relativeWeight, simple int startAtBar) =>
    float _currentWeight = 0.
    float _cumulativeWeight = 0.
    _size = array.size(array.from(_src))
    for i = 0 to _size + startAtBar
        y = _src[i]
        w = math.pow(1 + (math.pow(i, 2) / ((math.pow(_lookback, 2) * 2 * _relativeWeight))), -_relativeWeight)
        _currentWeight += y*w
        _cumulativeWeight += w
    yhat = _currentWeight / _cumulativeWeight
    yhat

// @function Gaussian Kernel - A weighted average of the source series. The weights are determined by the Radial Basis Function (RBF).
// @param _src <float series> The source series.
// @param _lookback <simple int> The number of bars used for the estimation. This is a sliding value that represents the most recent historical bars.
// @param _startAtBar <simple int> Bar index on which to start regression. The first bars of a chart are often highly volatile, and omission of these initial bars often leads to a better overall fit.
// @returns yhat <float series> The estimated values according to the Gaussian Kernel.
export gaussian(series float _src, simple int _lookback, simple int startAtBar) =>
    float _currentWeight = 0.
    float _cumulativeWeight = 0.
    _size = array.size(array.from(_src))
    for i = 0 to _size + startAtBar
        y = _src[i] 
        w = math.exp(-math.pow(i, 2) / (2 * math.pow(_lookback, 2)))
        _currentWeight += y*w
        _cumulativeWeight += w
    yhat = _currentWeight / _cumulativeWeight
    yhat

// @function Periodic Kernel - The periodic kernel (derived by David Mackay) allows one to model functions which repeat themselves exactly.
// @param _src <float series> The source series.
// @param _lookback <simple int> The number of bars used for the estimation. This is a sliding value that represents the most recent historical bars.
// @param _period <simple int> The distance between repititions of the function.
// @param _startAtBar <simple int> Bar index on which to start regression. The first bars of a chart are often highly volatile, and omission of these initial bars often leads to a better overall fit.
// @returns yhat <float series> The estimated values according to the Periodic Kernel.
export periodic(series float _src, simple int _lookback, simple int _period, simple int startAtBar) =>
    float _currentWeight = 0.
    float _cumulativeWeight = 0.
    _size = array.size(array.from(_src))
    for i = 0 to _size + startAtBar
        y = _src[i]
        w = math.exp(-2*math.pow(math.sin(math.pi * i / _period), 2) / math.pow(_lookback, 2))
        _currentWeight += y*w
        _cumulativeWeight += w
    yhat = _currentWeight / _cumulativeWeight
    yhat

// @function Locally Periodic Kernel - The locally periodic kernel is a periodic function that slowly varies with time. It is the product of the Periodic Kernel and the Gaussian Kernel.
// @param _src <float series> The source series.
// @param _lookback <simple int> The number of bars used for the estimation. This is a sliding value that represents the most recent historical bars.
// @param _period <simple int> The distance between repititions of the function.
// @param _startAtBar <simple int> Bar index on which to start regression. The first bars of a chart are often highly volatile, and omission of these initial bars often leads to a better overall fit.
// @returns yhat <float series> The estimated values according to the Locally Periodic Kernel.
export locallyPeriodic(series float _src, simple int _lookback, simple int _period, simple int startAtBar) =>
    float _currentWeight = 0.
    float _cumulativeWeight = 0.
    _size = array.size(array.from(_src))
    for i = 0 to _size + startAtBar
        y = _src[i]
        w = math.exp(-2*math.pow(math.sin(math.pi * i / _period), 2) / math.pow(_lookback, 2)) * math.exp(-math.pow(i, 2) / (2 * math.pow(_lookback, 2)))
        _currentWeight += y*w
        _cumulativeWeight += w
    yhat = _currentWeight / _cumulativeWeight
    yhat

// Examples:
yhat1 = rationalQuadratic(close, 8, 1, 25)
yhat2 = gaussian(close, 16, 25)
yhat3 = periodic(close, 8, 100, 25)
yhat4 = locallyPeriodic(close, 8, 24, 25)
plot(yhat1, color = color.red, title = "Rational Quadratic Kernel")
plot(yhat2, color = color.yellow, title = "Gaussian Kernel")
plot(yhat3, color = color.green, title = "Periodic Kernel")
plot(yhat4, color = color.aqua, title = "Locally Periodic Kernel")

Overview

KernelFunctions calculates a Rational Quadratic kernel, a Gaussian kernel based on a radial basis function, and a periodic kernel that models repeating behavior. Callers pass a source series, lookback length, and a start bar, plus relative weight or period where required. The library returns estimated series values and draws nothing itself. Its description states the kernels are non-repainting. It has no chart inputs and no trading rules.

Details

Published by

artificial-intelligence-edge on GitHub

Code credit

jdehorty, as written in the script's header

Type

Library, Pine Script v5

Draws

Library (no plots)

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

261 stars

AIActivationFunctionsBipolarSigmoid is a Pine Script library that provides mathematical implementations of the bipolar sigmoid activation function and its derivatives for machine learning algorithms. It calculates bipolar sigmoid values bounded between -1 and

Library v5 AI / machine learning
Updated 4 years ago · None stated GitHub repository of AIActivationFunctionsBipolarSigmoid

Ta

by nersent
29 stars

This Pine Script v5 library exports thin wrappers around built-in technical analysis functions. It covers moving averages, momentum measures such as RSI and CCI, volatility tools including ATR and standard deviation, range extremes, cross detection, and runnin

Library v5
Updated 11 months ago · Custom licence GitHub repository of Ta

Bands

by heyphat
26 stars

This library exports a Band type and functions that build a simple-moving-average basis with upper and lower envelopes from standard deviation. It classifies a source as above, below, or inside those envelopes, measures band width, and scales an imported z-sco

Library v6 Volatility & bandsMoving averages
Updated 2 months ago · AGPL-3.0 GitHub repository of Bands

Mylib

by ferranbt
21 stars

This script serves as a minimal utility library written in Pine Script v6. It provides an exported helper function that calculates the sum of two numeric arguments. As a reusable code library, it produces no visual plots, charts, or trading signals, and it con

Library v6
Updated 7 weeks ago · MPL-2.0 GitHub repository of Mylib

HLevel

by stupenkov
14 stars

HLevel is a Pine Script v5 utility library designed to manage horizontal price levels for cryptocurrency charts. It defines custom types for pivots and levels, along with methods to initialize, add, track, and expire price levels based on pivot high and pivot

Library v5
Updated 3 years ago · None stated GitHub repository of HLevel

Zignaly2Beta

by ruckard
13 stars

This library provides helper functions to format and build JSON webhook alert payloads for the Zignaly automated trading platform. It constructs formatted messages containing parameters such as trading pair, exchange, account type, leverage, margin mode, hedge

Library v5
Updated 1 year ago · None stated GitHub repository of Zignaly2Beta

More libraries

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers