This tutorial shows you how to build a real-time stock/crypto price alert system using a simple Python script powered by yfinance and SMTP email automation—all running locally on your own machine or on a server/cloud service. If a chosen stock falls below a certain price threshold, the script will send an email directly to an address you choose.
But this script is really just a starting point. You can easily modify it to send alerts based on major price movements, or even trigger notifications when a technical indicator hits a key level or threshold.
I walk through the setup, environment configuration, and core Python code that checks live stock prices and sends you an instant email alert when your target threshold is hit. This is perfect for anyone trading or investing who wants to stay on top of price dips even when stepping aside from watching the market.
For a deeper dive into building AI automations with Python, check out the AI Automation Crash Course linked here: http://crashcourseai.com/
Early access is $79 and includes a Premium AI Technical Analysis Dashboard python template bonus. The price will go up at launch on April 21st, 2025.
Env setup:
Full Code
import os
import time
from datetime import datetime
import yfinance as yf
import smtplib
from email.mime.text import MIMEText
from dotenv import load_dotenv
# === CONFIG ===
TICKER = "msft"
TARGET_PRICE = 371.6
CHECK_INTERVAL = 3 # seconds
# Load env vars from .env
load_dotenv()
FROM_EMAIL = os.getenv("FROM_EMAIL")
EMAIL_PASS = os.getenv("EMAIL_PASSWORD")
TO_EMAIL = os.getenv("TO_EMAIL")
SMTP_SERVER = os.getenv("SMTP_SERVER")
SMTP_PORT = int(os.getenv("SMTP_PORT"))
# === PRICE CHECK ===
def check_price(sym: str) -> float | None:
try:
stock = yf.Ticker(sym)
return (
stock.fast_info.get("last_price")
or stock.info.get("regularMarketPrice")
)
except Exception as e:
print(f"⚠️ Error fetching price: {e}")
return None
# === ALERT SENDER ===
def send_email(msg_body: str):
msg = MIMEText(msg_body)
msg["Subject"] = f"{TICKER} Price Alert"
msg["From"] = FROM_EMAIL
msg["To"] = TO_EMAIL
with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as smtp:
smtp.starttls()
smtp.login(FROM_EMAIL, EMAIL_PASS)
smtp.sendmail(FROM_EMAIL, [TO_EMAIL], msg.as_string())
print("✉️ Alert email sent.")
# === MAIN LOOP ===
if __name__ == "__main__":
while True:
price = check_price(TICKER)
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
if price is not None:
print(f"[{now}] {TICKER} = ${price:.2f}")
if price < TARGET_PRICE:
send_email(
f"As of {now}, {TICKER} dropped below ${TARGET_PRICE:.2f} (now ${price:.2f})"
)
break
else:
print("⚠️ No valid price fetched.")
time.sleep(CHECK_INTERVAL)
Learn more about Crash Course AI here: http://crashcourseai.com/
Subscribe to the Deep Charts YouTube Channel for more informative AI and Machine Learning Tutorials.