RicardoSantos

Function Mean Median Mode V0

EXPERIMENTAL:
Request for GLAZ
Functions to handle Mean, Median, Mode Calculation.
Open-source script

In true TradingView spirit, the author of this script has published it open-source, so traders can understand and verify it. Cheers to the author! You may use it for free, but reuse of this code in a publication is governed by House Rules. You can favorite it to use it on a chart.

Disclaimer

The information and publications are not meant to be, and do not constitute, financial, investment, trading, or other types of advice or recommendations supplied or endorsed by TradingView. Read more in the Terms of Use.

Want to use this script on a chart?
//@version=2
study(title='Function Mean Median Mode V0', overlay=true)

mean(_src, _length)=>
    _return = sum(_src, _length) / _length

median(_src, _length)=>
    _return = _src
    for _i = 0 to _length
        _return := _return == 0 ? _src : (_return + _src[_i]) / 2
    _return

mode_occurance(_value, _src, _length, _discrepancy_range)=>
    _current_value_occurance = 0
    for _i = 0 to _length
        if (_src[_i] >= _value - _discrepancy_range and _src[_i] <= _value + _discrepancy_range)
            _current_value_occurance := _current_value_occurance + 1
    _return = _current_value_occurance


mode(_src, _length, _discrepancy_range)=>
    _highest_occurence_value = 0
    _highest_occurance_number = 0
    for _i = 0 to _length
        _current_value_occurance = mode_occurance(_src[_i], _src, _length, _discrepancy_range)
        if (_current_value_occurance > _highest_occurance_number)
            _highest_occurance_number := _current_value_occurance
            _highest_occurence_value := _src[_i]
    _return = _highest_occurence_value

l = input(20)
r = input(0, type=float)

plot(series=mean(close, l), title='Mean', color=blue)
plot(series=median(close, l), title='Median', color=red)
plot(series=mode(close, l, r), title='Mode', color=black)