Comparison of exponential moving average (EMA) code written in Python

The most commonly used moving average after the simple moving average (SMA) is the exponential moving average (EMA). In addition to MACD, which is famous as a technical index that uses EMA, there are also DEMA, TEMA, and TriX that use EMA multiple times, and adaptive moving averages such as AMA, FrAMA, and VIDyA use EMA as a calculation method. I will.

This time, Comparing IIR filter type moving averages with pandas and scipy As a continuation of, let's compare some EMA codes.

EMA formula

When actually using EMA, the period is entered as a parameter, but here we use the formula directly to check the performance of the EMA itself.

y(n)=\alpha x(n)+(1-\alpha)y(n-1)

In other words, the parameter of EMA is $ \ alpha $ in the above formula.

Implementation by pandas

First, input data to be multiplied by EMA About Python code for simple moving average assuming Numba use Make it as a random walk as well.

import numpy as np
import pandas as pd

dn = np.random.randint(2, size=100000)*2-1
gwalk = np.cumprod(np.exp(dn*0.01))*100

In pandas, you can easily convert to Series class and execute EMA with ʻewmandmean methods. You can also directly assign ʻalpha as a parameter of ʻewm. ʻAlpha is in the range of 0 to 1, and there is no particular difference depending on the value, so enter 0.15 here.

def EMA1(x, alpha):
    return pd.Series(x).ewm(alpha=alpha).mean()

%timeit y1 = EMA1(gwalk, 0.15)

The execution time is as follows.

100 loops, best of 3: 8.62 ms per loop

Implementation of scipy with lflter

Comparing IIR filter type moving averages with pandas and scipy It is an implementation using scipy's filter function lfilter in the same way as.

from scipy.signal import lfilter
def EMA2(x, alpha):
    y,zf = lfilter([alpha], [1,alpha-1], x, zi=[x[0]*(1-alpha)])
    return y

%timeit y2 = EMA2(gwalk, 0.15)

The execution time is as follows.

1000 loops, best of 3: 631 µs per loop

So far in the previous article, it was said that scipy is fast, but this time there is a continuation.

Direct implementation of formulas using Numba

Code the EMA formula directly. However, if it is left as it is, it will be very slow, so use Numba to speed it up.

from numba import jit
@jit(nopython=True)
def EMA3(x, alpha):
    y = np.empty_like(x)
    y[0] = x[0]
    for i in range(1,len(x)):
        y[i] = alpha*x[i] + (1-alpha)*y[i-1]
    return y

%timeit y3 = EMA3(gwalk, 0.15)

If you add nopython = True to the argument of @ jit and no error occurs, you can expect speedup. In fact, the execution time is

1000 loops, best of 3: 227 µs per loop

And faster than scipy.

In the case of EMA as well, using Numba resulted in the fastest direct coding.

Recommended Posts

Comparison of exponential moving average (EMA) code written in Python
I compared the calculation time of the moving average written in Python
Fourier series verification code written in Python
Comparison of Japanese conversion module in Python3
About Python code for simple moving average assuming the use of Numba
A collection of code often used in personal Python
Python implementation comparison of multi-index moving averages (DEMA, TEMA)
Ruby, Python code fragment execution of selection in Emacs
List of Python code used in big data analysis
Null object comparison in Python
Equivalence of objects in Python
2.x, 3.x character code of python
Decrypt one line of code in Python lambda, map, list
Comparison of 4 Python web frameworks
Let's statically check and format the code of E2E automatic test written in Python [VS Code]
Comparison of how to use higher-order functions in Python 2 and 3
Generate QR code in Python
Comparison of data frame handling in Python (pandas), R, Pig
Gacha written in Python -BOX gacha-
Implementation of quicksort in Python
Character code learned in Python
I wrote the code to write the code of Brainf * ck in python
[Python] The value written in Openpyxl is displayed in exponential notation (E).
Squid Lisp written in Python: Hy
[Python] Generate QR code in memory
Automatically format Python code in Vim
Division of timedelta in Python 2.7 series
MySQL-automatic escape of parameters in python
Handling of JSON files in Python
Implementation of life game in Python
Compatibility diagnosis program written in python
Waveform display of audio in Python
Write selenium test code in python
Law of large numbers in python
Implementation of original sorting in Python
Speed comparison of Python XML parsing
Reversible scrambling of integers in Python
Simple gacha logic written in Python
Code tests around time in Python
Analyze the source code of your own simple search engine written in Python with the code visualization tool "SOURCE TRAIL"
Speed comparison of word-separation in Python / janome, sudachi, ginza, mecab, fugashi, tinysegmenter
Difference between Exponential Moving Average (EMA), Double Index Moving Average (DEMA) and Triple Index Moving Average (TEMA)
Code reading of faker, a library that generates test data in Python
Code reading of Safe, a library for checking password strength in Python
Example of python code for exponential distribution and maximum likelihood estimation (MLE)
Installation of Visual studio code and installation of python
Conversion of string <-> date (date, datetime) in Python
Stress Test with Locust written in Python
Check the behavior of destructor in Python
Handling of character code of file in IronPython
(Bad) practice of using this in Python
General Theory of Relativity in Python: Introduction
Output tree structure of files in Python
(Java, JavaScript, Python) Comparison of string processing
Display a list of alphabets in Python 3
Markov chain transition probability written in Python
Summary of various for statements in Python
python string comparison / use'list'and'in' instead of'==' and'or'
Playing card class in Python (with comparison)
Test of uniqueness in paired comparison method
[Python3] Rewrite the code object of the function