Key Concepts
TK Inter, Data Dashboards, Python, Pandas, Matplotlib, Y Finance, Candlestick Charts, GUI (Graphical User Interface), Data Visualization, Event Binding, Subplots, Figure Canvas, Stock Ticker, Technical Analysis, Portfolio Simulation.
Building Interactive Data Dashboards in Python with TK Inter
Introduction
The video demonstrates how to create interactive data dashboards in Python using TK Inter for the GUI, Pandas for data handling, and Matplotlib for visualizations. It covers building basic dashboards from scratch and showcases more advanced examples with readily available code.
Basic Titanic Data Dashboard
- Project Setup:
- Creating a new project with a virtual environment (using
venv,virtualenv, oruv). - Installing necessary packages:
pandasandmatplotlibusingpip install pandas matplotliborpip3 install pandas matplotlib.
- Creating a new project with a virtual environment (using
- Imports:
import tkinter as tkfrom tkinter import ttk(for advanced widgets)import pandas as pdimport matplotlib.pyplot as pltfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg(for embedding Matplotlib plots in TK Inter)
- Data Loading:
- Using
pandas.read_csv()to load the Titanic dataset (Titanic.csv). The data set contains information about passengers like age, name, and survival status (0 or 1).
- Using
- Class Structure:
- Creating a class
SimpleDashboardto encapsulate the dashboard logic. __init__(self, root): Constructor to initialize the TK Inter root instance, set the title and geometry of the window.
- Creating a class
- Control Frame:
- Creating a
tk.Framecalledcontrol_frameto hold interactive elements. - Adding a
tk.Labelwith text "Column" to indicate column selection. - Creating a
tk.StringVarcalledcolumn_variableto store the selected column name (defaulting to "Age"). - Adding a
ttk.Combobox(drop-down) to select columns ("Age" and "Fare"). - Binding the
"<<ComboboxSelected>>"event to theupdate_chartsmethod to update the charts when a new column is selected.
- Creating a
- Chart Frame:
- Creating a
tk.Framecalledchart_frameto hold the Matplotlib charts. - Using
chart_frame.pack(fill=tk.BOTH, expand=True)to make the frame fill the available space.
- Creating a
- Subplots Creation:
- Using
plt.subplots(2, 2, figsize=(12, 8))to create a 2x2 grid of subplots. - Storing the figure and axes objects as
self.figure,self.axis1,self.axis2,self.axis3, andself.axis4.
- Using
- Embedding Matplotlib Charts:
- Creating a
FigureCanvasTkAgginstance to embed the Matplotlib figure in the TK Inter window:self.canvas = FigureCanvasTkAgg(self.figure, chart_frame). - Packing the canvas using
self.canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True).
- Creating a
update_chartsMethod:- Retrieving the selected column name using
self.column_variable.get(). - Clearing previous plots using
self.axis1.clear(),self.axis2.clear(), etc. - Plotting a pie chart of survival rate on
self.axis1usingself.data_frame["Survived"].value_counts().plot.pie().- Labels: "Not Survived", "Survived"
autopct="%1.1f%%"for percentage formatting.
- Plotting a histogram of the selected column on
self.axis2usingself.data_frame[selected_column].hist().bins=20,color="skyblue",alpha=0.7.
- Plotting a bar chart of passenger classes on
self.axis3usingself.data_frame["Pclass"].value_counts().sort_index().plot.bar().- Colors: "red", "green", "blue".
- Plotting a scatter plot of the selected column versus "Fare" on
self.axis4, colored by survival status.- Iterating through survived values (0 and 1).
- Creating subsets of the data frame based on survival.
- Using
self.axis4.scatter()to plot the data. - Setting labels and legend.
- Calling
self.figure.tight_layout()to adjust subplot parameters for a tight layout. - Calling
self.canvas.draw()to update the canvas with the new plots.
- Retrieving the selected column name using
- Main Loop:
- Creating a TK Inter root instance:
root = tk.Tk(). - Creating an instance of the
SimpleDashboardclass:app = SimpleDashboard(root). - Starting the TK Inter event loop:
root.mainloop().
- Creating a TK Inter root instance:
Advanced Titanic Analytics Dashboard (Code Provided)
- Features:
- Data exploration with search functionality.
- Correlation heat map.
- Survival analysis.
- Age and fare distributions.
- Filtering by age, gender, and class.
- Export functionality.
- Implementation:
- Uses the same principles as the basic dashboard but with more UI elements, customization, and Matplotlib features.
- Employs tabs, buttons, combo boxes, and other TK Inter widgets.
Basic Stock Ticker Visualization
- Additional Package:
- Installing
yfinanceusingpip install yfinanceorpip3 install yfinanceto fetch stock data from Yahoo Finance.
- Installing
- Imports:
import tkinter as tkfrom tkinter import messagebox(for displaying error messages)import yfinance as yfimport matplotlib.pyplot as pltimport matplotlib.dates as mdatesfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
- Class Structure:
- Creating a class
CandlestickChartto encapsulate the stock visualization logic. __init__(self, root): Constructor to initialize the TK Inter root instance, set the title, geometry, and dark mode styling.
- Creating a class
- Dark Mode Styling:
- Setting the background color of the root window using
self.root.configure(bg="#2B2B2B"). - Using a dark theme for Matplotlib plots using
plt.style.use("dark_background").
- Setting the background color of the root window using
- Control Frame:
- Creating a
tk.Framecalledcontrol_frameto hold input fields and the load button. - Adding labels and entry fields for stock ticker, start date, and end date using
tk.Labelandtk.Entry. - Using
tk.StringVarto store the values entered in the entry fields. - Using the
gridlayout manager to position the labels and entry fields. - Adding a "Load Chart" button using
tk.Buttonand binding it to theload_chartmethod.
- Creating a
- Chart Frame:
- Creating a
tk.Framecalledchart_frameto hold the candlestick chart. - Using
chart_frame.pack(fill=tk.BOTH, expand=True)to make the frame fill the available space.
- Creating a
- Subplot Creation:
- Using
plt.subplots(figsize=(12, 6))to create a single subplot. - Storing the figure and axis objects as
self.figureandself.axis.
- Using
- Embedding Matplotlib Chart:
- Creating a
FigureCanvasTkAgginstance to embed the Matplotlib figure in the TK Inter window:self.canvas = FigureCanvasTkAgg(self.figure, chart_frame). - Packing the canvas using
self.canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True).
- Creating a
load_chartMethod:- Retrieving the ticker symbol, start date, and end date from the entry fields using
self.ticker_variable.get(),self.start_variable.get(), andself.end_variable.get(). - Fetching stock data from Yahoo Finance using
yf.Ticker(ticker).history(start=start_date, end=end_date). - Handling potential errors:
- Displaying an error message if no data is found using
messagebox.showerror(). - Displaying a generic error message for any other exceptions.
- Displaying an error message if no data is found using
- Calling the
create_candlestick_chartmethod to generate the candlestick chart.
- Retrieving the ticker symbol, start date, and end date from the entry fields using
create_candlestick_chartMethod:- Clearing the previous plot using
self.axis.clear(). - Extracting data from the stock data frame: dates, opens, closes, lows, highs.
- Determining up days (closing price >= opening price) and down days (closing price < opening price).
- Defining colors for up days (green) and down days (red).
- Creating candlestick charts using
self.axis.bar()to plot the body and wicks of the candles.- Using different colors for up and down days.
- Adjusting the width of the bars to create the candlestick effect.
- Setting the title, labels, and grid for the chart.
- Formatting the x-axis dates using
mdates.DateFormatterandmdates.MonthLocator. - Calling
self.figure.autofmt_xdate()to automatically format the x-axis dates. - Calling
self.figure.tight_layout()to adjust subplot parameters for a tight layout. - Calling
self.canvas.draw()to update the canvas with the new plot.
- Clearing the previous plot using
- Main Loop:
- Creating a TK Inter root instance:
root = tk.Tk(). - Creating an instance of the
CandlestickChartclass:app = CandlestickChart(root). - Starting the TK Inter event loop:
root.mainloop().
- Creating a TK Inter root instance:
Advanced Stock Analysis Dashboard (Code Provided)
- Features:
- Technical indicators (Bollinger Bands, Simple Moving Average, Exponential Moving Average).
- Key metrics (Market Cap, PE Ratio).
- Portfolio simulation.
- Stock comparison.
- Implementation:
- Uses the same principles as the basic stock ticker visualization but with more advanced Matplotlib features, calculations, and UI elements.
- Employs tabs and a navigation toolbar.
Conclusion
The video provides a comprehensive guide to building interactive data dashboards in Python using TK Inter and Matplotlib. It covers the basic steps of setting up a project, creating a GUI, loading data, generating plots, and embedding them in the TK Inter window. The advanced examples demonstrate how to create more sophisticated dashboards with additional features and customization. The key takeaway is that by combining the power of TK Inter for GUI development and Matplotlib for data visualization, developers can create powerful and interactive data dashboards in Python.
AI summaries can miss context or contain errors. Check important details against the original video.