I'm trying to convert pine script stdev to python code but it seems I'm doing it wrong https://www.tradingview.com/pine-script-reference/v4/#fun_stdev
Pine script:
//the same on pine
isZero(val, eps) => abs(val) <= eps
SUM(fst, snd) =>
EPS = 1e-10
res = fst + snd
if isZero(res, EPS)
res := 0
else
if not isZero(res, 1e-4)
res := res
else
15
pine_stdev(src, length) =>
avg = sma(src, length)
sumOfSquareDeviations = 0.0
for i = 0 to length - 1
sum = SUM(src[i], -avg)
sumOfSquareDeviations := sumOfSquareDeviations + sum * sum
stdev = sqrt(sumOfSquareDeviations / length)
Python code:
import talib as ta
def isZero(val, eps):
if abs(val) <= eps:
return True
else:
return False
def SUM(fst, snd):
EPS = 1e-10
res = fst + snd
if isZero(res, EPS):
res += 0
else:
if not isZero(res, 1e-4):
res = res
else:
res = 15
return res
def pine_stdev(src, length):
avg = ta.SMA(src, length)
sumOfSquareDeviations = 0.0
for i in range(length - 1):
s = SUM(src.iloc[i], -avg.iloc[i])
sumOfSquareDeviations = sumOfSquareDeviations + s * s
stdev = (sumOfSquareDeviations / length)*(sumOfSquareDeviations / length)
What am I doing wrong? And why SUM function returns 15?
Trading View has made a mistake in the code on the site. The number "15" should be written as "1e-5". You can use this code:
def SUM(fst, snd):
EPS = 1e-10
res = fst + snd
if isZero(res, EPS):
res = 0
else:
if not isZero(res, 1e-4):
res = res
else:
res = 1e-5
return res