【问题标题】:How would I calculate the Exponential Moving Average?我将如何计算指数移动平均线?
【发布时间】:2020-10-04 20:07:25
【问题描述】:

我从thread 发现了一个有用的sn-p。这个帖子已经有十多年的历史了,没有太多的讨论。然而,它继续获得大量观点 - 毫无疑问,它对未来的读者很有用。

def ema(s, n):
    """
    returns an n period exponential moving average for
    the time series s

    s is a list ordered from oldest (index 0) to most
    recent (index -1)
    n is an integer

    returns a numeric array of the exponential
    moving average
    """
    ema = []
    j = 1

    #get n sma first and calculate the next n period ema
    sma = sum(s[:n]) / n
    multiplier = 2 / float(1 + n)
    ema.append(sma)

    #EMA(current) = ( (Price(current) - EMA(prev) ) x Multiplier) + EMA(prev)
    ema.append(( (s[n] - sma) * multiplier) + sma)

    #now calculate the rest of the values
    for i in s[n+1:]:
        tmp = ( (i - ema[j]) * multiplier) + ema[j]
        j = j + 1
        ema.append(tmp)

    return ema

问题是 EMA 值实际上是附加的 SMA 数字。我们应该如何着手修复这个功能?

【问题讨论】:

    标签: python time-series


    【解决方案1】:

    使用一个临时数组进行ema 计算,并使用不同的数组返回,

    def ema(s, n):
        """
        returns an n period exponential moving average for
        the time series s
    
        s is a list ordered from oldest (index 0) to most
        recent (index -1)
        n is an integer
    
        returns a numeric array of the exponential
        moving average
        """
        ema1 = []
        ema2 = []
        j = 1
    
        #get n sma first and calculate the next n period ema
        sma = sum(s[:n]) / n
        multiplier = 2 / float(1 + n)
        ema1.append(sma)
    
        #EMA(current) = ( (Price(current) - EMA(prev) ) x Multiplier) + EMA(prev)
        ema1.append(( (s[n] - sma) * multiplier) + sma)
        ema2.append(( (s[n] - sma) * multiplier) + sma)
        #now calculate the rest of the values
        for i in s[n+1:]:
            tmp = ( (i - ema1[j]) * multiplier) + ema1[j]
            j = j + 1
            ema1.append(tmp)
            ema2.append(tmp)
    
        return ema2
    

    【讨论】:

    • 您好,感谢您的回复。运行代码时,我得到一个“'function'对象没有属性'append'。ema1 = []重复两次......应该是正确的吗?我还发现原始代码有一个错误...... s =应为 Python 3 删除数组。我将更新我的帖子以反映更改
    • 如果 s = array(s) 被删除,这个函数将是正确的。请接受更改。
    猜你喜欢
    • 2021-04-09
    • 1970-01-01
    • 2012-02-10
    • 2023-01-30
    • 2016-04-11
    • 1970-01-01
    • 1970-01-01
    • 2010-10-04
    相关资源
    最近更新 更多