Stream lit: Unleashing the Power of Python for Seamless Web UI Development and Machine Learning

Stream lit: Unleashing the Power of Python for Seamless Web UI Development and Machine Learning

In the realm of web development, the demand for intuitive and interactive user interfaces is ever-increasing. Developers are constantly seeking tools and frameworks that can simplify the process of building engaging web applications. One such tool that has gained significant traction is Streamlit. In this article, I will explore the power of Streamlit and how it can be utilized for web development and ML Applications.

Python Developers while building a website only focus on the backend functionality of the application and the Frontend or the UI Components are hardcoded using plain HTML and CSS, somewhat React rarely. This is where Stream Lit comes as a saviour.

In this blog article, I will show how you can use Streamlit and create seamless ML Python Applications with some great Ui Features overall.

I have created a Stock Prediction App using Streamlit, so let's first walk through the whole process of initiating the installation and getting started.

Getting Started ✨

Create an empty folder in your Visual Studio Code.

Inside the terminal of that folder :

pip install streamlit

Note: you need to have pip, python3 and virtualenv installed in your local system

  1. The first step is to create a new Python script. HomePage.py.

  2. Now you need to import Streamlit, pandas, numpy libraries into your project.

     import streamlit as st
     import pandas as pd
     import numpy as np
    
  3.   st.title('Streamlit Demonstration by Jyotindra')
    

st is used as a variable here from which title as an object is fetched and we pass the title in strings (");

  1. Now you need to run this simple Application using :

     streamlit run Homepage.py
    

Stream lit functions ✨

Streamlit has various containers which we can use such as containers, images, title, subheaders, images, dividers etc.

The below code will demonstrate how just a few lines of code resulted into the building of the hero section of my project.

# First Section
with st.container():
    left_col, right_col = st.columns((1,1))
with right_col:
    product_image = Image.open(ASSETS_DIR / "fifth.png")
    st.image(product_image, width=500)
with left_col:

    st.title("Investing Build your portfolio starting with just $1")
    st.subheader("We are providing our users with the best possible experience.")
    st.markdown(
        f'<button class="button"><a href={STRIPE_CHECKOUT} >💹Subscribe here</a></button>',
        unsafe_allow_html=True
    )

st.divider()

section2 = """
<div class="section2">
    <div class="description2">
        <h1 class="header2">Level up your options strategies</h1>
        <p>Powerful. Smooth. Trades.</p>
    </div>
</div>
"""

st.markdown(f'<div class="">{section2}</div>', unsafe_allow_html=True)

st.divider()

Fetch Data in Stream lit✨

You can even fetch data into your application using very simple lines of code which you may get from Streamlit Documentation.

DATE_COLUMN = 'date/time'
DATA_URL = ('https://s3-us-west-2.amazonaws.com/'
         'streamlit-demo-data/data-deformatio0n.csv.gz')

def load_data(nrows):
    data = pd.read_csv(DATA_URL, nrows=nrows)
    lowercase = lambda x: str(x).lower()
    data.rename(lowercase, axis='columns', inplace=True)
    data[DATE_COLUMN] = pd.to_datetime(data[DATE_COLUMN])
    return data

Create your Machine Learning Application.✨

Let me explain what this application can do:

  • Give a dropdown for the selection of stocks for prediction.

  • Plot Raw data and Predicted Data in the form of charts, and graphs.

  • Draw out future predictions of stocks based on records and forecast components.

Let's first import all the packages we need for the initialization proess.

import streamlit as st
from datetime import date

import yfinance as yf
from prophet import Prophet
from prophet.plot import plot_plotly
from plotly import graph_objs as go

Now let's add or assign the variables and states we wish to use later :

START = "2015-01-01"
TODAY = date.today().strftime("%Y-%m-%d")


st.sidebar.success("This is a sidebar")

st.title("Stock Prediction & Analysis")

stocks = ("AAPL", "GOOG", "MSFT", "GME", "TSLA", "AMZN", "NFLX")
selected_stock = st.selectbox("Select dataset for prediction", stocks)

n_years = st.slider("Years of prediction:", 1 , 4)
period = n_years * 365

Here AAPL, GOOG, MSFT, TSL, AMZN, NETFLIX means Apple, Google, Microsoft Office and Amazon.

Now let's predict the stock data with their volumes.

def plot_raw_data():
    fig = go.Figure()
    fig.add_trace(go.Scatter(x=data['Date'], y=data['Open'], name="stock_open"))
    fig.add_trace(go.Scatter(x=data['Date'], y=data['Close'], name="stock_close"))
    fig.layout.update(title='Time Series data with Rangeslider', xaxis_rangeslider_visible=True)
    st.plotly_chart(fig)

plot_raw_data()

Forecast plot for x number of years:

# Predict forecast with Prophet.
df_train = data[['Date','Close']]
df_train = df_train.rename(columns={"Date": "ds", "Close": "y"})

m = Prophet()
m.fit(df_train)
future = m.make_future_dataframe(periods=period)
forecast = m.predict(future)

Plot forecast components and predictive data

st.subheader('Forecast data')
st.write(forecast.tail())

st.subheader(f'Forecast plot for {n_years} years')
fig1 = plot_plotly(m, forecast)
st.plotly_chart(fig1)

st.subheader("Forecast components")
fig2 = m.plot_components(forecast)
st.write(fig2)

Your Application would look something like this:

As you can see, our application is ready and working using ML Models and Data Prediction. We haven't written a single line of code for Machine Learning Logic, still the application is fully functional and ready to be deployed on the Internet.

This is the Power of Streamlit which I was talking about. 🤖✨

You can check this project here : Stock Prediction Project

Next Article: How to perform Web Data Scrapping.

Until Next Time! ✨

Make sure you comment your thoughts and new ideas for this blog channel. Subscribe to my newsletter 💓 so that you will never miss any of my new articles or tech blog ever in future!