Build a Stock Tracker Email Bot in Python Using YFinance & smtplib

Build a Stock Tracker Email Bot in Python Using YFinance & smtplib

Build a Stock Tracker Email Bot in Python Using YFinance & smtplib

 

Monitoring stock prices manually each day can be tedious and prone to oversight. In this tutorial, we’ll automate the process by building a Python bot that tracks your favorite stocks and sends an email alert when prices cross defined thresholds. We’ll leverage the popular yfinance library to fetch stock data and smtplib to send automated emails. Whether you’re just automating for personal use or integrating this into a broader dashboard, this provides a solid foundation.

1. Setting Up Dependencies and Environment

Before we start coding, ensure you have the correct Python dependencies installed. We’ll use:

  • yfinance: To pull real-time and historical stock data
  • smtplib and email: To construct and send email alerts
  • schedule: For daily execution if needed

Install the necessary packages using pip:

pip install yfinance schedule

We also recommend storing credentials (like email password) securely using environment variables or a secrets manager, especially in production scenarios.

2. Fetching Real-Time Stock Data with YFinance

We’ll start by fetching real-time stock prices using the yfinance library. Here’s how:

import yfinance as yf

def get_stock_price(ticker):
    stock = yf.Ticker(ticker)
    data = stock.history(period='1d')
    if not data.empty:
        return data['Close'].iloc[-1]
    return None

price = get_stock_price("AAPL")
print(f"Current AAPL Price: ${price:.2f}")

The get_stock_price function pulls the most recent closing price of the given stock ticker. This is suitable for daily checks and works reliably even after market close.

3. Constructing the Email Alert Logic

Next, let’s set up logic to detect when a stock price goes above or below preset thresholds. Then, we construct an email alert using email.mime modules and send it via SMTP.

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import os

def send_email(subject, body, recipient):
    sender = os.getenv("BOT_EMAIL")
    password = os.getenv("EMAIL_PASSWORD")

    msg = MIMEMultipart()
    msg['From'] = sender
    msg['To'] = recipient
    msg['Subject'] = subject

    msg.attach(MIMEText(body, 'plain'))

    try:
        with smtplib.SMTP('smtp.gmail.com', 587) as server:
            server.starttls()
            server.login(sender, password)
            server.sendmail(sender, recipient, msg.as_string())
        print("Alert email sent successfully!")
    except Exception as e:
        print(f"Failed to send email: {e}")

For Gmail, you may need to enable app-specific passwords or allow access to less secure apps if using standard credentials.

4. Putting It Together: The Stock Alert Bot

Combine the stock checker and email sender into a cohesive function. Here’s the complete logic:

def check_and_alert(ticker, threshold, direction, recipient):
    price = get_stock_price(ticker)
    if price is None:
        print("Failed to fetch price")
        return

    if (direction == 'above' and price > threshold) or \
       (direction == 'below' and price < threshold):

        subject = f"Stock Alert: {ticker} is {direction} ${threshold}"
        body = f"{ticker} current price is ${price:.2f}, which is {direction} your threshold of ${threshold}."
        send_email(subject, body, recipient)
    else:
        print(f"{ticker} is at ${price:.2f}. No alert triggered.")

This function takes the ticker symbol, threshold value, alert direction ("above" or "below"), and the recipient's email. If the condition is met, an alert email is sent out.

5. Automating Daily Checks Using the schedule Library

To automate this check daily at a specific time, use the schedule library. Here's how you can set it to run every day at 9:30 AM (just after market open):

import schedule
import time

schedule.every().day.at("09:30").do(
    check_and_alert,
    ticker="AAPL",
    threshold=180,
    direction="above",
    recipient="you@example.com"
)

print("Stock Tracker Bot is running...")
while True:
    schedule.run_pending()
    time.sleep(60)

This script runs indefinitely, checking the condition every minute to see if it's 9:30 AM. For production deployment, consider using cron jobs, background services, or hosting on cloud platforms like AWS Lambda or Heroku.

Final Thoughts and Tips

  • Schedule multiple checks across different times to catch daytime movements.
  • Add logging to audit alerts and issues.
  • Support multiple stocks with a list of tickers and thresholds.
  • Use HTML emails for better formatting and visual alerts.

This bot serves as a solid foundation for automating trade signals, alerting patterns, or simply keeping an eye on your watchlist. With some enhancements, you can transform it into a sophisticated financial monitoring system.

 

Useful links: