Moving Average Convergence/Divergence on Python

I've created a Moving Average Convergence/Divergence (MACD) Indicator using Python programing language on Google Colab. 

I also have an extra feature in my code which is "BUY & SELL" signal, whenever the MACD cross each other and gives a Buy or Sell signal it is reflected on the screen with "Red & Green" arrows, this is done by using the concept of "flag" which you will now see in my code.


#import the Libraries
import pandas as pd
import numpy as np
import pandas_datareader as dr
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')


from google.colab import files
uploaded = files.upload()


df = pd.read_csv('CIPLA.NS.csv')
df = df.set_index(pd.DatetimeIndex(df['Date'].values))
df




#visually show the stock price
plt.figure(figsize=(12.24.5))
plt.plot(df['Close'], label='Close')
plt.title('Close Price History')
plt.xlabel('Date')
plt.ylabel('Price')
plt.show()



#calculate the MACD and Signal Line indicators
#calculate the short term exponential moving average (EMA)
ShortEMA = df.Close.ewm(span=12, adjust=False).mean()

#calculate the long term exponential moving average (EMA)
LongEMA = df.Close.ewm(span=26, adjust=False).mean()

#calculate the MACD line
MACD = ShortEMA - LongEMA

#calculate the signal line
signal = MACD.ewm(span=9, adjust=False).mean()


plt.figure(figsize=(18.28.5))
plt.plot(df.index, MACD, label = 'YESBANK MACD', color='red')
plt.plot(df.index, signal, label = 'YESBANK Signal Line', color='blue')
plt.legend(loc = 'upper left')
plt.show()




#create new column for data 
df['MACD'] = MACD
df['Signal Line'] = signal
df




#create a function to signal when to buy or sell a stock

def buy_sell(signal):
  Buy = []
  Sell = []
  flag = -1

  for i in range(0len(signal)):
    if signal['MACD'][i] > signal['Signal Line'][i]:
      Sell.append(np.nan)
      if flag != 1:
        Buy.append(signal['Close'][i])
        flag = 1
      else:
        Buy.append(np.nan)
    elif signal['MACD'][i] < signal['Signal Line'][i]:
      Buy.append(np.nan)
      if flag != 0:
        Sell.append(signal['Close'][i])
        flag = 0
      else:
        Sell.append(np.nan)
    else:
      Buy.append(np.nan)
      Sell.append(np.nan)

  return (Buy, Sell)


 #create buy and sell column 
a = buy_sell(df)
df['Buy_Signal_Price'] = a[0]
df['Sell_Signal_Price'] = a[1]


df





#visually showing the stock BUY SELL signal
plt.figure(figsize=(18.28.5))
plt.scatter(df.index, df['Buy_Signal_Price'], color='green', label='Buy', marker='^', alpha =1)
plt.scatter(df.index, df['Sell_Signal_Price'], color='red', label='Sell', marker='v', alpha =1)
plt.plot(df['Close'], label='Close Price', alpha = 0.35)
plt.title('Close Price ')
plt.xlabel('Date')
plt.ylabel('Close Price')
plt.legend(loc = 'upper left')
plt.show()





These predictions are based on historical data of stocks and statistics behind MACD so
there might be chances that it may not give the appropriate predicted result but it
works pretty well.

Comments

Popular posts from this blog

Net Present Value (NPV) On Python Using Numpy

Commodity Channel Index ( CCI ) Using Python

SMA Trading Strategy Using Python