DEV Community

Max Klein
Max Klein

Posted on

Building a Stock Price Bot with Python: Complete Tutorial

In today’s fast-paced financial markets, staying ahead of the curve means having access to real-time data and automation. Imagine a tool that continuously monitors stock prices, sends alerts when thresholds are crossed, and even logs historical data for analysis—all without lifting a finger. That’s the power of a stock price bot, and in this tutorial, you’ll learn how to build one using Python. Whether you’re a developer looking to automate your trading strategies or a beginner eager to dive into financial data, this guide will walk you through every step of the process. Let’s get started!


Prerequisites

Before we jump into coding, ensure your environment meets the following requirements:

📦 Software and Tools

  • Python 3.8+ installed on your system. Download Python here.
  • pip (Python’s package installer) for managing dependencies.
  • A code editor like Visual Studio Code, PyCharm, or Jupyter Notebook.

📌 Required Libraries

You’ll need the following Python libraries:

  • yfinance: For fetching stock data from Yahoo Finance.
  • requests: For interacting with APIs (if needed).
  • schedule: For scheduling recurring tasks (e.g., daily price checks).
  • datetime: For handling dates and times.

Install them using pip:

pip install yfinance requests schedule
Enter fullscreen mode Exit fullscreen mode

Tip: Always use a virtual environment (via venv or conda) to isolate dependencies and avoid conflicts.


Setting Up Your Development Environment

  1. Create a Project Folder Organize your code by creating a dedicated directory for your bot:
   mkdir stock_price_bot
   cd stock_price_bot
Enter fullscreen mode Exit fullscreen mode
  1. Initialize a Virtual Environment
   python -m venv venv
   source venv/bin/activate  # On Windows: venv\Scripts\activate
Enter fullscreen mode Exit fullscreen mode
  1. Install Dependencies Run the pip install command from the prerequisites section.

Step 1: Fetching Real-Time Stock Data with yfinance

The yfinance library is a game-changer for stock data. It provides access to Yahoo Finance’s API, allowing you to retrieve current prices, historical data, and company fundamentals with minimal code.

✅ Example: Get the Current Price of a Stock

import yfinance as yf

def get_current_price(symbol):
    try:
        stock = yf.Ticker(symbol)
        price = stock.info["regularMarketPrice"]
        return price
    except Exception as e:
        print(f"Error fetching data for {symbol}: {e}")
        return None

# Example usage
symbol = "AAPL"
price = get_current_price(symbol)
if price:
    print(f"Current price of {symbol}: ${price:.2f}")
Enter fullscreen mode Exit fullscreen mode

🔍 Explanation

  • yf.Ticker(symbol) initializes a stock object.
  • stock.info is a dictionary containing metadata like price, volume, and market cap.
  • regularMarketPrice gives the latest price (may vary slightly based on market hours).

Warning: Yahoo Finance’s API may throttle requests if you make too many calls in a short time. Use this responsibly.


Step 2: Monitoring Price Changes and Sending Alerts

Now that we can fetch current prices, let’s build a function to monitor changes and send alerts when a stock crosses a predefined threshold.

🚨 Example: Price Alert System

import time
import smtplib  # For sending emails (basic example)

def send_email_alert(subject, body, to_email):
    from_email = "your_email@example.com"
    from_password = "your_email_password"

    try:
        server = smtplib.SMTP("smtp.gmail.com", 587)
        server.starttls()
        server.login(from_email, from_password)
        message = f"Subject: {subject}\n\n{body}"
        server.sendmail(from_email, to_email, message)
        server.quit()
        print("Email alert sent successfully!")
    except Exception as e:
        print(f"Failed to send email: {e}")

def monitor_price(symbol, threshold, email):
    while True:
        price = get_current_price(symbol)
        if price and price > threshold:
            send_email_alert(
                subject=f"Price Alert for {symbol}",
                body=f"The price of {symbol} has exceeded ${threshold}! Current price: ${price:.2f}",
                to_email=email
            )
        time.sleep(60)  # Check every 60 seconds

# Example usage
monitor_price("TSLA", 300, "your_email@example.com")
Enter fullscreen mode Exit fullscreen mode

⚠️ Important Notes

  • Replace your_email@example.com and your_email_password with valid credentials. Consider using OAuth2 or email services like Mailgun for better security.
  • This is a basic example. In production, avoid hardcoding sensitive info like passwords.

Step 3: Logging Historical Data for Analysis

Tracking historical data lets you analyze trends and make data-driven decisions. Let’s modify our bot to log prices to a CSV file.

📊 Example: Save Historical Data

import csv
from datetime import datetime

def log_price_to_csv(symbol, price):
    filename = f"{symbol}_history.csv"
    try:
        with open(filename, "a", newline="") as file:
            writer = csv.writer(file)
            writer.writerow([datetime.now(), price])
        print(f"Logged price for {symbol} to {filename}")
    except Exception as e:
        print(f"Error logging data: {e}")

# Example usage
log_price_to_csv("AAPL", 190.50)
Enter fullscreen mode Exit fullscreen mode

📈 Enhancements

  • Use Pandas to handle CSV files for more complex analysis.
  • Store data in a database (e.g., SQLite) for scalability.

Step 4: Automating the Bot with a Scheduler

Manually running the bot isn’t efficient. Let’s use the schedule library to automate checks at regular intervals.

⏰ Example: Schedule Daily Price Checks

import schedule
import time

def job():
    print("Running scheduled task...")
    monitor_price("AAPL", 190, "your_email@example.com")

# Schedule the job every day at 9 AM
schedule.every().day.at("09:00").do(job)

while True:
    schedule.run_pending()
    time.sleep(1)
Enter fullscreen mode Exit fullscreen mode

Tip: For production use, consider using cron jobs (Linux/Mac) or Task Scheduler (Windows) for more reliable automation.


Step 5: Deploying Your Bot

Once your bot is working locally, deploy it to a cloud service or server for continuous operation.

🚀 Deployment Options

  • Heroku: Easy to deploy Python apps with a free tier.
  • AWS Lambda: Serverless option for running scripts on a schedule.
  • DigitalOcean: Affordable VPS for full control.

🛡️ Best Practices for Deployment

  • Use environment variables to store API keys and credentials.
  • Set up monitoring (e.g., via Sentry or Datadog) to track errors.
  • Implement rate limiting to avoid API abuse.

Conclusion

Congratulations—you’ve built a fully functional stock price bot that fetches real-time data, sends alerts, and logs historical information! This is just the beginning. With Python’s versatility, you can expand your bot to include features like:

  • GUI dashboards (using Tkinter or Streamlit).
  • Machine learning models for price prediction.
  • Integration with trading platforms (e.g., Alpaca or Interactive Brokers).

Next Steps

Here are some ideas to take your bot to the next level:

  1. Add Multiple Stock Support

    Modify the code to handle a list of symbols and thresholds.

  2. Implement Webhooks

    Use services like IFTTT or Zapier to trigger actions based on price changes.

  3. Build a Web Interface

    Use Flask or Django to create a dashboard for viewing stock data.

  4. Explore Alternative APIs

    Try Alpha Vantage, IEX Cloud, or Polygon.io for more advanced features.

  5. Automate Backtesting

    Use historical data to simulate trading strategies and evaluate performance.


Final Thoughts

Building a stock price bot is a powerful way to automate financial monitoring and analysis. As you continue refining your bot, always prioritize security, reliability, and scalability. Whether you’re tracking your portfolio or experimenting with algorithmic trading, Python gives you the tools to succeed. Now go forth and code! 🚀

Built by N3X1S INTELLIGENCE — we automate data extraction at scale. Need custom scraping, bots, or data pipelines? Hire us on Fiverr.

Top comments (0)