Track Multiple Stocks and Set Price Alerts with Python and Yahoo Finance API

Category > PYTHON || Published on : Wednesday, March 22, 2023 || Views: 1663 || Python Yahoo Finance API stock trading price alerts data analysis programmin


In the world of stock trading, it's important to stay up-to-date on the latest market trends and track the stocks you're interested in. One way to do this is to set price alerts that notify you when a stock's price crosses a certain threshold. In this article, we'll use Python and the Yahoo Finance API to track multiple stocks and set price alerts.

The program to track multiple stocks by creating a list of stock symbols and alert prices, and looping through them to continuously check the live prices and send email notifications when they cross the alert prices. Here's an example of how you could modify the program to track 10 stocks:

import yfinance as yf
import smtplib

# Enter your email credentials
email_address = "your_email_address"
email_password = "your_email_password"

# Create a list of stock symbols and alert prices
stocks = [("AAPL", 150), ("GOOGL", 2500), ("AMZN", 3500), ("TSLA", 800), ("MSFT", 250), ("NVDA", 700), ("JPM", 150), ("BAC", 30), ("WMT", 140), ("DIS", 180)]

# Function to send email notification
def send_email_notification(stock_symbol, alert_price):
    with smtplib.SMTP("smtp.gmail.com", 587) as smtp:
        smtp.ehlo()
        smtp.starttls()
        smtp.ehlo()
        smtp.login(email_address, email_password)
        subject = f"Alert: {stock_symbol} Price Crossed {alert_price}!"
        body = f"The live price of {stock_symbol} has crossed {alert_price}."
        message = f"Subject: {subject}\n\n{body}"
        smtp.sendmail(email_address, email_address, message)

# Continuously check the stock prices and send alerts if necessary
while True:
    for stock in stocks:
        stock_symbol = stock[0]
        alert_price = stock[1]
        try:
            stock_data = yf.Ticker(stock_symbol).history(period="1d")
            current_price = stock_data["Close"][0]
            if current_price > alert_price:
                send_email_notification(stock_symbol, alert_price)
        except Exception as e:
            print(f"An error occurred while fetching the stock data for {stock_symbol}: {e}")
    time.sleep(60)  # wait for 60 seconds before checking the prices again

Here's how the modified program works:

  1. We create a list of stocks that we want to track, where each stock is represented as a tuple containing the stock symbol and alert price.

  2. Inside the while loop, we loop through the list of stocks using a for loop and get the stock symbol and alert price for each stock.

  3. Inside the try block, we fetch the historical data for each stock and get the current price of the stock from the "Close" column of the historical data.

  4. If the current price of the stock is greater than the alert price, we call the send_email_notification function to send an email notification.

  5. If any exception occurs during the execution of the try block, we catch the exception in the except block and print an error message to the console. The program will continue to run and retry fetching the stock data until it succeeds.

  6. We add a time.sleep() statement at the end of the loop to wait for 60 seconds before checking the prices again. This is to prevent making too many requests to the Yahoo Finance API, which could cause our IP address to be blocked.

Note: You may want to adjust the time.sleep() duration depending on how frequently you want to check the prices. Also, keep in mind that the Yahoo Finance API has rate limits, so you should avoid making too many requests in a short period of time.