In this tutorial, we’ll build a simple real-time stock price monitoring application using Python, Tkinter, and threading. This project fetches live stock data dynamically and displays it in a user-friendly graphical interface, demonstrating the basics of real-time data visualization.
To run this application, you need to install the yfinance
and matplotlib
libraries. Run the following commands in your terminal:
pip install yfinance
pip install matplotlib
Below is the complete code for the application. Bootstrap 4 colors are applied for easy readability.
# Importing necessary libraries
import tkinter as tk
from tkinter import ttk
import yfinance as yf
import threading
import time
# Fetch stock price
def fetch_stock_price():
try:
stock = yf.Ticker("AAPL") # Apple stock symbol
data = stock.history(period="1d", interval="1m") # Intraday data (1-minute interval)
price = data['Close'].iloc[-1] # Get the most recent closing price
return round(price, 2) # Round to 2 decimal places
except Exception as e:
return None
# Update stock price dynamically
def update_stock_price():
while True:
price = fetch_stock_price() # Fetch latest price
if price:
price_var.set(f"${price}") # Update label with current price
else:
price_var.set("Error fetching price")
time.sleep(5) # Update every 5 seconds
# Start background thread for price updates
def start_tracking():
threading.Thread(target=update_stock_price, daemon=True).start()
# Tkinter window setup
root = tk.Tk()
root.title("Apple Stock Tracker")
root.geometry("400x200")
# Label for stock name
stock_label = tk.Label(root, text="Apple Inc. (AAPL)", font=("Arial", 16, "bold"), fg="#007bff")
stock_label.pack(pady=10)
# Label for real-time stock price
price_var = tk.StringVar(value="Fetching...")
price_label = tk.Label(root, textvariable=price_var, font=("Arial", 24, "bold"), fg="#28a745")
price_label.pack(pady=20)
# Start button
start_button = ttk.Button(root, text="Start Tracking", command=start_tracking)
start_button.pack(pady=10)
# Run the Tkinter event loop
root.mainloop()
fetch_stock_price
function retrieves the latest stock price from Yahoo Finance.update_stock_price
function runs in a separate thread, updating the price every 5 seconds without blocking the GUI.StringVar
dynamically updates the displayed price.Now that you have a working real-time stock tracker, here are some ideas for expanding it:
After building the real-time stock tracker, you can further enhance your project by learning how to display the stored stock data:
This tutorial provides a foundational understanding of how to combine Tkinter, threading, and live data to build real-time data visualization applications. By extending this project, you can create more sophisticated tools tailored to your needs.