首页 指标 正文
  • 本文约786字,阅读需4分钟
  • 1894
  • 24

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

温馨提示:本文最后更新于2021年11月17日 20:57,若内容或图片失效,请在下方留言或联系博主。

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")
结果基本一致

或者使用Talib里的库:

import talib
talib.STDDEV(df['Close'].values, timeperiod=200)

结果也是一样的

评论