Library · Pine Script v5 · Library

AnalysisInterpolationLoess

by ricardosantos79· code credited to RicardoSantos

This Pine Script v5 library provides a LOESS local weighted smoothing routine for paired x and y sample arrays.

View on GitHub

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

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

AnalysisInterpolationLoess.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 LOESS, local weighted Smoothing function.
library(title='AnalysisInterpolationLoess')

// reference:
// https://commons.apache.org/proper/commons-math/javadocs/api-3.3/org/apache/commons/math3/analysis/interpolation/LoessInterpolator.html

// @function Helper function for the loess library
// @param value float, value.
// @returns float
tricubic (float value) => //{
    if value > 1.0
        0.0
    else
        math.pow(1 - math.pow(value, 3), 3)
//}

// @function Helper function for the loess library
// @param value float, value.
// @param exponent float, exponent.
// @returns float
polyweight (float value, float exponent) => //{
    if value > 1.0
        0.0
    else
        math.pow(1 - math.pow(value, exponent), exponent)
//{ credit to @midtownSk8rguy
//}}

// @function LOESS, local weighted Smoothing function.
// @param sample_x int array, x values.
// @param sample_y float array, y values.
// @param point_span int, local point interval span.
export loess (int[] sample_x, float[] sample_y, int point_span=2) => //{
    int _size_x = array.size(id=sample_x)-1
    int _size_y = array.size(id=sample_y)-1
    // to improve performance there is:
    // no monotonic sequence check, no null checks.
    if _size_x < 1 or _size_y < 1
        runtime.error('AnalysisInterpolationLoess -> loess(): samples x and y must have at the least 1 element.')
        float[] _A = na
    else if _size_x != _size_y
        runtime.error('AnalysisInterpolationLoess -> loess(): samples x and y must have the same number of elements.')
        float[] _A = na
    else if point_span < 1
        runtime.error('AnalysisInterpolationLoess -> loess(): point_span must be positive integer number over 0.')
        float[] _A = na
    else if 2 * point_span > _size_x
        runtime.error('AnalysisInterpolationLoess -> loess(): point_span must be smaller than sample size.')
        float[] _A = na
    else
        float[] _yloess = array.new_float(size=1 + _size_x)
        for _i = 0 to _size_x
            int _xi = array.get(id=sample_x, index=_i)
            // define the index interval to pool the values
            int _start = 0
            int _end = _size_x
            if _i < 1 + point_span
                _start := math.max(0, _i - point_span)
                _end := _i + point_span
            else
                _start := _i - point_span
                _end := math.min(_i + point_span, _size_x)
            // grab the values for the interval span
            int[] _span_x = array.slice(id=sample_x, index_from=_start, index_to=_end)
            float[] _span_y = array.slice(id=sample_y, index_from=_start, index_to=_end)
            // calculate the distance, weights then perform local regression
            int _size_s = array.size(id=_span_x)-1
            float _sum_w = 0.0
            float _sum_x = 0.0
            float _sum_x2 = 0.0
            float _sum_y = 0.0
            float _sum_xy = 0.0
            for _s = 0 to _size_s
                int _xs = array.get(id=_span_x, index=_s)
                float _ys = array.get(id=_span_y, index=_s)
                int _ds = math.abs(_xs-_xi)
                float _ws = tricubic(_ds / point_span)
                float _wxs = _ws * _xs
                _sum_w += _ws
                _sum_x += _wxs
                _sum_x2 += _wxs * _xs
                _sum_y += _ws * _ys
                _sum_xy += _wxs * _ys
            float _mean_x = _sum_x / _sum_w
            float _mean_y = _sum_y / _sum_w
            float _mean_xy = _sum_xy / _sum_w
            float _mean_x2 = _sum_x2 / _sum_w
            float _mx2xx = _mean_x2 - math.pow(_mean_x, 2)
            float _beta = 0.0
            if math.sqrt(math.abs(_mx2xx)) < 1.0e-15
                _beta := (_mean_xy - _mean_x * _mean_y) / _mx2xx
            float _alpha = _mean_y - _beta * _mean_x
            //update current y loess value at _i index
            array.set(id=_yloess, index=_i, value=_beta * _xi + _alpha)
        _yloess
//{ usage:
// length = input.int(50)
// npoints= input.int(7)
// f_l1(_x1, _y1, _x2, _y2) => line.new(_x1, _y1, _x2, _y2, color=#DDDD00, style=line.style_solid, width=1)

// import RicardoSantos/ArrayExtension/2 as ae
// a = bar_index < length ? array.from(0) : ae.to_int(ae.sequence_from_series(bar_index, length, 0, true), 'floor')
// b = bar_index < length ? array.from(0.0) : ae.sequence_from_series(close, length, 0, true)

// if barstate.islastconfirmedhistory
//     c = loess(a, b, npoints)
//     label.new(bar_index, 0.0, str.tostring(c, '#.###'))


//     for _i = 1 to array.size(a)-1
//         _x1 =  array.get(a, _i-1)
//         _x2 =  array.get(a, _i  )
//         _by1 = array.get(c, _i-1)
//         _by2 = array.get(c, _i)
//         f_l1(_x1, _by1, _x2, _by2)

// plot(close)
//}}

// @function aLOESS, adaptive local weighted Smoothing function.
// @param sample_x int array, x values.
// @param sample_y float array, y values.
// @param point_span int, local point interval span.
export aloess (int[] sample_x, float[] sample_y, int point_span=2, float span_exponent=3.0) => //{
    int _size_x = array.size(id=sample_x)-1
    int _size_y = array.size(id=sample_y)-1
    // to improve performance there is:
    // no monotonic sequence check, no null checks.
    if _size_x < 1 or _size_y < 1
        runtime.error('AnalysisInterpolationLoess -> aloess(): samples x and y must have at the least 1 element.')
        float[] _A = na
    else if _size_x != _size_y
        runtime.error('AnalysisInterpolationLoess -> aloess(): samples x and y must have the same number of elements.')
        float[] _A = na
    else if point_span < 1
        runtime.error('AnalysisInterpolationLoess -> aloess(): point_span must be positive integer number over 0.')
        float[] _A = na
    else if 2 * point_span > _size_x
        runtime.error('AnalysisInterpolationLoess -> aloess(): point_span must be smaller than sample size.')
        float[] _A = na
    else
        float[] _yloess = array.new_float(size=1 + _size_x)
        for _i = 0 to _size_x
            int _xi = array.get(id=sample_x, index=_i)
            // define the index interval to pool the values
            int _start = 0
            int _end = _size_x
            if _i < 1 + point_span
                _start := math.max(0, _i - point_span)
                _end := _i + point_span
            else
                _start := _i - point_span
                _end := math.min(_i + point_span, _size_x)
            // grab the values for the interval span
            int[] _span_x = array.slice(id=sample_x, index_from=_start, index_to=_end)
            float[] _span_y = array.slice(id=sample_y, index_from=_start, index_to=_end)
            // calculate the distance, weights then perform local regression
            int _size_s = array.size(id=_span_x)-1
            float _sum_w = 0.0
            float _sum_x = 0.0
            float _sum_x2 = 0.0
            float _sum_y = 0.0
            float _sum_xy = 0.0
            for _s = 0 to _size_s
                int _xs = array.get(id=_span_x, index=_s)
                float _ys = array.get(id=_span_y, index=_s)
                int _ds = math.abs(_xs-_xi)
                float _ws = polyweight(_ds / point_span, span_exponent)
                float _wxs = _ws * _xs
                _sum_w += _ws
                _sum_x += _wxs
                _sum_x2 += _wxs * _xs
                _sum_y += _ws * _ys
                _sum_xy += _wxs * _ys
            float _mean_x = _sum_x / _sum_w
            float _mean_y = _sum_y / _sum_w
            float _mean_xy = _sum_xy / _sum_w
            float _mean_x2 = _sum_x2 / _sum_w
            float _mx2xx = _mean_x2 - math.pow(_mean_x, 2)
            float _beta = 0.0
            if math.sqrt(math.abs(_mx2xx)) < 1.0e-15
                _beta := (_mean_xy - _mean_x * _mean_y) / _mx2xx
            float _alpha = _mean_y - _beta * _mean_x
            //update current y loess value at _i index
            array.set(id=_yloess, index=_i, value=_beta * _xi + _alpha)
        _yloess
//{ usage:
adaptive = input.bool(false)
length = input.int(50)
npoints = input.int(7)
exp = input.float(3.0)
f_l1(_x1, _y1, _x2, _y2) => line.new(_x1, _y1, _x2, _y2, color=#DDDD00, style=line.style_solid, width=1)

import RicardoSantos/ArrayGenerate/1 as ag
import RicardoSantos/ArrayExtension/1 as ae

a = bar_index <= length ? array.from(0) : ae.to_int(ag.sequence_from_series(bar_index, length, 0, true), 'floor')
b = bar_index <= length ? array.from(0.0) : ag.sequence_from_series(close, length, 0, true)
if barstate.islastconfirmedhistory
    c = adaptive ? aloess(a, b, npoints, exp) : loess(a, b, npoints)
    // label.new(bar_index, 0.0, str.tostring(c, '#.###'))


    for _i = 1 to array.size(a)-1
        _x1 =  array.get(a, _i-1)
        _x2 =  array.get(a, _i  )
        _by1 = array.get(c, _i-1)
        _by2 = array.get(c, _i)
        f_l1(_x1, _by1, _x2, _by2)

plot(close)
//}}

Overview

AnalysisInterpolationLoess builds a local neighborhood around each sample, applies a tricubic distance weight, and fits a weighted local regression. A separate polynomial weight helper uses a configurable exponent. Callers pass the point span that sets the neighborhood width. The library draws nothing and performs no trading signals, entries, or exits. It rejects mismatched, empty, or oversized spans with runtime errors and skips monotonic and null checks for speed.

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
adaptiveboolfalseadaptive
lengthint50length
npointsint7npoints
expfloat3.0exp
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