Library · Pine Script v5 · Library

ArrayStatistics

by ricardosantos79· code credited to RicardoSantos

ArrayStatistics is a Pine Script v5 library of exported functions that compute descriptive statistics on numeric arrays.

View on GitHub

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

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

ArrayStatistics.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 Statistic Functions using arrays.
library(title="ArrayStatistics")

import RicardoSantos/ArrayExtension/1 as ae
import RicardoSantos/ArrayOperationsFloat/1 as aof

// @function Root Mean Squared
// @param sample float array, data sample points.
// @returns float
export rms(float[] sample) => //{
    int _size = array.size(sample)
    if _size > 0
        float _sum2 = array.sum(aof.power(sample, array.from(2.0)))
        math.sqrt(_sum2 / _size)
//{ usage:
// a = array.from(10, 4, 6, 8.0)//ae.sequence_float(1.0, 20.0, 1.0)
// plot(rms(a))
//{ reference:
//      https://www.geeksforgeeks.org/program-to-calculate-root-mean-square/
//      https://github.com/vjaunet/fortran_lib_ifort/blob/master/SOURCE/lib_stat.f90
//}}

// @function Pearson's 1st Coefficient of Skewness.
// @param sample float array, data sample.
// @returns float
export skewness_pearson1 (float[] sample) => //{
    (array.avg(sample) - array.mode(sample)) / array.stdev(sample)
//{ usage:
// plot(skewness_pearson1(array.from(10.0,3,4,5,8,3,5,2)))
//{ reference:
//      https://www.investopedia.com/terms/s/skewness.asp
//      https://www.statisticshowto.com/pearsons-coefficient-of-skewness/
//}}}

// @function Pearson's 2nd Coefficient of Skewness.
// @param sample float array, data sample.
// @returns float
export skewness_pearson2 (float[] sample) => //{
    (3.0 * (array.avg(sample) - array.median(sample))) / array.stdev(sample)
//{ usage:
// plot(skewness_pearson2(array.from(10.0,3,4,5,8,3,5,2)))
//{ reference:
//      https://www.investopedia.com/terms/s/skewness.asp
//      https://www.statisticshowto.com/pearsons-coefficient-of-skewness/
//}}}

// @function Pearson correlation coefficient measures the linear relationship between two datasets.
// @param sample_a float array, sample with data.
// @param sample_b float array, sample with data.
// @returns float p 
export pearsonr(float[] sample_a, float[] sample_b) => //{
    int _size_a = array.size(id=sample_a)
    int _size_b = array.size(id=sample_b)
    if _size_a > 0 and _size_b > 0
        float _err_sum_ab = array.covariance(id1=sample_a, id2=sample_b)
        float _err_sum_a2 = array.stdev(id=sample_a)
        float _err_sum_b2 = array.stdev(id=sample_b)
        float _r = _err_sum_ab / (_err_sum_a2 * _err_sum_b2)
//{
// usage:
float[] a = array.from(1.0, 2.0, 3.0, 4.0, 5.0)
float[] b = array.from(10.0, 9.0, 2.5, 6.0, 4.0)
plot(pearsonr(a, b))// 0.74
//}}

// @function Kurtosis of distribution.
// @param sample float array, data sample.
// @returns float
export kurtosis (float[] sample) => //{
    int _size = array.size(sample)
    float _mean = array.avg(sample)
    if _size > 0
        float _m2 = 0.0
        float _m4 = 0.0
        for _i = 0 to _size-1
            float _e = array.get(sample, _i) - _mean
            _m2 += math.pow(_e, 2)
            _m4 += math.pow(_e, 4)
        _m2 /= _size
        _m4 /= _size
        _m4 / math.pow(_m2, 2.0)
//{ usage:
// plot(kurtosis(array.from(42, 20, 38, 78, 54, 26))) // 2.35
//{ reference:
//      https://www.educba.com/kurtosis-formula/
//}}}

// @function Get range around median containing specified percentage of values.
// @param sample int array, Histogram array.
// @param percent float, Values percentage around median.
// @returns tuple with [int, int], Returns the range which containes specifies percentage of values.
export range_int ( int[] sample, float percent ) => //{
    int _size = array.size(sample)
    if _size < 1
        runtime.error('ArrayStatistics -> range_int(): Parameter "sample" needs to have 1 or more elements.')
        [0, 0]
    else
        int _total = array.sum(sample)
        int _h = int(_total * ( percent + ( 1 - percent ) / 2 ))
        int _hits = _total
        int _min = -1
        int _max = _size
        // get range min value
        for _i = 0 to _size-1
            _min += 1
            _hits -= array.get(sample, _min)
            if _hits < _h
                break
        // get range max value
        _hits := _total
        for _i = _size - 1 to 0
            _max -= 1
            _hits -= array.get(sample, _max)
            if _hits < _h
                break
        [_min, _max]
//{ usage:
// create histogram array
int[] histogram = array.from(1, 1, 2, 3, 6, 8, 11, 12, 7, 3)
// 
[min, max] = range_int(histogram, input.float(0.75)) // 75% range around median: ([4, 8])
plot(min), plot(max)
//{ remarks:
//      The input array is treated as histogram, i.e. its indexes are
//          treated as values of stochastic function, but array values
//          are treated as "probabilities" (total amount of hits).
//      The method calculates range of stochastic variable, which summary
//          probability comprises the specified percentage of histogram's hits.
//}}}

Overview

ArrayStatistics returns root mean square, Pearson first and second skewness coefficients, the Pearson correlation between two samples, and kurtosis from fourth and second central moments. A further function finds an index range around the median that covers a chosen percentage of a histogram array. It draws nothing and exposes no user inputs; callers supply float or integer arrays and receive scalar or tuple results. Empty samples are guarded by size checks.

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