Library · Pine Script v5 · Library

MathGaussFunction

by ricardosantos79· code credited to RicardoSantos

This mathematical utility library implements one-dimensional and two-dimensional Gaussian functions and kernel generators in Pine Script.

View on GitHub

GitHub stars261on the repository
Pine versionv5runs as is
Lines of code111
Settings0inputs
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

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

MathGaussFunction.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 Implements multiple gauss methods.
library(title='MathGaussFunction')

// reference:
//      https://github.com/andrewkirillov/AForge.NET/blob/master/Sources/Math/Gaussian.cs

// imports:
import RicardoSantos/ArrayExtension/3 as ae
// ArrayExtension.index_2d_to_1d()

// @function 1-D Gaussian function.
// @param point_x float, x value.
// @param sigma float, sigma value, default=1.0.
// @returns float, function's value at point_x.
export f_1d (float point_x, float sigma=1.0 ) => //{
    float _sigma2 = math.pow(sigma, 2)
    float _x2 = point_x * point_x
    math.exp(_x2 / (-2 * _sigma2)) / (math.sqrt(2 * math.pi ) * sigma)
//{ usage:
// s = input.float(0.5)
// plot(gauss_1d(1.0/(bar_index%1000), s))
//{ remarks:
//      The function calculates 1-D Gaussian function:
//      f(x) = exp( x * x / ( -2 * s * s ) ) / ( s * sqrt( 2 * PI ) )
//}}}

// @function 2-D Gaussian function.
// @param point_x float, x value.
// @param point_y float, y value.
// @param sigma float, sigma value, default=1.0.
// @returns float, function's value at (point_x, point_y).
export f_2d (float point_x, float point_y, float sigma=1.0 ) => //{
    float _sigma2 = math.pow(sigma, 2)
    float _x2 = point_x * point_x
    float _y2 = point_y * point_y
    math.exp((_x2 + _y2) / (-2 * _sigma2)) / (2 * math.pi * _sigma2)
//{ usage:
// s = input.float(0.5)
// plot(f_2d(1.0/(bar_index%1000), 1.0/(bar_index%500), s))
//{ remarks:
//      The function calculates 2-D Gaussian function:
//      f(x, y) = exp( x * x + y * y / ( -2 * s * s ) ) / ( s * s * 2 * PI )
//}}}

// @function 1-D Gaussian kernel.
// @param size int, Kernel size (should be odd), [3, 101].
// @param sigma float, sigma value, default=1.0.
// @returns float array, Returns 1-D Gaussian kernel of the specified size.
export kernel_1d (int size, float sigma=1.0) => //{
    // check for even size and for out of range
    if (((size % 2) == 0) or (size < 3) or (size > 101))
        error('MathGaussFunction -> kernel_1d(): wrong kernal size, should be positive, odd and < 100.')
        float[] _K = na
    else
        // radius
        int _r = size / 2
        // kernel
        float[] _K = array.new_float(size)
        // compute kernel
        for _i = 0 to size-1
            int _x = -_r + _i
            array.set(_K, _i, f_1d(_x, sigma))
        _K
//{ usage:
// int size = input.int(99)
// float sigma = input.float(1.0)
// float[] K = kernel_1d(size, sigma)
// plot(array.get(K, bar_index%size))
//{ remarks: 
//      The function calculates 1-D Gaussian kernel, which is array
//      of Gaussian function's values in the [-r, r] range of x value, where:
//      r = floor(size / 2)
//}}}

// @function 2-D Gaussian kernel.
// @param size int, Kernel size (should be odd), [3, 101].
// @param sigma float, sigma value, default=1.0.
// @returns float array, Returns 2-D Gaussian kernel of the specified size.
export kernel_2d( int size, float sigma=1.0) => //{
    // check for even size and for out of range
    if (((size % 2) == 0) or (size < 3) or (size > 101))
        error('MathGaussFunction -> kernel_2d(): wrong kernal size, should be positive, odd and < 100.')
        float[] _K = na
    else
        // radius
        int _r = size / 2
        // kernel
        float[] _K = array.new_float(size*size)
        // compute kernel
        for _i = 0 to size-1
            int _y = _r + _i
            for _j = 0 to size-1
                int _x = -_r + _j
                array.set(_K, ae.index_2d_to_1d(size, size, _i, _j), f_2d(_x, _y, sigma))
        _K

//{ usage:
// int size = input.int(11)
// float sigma = input.float(3.1416)
// float[] K = kernel_2d(size, sigma)
// plot(array.get(K, bar_index%(size*size)))
//{ remarks: 
//      The function calculates 2-D Gaussian kernel, which is array
//      of Gaussian function's values in the [-r, r] range of x value, where:
//      r = floor(size / 2)
//}}}

Overview

MathGaussFunction calculates standard Gaussian distribution values for single coordinates or coordinate pairs based on a specified sigma value. Additionally, it constructs normalized one-dimensional and two-dimensional kernel arrays across odd window sizes up to 101 elements. The library does not plot on the chart or generate trading signals, serving instead as a calculation module for custom filters, smoothers, or indicators.

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.

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