Loading ...

【原生代码】Python3 实现TradingView中的STDEV标准差

Author: 苏慕白, Created: 2021-11-17 21:06:08, Updated:

TradingView Pine原版代码

plot(stdev(close, 5))

//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)
plot(pine_stdev(close, 5))

Python3实现:

import math  #求平方根

"""字典转数组"""
def GetSrc(r, name):
    if name == 'o+h+l+c':
        src = [ (v['Open'] + v['High'] + v['Low'] + v['Close']) / 4 for v in r ]

    elif name == 'h+l+c':
        src = [ (v['High'] + v['Low'] + v['Close']) / 3 for v in r ]

    elif name == 'h+l':
        src = [ (v['High'] + v['Low']) / 2 for v in r ]

    else:
        src = [ v[name] for v in r ] if name else r

    return src
	
#移动平均线
def SMA(r, days, name=0):
    cps = GetSrc(r, name)
    emas = [0 for i in range(len(cps))]  # 创造一个和cps一样大小的集合

    for i in range(len(cps)):
        if i < days-1:
            emas[i] = 0
        else:
            ma = 0
            for i2 in range(i-days,i):
                i2 += 1
                ma += cps[i2]
            emas[i] = ma / days
    return emas
	
def STDEV_isZero(val, eps):
    return abs(val) <= eps

def STDEV_SUM(fst, snd):
    res = fst + snd
    if STDEV_isZero(res, 1e-10):
        res = 0
    elif STDEV_isZero(res, 1e-4):
        res = 15
    return res

def STDEV(r, days, name=0):
    src = GetSrc(r, name)
    avg = SMA(src, days)
    stdev = [0 for i in range(len(src))]
    for i in range(len(src)):
        if i > days:
            sumOfSquareDeviations = 0
            for i2 in range(days):
                i3 = i-i2
                sum = STDEV_SUM(src[i3], -avg[i])
                sumOfSquareDeviations = sumOfSquareDeviations + sum * sum
            stdev[i] = math.sqrt(sumOfSquareDeviations / days)

    return stdev
	

调用方法:STDEV(r, 5, “Close”) 结果基本一致

转自:https://sumubai.cc/post/33


More

此世哦是我唯一 这个看什么的啊