【问题标题】:How do I calculate the Exponential Moving Average in Python如何在 Python 中计算指数移动平均线
【发布时间】:2021-01-23 14:41:04
【问题描述】:

我一直在尝试计算股票价格的指数移动平均线 (EMA)。我有以下方法:

def ema(self, prices, period):
    if len(prices) < period:
        return 'Not enough data to calculate EMA'

    return self.ema_helper(prices, period, (2 / (period + 1)), len(prices))


def ema_helper(self, prices, N, k, length):
    if len(prices) == length-N:
        return prices[0]
    
    return prices[0] * k + self.ema_helper(prices[1:], N, k, length) * (1 - k)

我要放弃这个公式:

EMA = Price(t) × k + EMA(y) × (1 − k)

where:
t = today
y = yesterday
N = number of days in EMA
k = 2 ÷ (N + 1)

为什么不计算 EMA?

这是我正在使用的数据集:(从最新价格 22.27 到最旧价格 22.17

[22.27, 22.19, 22.08, 22.17, 22.18, 22.13, 22.23, 22.43, 22.24, 22.29, 22.15, 22.39, 22.38, 22.61, 23.36, 24.05, 23.75, 23.83, 23.95, 23.63, 23.82, 23.87, 23.65, 23.19, 23.1, 23.33, 22.68, 23.1, 22.4, 22.17]

期间是 EMA 中的天数。我假设10 day EMA

【问题讨论】:

    标签: python moving-average algorithmic-trading trading


    【解决方案1】:

    您的 EMA 使用昨天的结果,因此需要保留。也许宁愿使用这样的列表(这当然可以清理和改进,我只是更改了 ema_helper):

    def ema_helper(prices, N, k, length):
        if len(prices) == length-N:
            return prices[0]
        res_ema = [p for p in prices[:N]] # this keeps the ema
        for t in range(N, length):
            res_ema.append(prices[t] * k + res_ema[t-1] * (1 - k))
        return res_ema
    

    这会产生

    [22.27, 22.19, 22.08, 22.17, 22.18, 22.13, 22.23, 22.43, 22.24, 22.29, 22.264545454545452, 22.287355371900823, 22.304199849737035, 22.359799877057576, 22.541654444865287, 22.815899091253414, 22.98573562011643, 23.139238234640715, 23.286649464706038, 23.349076834759483, 23.434699228439577, 23.513844823268744, 23.538600309947153, 23.475218435411307, 23.406996901700158, 23.3929974650274, 23.263361562295145, 23.233659460059663, 23.082085012776083, 22.916251374089523]
    

    为您的数据集。 (我假设您是从Moving Averages 获取的),值对应。

    如果你只需要最后一个值,你也可以使用(这里不需要列表):

    def ema_helper(prices, N, k, length):
        if len(prices) == length-N:
            return prices[0]
        res_ema = prices[N-1]
        for t in range(N, length):
            res_ema = (prices[t] * k + res_ema * (1 - k))
        return res_ema
    

    给出22.916251374089523(或者只取最后一个列表项res_ema[-1])。

    【讨论】:

    • 我从towardsdatascience.com/trading-toolbox-02-wma-ema-62c22205e2a9得到数据我如何让它只返回当前的EMA而不是以前的?
    • 真有趣,他们采用了相同的数据集!我已将该选项添加到我的答案中。
    • 为什么您提供的 ema 对上面的链接给出了不同的答案?
    • 哦,链接中的 10 天 EMA(右侧最后一个列表条目)显示为 22.916,同样如此。我看错栏了吗?
    • 啊,我明白你的意思了......在示例中,数据从最旧到最新。如何翻转它以使数据从最新到最旧?
    猜你喜欢
    • 2021-04-09
    • 2010-10-04
    • 1970-01-01
    • 2021-05-30
    • 2012-02-10
    • 2020-10-04
    • 2023-01-30
    • 2019-03-17
    相关资源
    最近更新 更多