# MACD
```python=
# Compedium : Stock Investment Strategy Using MACD Crossover To Determine When To Buy & Sell
# Import The Needed Library
import pandas as pd
import numpy as np
from datetime import datetime
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
# Store The Data Into The 'df' (DataFrame) Variable
df = pd.read_csv('2327 國巨.csv')
# Set The Date As The Index For The Data
df = df.set_index(pd.DatetimeIndex(df['Date'].values))
# Calculate The MACD & Signal Line Indicators
# Calculate The Short Term Exponential Moving Average
ShortEMA = df.Close.ewm(span=12, adjust=False).mean() # Fast Moving Average
# Calculate The Long Term Exponential Moving Average
LongEMA = df.Close.ewm(span=26, adjust=False).mean() # Slow Moving Average
# Calculate The Moving Average Convergence / Divergence (MACD)
MACD = ShortEMA - LongEMA
# Calcualte The Signal Line
signal = MACD.ewm(span=9, adjust=False).mean()
# Create New Columns For The DataFrame
df['MACD'] = MACD
df['Signal Line'] = signal
# Create A Function To Signal When To Buy And Sell An Asset
def buy_sell(signal):
sigPriceBuy = []
sigPriceSell = []
flag = (-1)
for i in range(0,len(signal)):
# If MACD > Signal Line, Buy The Stock. If Not, Sell The Stock
if signal['MACD'][i] > signal['Signal Line'][i]:
if flag != 1:
sigPriceBuy.append(signal['Close'][i])
sigPriceSell.append(np.nan)
flag = 1
else:
sigPriceBuy.append(np.nan)
sigPriceSell.append(np.nan)
elif signal['MACD'][i] < signal['Signal Line'][i]:
if flag != 0:
sigPriceSell.append(signal['Close'][i])
sigPriceBuy.append(np.nan)
flag = 0
else:
sigPriceBuy.append(np.nan)
sigPriceSell.append(np.nan)
else: # Handling nan values
sigPriceBuy.append(np.nan)
sigPriceSell.append(np.nan)
return (sigPriceBuy, sigPriceSell)
# Create buy and sell columns
x = buy_sell(df)
df['Buy_Signal_Price'] = x[0]
df['Sell_Signal_Price'] = x[1]
# Visually Show The Stock's Buy & Sell Signals
# Create The Title
title = 'Close Price History Buy / Sell Signals'
# Get The Stocks
my_stocks = df
#Create And Plot The Graph
plt.figure(figsize=(12.2,4.5)) # width = 12.2in, height = 4.5
plt.scatter(my_stocks.index, my_stocks['Buy_Signal_Price'], color = 'green', label='Buy Signal', marker = '^', alpha = 1)
plt.scatter(my_stocks.index, my_stocks['Sell_Signal_Price'], color = 'red', label='Sell Signal', marker = 'v', alpha = 1)
plt.plot( my_stocks['Close'], label='Close Price', alpha = 0.35) # plt.plot( X-Axis , Y-Axis, line_width, alpha_for_blending, label)
plt.xticks(rotation=45)
plt.title(title)
plt.xlabel('Date',fontsize=18)
plt.ylabel('Close Price NTD ($)',fontsize=18)
plt.legend(loc='upper left')
plt.show()
```