I’m trying to compute the moving average divergence convergence (MACD) which is a technical indicator in trading. To compute MACD we have to find out exponential moving average over a certain period or a time window n(I will be providing the procedure, code on how the moving average and a sample input before the signal column is computed). The signal values range from -10 to 10. I kept getting KeyError: ‘close’. I could not understand how to proceed further please do let me know how I can correct this.
# How to compute ema ?
# 1. Calculate the SMA
# (Period Values / Number of Periods)
# 2. Calculate the Multiplier
# (2 / (Number of Periods + 1) therefore (2 / (5+1) = 33.333%
# 3. Calculate the EMA
# For the first EMA, we use the SMA(previous day) instead of EMA(previous day).
# EMA = {Close - EMA(previous day)} x multiplier + EMA(previous day)
# How to compute macd ?
# Calculate the short-term EMA (Exponential Moving Average): This is often based on a 12-period EMA.
# Calculate the long-term EMA: This is often based on a 26-period EMA.
# Calculate the MACD Line: Subtract the long-term EMA from the short-term EMA.
# Calculate the Signal Line: Calculate a 9-period EMA of the MACD Line to create the Signal Line.
def compute_ema(df,n):
df['sma'] = df['close'].rolling(n).mean()
multiplier = 2/(n + 1)
df.dropna(inplace=True)
df['ema'] = np.nan
for i in range(len(df)):
if i == 1:
df.loc[df.index[i], 'ema'] = (df.loc[df.index[i],'close'] - df.loc[df.index[i - 1],'sma']) * multiplier + df.loc[df.index[i - 1], 'sma']
# df['ema'].iloc[i] = (df['close'].iloc[i] - df['sma'].iloc[i-1]) + df['sma'].iloc[i-1]
else:
df.loc[df.index[i], 'ema'] = (df.loc[df.index[i],'close'] - df.loc[df.index[i - 1],'ema']) * multiplier + df.loc[df.index[i - 1], 'ema']
return df
df['fast'] = compute_ema(df, n=12)
df['slow'] = compute_ema(df, n=26)
df['macd'] = df['fast'] - df['slow']
df['signal'] = compute_ema(df['macd'],n)
KeyError: 'close'
The above exception was the direct cause of the following exception:
KeyError Traceback (most recent call last)
Cell In[41], line 1
----> 1 df['signal'] = compute_ema(df['macd'],n)
Cell In[21], line 24
23 def compute_ema(df,n):
...
3815 # InvalidIndexError. Otherwise we fall through and re-raise
3816 # the TypeError.
3817 self._check_indexing_error(key)