Building Interactive Web Apps with Python and Streamlit

Python has become one of the most popular programming languages. It allows developers to build applications for data analysis, machine learning, automation, web development, and more…

One library that makes web development easier is Streamlit. This tool lets you build data-driven web applications. Unlike Flask or Django, Streamlit removes the need for complex front-end coding. You write Python, and Streamlit handles the interface.

Installing Streamlit and Dependencies

To get started, install Streamlit using pip:

pip install streamlit

If your application requires additional packages, install them as well. For example, if your app needs Pandas and Matplotlib:

If your application requires additional packages, install them as well. For example, if your app needs Pandas and Matplotlib:

Once everything is installed, verify Streamlit works by running:

streamlit hello

What Streamlit Does Well

Streamlit is great for rapid prototyping. It allows you to create interactive dashboards and data visualizations with little effort.

Here’s what makes it useful:

  1. Simplicity — You write Python scripts, and Streamlit turns them into web apps automatically.
  2. Live updates — When the script changes, Streamlit updates the app without restarting.
  3. Widgets without effort — Buttons, sliders, and file uploaders work without writing JavaScript.
  4. Built-in caching — Expensive computations run once and store results for later use.
  5. Integration with data tools — Works well with Pandas, Matplotlib, and machine learning models.

For developers working in data science or machine learning, Streamlit speeds up workflow.

What Streamlit Lacks

While powerful, Streamlit has limits:

  1. Not ideal for multi-user applications — Streamlit runs scripts from top to bottom. This makes handling user authentication or sessions challenging.
  2. Limited customization — Streamlit provides widgets, but they lack deep customization.
  3. Scaling issues — Designed for small projects, Streamlit struggles with high-traffic applications.
  4. Lack of page navigation — Unlike traditional web frameworks, Streamlit doesn’t support multi-page navigation well.

For small projects, these limitations may not matter. For larger applications, Flask or Django may work better.

Building a Streamlit App

Let’s build a Stock Price Dashboard that fetches stock data, charts trends, and allows users to select different stocks.

Step 1: Install Dependencies

This app requires yfinance (to fetch stock data) and Matplotlib (to plot charts). Install them with:

pip install yfinance matplotlib

Step 2: Write the Streamlit Script

Create a new file called app.py and add the following code:

import streamlit as st
import yfinance as yf
import matplotlib.pyplot as plt

# Set app title
st.title("Stock Price Dashboard")

# User selects stock ticker
ticker = st.text_input("Enter Stock Ticker", "AAPL")

# Set date range
start_date = st.date_input("Start Date", value=pd.to_datetime("2023-01-01"))
end_date = st.date_input("End Date", value=pd.to_datetime("today"))

# Fetch stock data
if st.button("Fetch Data"):
    try:
        stock_data = yf.download(ticker, start=start_date, end=end_date)
        st.write(f"Displaying data for {ticker}")

        # Show stock prices
        st.write(stock_data.tail())

        # Plot closing price
        fig, ax = plt.subplots()
        ax.plot(stock_data.index, stock_data["Close"], label="Closing Price", color="blue")
        ax.set_xlabel("Date")
        ax.set_ylabel("Price (USD)")
        ax.set_title(f"{ticker} Stock Price")
        ax.legend()
        st.pyplot(fig)

    except Exception as e:
        st.error(f"Error fetching data: {e}")

Step 3: Run the App

Start the application by running:

streamlit run app.py

Your browser will open with the stock price dashboard.

Understanding the Code

  1. st.title("Stock Price Dashboard") – Creates the page title.
  2. st.text_input("Enter Stock Ticker", "AAPL") – Provides a text box for users to enter stock symbols.
  3. st.date_input("Start Date") and st.date_input("End Date") – Allow users to set a date range.
  4. st.button("Fetch Data") – Runs data fetching when clicked.
  5. yf.download(ticker, start=start_date, end=end_date) – Uses yfinance to get stock prices.
  6. st.write(stock_data.tail()) – Displays recent stock prices in a table.
  7. matplotlib for plotting – Creates a closing price chart and displays it with st.pyplot(fig).

This app enables users to retrieve stock data and visualize trends easily.

Expanding the App

To improve the app, consider adding:

  • Moving averages — Calculate and plot 50-day or 200-day averages.
  • More chart types — Include volume, RSI, or Bollinger Bands.
  • Multiple tickers — Allow users to compare stocks side by side.

You can also find this article at Medium.com

Leave a Reply