Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
638 views
in Technique[技术] by (71.8m points)

How do I calculate the Exponential Moving Average in Python

I've been trying to calculate the Exponential Moving Average (EMA) for stock prices. I have the following methods:

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)

I'm going off of this formula:

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

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

Why is it not calculating the EMA?

This is the dataset I'm using: (from the latest price 22.27 to the oldest price 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]

The period is the number of days in EMA. I am assuming a 10 day EMA.

question from:https://stackoverflow.com/questions/65860467/how-do-i-calculate-the-exponential-moving-average-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

Please log in or register to answer this question.

Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...