Sunday, November 19, 2023

Building a Stock Screener in Python to Identify MACD Equals Signal Opportunities

 Introduction:

Stock screeners are invaluable tools for investors looking to identify potential trading opportunities. In this article, we'll explore how to create a simple yet effective stock screener in Python using financial data from Yahoo Finance. Specifically, we'll focus on scanning for stocks where the MACD (Moving Average Convergence Divergence) equals the Signal line within the last 24 hours. Check out my related article about MACD Trading Strategy(Making some modifications on my article "How I will trade using MACD as indicator").


Prerequisites:

Before diving into the code, make sure you have the required libraries installed. You can install them using:

pip install pandas yahoo_fin yfinance


The Python Code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import pandas as pd
from yahoo_fin import stock_info as si
import yfinance as yf
import datetime


# Fetch the list of Nasdaq tickers
df2 = pd.DataFrame(si.tickers_nasdaq())

# Set the date range for the stock data
end_date = datetime.datetime.today().strftime('%Y-%m-%d')
start_date = (datetime.datetime.today() - datetime.timedelta(days=1)).strftime('%Y-%m-%d')

# Loop through each stock ticker
for ticker in df2[0]:
    try:
        # Download stock data from Yahoo Finance
        data = yf.download(ticker, start=start_date, end=end_date, interval='1m')
        
        # Calculate MACD and Signal line
        # Calculate MACD
        data['ema_12'] = data['Close'].ewm(span=12, adjust=False).mean()
        data['ema_26'] = data['Close'].ewm(span=26, adjust=False).mean()
        data['macd'] = data['ema_12'] - data['ema_26']
        data['signal'] = data['macd'].ewm(span=9, adjust=False).mean()
        # Delete rows where macd and signal both equal 0
        data = data[(data['macd'] != 0) & (data['signal'] != 0)]
        # Check if there is an instance where MACD equals Signal
        if any(data['macd'] == data['signal']):
            print(f"Opportunity found for {ticker}: MACD equals Signal")
    except:
        pass  # Handle exceptions, e.g., delisted stocks or connection issues

Understanding the Code:

1. Fetching Tickers: We use the si.tickers_nasdaq() function from the yahoo_fin library to get a list of Nasdaq stock tickers. 
2. Downloading Stock Data: For each ticker, we use yfinance to download historical stock data for the last 24 hours with a 1-minute interval.
3. Calculating MACD and Signal:
    • data['ema_12'] = data['Close'].ewm(span=12, adjust=False).mean(): This line calculates the 12-period Exponential Moving Average (EMA) of the closing prices. It uses the ewm method in pandas, which stands for exponentially weighted moving average. The span parameter defines the window size, and adjust=False means that equal weights are assigned to all values in the window.
    • data['ema_26'] = data['Close'].ewm(span=26, adjust=False).mean(): Similar to the first line, this calculates the 26-period EMA of the closing prices.
    • data['macd'] = data['ema_12'] - data['ema_26']: This line computes the MACD line by subtracting the 26-period EMA from the 12-period EMA. The MACD line represents the difference between these two moving averages.
    • data['signal'] = data['macd'].ewm(span=9, adjust=False).mean(): Here, the code calculates the 9-period EMA of the MACD line, creating the signal line. The signal line is often used to generate buy or sell signals when it crosses the MACD line.
              4.Identifying Opportunities: We check if there is any instance where the MACD equals the Signal line. If found, we print a message indicating a potential trading opportunity.

              Conclusion:

              By building this simple stock screener in Python, you can quickly identify stocks exhibiting MACD equals Signal patterns. However, it's crucial to conduct further analysis and consider other factors before making any trading decisions. Additionally, remember to handle exceptions gracefully to ensure the robustness of your stock screener.

              This is just one of several scenarios, for complete details check the related article on my patreon.

              No comments:

              Post a Comment

              Managing Trading Risks by Knowing Calendar Events That Affect Market Volatility

                Introduction to Trading Risks In Forex and other financial markets, risk management is one of the most critical aspects of successful trad...