Real-Time Data Visualization with Tkinter

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.

Why Use Tkinter for Data Visualization?

  • Lightweight GUI: Tkinter is easy to set up and comes pre-installed with Python.
  • Real-Time Updates: By integrating threading, we can fetch live data without freezing the interface.
  • Beginner-Friendly: This example is a great starting point for building more complex real-time data visualization applications.

Key Libraries Used

  • yfinance: A Python library for retrieving real-time stock prices and other financial data from Yahoo Finance.
  • Tkinter: Python’s built-in library for creating graphical user interfaces, used here for building a responsive desktop app.
  • threading: Enables background tasks like fetching live stock prices without freezing the main application.

Installation of Required Libraries

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

Full Code: Real-Time Stock Price Tracker

Displaying Apple stock price : real time data

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()

How It Works

  • Fetching Stock Data: The fetch_stock_price function retrieves the latest stock price from Yahoo Finance.
  • Background Thread: The update_stock_price function runs in a separate thread, updating the price every 5 seconds without blocking the GUI.
  • Tkinter Integration:
    • A StringVar dynamically updates the displayed price.
    • Labels and buttons provide a clean, user-friendly interface.

Next Steps

Now that you have a working real-time stock tracker, here are some ideas for expanding it:

  • Add a dropdown menu to select different stocks.
  • Display a graph of the stock’s price over time for better data visualization.
  • Introduce alerts for specific price thresholds.
  • Allow users to track multiple stocks in separate windows.
Real-Time Stock Monitoring with Graphs

After building the real-time stock tracker, you can further enhance your project by learning how to display the stored stock data:

  • Fetch and display stored stock prices from the SQLite database.
  • Use a dropdown menu to select different stocks for data display.
  • View data in a tabular format with stock name, price, and timestamp columns.
  • Leverage Tkinter’s Treeview widget for an interactive table.
View Stored Stock Data

Conclusion

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.


Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer