The following example shows how to calculate Exponential Moving Average (EMA) values for a stock, using various periods, in Python.
We are using the TA (Technical Analysis) library.
The example below calculates the 10 EMA on a one minute chart and the 25 EMA on a 1 minute chart.
The window parameter can be adjusted to any desired value to calculate other useful periods such as the 50 or 200 EMA.
The example uses Yahoo Finance data via the yfinance library.
calculate-emas.py:
import yfinance as yf from ta.trend import EMAIndicator ticker = 'META' EMA10_WINDOW = 10 EMA25_WINDOW = 25 # EMAs on 1 minute timeframe. data = yf.download(tickers=ticker, period='1d', interval='1m' ) closeValues = data['Close'] emaIndicator10 = EMAIndicator(close=closeValues, window=EMA10_WINDOW ) emaIndicator25 = EMAIndicator(close=closeValues, window=EMA25_WINDOW ) # These return Pandas series. emaSeries10 = emaIndicator10.ema_indicator() emaSeries25 = emaIndicator25.ema_indicator() print('Last 5 values for EMA 10: ') print(emaSeries10.tail(5)) print() print('Last 5 values for EMA 25: ') print(emaSeries25.tail(5))
Example run:
$ python calculate-emas.py [*********************100%%**********************] 1 of 1 completed Last 5 values for EMA 10: Datetime 2024-11-04 14:57:00-05:00 562.326530 2024-11-04 14:58:00-05:00 562.321704 2024-11-04 14:59:00-05:00 562.249574 2024-11-04 15:00:00-05:00 562.289524 2024-11-04 15:01:00-05:00 562.278698 Name: ema_10, dtype: float64 Last 5 values for EMA 25: Datetime 2024-11-04 14:57:00-05:00 562.883210 2024-11-04 14:58:00-05:00 562.838347 2024-11-04 14:59:00-05:00 562.768088 2024-11-04 15:00:00-05:00 562.745104 2024-11-04 15:01:00-05:00 562.705480 Name: ema_25, dtype: float64
References
https://technical-analysis-library-in-python.readthedocs.io/en/latest/ta.html