A note on speeding up Python code with Numba

Introduction

Comparison of moving average calculation time written in Python So, I found that the moving average (LWMA) using the for statement is slow and unusable, but there are some technical indicators of MetaTrader that can not be written without using the for statement, so I can not give up. So I tried to speed it up.

For the time being, I knew that there was Cython for speeding up, but it was that I had to rewrite the code, so when I checked other things, there was Numba. This time is a memo when I tried Numba.

Very slow code with for statement

import numpy as np
import pandas as pd
dataM1 = pd.read_csv('DAT_ASCII_EURUSD_M1_2015.csv', sep=';',
                     names=('Time','Open','High','Low','Close', ''),
                     index_col='Time', parse_dates=True)

def LWMA(s, ma_period):
    y = pd.Series(0.0, index=s.index)
    for i in range(len(y)):
        if i<ma_period-1: y[i] = 'NaN'
        else:
            y[i] = 0
            for j in range(ma_period):
                y[i] += s[i-j]*(ma_period-j)
            y[i] /= ma_period*(ma_period+1)/2
    return y

%timeit MA = LWMA(dataM1['Close'], 10)
1 loop, best of 3: 3min 14s per loop

Like previous article, it will take more than 3 minutes.

Try using Numba

Numba seems to be in Anaconda, so just import it and add @ numba.jit.

import numba
@numba.jit
def LWMA(s, ma_period):
    y = pd.Series(0.0, index=s.index)
    for i in range(len(y)):
        if i<ma_period-1: y[i] = 'NaN'
        else:
            y[i] = 0
            for j in range(ma_period):
                y[i] += s[i-j]*(ma_period-j)
            y[i] /= ma_period*(ma_period+1)/2
    return y

%timeit MA = LWMA(dataM1['Close'], 10)
1 loop, best of 3: 3min 14s per loop

Oh, the same result. It has no effect. Is Numba dedicated to Numpy by name?

Try changing pandas to numpy

I changed the input data from pandas Series type to numpy array type.

@numba.jit
def LWMA(s, ma_period):
    y = np.zeros(len(s))
    for i in range(len(y)):
        if i<ma_period-1: y[i] = 'NaN'
        else:
            y[i] = 0
            for j in range(ma_period):
                y[i] += s[i-j]*(ma_period-j)
            y[i] /= ma_period*(ma_period+1)/2
    return y

%timeit MA = LWMA(dataM1['Close'].values, 10)
1 loop, best of 3: 2.11 s per loop

This time it's faster. About 90 times. However, it is still slower than the few milliseconds of scipy.

Try to remove the if statement

Even if I compile it, it is decided that the code should be simple, so I removed the if statement. Actually, this if statement was a code that may or may not be present.

@numba.jit
def LWMA(s, ma_period):
    y = np.zeros(len(s))
    for i in range(len(y)):
        for j in range(ma_period):
            y[i] += s[i-j]*(ma_period-j)
        y[i] /= ma_period*(ma_period+1)/2
    return y

%timeit MA = LWMA(dataM1['Close'].values, 10)
100 loops, best of 3: 5.73 ms per loop

came out! millisecond. Even if there was a for statement, it could be as fast as scipy. You can do it, Python.

Summary

I was able to speed up the code that was slowed down by using the for statement by using Numba. However, it worked for numpy and had no effect for pandas.

Reference article

I thought it was slow to use the for statement in NumPy, but that wasn't the case

Recommended Posts

A note on speeding up Python code with Numba
Tips for speeding up python code correctly with numba
I tried speeding up Python code including if statements with Numba and Cython
Roughly speed up Python with numba
Set up a Python development environment with Visual Studio Code
A note on what you did to use Flycheck with Python
A memo with Python2.7 and Python3 on CentOS
Map rent information on a map with python
Run Python code on A2019 Community Edition
Steps to create a Python virtual environment with VS Code on Windows
Build a python environment with ansible on centos6
[Note] Create a one-line timezone class with python
A note on optimizing blackbox functions in Python
Folium: Visualize data on a map with Python
Set up a Python development environment on Marvericks
Decrypt a string encrypted on iOS with Python
Visualize grib2 on a map with python (matplotlib)
Build a python execution environment with VS Code
A note I was addicted to when running Python with Visual Studio Code
Python Ver. To introduce WebPay with a little code.
Make a breakpoint on the c layer with python
I made a Python3 environment on Ubuntu with direnv.
Launch Django on a Docker container with docker-compose up
Reading, displaying and speeding up gifs with python [OpenCV]
Set up a Python development environment with Sublime Text 2
[Vagrant] Set up a simple API server with python
Get country code with python
Set up Python 3.4 on Ubuntu
Python with VS Code (Windows 10)
[Note] Operate MongoDB with Python
Debug Python with VS Code
Make a fortune with Python
Create a directory with python
Regarding speeding up python (memo)
Document Python code with Doxygen
A note about [python] __debug__
A note about hitting the Facebook API with the Python SDK
Create a list in Python with all followers on twitter
[python] Reverse with slices! !! (There is also a commentary on slices!)
[python] A note when trying to use numpy with Cython
A note on touching Microsoft's face recognition API in Python
Try to bring up a subwindow with PyQt5 and Python
Build a Python environment with WSL + Pyenv + Jupyter + VS Code
[Python] Create a screen for HTTP status code 403/404/500 with Django
I want to set up a GUI development environment with Python or Golang on Mac
Building a Python environment on Mac
[Python] What is a with statement?
Solve ABC163 A ~ C with Python
Control the motor with a motor driver using python on Raspberry Pi 3!
Operate a receipt printer with python
A python graphing manual with Matplotlib.
Build a 64-bit Python 2.7 environment with TDM-GCC and MinGW-w64 on Windows 7
Let's make a GUI with python.
Building a Python environment on Ubuntu
Python: A Note About Classes 1 "Abstract"
Build a Python environment on your Mac with Anaconda and PyCharm
Solve ABC166 A ~ D with Python
Create a Python environment on Mac (2017/4)
Create a virtual environment with Python!
Try to create a python environment with Visual Studio Code & WSL
I made a fortune with Python.