DEV Community

Jean Pier Elias
Jean Pier Elias

Posted on

Building a web app on auto parts sales analysis using Streamlit with deployment on StreamShare

Streamlit

  • It is an open source Python library for creating interactive web
    applications quickly and easily.

  • Ideal for developing dashboards for data visualization,
    applications for machine learning models, tools for exploratory
    data analysis, and rapid prototyping of web applications.

  • It allows us to create interactive user interfaces using simple
    Python code, without the need to write HTML, CSS or JavaScript.

  • Widely used in data science, data analysis, machine learning, and web application development.

Streamshare

  • It is a cloud service that complements Streamlit, allowing to
    deploy and share web applications created with Streamlit.

  • It facilitates the process of putting applications developed
    with Streamlit into production, without the need to configure
    servers or web infrastructure.

  • It allows us to upload and host Streamlit applications in the
    cloud, generating public URLs to share with other users.

  • It is useful for sharing analysis results, collaborating on data
    science projects, creating web application demos, and
    distributing web applications to a wider audience.

1. Installing Streamlit:

  • To be able to use Streamlit, we will have to install the package through the console (CMD), to do so we execute the following command line: pip install streamlit

Image description
2. Creating the web app code :

  • For the demonstration of the use of Streamlite, a basic web app was developed, about the analysis of auto parts sales, which will show different data visualization graphs:
# Importación de Librerías
import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt

# Datos de productos y ventas
productos = {
    'Articulos': ['Cremalleras', 'Baterías', 'Faros', 'Radiadores'],
    'Stock': [250, 46, 25, 145],
    'Pre. Und': [275.00, 180.00, 90.00, 150.00]
}
productos_df = pd.DataFrame(productos)

ventas = {
    'Mes': ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo'],
    'Cremalleras': [7425, 6325, 11550, 5225, 4125],
    'Baterías': [900, 1440, 1260, 2160, 1980],
    'Faros': [720, 270, 450, 270, 360],
    'Radiadores': [3300, 4650, 2700, 3600, 1950]
}
ventas_df = pd.DataFrame(ventas)

# Cálculo de Ingresos, Egresos y Ganancia Neta
precios = {'Cremalleras': 275.00, 'Baterías': 180.00, 'Faros': 90.00, 'Radiadores': 150.00}

ventas_df['Ingresos'] = (ventas_df.drop('Mes', axis=1) * pd.Series(precios)).sum(axis=1)
ingresos_totales = 60660.00

egresos_totales = ingresos_totales * 0.5
ganancia_neta = ingresos_totales - egresos_totales

ventas_df['Egresos'] = ventas_df['Ingresos'] * (egresos_totales / ingresos_totales)

# Configuración de la Página Streamlit
st.set_page_config(page_title="Ventas de Autopartes", layout="wide")

# Título y Subtítulos
st.title("Ventas de Autopartes")
st.subheader("Tabla de Productos y Stock")
st.table(productos_df)

# Tabla de Ventas por Mes
st.subheader("Tabla de Ventas por Mes (en S/)")
st.table(ventas_df.drop(['Ingresos', 'Egresos'], axis=1).applymap
         (lambda x: f"S/ {x:,.2f}" if isinstance(x, (int, float)) else x))

# Ingresos y Egresos por Mes (Gráfico de Barras)
st.subheader("Ingresos y Egresos por Mes (en S/)")
fig, ax = plt.subplots()
ventas_df[['Mes', 'Ingresos', 'Egresos']].plot(kind='bar', x='Mes', ax=ax)
ax.set_xlabel('Mes')
ax.set_ylabel('Monto (S/)')
st.pyplot(fig)

# Distribución de Ingresos por Artículo (Gráfico de Pastel)
st.subheader("Distribución de Ingresos por Artículo (Enero) (en S/)")
fig, ax = plt.subplots()
ax.pie(ventas_df.iloc[0, 1:5], labels=ventas_df.columns[1:5], autopct='%1.1f%%')
ax.axis('equal')
st.pyplot(fig)

# Tendencia de Ventas (Gráfico de Líneas)
st.subheader("Tendencia de Ventas (en S/)")
fig, ax = plt.subplots()
for col in ventas_df.columns[1:5]:
    ax.plot(ventas_df['Mes'], ventas_df[col], marker='o', label=col)
ax.set_xlabel('Mes')
ax.set_ylabel('Monto (S/)')
ax.legend()
st.pyplot(fig)

# Resumen de Ventas (Métricas)
st.subheader("Resumen de Ventas (en S/)")
col1, col2, col3 = st.columns(3)
col1.metric("Ingresos Totales", f"S/ {ingresos_totales:,.2f}")
col2.metric("Egresos Totales", f"S/ {egresos_totales:,.2f}")
col3.metric("Ganancia Neta", f"S/ {ganancia_neta:,.2f}")

Enter fullscreen mode Exit fullscreen mode
  • We run our program using the following command line: streamlit run (filename)

Image description
-After executing the above command, a web page with our graphics
that we have defined in the code of the example exercise will
automatically open locally:

Image description

Image description

Image description

Image description

Image description

3. Deployment using Streamlit Share :

  • We enter the Streamlit share page, where we will have 3 options to deploy our web app, in this case we will make use of a previously created repository where we have uploaded our example exercise:

Image description

  • In the repository where we upload the exercise, we must make sure that it is in the main branch. In addition, if necessary, we must add the requirements in a .txt file.

Image description

  • Now, returning to Streamlit Share, we must select the name of our repository, in which branch it is located, the name of the file where we uploaded the code and click on deploy.

Image description

  • We waited a few minutes, and we will see that our deployment of our exercise could be completed.

Image description

Image description

Image description

Image description

As we can see, from the Streamlit installation process to deployment using Streamlit Share is done quickly and easily.
Link of the deployed test exercise:
https://app-example-vydyjngb4z5cbzz9ljqufe.streamlit.app/

Top comments (0)