Is this python function to calculate ZLEMA correct (and optimised)?

21 views Asked by At

Trying to code a Zero-Lag Exponential Moving Average ZLEMA in Python (nicknamed ZLEMAX). Unfortunately, it seems to return wrong values, although I used well documented formulas to derive the code.

My code so far:

def ZLEMAX(close, period):
    if period >= 3:
        lag = (period - 1) // 2
    else:
        lag = 1
    emadata = close.astype(float) + (close.astype(float) - np.roll(close,lag).astype(float))
    n = len(close)
    zlema = np.full(n, np.nan)
    alpha = 2 / (period + 1)
    zlema[0] = emadata[0]
    for i in range(1, n):
        zlema[i] = (alpha * emadata[i]) + ((1 - alpha) * zlema[i - 1])
    zlema[:period+1] = np.nan
    return zlema

Unfortunately, it seems to return wrong values, compared to Pandas-TA as a reference.

# Example usage:
period = 6
testdata = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 9, 10]
testdf = pd.DataFrame(testdata, columns=['close'])
testarr = np.array(testdata)

# Compute ZLEMA using your implementation
zlemax = ZLEMAX(close=testarr, period=period)
print("ZLEMAX values:", zlemax)

# Compute ZLEMA using pandas-TA
zlema_pandas_ta = pt.zlma(close=testdf['close'], length=period, mamode='ema')
print("pandas-TA ZLEMA values:", np.array(zlema_pandas_ta))
ZLEMAX values: [       nan        nan        nan        nan        nan        nan
        nan 6.40905818 7.72075584 8.94339703 4.38814074 1.42010053
 2.44292895 3.45923496 4.47088212 5.47920151 6.48514394 7.48938853
 8.49242038 9.49458598 4.78184713 1.70131938 6.07237098 9.48026499]
pandas-TA ZLEMA values: [       nan        nan        nan        nan        nan        nan
        nan 7.5        8.5        9.5        4.78571429 1.70408163
 2.64577259 3.60412328 4.57437377 5.55312412 6.5379458  7.52710414
 8.5193601  9.51382865 4.79559189 1.71113706 6.07938362 9.48527401]

I tried various syntaxes and formulas, and this is the closest I got to the results from Pandas-TA.

I am not sure where the calculation error is (or are). Also, trying to keep the code as simple as possible. The ZLEMAX code can certainly be improved/optimised and I am not sure how to apply jit/njit (or other ways to accelerate/multiprocessor/GPU accelerate/cache, etc.).

Thanks!

0

There are 0 answers