Ensemble Empirical Mode Decomposition (EEMD)

I've made a python script to use EEMD
It's not so wonderful analysis but shows AmiPy example
FE
AFL

_N(pdir = "C:\\Proj\\AmiPy\\PyEMD\\");	// proj directory
_N(pjn = "PyEMD");						// project name
_N(pfn = "PyEMD (1.0)");				// python filename
_N(ctxt = "PyEmd (1.0)");				// context-this AFL filename
/* DESC
Via chart paramter settings
	- decompose signal 
	- plot constituents
	- plot timeseries estimate by adding constituent eIMFs
- indicator input range visible bars e.g. [0...113]
- pyPlot signal & IMFs
*/
/* Notes
- enable in python script (amiArgs,amiRtn),
  allows amiPy print of AFL inputs and return matrix in interpretation window
- enable in python script (dspy),
  allows python to save to file the plotted data and results
- indicator mode uses chart bars plus 31 prefixed bars with valid price data
  after an edit/save, need to 'Apply' to reset back to indicator mode,
  otherwise the full barindex data used
*/

/// LOGGING
//PyChangeLoggingOptions("","wsemd");
/// PARAMETERS
pSig = ParamTrigger("Decompose Signal","Click");
pImf = ParamToggle("Chart IMFs","N|Y",0);
pHat = ParamToggle("Chart Estimate Signal","N|Y",0);
pCsv = ParamTrigger("Clear StaticVars","Click");
pPsv = ParamToggle("Persistent StaticVars","N|Y",0);
/// CONSTANTS

/// INPUTS
field = Close;
/// VARIABLES
bi  = BarIndex();
fvb = FirstVisibleValue(bi);
lvb = LastVisibleValue(bi);
lvx = Status("lastvisiblebar"); // barcount-1+blanks
blank = lvx-lvb;
tot	= lvb-fvb+1;
/// INITIALISE
// clears/removes all staticvars
if(pCsv) {
	StaticVarRemove(pjn+"*");
}
/// TICKER
// remove Norgate suffix
cnt = StrFind(Name(),".au");
if(cnt!=0) { ticker = StrLeft(Name(),cnt-1); }
else { ticker = Name(); }
/// lOAD PYTHON SCRIPT
PyLoadFromFile(ctxt,pdir+pfn+".py");
/// RUN SCRIPT
tmp = Null;
if(pSig) {	// pyemd decompose signal to constituents, returned as matrix
	IMFS = PyEvalFunction(ctxt,"eemd_IMFs",field,bi);
	rows = MxGetSize(IMFS,0);
	cols = MxGetSize(IMFS,1);
	// save size, constituents as static variables
	StaticVarSet(pjn+"_"+ticker+"_nrows",rows,pPsv);
	for(i=0;i<rows;i++) {
		tmp = MxGetBlock(IMFS,i,i,0,cols-1,True);
		StaticVarSet(pjn+"_"+ticker+"_y"+i,tmp,pPsv);
	}
}
/// CHARTING
SetChartBkColor(ColorRGB(0,0,0));
SetChartOptions(0,chartShowArrows|chartShowDates);
Plot(C,"C",colorWhite,styleCandle|styleNoTitle,Null,Null,0,0,0);
// get saved IMFS
yhat = 0;
rows = StaticVarGet(pjn+"_"+ticker+"_nrows");
if(rows>0) {	// retrieve constituents from static variables, display
	for(i=0;i<rows;i++) {
		ynew = StaticVarGet(pjn+"_"+ticker+"_y"+i,True);
		yhat = yhat+ynew;
		if(pImf) {
			Plot(ynew,"Ynew"+i,colorRed,styleLine,Null,Null,0,0,1);
		}
	}
	if(pHat) {		// display some reconstructed signal
		Plot(yhat,"Yhat",colorWhite,styleLine,Null,Null,0,0,1);
	}
}
/// TITLE
_N(Title = StrFormat("<<"+pdir+pfn+".py"+">>  <<Context: "+ctxt+">>"+
					"\n{{NAME}} - {{INTERVAL}} {{DATE}},"+
					" Open %g, Hi %g, Lo %g, Close %g (%.1f%%)",
					 O, H, L, C, SelectedValue( ROC( C, 1 ) ) ));
// thanks @beppe					 
_N(Title = Title+"\nfvb(bi):     "+fvb+ "      lvb(bi):   "+lvb+"    bars(bi):  "+tot);
_N(Title = Title+"\nlvb(status): "+lvx+"  BLANKS: " + blank);
_N(Title = Title+"  Barcount: " + BarCount);
_N(Title = Title + StrFormat("\n{{VALUES}}"));

and here is python script

# -*- coding: utf-8 -*-
'''
Ensemble empirical mode decomposition (EEMD)

EMD-Signal:
https://pypi.org/project/EMD-signal/
https://pyemd.readthedocs.io/en/latest/intro.html
https://github.com/laszukdawid/PyEMD
'''
from __future__ import division, print_function

import sys

import numpy as np
import matplotlib.pyplot as plt

from PyEMD import EEMD
import AmiPy

# settings
#eemd = EEMD(spline_kind='piecewise cubic')
eemd = EEMD(spline_kind='akima')
eemd = EEMD(trials=20)
eemd = EEMD(parallel=True)
eemd = EEMD(separate_trends=True)
eemd = EEMD(processes=10)

# proj folder
proj_path = 'C:\\Proj\\AmiPy\\PyEMD\\'
images_path = proj_path + 'images\\'

# images folder
if images_path not in sys.path:
    sys.path.append(images_path)

# plot signal and eIMFs
dspy = False
# print AFL messages
amiArgs = False
amiRtn = False

def eemd_IMFs(S,t):
    # print args passed
    if amiArgs:
        AmiPy.Print("\nt="+np.str_(t))
        AmiPy.Print("\nS="+np.str_(S))
        AmiPy.Print("\npassed bars= "+np.str_(len(S)))
    
    # Assign EEMD to `eemd` variable
    eemd = EEMD()

    # Say we want detect extrema using parabolic method
    emd = eemd.EMD
    emd.extrema_detection="parabol"

    # Execute EEMD on S
    eIMFs = eemd.eemd(S, t)
    nIMFs = eIMFs.shape[0]
    col = eIMFs.shape[1]

    # Plot results
    if dspy:
        plt.figure(figsize=(12,9))
        plt.subplot(nIMFs+1, 1, 1)
        plt.plot(t, S, 'r')

        for n in range(nIMFs):
            plt.subplot(nIMFs+1, 1, n+2)
            plt.plot(t, eIMFs[n], 'g')
            plt.ylabel("eIMF"+str(n+1))
            plt.locator_params(axis='y', nbins=5)

        plt.xlabel("Time [s]")
        plt.tight_layout()
        plt.savefig(images_path+'eemd_example', dpi=120)
        #plt.show() seems to hang??

    # amiPrint to interpretation window
    AmiPy.Print("\nrow/col= ["+np.str_(nIMFs)+"]["+np.str_(col)+"]")

    if amiRtn:
        AmiPy.Print("\neIMFs= "+np.str_(eIMFs))

    return eIMFs


if __name__ == "__main__":
    s = np.random.random(100)
    eemd = EEMD()
    eIMFs = eemd(s)
1 Like

forgot the plots and chart capture
Screenshot 2021-09-26 170043
eemd_example_101

2 Likes