Library · Pine Script v5 · Library

FunctionBestFitFrequency

by ricardosantos79· code credited to RicardoSantos

FunctionBestFitFrequency is a Pine Script v5 library that smooths a float array with a rolling average and searches a frequency range for the moving-average length whose residual signs are closest to evenly split.

View on GitHub

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

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

FunctionBestFitFrequency.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='FunctionBestFitFrequency')

import RicardoSantos/ArrayExtension/1 as ae

// @function Moving Average values for selected data.
// @param sample float array, sample data values.
// @param length int, length to smooth the data.
// @param ommit_initial bool, default=true, ommit values at the start of the data under the length.
// @param fillna string, default='na', options='na', '0', 'avg'
// @returns float array
//  errors: 
//      length > sample size "Canot call array methods when id of array is na."
export array_moving_average (float[] sample, int length, bool ommit_initial=true, string fillna='na') => //{
    int _size = array.size(id=sample)
    if _size > 1 and _size > length
        float[] _ma = array.copy(id=sample)
        float _nav = float(na)
        if fillna == '0'
            _nav := 0
        if fillna == 'avg'
            _nav := array.avg(id=sample)
        float[] _ma_total = array.new_float(0)
        for _i = 0 to _size-1
            array.push(id=_ma_total, value=array.get(id=sample, index=_i))
            if array.size(id=_ma_total) > length
                array.shift(id=_ma_total)
            if ommit_initial and _i < length
                array.set(id=_ma, index=_i, value=_nav)
            else
                float _avg = array.avg(id=_ma_total)
                array.set(id=_ma, index=_i, value=_avg)
        _ma
//{
// usage:
int length = input.int(defval=6)
bool ommit_init = input.bool(true)
string fill_na = input.string(defval='na', options=['na', '0', 'avg'])
rngs0 = array.from(79, 47, 5, 82, 31, 77, 58, 45, 15, 76, 76, 33, 47, 8, 1, 14, 65, 16, 16, 10, 60)
string tex = str.format('S: {0}', rngs0) 
for _i = 2 to length
    tex += str.format('\n{0}: {1}', _i, str.tostring(array_moving_average(rngs0, _i, ommit_init, fill_na), '#.##'))
if barstate.islast
    label.new(bar_index, 0.0, tex)
//}}

// @function Search a frequency range for the fairest moving average frequency.
// @param sample float array, sample data to based the moving averages.
// @param start int lowest frequency.
// @param end int highest frequency.
// @returns tuple with (int frequency, float percentage)
export best_fit_frequency (float[] sample, int start, int end) => //{
    int _size = array.size(id=sample)
    if _size > 0 and end < _size and start > 0 and start <= end
        int _best = 0
        float _percent = -999
        for _freq = start to end
            float[] _avg = array_moving_average(sample=sample, length=_freq, ommit_initial=false, fillna='avg')
            float _esum = 0.0
            for _i = 0 to _size-1
                float _erri = array.get(id=sample, index=_i) - array.get(id=_avg, index=_i)
                if _erri >= 0 
                    _esum += 1
            float _tentative = -0.5 + (_esum / (_size-1))
            if math.abs(_tentative) < math.abs(_percent)
                _best := _freq
                _percent := _tentative
        [_best, _percent]
//{ usage:
float[] sample = ae.sequence_from_series(src=close, length=input(100), shift=0, direction_forward=true)
[best, percent] = best_fit_frequency(sample, input(2), input(20))
plot(best)
plot(percent)
//}}

Overview

The array function can omit early values shorter than the window and fill them with na, zero, or the sample average. The search returns the chosen frequency and a percentage score. Usage examples read a close-price sample and plot both outputs; the library itself draws nothing.

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
lengthint6length
ommit_initbooltrueommit_init
fill_nastringnafill_na
lengthint100length
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