20 – Real-World Python Projects – Stock Price Tracker

๐ŸŽฏ Project Objective

To build a Python-based Stock Price Tracker that fetches real-time stock market data, visualizes price trends, and sends alerts when prices cross certain thresholds.


๐Ÿง  Skills Youโ€™ll Learn

  • Using APIs (like Yahoo Finance or Alpha Vantage)
  • Working with JSON data
  • Data analysis using pandas
  • Plotting graphs with matplotlib
  • Automating alerts via email/SMS
  • Scheduling periodic updates

โš™๏ธ Technology Stack

LibraryPurpose
requestsFetch stock data from APIs
pandasStore and analyze stock data
matplotlibPlot price trends
time, datetimeHandle time-based tracking
smtplib (optional)Send email alerts
schedule (optional)Automate periodic tracking

๐Ÿงฉ Step 1 โ€” Auto-Install Required Libraries

import subprocess, sys

def install(package):
    try:
        __import__(package)
    except ImportError:
        subprocess.check_call([sys.executable, "-m", "pip", "install", package])

for pkg in ["requests", "pandas", "matplotlib", "schedule"]:
    install(pkg)

๐Ÿงพ Step 2 โ€” Import Required Modules

import requests
import pandas as pd
import matplotlib.pyplot as plt
import time
from datetime import datetime

๐Ÿ“Š Step 3 โ€” Fetch Real-Time Stock Data

Using the Yahoo Finance API (unofficial) via RapidAPI or public endpoint:

def get_stock_price(symbol):
    url = f"https://query1.finance.yahoo.com/v7/finance/quote?symbols={symbol}"
    response = requests.get(url)
    data = response.json()
    price = data['quoteResponse']['result'][0]['regularMarketPrice']
    return price

๐Ÿงฎ Step 4 โ€” Track and Store Prices Over Time

symbol = "AAPL"  # Example: Apple Inc.
prices = []
timestamps = []

for i in range(5):  # Fetch 5 times for demo
    price = get_stock_price(symbol)
    prices.append(price)
    timestamps.append(datetime.now().strftime("%H:%M:%S"))
    print(f"{symbol} Price: ${price}")
    time.sleep(2)  # Wait before next check

df = pd.DataFrame({"Time": timestamps, "Price": prices})
print(df)

๐Ÿ“ˆ Step 5 โ€” Visualize Stock Price Trend

plt.plot(df["Time"], df["Price"], marker="o")
plt.title(f"{symbol} Stock Price Over Time")
plt.xlabel("Time")
plt.ylabel("Price (USD)")
plt.grid(True)
plt.show()

โœ… This shows a live trend of stock price changes.


โš ๏ธ Step 6 โ€” Add Price Alerts

THRESHOLD = 210.0  # Example alert limit

if price >= THRESHOLD:
    print(f"๐Ÿšจ Alert: {symbol} has crossed ${THRESHOLD}!")

๐Ÿ“ฌ Step 7 โ€” (Optional) Send Email Alert

import smtplib

def send_email_alert(symbol, price):
    sender = "youremail@gmail.com"
    receiver = "targetemail@gmail.com"
    password = "yourpassword"

    message = f"Subject: Stock Alert\n\n{symbol} price reached ${price}"

    with smtplib.SMTP("smtp.gmail.com", 587) as server:
        server.starttls()
        server.login(sender, password)
        server.sendmail(sender, receiver, message)

# Example usage:
# send_email_alert(symbol, price)

โœ… You can replace the credentials with environment variables for safety.


๐Ÿ”„ Step 8 โ€” Automate Daily Tracking

import schedule

def job():
    price = get_stock_price("AAPL")
    print(f"{datetime.now()} โ€” AAPL: ${price}")

schedule.every(5).minutes.do(job)

while True:
    schedule.run_pending()
    time.sleep(1)

โœ… Automatically checks every 5 minutes and logs updates.


๐Ÿ“˜ Full Combined Version

import subprocess, sys, time, requests, pandas as pd, matplotlib.pyplot as plt
from datetime import datetime

def install(package):
    try:
        __import__(package)
    except ImportError:
        subprocess.check_call([sys.executable, "-m", "pip", "install", package])

for pkg in ["requests", "pandas", "matplotlib"]:
    install(pkg)

def get_stock_price(symbol):
    url = f"https://query1.finance.yahoo.com/v7/finance/quote?symbols={symbol}"
    data = requests.get(url).json()
    return data['quoteResponse']['result'][0]['regularMarketPrice']

symbol = input("Enter Stock Symbol (e.g., AAPL, TSLA): ").upper()
prices, times = [], []

print(f"Tracking {symbol} stock price...")
for i in range(10):
    price = get_stock_price(symbol)
    prices.append(price)
    times.append(datetime.now().strftime("%H:%M:%S"))
    print(f"{symbol} Price: ${price}")
    time.sleep(5)

df = pd.DataFrame({"Time": times, "Price": prices})
df.to_csv(f"{symbol}_prices.csv", index=False)

plt.plot(df["Time"], df["Price"], marker="o", color="blue")
plt.title(f"{symbol} Stock Tracker")
plt.xlabel("Time")
plt.ylabel("Price (USD)")
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

๐ŸŒ Real-Life Applications

โœ… Monitor personal investment portfolios
โœ… Integrate into financial dashboards
โœ… Automate buy/sell alerts
โœ… Collect data for ML-based price prediction
โœ… Power up Excel dashboards via Python


๐Ÿ’ก Next-Level Enhancements

FeatureDescription
๐Ÿ“ˆ Multiple Stock ComparisonTrack multiple tickers in one plot
๐Ÿงพ Historical DataFetch past data using yfinance
๐Ÿ“Š Candlestick ChartsUse mplfinance for advanced visualizations
๐Ÿ”” Telegram/Discord AlertsSend price updates to chat apps
โ˜๏ธ Web DashboardDisplay live prices using Flask or Streamlit


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *