|
| 1 | +""" |
| 2 | + Calculates exponential moving average (EMA) on the series of numbers |
| 3 | + Wikipedia Reference: https://en.wikipedia.org/wiki/Exponential_smoothing |
| 4 | + Reference: https://www.investopedia.com/terms/e/ema.asp#toc-what-is-an-exponential-moving-average-ema |
| 5 | +
|
| 6 | + Exponential moving average is used in financial field to analyze changes stock prices. |
| 7 | + EMA is used in conjuction with Simple moving average (SMA), EMA reacts to the changes in |
| 8 | + the value quicker than SMA, which is one of the advantages of using EMA. |
| 9 | +""" |
| 10 | + |
| 11 | +import numpy as np |
| 12 | + |
| 13 | +def exponential_moving_average(series : list[float], window_size : int) -> list [float]: |
| 14 | + ''' |
| 15 | + :param series: Array of numbers (Time series data) |
| 16 | + :param window_size: Window size for calculating average (window_size > 0) |
| 17 | + :return: Resulting array of exponentially averaged numbers |
| 18 | +
|
| 19 | + Formula: |
| 20 | +
|
| 21 | + st = alpha * xt + (1 - alpha) * st_prev |
| 22 | + alpha = 2/(1 + window_size) - smoothing factor |
| 23 | +
|
| 24 | + Exponential moving average (EMA) is a rule of thumb technique for |
| 25 | + smoothing time series data using the exponential window function. |
| 26 | + ''' |
| 27 | + |
| 28 | + if (window_size <= 0): |
| 29 | + raise ValueError("window_size must be > 0") |
| 30 | + elif (window_size >= len(series)): |
| 31 | + raise ValueError("window_size must be < length of series") |
| 32 | + |
| 33 | + # Resultent array |
| 34 | + exp_averaged_arr : list[float] = [] |
| 35 | + |
| 36 | + # Calculating smoothing factor |
| 37 | + alpha = 2 / (1 + window_size) |
| 38 | + |
| 39 | + # Exponential average at timestamp t |
| 40 | + st = series[0] |
| 41 | + |
| 42 | + for t in range(len(series)): |
| 43 | + if t <= window_size: |
| 44 | + # Assigning simple moving average till the window_size for the first time |
| 45 | + # is reached |
| 46 | + st = (st + series[t]) * 0.5 |
| 47 | + exp_averaged_arr.append(st) |
| 48 | + else: |
| 49 | + # Calculating exponential moving average based on current timestamp data |
| 50 | + # point and previous exponential average value |
| 51 | + st = (alpha * series[t]) + ((1 - alpha) * st) |
| 52 | + exp_averaged_arr.append(st) |
| 53 | + |
| 54 | + return exp_averaged_arr |
| 55 | + |
| 56 | +if __name__ == "__main__": |
| 57 | + import doctest |
| 58 | + |
| 59 | + doctest.testmod() |
| 60 | + |
| 61 | + test_series = [2,5,3,8.2,6,9,10] |
| 62 | + test_window_size = 3 |
| 63 | + result = exponential_moving_average(test_series, test_window_size) |
| 64 | + print("Test series: ", test_series) |
| 65 | + print("Window size: ", test_window_size) |
| 66 | + print("Result: ", result) |
| 67 | + |
0 commit comments