Calculating EMA from SMA in python

Viewed 84

I've defined a function that calculates SMA(Simple Moving average), compares the value to the closing price 'p' and gives a signal as to whether we should buy or sell, represented by a 1 or -1 respectively.

I now want to create a function for EMA(Exponential Moving Average). The formula for EMA is EMA = Closing price x multiplier + EMA (previous day) x (1-multiplier) where the multiplier is [2 ÷ (number of observations + 1)].

However, I'm not sure how to do this in Spyder/Python.

My code for SMA is:

def SMA(p,window=10,signal_type='buy only'):
    #input price "p", look-back window "window",
    #signal type = buy only (default) --gives long signals, sell only --gives sell signals, both --gives both long and short signals
    #return a list of signals = 1 for long position and -1 for short position
    signals = np.zeros(len(p))
    if len(p)<window:
        #no signal if no sufficient data
        return signals
    sma = list(np.zeros(window)+np.nan) #the first few prices does not give technical indicator values 
    sma += [np.average(p[k:k+window]) for k in np.arange(len(p)-window)]
    for i in np.arange(len(p)-1):
        if np.isnan(sma[i]):
            continue #skip the open market time window
        if sma[i]<p[i] and (signal_type=='buy only' or signal_type=='both'):
            signals[i] = 1
        elif sma[i]>p[i] and (signal_type=='sell only' or signal_type=='both'):
            signals[i] = -1
    return signals

This gets called in another file like so, I want to be able to just change 'backtest.SMA' to 'backtest.EMA' so I can see the signals that EMA produces.

signals = backtest.SMA(this_dat['Close'].values, window=10)

('this_dat['Close'].values' is a list of closing price values taken from a table)

I defined EMA in the same way I defined SMA but I'm not sure how to obtain EMA

def EMA(p,window=10,signal_type='buy only'):
   
    signals = np.zeros(len(p))
    if len(p)<window:
        #no signal if no sufficient data
        return signals
    
   

    multiplier=(2/(len(p)+1))
    
    ema = list(np.zeros(window)+np.nan)
    #ema = Closing price x multiplier + EMA (previous day) x (1-multiplier)#
    ema +=
    
    
    
    for i in np.arange(len(p)-1):
        if np.isnan(ema[i]):
            continue #skip the open market time window
        if ema[i]<p[i] and (signal_type=='buy only' or signal_type=='both'):
            signals[i] = 1
        elif ema[i]>p[i] and (signal_type=='sell only' or signal_type=='both'):
            signals[i] = -1
    return signals

I need help finding a way to write that forumla for EMA in python, I can't figure it out. If anyone knows a package I can use that might work then I'm also open to trying it but I would prefer if I could find EMA using my SMA function as a template.

Any help would be greatly appreciated, thanks

0 Answers
Related