๐ฏ 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
| Library | Purpose |
|---|---|
requests | Fetch stock data from APIs |
pandas | Store and analyze stock data |
matplotlib | Plot price trends |
time, datetime | Handle 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
| Feature | Description |
|---|---|
| ๐ Multiple Stock Comparison | Track multiple tickers in one plot |
| ๐งพ Historical Data | Fetch past data using yfinance |
| ๐ Candlestick Charts | Use mplfinance for advanced visualizations |
| ๐ Telegram/Discord Alerts | Send price updates to chat apps |
| โ๏ธ Web Dashboard | Display live prices using Flask or Streamlit |

Leave a Reply