Build a Stock Price Alert Bot with Python
Ever stared at a stock chart, watched it dip below your target, and missed the chance to buy because you were busy doing literally anything else? That frustrating moment is exactly why you need a stock price alert bot. Instead of glued to your screen waiting for a number to change, you can let Python do the watching and ping you instantly when your target price hits. Today, you’ll build a fully functional alert bot that checks stock prices and sends you a notification the moment a stock crosses your threshold—you can run this script on your laptop right now.
Why Build Your Own Alert Bot?
Most trading platforms offer basic alerts, but they often lack customization or require you to pay for premium features. A Python bot gives you complete control: you can monitor multiple stocks, set different thresholds for each, and choose how you get notified (email, desktop toast, or even Telegram). Plus, it’s a fantastic way to practice working with APIs, loops, and conditional logic in a real-world scenario.
The beauty of this project is its simplicity. You don’t need a complex backend or a database. A single Python script using the yfinance library can fetch live data and trigger alerts in seconds.
Setting Up Your Environment
Before writing code, you need the right tools. Ensure you have Python 3.8+ installed on your system. You can download it from python.org. Next, you’ll need pip, Python’s package manager, to install dependencies.
Grab a code editor like Visual Studio Code, PyCharm, or even Jupyter Notebook. Create a new folder for your project and open it in your editor.
You’ll need three key libraries:
-
yfinance: Fetches real-time stock data from Yahoo Finance. -
schedule: Handles recurring tasks (checking prices every few minutes). -
datetime: Manages timestamps for your logs.
Install them all at once with this command:
pip install yfinance schedule datetime
Building the Core Logic
Now, let’s write the script. We’ll create a function that checks a stock’s price, compares it to your target, and prints a notification if the condition is met.
Here’s a complete, working example that monitors Tesla (TSLA) and alerts you if the price drops below $200 or rises above $250:
import yfinance as yf
import schedule
from datetime import datetime
# Define your stock and thresholds
STOCK_SYMBOL = "TSLA"
LOWER_THRESHOLD = 200.00
UPPER_THRESHOLD = 250.00
CHECK_INTERVAL = 5 # Check every 5 minutes
def check_stock_price():
try:
# Fetch latest data
stock = yf.Ticker(STOCK_SYMBOL)
# Get the current price (last trade)
current_price = stock.history(period="1d", interval="1m")["Close"].iloc[-1]
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(f"[{timestamp}] {STOCK_SYMBOL} is now at: ${current_price:.2f}")
# Check conditions
if current_price <= LOWER_THRESHOLD:
print(f"🚨 ALERT: {STOCK_SYMBOL} dropped below ${LOWER_THRESHOLD}! Time to buy?")
elif current_price >= UPPER_THRESHOLD:
print(f"🚨 ALERT: {STOCK_SYMBOL} surged above ${UPPER_THRESHOLD}! Time to sell?")
except Exception as e:
print(f"Error fetching data: {e}")
# Schedule the check
schedule.every(CHECK_INTERVAL).minutes.do(check_stock_price)
print(f"🚀 Alert bot started for {STOCK_SYMBOL}. Checking every {CHECK_INTERVAL} mins...")
# Run the scheduler
while True:
schedule.run_pending()
import time
time.sleep(1)
Save this as stock_alert.py. Run it in your terminal:
python stock_alert.py
You’ll see live updates in your console. When the price hits your threshold, you’ll get an instant alert message.
Customizing for Your Needs
This script is a starting point. Here’s how to make it truly useful for you:
Monitor Multiple Stocks
Replace the single symbol with a list:
stocks = ["AAPL", "MSFT", "GOOGL"]
thresholds = {
"AAPL": (150, 180),
"MSFT": (300, 350),
"GOOGL": (120, 140)
}
Loop through each stock and apply its own thresholds.
Add Email Notifications
To get alerts via email, use Python’s built-in smtplib library. You’ll need:
- Your email address
- An SMTP server (e.g., Gmail’s
smtp.gmail.com) - An app password (not your regular password)
Add this function to send an email when an alert triggers:
import smtplib
from email.message import EmailMessage
def send_email_alert(message):
msg = EmailMessage()
msg["From"] = "your_email@gmail.com"
msg["To"] = "your_email@gmail.com"
msg["Subject"] = "Stock Alert!"
msg.set_content(message)
with smtplib.SMTP_SSL("smtp.gmail.com", 465) as server:
server.login("your_email@gmail.com", "your_app_password")
server.send_message(msg)
Call send_email_alert() inside your alert condition.
Send Desktop Toast Notifications
For a more modern feel, use the toast library (Windows) or plyer (cross-platform) to show pop-up alerts on your screen. This is especially useful if you’re running the bot in the background while working.
Pro Tips for Real-World Use
-
Run it in the background: Use tools like
cron(Linux/Mac) or Task Scheduler (Windows) to keep the bot running even after you close your terminal. -
Use environment variables: Store sensitive data (like email passwords) in a
.envfile instead of hardcoding them. - Add logging: Write alerts to a log file so you can track price movements over time.
- Try webhooks: Connect your bot to services like IFTTT or Zapier to trigger actions (e.g., send a Slack message, create a Trello task) when an alert fires.
Ready to Automate Your Trading?
You now have a working stock price alert bot that you can tweak, expand, and deploy today. Whether you’re watching for a dip to buy or a spike to sell, this script puts you in control without staring at charts all day.
Don’t let this be just another tutorial you read and forget. Copy the code, run it, and set your first alert. Pick a stock you’re interested in, set a realistic threshold, and let Python do the watching.
If you add email notifications, monitor multiple stocks, or build a web dashboard, share your version in the comments below. Let’s build a community of traders who code their own tools. 🚀
If you found this helpful, consider buying me a coffee ☕ — it keeps these articles coming!
Also check out my AI tools collection: AI 次元世界 — free AI tools for developers.
💡 Related: **Content Creator Ultimate Bundle (Save 33%)* — $29.99*
喜欢这篇文章?关注获取更多Python自动化内容!
Top comments (0)