pine-scriptpine-script-v4

Calculating standard deviation of last N elements of in a pine series


Try to calculate the standard deviation of last 5 elements of a series below is the implementation I copied from TradingView official's ADX implementation

//@version=4
study(title="DMI movement out of 2SD in last 10 points", shorttitle="StrategyX", format=format.price, precision=4, resolution="")
lensig = input(14, title="ADX Smoothing", minval=1, maxval=50)
len = input(14, minval=1, title="DI Length")

up = change(high)
down = -change(low)
plusDM = na(up) ? na : (up > down and up > 0 ? up : 0)
minusDM = na(down) ? na : (down > up and down > 0 ? down : 0)
trur = rma(tr, len)
plus = fixnan(100 * rma(plusDM, len) / trur)
minus = fixnan(100 * rma(minusDM, len) / trur)
sum = plus + minus
adx = 100 * rma(abs(plus - minus) / (sum == 0 ? 1 : sum), lensig)

What I was trying to do is to get the standard deviation of the latest 5 plus (DMI+) data points, I tried multiple approaches..

  1. Create an array, then push in the data point one by one

But turned out I can't get the data point from the plus series. It should return a variable (the fifth last element) but not another series (according to the official doc: https://www.tradingview.com/pine-script-reference/v4/#op_[])

plus[5] // do not understand why it is still a series but not a float
  1. Convert Series to array, then do reverse and slice

which again failed as there is no way to convert series to array

any help would be greatly appreciated :pray thanks


Solution

  • Have you tried the built-in stdev function?

    plus2StDev = 2 * stdev(plus, 5)
    plot(plus2StDev)
    

    But turned out I can't the data point from the plus series Could be during the early stages of runtime the data doesn't exists yet, for example on the first bar there is no past values of plus series. You can use nz function to safely access the series history data - nz(plus[5]).

    custom stdev function shared by tradingview user alexgrover:

    f_stdev(src, length) => length == 1 ? 0 : sqrt(sma(pow(src, 2), length) - pow(sma(src, length), 2)) 
    plus2StDev = 2 * f_stdev(plus, 5)
    plot(plus2StDev)