The MACD (Transferring Common Convergence Divergence) is a well-liked technical evaluation device utilized by merchants to establish potential purchase and promote alerts. Let’s first perceive how it’s calculated;
Calculation:
- The MACD line is calculated by subtracting the 26-period Exponential Transferring Common (EMA) from the 12-period EMA.
- The sign line is a nine-period EMA of the MACD line.
- The MACD histogram represents the distinction between the MACD line and the sign line.
When the MACD line crosses above the sign line, it may be a purchase sign. This text gives invaluable steerage if you wish to improve your buying and selling insights!
On this chapter, I’ll write a code that checks S&P 500 shares for 3 months, offering a enough window to calculate the MACD values for every inventory. We are going to then choose those that present a consecutive optimistic sign over 4 days. Let’s dive into the code and see how we will implement this step-by-step.
1- Grabbing S&P 500 ticker names
import pandas as pd
from bs4 import BeautifulSoup
import matplotlib.pyplot as plt
from urllib.request import urlopen, Request
from urllib.parse import quote
from urllib.error import HTTPError
import yfinance as yf# Operate to fetch S&P 500 inventory tickers
def get_sp500_tickers():
sp500_url = 'https://en.wikipedia.org/wiki/List_of_Spercent26P_500_companies'
html = urlopen(sp500_url)
soup = BeautifulSoup(html, 'html.parser')
desk = soup.discover('desk', {'id': 'constituents'})
tickers = []
for row in desk.find_all('tr')[1:]:
ticker = row.find_all('td')[0].textual content.strip()
tickers.append(ticker)
return tickers
sp500_tickers = get_sp500_tickers()
# Record of person brokers to rotate
user_agents = [
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.1 Safari/605.1.15',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Firefox/89.0'
]
2- MACD calculation
# Calculate the 12-period EMA
information['EMA12'] = information['Close'].ewm(span=12, alter=False).imply()# Calculate the 26-period EMA
information['EMA26'] = information['Close'].ewm(span=26, alter=False).imply()
# Calculate MACD (the distinction between 12-period EMA and 26-period EMA)
information['MACD'] = information['EMA12'] - information['EMA26']
# Calculate the 9-period EMA of MACD (Sign Line)
information['Signal_Line'] = information['MACD'].ewm(span=9, alter=False).imply()
3- Examine for MACD crossovers within the final 3 days
macd_above_signal = all(information['MACD'].iloc[-(i+1)] > information['Signal_Line'].iloc[-(i+1)] for i in vary(3))if macd_above_signal:
cross_above_signals.append(ticker)
besides Exception as e:
print(f"Error processing ticker {ticker}: {e}")
# Create a DataFrame from the outcomes
results_df = pd.DataFrame(cross_above_signals, columns=['Ticker'])
# Save the DataFrame to an Excel file
results_df.to_excel('cross_above_signals.xlsx', index=False)
The outcome introduced a considerable variety of shares that met our standards, with 177 shares reaching our goal for at the moment.
As seen above, our code works correctly and brings the right shares as an output. Now we will add yet another indicator that we’re accustomed to from our earlier chapters. In fact, I’m speaking about RSI 🙂
# Operate to calculate RSI
def calculate_rsi(information, interval=14):
delta = information['Close'].diff()
achieve = delta.the place(delta > 0, 0)
loss = -delta.the place(delta < 0, 0)
avg_gain = achieve.rolling(window=interval, min_periods=1).imply()
avg_loss = loss.rolling(window=interval, min_periods=1).imply()
rs = avg_gain / avg_loss
rsi = 100 - (100 / (1 + rs))
return rsi
Now, we will filter out the shares which over-bought or those which have the cloud hanging over them.