Library · Pine Script v5 · Library

MathStatisticsKernelFunctions

by ricardosantos79· code credited to RicardoSantos

MathStatisticsKernelFunctions is a Pine Script utility library providing statistical kernel weighting functions, including uniform, triangular, Epanechnikov, quartic, triweight, and tricubic kernels.

View on GitHub

GitHub stars261on the repository
Pine versionv5runs as is
Lines of code197
Settings2inputs
LicenceNone statedfile: MPL-2.0
Last update4 years ago13 Nov 2021

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

197 lines of Pine Script v5 from beta/libs/Math/Statistics/MathStatisticsKernelFunctions.pinescript, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

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

//@version=5

// @description TODO: add library description here
library(title='MathStatisticsKernelFunctions')

// reference:
//      list: https://en.wikipedia.org/wiki/Kernel_%28statistics%29
//      


//    y+
//      |    ---------------------------------    
//      |    |               |               |
//      |    |               |               |
//      |    |               |               |
//   -x -----o---------------o---------------o------ +x
//      -bandwidth      origin (0)      +bandwidth

// @function Uniform kernel.
// @param distance float, distance to kernel origin.
// @param bandwidth float, default=1.0, bandwidth limiter to weight the kernel.
// @returns float.
export uniform (float distance, float bandwidth=1.0) => //{
    if math.abs(distance) > bandwidth
        0.0
    else
        0.5
//{ usage
// b = -1 + (bar_index%100) * 0.02,  plot(uniform(b, 0.9), color=color.red), plot(b, color=color.silver)
//{ remarks:
//}}}

// @function Triangular kernel.
// @param distance float, distance to kernel origin.
// @param bandwidth float, default=1.0, bandwidth limiter to weight the kernel.
// @returns float.
export triangular (float distance, float bandwidth=1.0) => //{
    if math.abs(distance) > bandwidth
        0.0
    else
        1.0 -  math.abs(distance / bandwidth)
//{ usage
// b = -1.0 + (bar_index%100) * 0.02,  plot(triangular(b, 0.75)), plot(b, color=color.red)
//{ remarks:
//}}}

// @function Epanechnikov kernel.
// @param distance float, distance to kernel origin.
// @param bandwidth float, default=1.0, bandwidth limiter to weight the kernel.
// @returns float.
export epanechnikov (float distance, float bandwidth=1.0) => //{
    if math.abs(distance) > bandwidth
        0.0
    else
        0.25 * (1.0 - math.pow(distance/bandwidth, 2.0))
//{ usage
// b = -1 + (bar_index%100) * 0.02,  plot(epanechnikov(b, 0.9)), plot(b, color=color.red)
//{ remarks:
//}}}

// @function Quartic kernel.
// @param distance float, distance to kernel origin.
// @param bandwidth float, default=1.0, bandwidth limiter to weight the kernel.
// @returns float.
export quartic (float distance, float bandwidth=1.0) => //{
    if math.abs(distance) > bandwidth
        0.0
    else
        0.9375 * math.pow(1.0 - math.pow(distance/bandwidth, 2.0), 2.0)
//{ usage
// b = -1 + (bar_index%100) * 0.02,  , plot(b, color=color.red)
//{ remarks:
//}}}

// @function Triweight kernel.
// @param distance float, distance to kernel origin.
// @param bandwidth float, default=1.0, bandwidth limiter to weight the kernel.
// @returns float.
export triweight (float distance, float bandwidth=1.0) => //{
    if math.abs(distance) > bandwidth
        0.0
    else
        (35.0 / 32.0) * math.pow(1.0 - math.pow(distance/bandwidth, 2.0), 3.0)
//{ usage
// b = -1 + (bar_index%100) * 0.02,  plot(triweight(b, 0.9)), plot(b, color=color.red)
//{ remarks:
//}}}

// @function Tricubic kernel.
// @param distance float, distance to kernel origin.
// @param bandwidth float, default=1.0, bandwidth limiter to weight the kernel.
// @returns float.
export tricubic (float distance, float bandwidth=1.0) => //{
    if math.abs(distance) > bandwidth
        0.0
    else
        (70.0 / 81.0) * math.pow(1.0 - math.pow(math.abs(distance)/bandwidth, 3.0), 3.0)
//{ usage
// b = -1 + (bar_index%100) * 0.02,  plot(tricubic(b, 0.9)), plot(b, color=color.red)
//{ remarks:
//}}}

// @function Gaussian kernel.
// @param distance float, distance to kernel origin.
// @param bandwidth float, default=1.0, bandwidth limiter to weight the kernel.
// @returns float.
export gaussian (float distance, float bandwidth=1.0) => //{
    1.0 / math.sqrt(2.0 * math.pi) * math.pow(math.e, -0.5 * math.pow(distance / bandwidth, 2.0))
//{ usage
// b = -math.pi + (bar_index%100) * (math.pi*0.02),  plot(b, color=color.red), plot(gaussian(b, 3.0)), plot(gaussian(b, 2.0), color=color.aqua), plot(gaussian(b, 1.0), color=color.yellow)
//{ remarks:
//}}}

// @function Cosine kernel.
// @param distance float, distance to kernel origin.
// @param bandwidth float, default=1.0, bandwidth limiter to weight the kernel.
// @returns float.
export cosine (float distance, float bandwidth=1.0) => //{
    if math.abs(distance) > bandwidth
        0.0
    else
        (math.pi / 4.0) * math.cos(math.pi / 2.0 * (distance / bandwidth))
//{ usage
// b = -1 + (bar_index%100) * 0.02,  plot(cosine(b, 0.5)), plot(b, color=color.red)
//{ remarks:
//}}}

// @function logistic kernel.
// @param distance float, distance to kernel origin.
// @param bandwidth float, default=1.0, bandwidth limiter to weight the kernel.
// @returns float.
export logistic (float distance, float bandwidth=1.0) => //{
    _d = distance / bandwidth
    1.0 / (math.pow(math.e, _d) + 2.0 + math.pow(math.e, -_d))
//{ usage
// b = -1 + (bar_index%100) * 0.02,  plot(logistic(b, 0.1)), plot(b, color=color.red)
//{ remarks:
//}}}

// @function Sigmoid kernel.
// @param distance float, distance to kernel origin.
// @param bandwidth float, default=1.0, bandwidth limiter to weight the kernel.
// @returns float.
export sigmoid (float distance, float bandwidth=1.0) => //{
    _d = distance / bandwidth
    2.0 / math.pi * (1.0 / (math.pow(math.e, _d) + math.pow(math.e, -_d)))
//{ usage
// b = -1 + (bar_index%100) * 0.02,  plot(sigmoid(b, 0.1)), plot(b, color=color.red)
//{ remarks:
//}}}

// @function Kernel selection method.
// @param kernel string, kernel to select. (options="uniform", "triangle", "epanechnikov", "quartic", "triweight", "tricubic", "gaussian", "cosine", "logistic", "sigmoid")
// @param distance float, distance to kernel origin.
// @param bandwidth float, default=1.0, bandwidth limiter to weight the kernel.
// @returns float.
export select (string kernel, float distance, float bandwidth=1.0) => //{
    switch (kernel)
        'uniform' => uniform(distance, bandwidth)
        'triangle' => triangular(distance, bandwidth)
        'epanechnikov' => epanechnikov(distance, bandwidth)
        'quartic' => quartic(distance, bandwidth)
        'triweight' => triweight(distance, bandwidth)
        'tricubic' => tricubic(distance, bandwidth)
        'gaussian' => gaussian(distance, bandwidth)
        'cosine' => cosine(distance, bandwidth)
        'logistic' => logistic(distance, bandwidth)
        'sigmoid' => sigmoid(distance, bandwidth)
        => runtime.error('MathStatisticsKernel -> select(): "kernel" invalid kernel.'), float(na)
//{ usage
// b = -1 + (bar_index%100) * 0.02,  plot(select('uniform', b, 0.1)), plot(b, color=color.red)
//{ remarks:
//}}}



string choice = input.string(defval='uniform', options=["uniform", "triangle", "epanechnikov", "quartic", "triweight", "gaussian", "cosine", "logistic", "sigmoid"])
float bandwidth = input.float(0.5)

test = -1.0 + (bar_index % 100) * 0.02 

plot(series=test, title='cycle', color=color.silver)
plot(series=uniform(test, bandwidth), title='uniform', color=color.red)
plot(series=triangular(test, bandwidth), title='triangle', color=color.lime)
plot(series=epanechnikov(test, bandwidth), title='epanechnikov', color=color.blue)
plot(series=quartic(test, bandwidth), title='quartic', color=color.aqua)
plot(series=triweight(test, bandwidth), title='triweight', color=color.purple)
plot(series=tricubic(test, bandwidth), title='tricubic', color=color.fuchsia)
plot(series=gaussian(test, bandwidth), title='gaussian', color=color.orange)
plot(series=cosine(test, bandwidth), title='cosine', color=color.yellow)
plot(series=logistic(test, bandwidth), title='logistic', color=color.olive)
plot(series=sigmoid(test, bandwidth), title='sigmoid', color=color.maroon)

plot(series=select(choice, test, bandwidth), title='choice', color=color.gray)

Overview

Each function takes a distance relative to the kernel origin and an optional bandwidth limit to calculate a weighted output score. When distances exceed the specified bandwidth, the kernels return zero. As a helper library, it plots nothing on the price chart and produces no direct trading signals or order executions. It serves as a mathematical calculation component for custom smoothing, regression, or machine learning tools.

Details

Published by

ricardosantos79 on GitHub

Code credit

RicardoSantos, 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.

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
choicestringuniformchoice
bandwidthfloat0.5bandwidth
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

KernelFunctions

by artificial-intelligence-edge
75 stars

KernelFunctions is a Pine Script v5 library that exports kernel weight functions for Nadaraya-Watson style estimation. It calculates a Rational Quadratic kernel, a Gaussian kernel based on a radial basis function, and a periodic kernel that models repeating be

Library v5
Updated 2 days ago · MIT GitHub repository of KernelFunctions

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