Try implementing MetaTrader's LWMA with scipy's FIR filter function

This is my first post, but I'll suddenly get into the main subject. Recently, I implemented a technical indicator function of MetaTrder5 (MT5) in Python. → GitHub

In MT5, there are SMA, EMA, SMMA, LWMA as the types of moving average, but SMA (simple moving average) was easy to write using pandas.

import numpy as np
import pandas as pd
def MAonSeries(s, ma_period, ma_method):
    if ma_method == 'SMA':    
    return s.rolling(ma_period).mean()

I was looking for a method function that could easily write LWMA (Linear Weighted Moving Average), but I didn't know, so I calculated it as it was.

def MAonSeries(s, ma_period, ma_method):
    if ma_method == 'LWMA':
        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

However, I wanted to write it easier, so I looked it up and found that [lfilter ()](http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal. There was a filter function called lfilter.html # scipy.signal.lfilter). This seems to be compatible with both FIR filter and IIR filter, and I could write it like this using this.

from scipy.signal import lfilter    
def MAonSeries(s, ma_period, ma_method):
    if ma_method == 'LWMA':
        h = np.arange(ma_period, 0, -1)*2/ma_period/(ma_period+1)
        y = lfilter(h, 1, s)
        y[:ma_period-1] = 'NaN'
        return pd.Series(y, index=s.index)

This made it a little cleaner.

Recommended Posts

Try implementing MetaTrader's LWMA with scipy's FIR filter function
Try function optimization with Optuna
Try implementing RBM with chainer.
Try implementing XOR with PyTorch