import streamlit as st import pandas as pd import plotly.express as px import plotly.graph_objects as go # Configuración de la página principal st.set_page_config(page_title="Customer Insights App", page_icon=":bar_chart:") # Cargar el archivo CSV que ya está disponible en la web df = pd.read_csv("df_clean.csv") # Asegúrate de que la ruta del archivo es correcta # Ignorar las dos últimas columnas df = df.iloc[:, :-2] # Asegurarse de que el código del cliente sea una cadena (string) df['CLIENTE'] = df['CLIENTE'].astype(str) # Diseño de la página principal st.title("Welcome to Customer Insights App") st.markdown(""" This app helps businesses analyze customer behaviors and provide personalized recommendations based on purchase history. Use the tools below to dive deeper into your customer data. """) # Menú de navegación page = st.selectbox("Selecciona la herramienta que quieres utilizar", ["", "Customer Analysis", "Customer Recommendations"]) # Página Home if page == "": st.markdown("## Welcome to the Customer Insights App") st.write("Use the dropdown menu to navigate between the different sections.") # Página Customer Analysis elif page == "Customer Analysis": st.title("Customer Analysis") st.markdown(""" Use the tools below to explore your customer data. """) # Campo para filtrar clientes partial_code = st.text_input("Enter part of Customer Code (or leave empty to see all)") # Filtrar las opciones de clientes que coincidan con el código parcial if partial_code: filtered_customers = df[df['CLIENTE'].str.contains(partial_code)] else: filtered_customers = df # Crear una lista de clientes filtrados para el selectbox customer_list = filtered_customers['CLIENTE'].unique() # Selección de cliente con autocompletar filtrado customer_code = st.selectbox("Select Customer Code", customer_list) if customer_code: # Filtrar datos para el cliente seleccionado customer_data = df[df["CLIENTE"] == customer_code] if not customer_data.empty: st.write(f"### Analysis for Customer {customer_code}") # Obtener las 6 columnas con los valores más altos (ignorar la columna de cliente) top_6_manufacturers = customer_data.iloc[:, 1:].T.nlargest(6, customer_data.index[0]) # Ordenar los fabricantes por valor descendente para mejor visualización top_6_manufacturers = top_6_manufacturers.sort_values(by=customer_data.index[0], ascending=False) # Preparar los valores y fabricantes values = top_6_manufacturers[customer_data.index[0]].values.tolist() manufacturers = top_6_manufacturers.index.tolist() # Mostrar los resultados de cada fabricante st.write("### Resultados porcentaje fabricante (ordenados):") for manufacturer, value in zip(manufacturers, values): st.write(f"{manufacturer} = {value:.4f}") # Normalizar los valores para que sumen 1 total = sum(values) values = [v / total for v in values] # Crear el gráfico de radar fig = go.Figure() # Add the data trace (pink line) fig.add_trace(go.Scatterpolar( r=values + values[:1], # Repeat first value to close the polygon theta=manufacturers + manufacturers[:1], fill='toself', fillcolor='rgba(255, 105, 180, 0.2)', # Light pink fill line=dict(color='rgb(255, 105, 180)', width=2), # Pink line mode='lines+markers', marker=dict(size=8, color='rgb(255, 105, 180)') # Pink markers )) # Add the outer boundary (blue line) fig.add_trace(go.Scatterpolar( r=[1]*len(manufacturers) + [1], # A list of 1's to create the outer boundary theta=manufacturers + manufacturers[:1], mode='lines', line=dict(color='rgb(100, 149, 237)', width=2), # Cornflower blue showlegend=False )) # Update the layout fig.update_layout( polar=dict( radialaxis=dict( visible=True, range=[0, 1], showline=False, showticklabels=False, ), angularaxis=dict( showline=True, linecolor='rgb(192, 192, 192)', # Light gray tickcolor='rgb(192, 192, 192)', ), gridshape='circular', ), showlegend=False, paper_bgcolor='white', plot_bgcolor='white', ) # Add radial grid lines for i in range(1, 5): # 4 concentric circles fig.add_shape( type="circle", xref="x", yref="y", x0=-i/4, y0=-i/4, x1=i/4, y1=i/4, line=dict(color="rgb(192, 192, 192)", width=1), ) # Show the plot in Streamlit st.plotly_chart(fig) # Ventas del cliente 2021-2024 (si los datos existen) if 'VENTA_2021' in df.columns and 'VENTA_2022' in df.columns and 'VENTA_2023' in df.columns and 'VENTA_2024' in df.columns: years = ['2021', '2022', '2023', '2024'] sales_columns = ['VENTA_2021', 'VENTA_2022', 'VENTA_2023', 'VENTA_2024'] customer_sales = customer_data[sales_columns].values[0] fig_sales = px.line(x=years, y=customer_sales, markers=True, title=f'Sales Over the Years for Customer {customer_code}') fig_sales.update_layout(xaxis_title="Year", yaxis_title="Sales") st.plotly_chart(fig_sales) else: st.warning("Sales data for 2021-2024 not available.") else: st.warning(f"No data found for customer {customer_code}. Please check the code.") # Página Customer Recommendations elif page == "Customer Recommendations": st.title("Customer Recommendations") st.markdown(""" Get tailored recommendations for your customers based on their purchasing history. """) # Campo para filtrar clientes partial_code = st.text_input("Enter part of Customer Code for Recommendations (or leave empty to see all)") # Filtrar las opciones de clientes que coincidan con el código parcial if partial_code: filtered_customers = df[df['CLIENTE'].str.contains(partial_code)] else: filtered_customers = df # Crear una lista de clientes filtrados para el selectbox customer_list = filtered_customers['CLIENTE'].unique() # Selección de cliente con autocompletar filtrado customer_code = st.selectbox("Select Customer Code for Recommendations", customer_list) if customer_code: customer_data = df[df["CLIENTE"] == customer_code] if not customer_data.empty: # Mostrar historial de compras del cliente seleccionado st.write(f"### Purchase History for Customer {customer_code}") st.write(customer_data) # Generar recomendaciones (placeholder) st.write(f"### Recommended Products for Customer {customer_code}") # Aquí puedes reemplazar con la lógica del modelo de recomendación st.write("Product A, Product B, Product C") else: st.warning(f"No data found for customer {customer_code}. Please check the code.")