Streamlit: A Python Library That Speeds Up Data App Development by 10x!

Streamlit: A Python Library That Speeds Up Data App Development by 10x!

Hello everyone~ I’m Yujie.

Today, I want to introduce a particularly powerful tool – Streamlit.

If you find developing data visualization web applications troublesome, or if front-end development gives you a headache, you must try this library!

It allows you to easily build beautiful data applications using pure Python code.

Streamlit: A Python Library That Speeds Up Data App Development by 10x!

Why Choose Streamlit?

Traditional web application development usually requires:

  • • Learning HTML/CSS/JavaScript

  • • Configuring complex web frameworks

  • • Handling front-end and back-end interactions

  • • Setting up a development environment

With Streamlit, none of these are necessary! If you know Python, you can create professional-level data applications. Its features include:

  • • Pure Python code

  • • No front-end knowledge required

  • • Real-time hot reloading

  • • A rich component library

Installation Guide

System Requirements

  • • Python 3.7+

  • • pip package manager

  • • Recommended: More than 4GB of RAM

Installation Command

pip install streamlit

Verify Installation

Create a file hello.py:

import streamlit as st
st.write("Hello, Streamlit!")

Run the command:

streamlit run hello.py

Common Issues

  1. 1. Solution for port being occupied: Use a different port streamlit run hello.py --server.port 8501

  2. 2. Solution for webpage not opening: Check firewall settings or use localhost to access

Basic Usage

Let’s take a look at the basic functionalities of Streamlit:

import streamlit as st
import pandas as pd
import numpy as np

# Set page title
st.title("My First Streamlit App")

# Add text
st.write("This is a simple data display page")

# Display data table
df = pd.DataFrame({
    'Name': ['Xiao Ming', 'Xiao Hong', 'Xiao Zhang'],
    'Age': [25, 28, 22],
    'City': ['Beijing', 'Shanghai', 'Guangzhou']
})
st.dataframe(df)

# Draw chart
chart_data = pd.DataFrame(
    np.random.randn(20, 3),
    columns=['Stock A', 'Stock B', 'Stock C'])
st.line_chart(chart_data)

Core Components

  1. 1. Input Components

# Text input
name = st.text_input("Please enter your name")

# Number slider
age = st.slider("Select age", 0, 100, 25)

# Selection box
option = st.selectbox(
    "Choose your favorite programming language",
    ["Python", "Java", "JavaScript"]
)
  1. 2. Layout Components

# Create sidebar
st.sidebar.title("Settings")

# Create tabs
tab1, tab2 = st.tabs(["Chart", "Data"])
with tab1:
    st.write("This is the chart")
with tab2:
    st.write("This is the data")

Practical Cases

Case 1: Stock Data Analyzer

import streamlit as st
import yfinance as yf
import pandas as pd
import plotly.express as px

def stock_analyzer():
    """
    Create a simple stock data analysis application
    """
    st.title("📈 Stock Data Analyzer")
    
    # Sidebar configuration
    st.sidebar.header("Parameter Settings")
    symbol = st.sidebar.text_input("Stock Code", "AAPL")
    period = st.sidebar.selectbox(
        "Time Range",
        ["1mo", "3mo", "6mo", "1y", "2y", "5y"]
    )
    
    # Load data
    @st.cache_data  # Use cache to improve performance
    def load_data(ticker, period):
        data = yf.download(ticker, period=period)
        return data
    
    try:
        # Show loading prompt
        with st.spinner('Loading data...'):
            data = load_data(symbol, period)
            
        # Show stock information
        st.subheader(f"{symbol} Stock Data")
        st.dataframe(data.tail())
        
        # Draw stock price trend chart
        fig = px.line(data, 
                     y=['Close', 'Open'], 
                     title='Stock Price Trend')
        st.plotly_chart(fig)
        
        # Calculate technical indicators
        data['SMA20'] = data['Close'].rolling(window=20).mean()
        data['SMA50'] = data['Close'].rolling(window=50).mean()
        
        # Show technical analysis chart
        fig_tech = px.line(data, 
                          y=['Close', 'SMA20', 'SMA50'],
                          title='Technical Analysis')
        st.plotly_chart(fig_tech)
        
        # Show basic statistics
        st.subheader("Statistical Summary")
        col1, col2, col3 = st.columns(3)
        with col1:
            st.metric("Current Price", 
                     f"${data['Close'][-1]:.2f}",
                     f"{((data['Close'][-1]/data['Close'][-2])-1)*100:.2f}%")
        with col2:
            st.metric("Volume", 
                     f"{data['Volume'][-1]:,.0f}")
        with col3:
            st.metric("Volatility", 
                     f"{data['Close'].std():.2f}")
            
    except Exception as e:
        st.error(f"An error occurred: {str(e)}")
        
if __name__ == "__main__":
    stock_analyzer()

Case 2: Intelligent Text Analysis Tool

import streamlit as st
from textblob import TextBlob
import matplotlib.pyplot as plt
import seaborn as sns
import nltk
from wordcloud import WordCloud

def text_analyzer():
    """
    Create a text analysis tool
    """
    st.title("📝 Intelligent Text Analysis Tool")
    
    # Text input
    text = st.text_area("Please enter the text to analyze:", 
                       height=200)
    
    if text:
        # Create analyze button
        if st.button("Start Analysis"):
            # Sentiment analysis
            blob = TextBlob(text)
            sentiment = blob.sentiment.polarity
            
            # Show sentiment score
            st.subheader("Sentiment Analysis")
            col1, col2 = st.columns(2)
            with col1:
                st.metric("Sentiment Score", f"{sentiment:.2f}")
            with col2:
                sentiment_label = "Positive" if sentiment > 0 else "Negative" if sentiment < 0 else "Neutral"
                st.metric("Sentiment Tendency", sentiment_label)
            
            # Text statistics
            st.subheader("Text Statistics")
            col3, col4, col5 = st.columns(3)
            with col3:
                st.metric("Character Count", len(text))
            with col4:
                st.metric("Word Count", len(text.split()))
            with col5:
                st.metric("Sentence Count", len(blob.sentences))
            
            # Generate word cloud
            st.subheader("Word Cloud")
            wordcloud = WordCloud(width=800, height=400,
                                background_color='white').generate(text)
            
            fig, ax = plt.subplots(figsize=(10, 5))
            ax.imshow(wordcloud, interpolation='bilinear')
            ax.axis('off')
            st.pyplot(fig)
            
            # Common words analysis
            words = nltk.word_tokenize(text.lower())
            word_freq = nltk.FreqDist(words)
            
            st.subheader("Common Words Analysis")
            word_data = pd.DataFrame(word_freq.most_common(10),
                                   columns=['Word', 'Frequency'])
            fig = px.bar(word_data, x='Word', y='Frequency')
            st.plotly_chart(fig)

if __name__ == "__main__":
    text_analyzer()

Conclusion

Through this article, we learned about Streamlit, a powerful data application development tool. Its advantages include:

  • • Extremely high development efficiency

  • • No front-end knowledge required

  • • A rich and easy-to-use component library

  • • Simple and convenient deployment

  • • Real-time hot reloading

If you need to quickly develop data visualization applications, Streamlit is definitely the best choice!

For those who want to learn more, you can check the official documentation: https://docs.streamlit.io/

That’s all for today’s sharing! If you found it useful, please give it a thumbs up~ If you have any questions, feel free to leave a message in the comments, and I will reply promptly! Remember, the most important thing about learning new technologies is to practice hands-on, so go ahead and give it a try!

See you next time~ We’ll continue to share more useful Python tools!

Leave a Comment