File size: 7,730 Bytes
89e696a
36f3034
 
d496756
89e696a
36f3034
2c1bfb4
 
45bb8a5
f637681
 
 
 
45bb8a5
d0f6704
 
 
ab9c8b0
2c1bfb4
 
 
 
 
 
ab9c8b0
3a7c531
2c1bfb4
36f3034
b6148e0
ab9c8b0
 
36f3034
 
ab9c8b0
36f3034
 
 
 
 
d0f6704
 
 
 
 
 
 
 
 
 
 
 
 
 
45bb8a5
 
 
d0f6704
45bb8a5
 
 
f637681
d83eed5
 
 
15cdf0a
 
 
416d73b
37c1fbe
 
11ebafd
416d73b
15cdf0a
416d73b
 
 
 
 
 
 
 
 
 
accd0d7
416d73b
accd0d7
 
416d73b
accd0d7
 
416d73b
accd0d7
45bb8a5
d83eed5
accd0d7
 
 
 
 
 
 
 
 
 
416d73b
45bb8a5
 
 
accd0d7
 
 
 
 
 
 
 
 
 
19c9d1c
416d73b
accd0d7
 
45bb8a5
19c9d1c
accd0d7
 
 
 
 
 
 
 
 
 
416d73b
45bb8a5
f637681
 
 
 
 
45bb8a5
f637681
 
 
 
 
45bb8a5
 
accd0d7
36f3034
ab9c8b0
36f3034
 
 
 
 
d0f6704
 
 
 
 
 
 
 
 
 
 
 
 
 
45bb8a5
 
d0f6704
f637681
45bb8a5
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
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.")