Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
412 lines (346 loc) · 12.6 KB
/
Copy pathapp.py
File metadata and controls
412 lines (346 loc) · 12.6 KB
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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
import streamlit as st
import pandas as pd
import plotly.express as px
st.set_page_config(page_title="📊 Bike Sales Dashboard", layout="wide")
st.markdown(
"""
<style>
.glass {
background: rgba(20, 20, 20, 0.4);
padding: 16px;
border-radius: 16px;
border: 1px solid rgba(255,255,255,0.12);
box-shadow: 0 10px 30px rgba(0,0,0,0.35);
}
.kpi-good {
color: #2ecc71;
font-weight: 800;
}
.kpi-bad {
color: #e74c3c;
font-weight: 800;
}
</style>
""",
unsafe_allow_html=True,
)
st.title("📊 Bike Sales Dashboard")
@st.cache_data
def load_data():
df = pd.read_excel("Bike sales.xlsx")
df.columns = [str(c).strip() for c in df.columns]
return df
try:
df = load_data()
except Exception as e:
st.error(f"Failed to load 'Bike sales.xlsx'. Error: {e}")
st.stop()
available = set(df.columns)
def pick_col(candidates):
for c in candidates:
if c in available:
return c
return None
country_col = pick_col(["Country"])
category_col = pick_col(["Product_Category", "Product Category", "Category"])
age_col = pick_col(["Age_Group", "Age Group", "Customer Age"])
revenue_col = pick_col(["Revenue"])
profit_col = pick_col(["Profit", "Total Profit", "Net Profit"])
year_col = pick_col(["Year", "Order_Date", "Order Date", "Date"])
# Fallback if revenue column name differs
if revenue_col is None:
num_cols = [c for c in df.columns if pd.api.types.is_numeric_dtype(df[c])]
if not num_cols:
st.error("No numeric column found to plot revenue.")
st.stop()
revenue_col = num_cols[0]
# Optional column for deeper filtering/analysis
ship_col = pick_col(["Ship Mode", "Shipping", "Shipping Mode", "Ship_Mode"])
region_col = pick_col(["Region", "Area"])
st.sidebar.header("🧰 Filters")
# Defensive: ensure filtered_df is always a DataFrame
filtered_df = df.copy()
if not isinstance(filtered_df, pd.DataFrame):
st.error("Dataframe is empty/invalid after loading. Check 'Bike sales.xlsx'.")
st.stop()
def apply_radio_multiselect_filter(col, label, key_prefix: str):
"""Radio selects All vs Custom. If Custom -> show multiselect in a framed container."""
if not col:
return filtered_df
mode = st.sidebar.radio(
f"{label} filter mode",
options=["All", "Custom"],
index=0,
key=f"{key_prefix}_mode",
horizontal=False,
)
if mode == "All":
return filtered_df
vals = sorted(filtered_df[col].dropna().unique().tolist())
# Frame the multiselect area (Streamlit border container)
with st.sidebar.container(border=True):
chosen = st.multiselect(
label,
vals,
default=vals,
key=f"{key_prefix}_multiselect",
)
if chosen:
return filtered_df[filtered_df[col].isin(chosen)]
return filtered_df
filtered_df = apply_radio_multiselect_filter(country_col, "Country", "country")
filtered_df = apply_radio_multiselect_filter(category_col, "Product Category", "category")
filtered_df = apply_radio_multiselect_filter(age_col, "Age Group", "age")
filtered_df = apply_radio_multiselect_filter(region_col, "Region", "region")
filtered_df = apply_radio_multiselect_filter(ship_col, "Ship Mode", "ship")
# Defensive: ensure filtered_df is still a valid DataFrame after filtering
if not isinstance(filtered_df, pd.DataFrame):
st.warning("Selected filters resulted in no data to display. Showing full dataset instead.")
filtered_df = df
if year_col is not None and year_col in filtered_df.columns:
parsed = pd.to_datetime(filtered_df[year_col], errors="coerce")
if parsed.notna().any():
years = sorted(parsed.dt.year.dropna().unique().tolist())
else:
years = sorted(filtered_df[year_col].dropna().unique().tolist())
chosen_years = st.sidebar.multiselect("Year", years, default=years)
if chosen_years:
parsed2 = pd.to_datetime(filtered_df[year_col], errors="coerce")
if parsed2.notna().any():
filtered_df = filtered_df[parsed2.dt.year.isin(chosen_years)]
else:
filtered_df = filtered_df[filtered_df[year_col].isin(chosen_years)]
# Allow user to adjust how many top items are shown
st.sidebar.header("⚙️ Display")
top_n = st.sidebar.slider("Top N items", min_value=5, max_value=30, value=15, step=1)
# KPI calculations
revenue_series = pd.to_numeric(filtered_df[revenue_col], errors="coerce")
total_revenue = float(revenue_series.fillna(0).sum())
profit_series = None
total_profit = None
profit_margin = None
if profit_col:
profit_series = pd.to_numeric(filtered_df[profit_col], errors="coerce")
total_profit = float(profit_series.fillna(0).sum())
if total_revenue != 0:
profit_margin = (total_profit / total_revenue) * 100
# KPIs
st.subheader("✨ KPI Overview")
col1, col2, col3, col4 = st.columns(4)
def kpi_card(title: str, value_html: str):
st.markdown(
f"""
<div class='glass' style='min-height:120px'>
<div style='font-size:14px; opacity:0.9; font-weight:700;'>{title}</div>
<div style='font-size:26px; font-weight:900; margin-top:10px;'>{value_html}</div>
</div>
""",
unsafe_allow_html=True,
)
with col1:
kpi_card("Total Revenue", f"${total_revenue:,.2f}")
with col2:
if profit_col and total_profit is not None:
cls = "kpi-good" if total_profit >= 0 else "kpi-bad"
kpi_card("Total Profit", f"<span class='{cls}'>${total_profit:,.2f}</span>")
else:
kpi_card("Total Profit", "<span style='opacity:0.7'>N/A</span>")
with col3:
if profit_margin is not None:
cls = "kpi-good" if profit_margin >= 0 else "kpi-bad"
kpi_card("Profit Margin", f"<span class='{cls}'>{profit_margin:.2f}%</span>")
else:
kpi_card("Profit Margin", "<span style='opacity:0.7'>N/A</span>")
with col4:
if profit_series is not None:
profit_count = int((profit_series.fillna(0) >= 0).sum())
loss_count = int((profit_series.fillna(0) < 0).sum())
parts = [f"↑ <b>{profit_count}</b>"] # profit rows
if loss_count > 0:
parts.append(f" <span class='kpi-bad'>↓ {loss_count}</span>")
kpi_card("Profit/Loss", "".join(parts))
else:
kpi_card("Profit/Loss", "<span style='opacity:0.7'>N/A</span>")
# Charts
st.markdown(
'<div class="glass"><b>📈 Page Analysis</b><div style="opacity:0.8; margin-top:4px; font-size:13px;">Interactive KPIs, revenue distribution, profit signals, and heatmap analytics</div></div>',
unsafe_allow_html=True,
)
st.divider()
# Charts
st.subheader("📈 Analytics")
# Revenue bars
c1, c2 = st.columns(2)
if country_col:
rev_country = (
filtered_df.groupby(country_col, dropna=False)[revenue_col]
.sum()
.reset_index()
.sort_values(revenue_col, ascending=False)
.head(top_n)
)
with c1:
st.markdown('<div class="glass">', unsafe_allow_html=True)
fig = px.bar(
rev_country,
x=revenue_col,
y=country_col,
orientation="h",
title=f"Revenue by Country (Top {top_n})",
text_auto=True,
)
st.plotly_chart(fig, use_container_width=True)
st.markdown("</div>", unsafe_allow_html=True)
if category_col:
rev_cat = (
filtered_df.groupby(category_col, dropna=False)[revenue_col]
.sum()
.reset_index()
.sort_values(revenue_col, ascending=False)
.head(top_n)
)
with c2:
st.markdown('<div class="glass">', unsafe_allow_html=True)
fig = px.bar(
rev_cat,
x=revenue_col,
y=category_col,
orientation="h",
title=f"Revenue by Category (Top {top_n})",
text_auto=True,
)
st.plotly_chart(fig, use_container_width=True)
st.markdown("</div>", unsafe_allow_html=True)
# Pie charts
st.subheader("🥧 Revenue Share (Pie) & Profit Signals")
p1, p2 = st.columns(2)
if country_col:
with p1:
st.markdown('<div class="glass">', unsafe_allow_html=True)
pie_country = (
filtered_df.groupby(country_col, dropna=False)[revenue_col]
.sum()
.reset_index()
.sort_values(revenue_col, ascending=False)
.head(top_n)
)
fig_pie = px.pie(
pie_country,
names=country_col,
values=revenue_col,
hole=0.35,
title="Revenue Share by Country",
)
fig_pie.update_traces(textposition="inside", textinfo="percent+label")
st.plotly_chart(fig_pie, use_container_width=True)
st.markdown("</div>", unsafe_allow_html=True)
if category_col:
with p2:
st.markdown('<div class="glass">', unsafe_allow_html=True)
pie_cat = (
filtered_df.groupby(category_col, dropna=False)[revenue_col]
.sum()
.reset_index()
.sort_values(revenue_col, ascending=False)
.head(top_n)
)
fig_pie2 = px.pie(
pie_cat,
names=category_col,
values=revenue_col,
hole=0.35,
title="Revenue Share by Category",
)
fig_pie2.update_traces(textposition="inside", textinfo="percent+label")
st.plotly_chart(fig_pie2, use_container_width=True)
st.markdown("</div>", unsafe_allow_html=True)
# Profit/Loss visualization
if profit_col:
st.subheader("💰 Profit / Loss by Segment")
seg_col = country_col or category_col or region_col
if seg_col:
profit_loss_data = filtered_df.copy()
profit_loss_data[profit_col] = pd.to_numeric(profit_loss_data[profit_col], errors="coerce")
agg_pl = (
profit_loss_data.groupby(seg_col, dropna=False)[profit_col]
.sum()
.reset_index()
.sort_values(profit_col, ascending=False)
.head(top_n)
)
colors = ["#2ecc71" if v >= 0 else "#e74c3c" for v in agg_pl[profit_col].fillna(0).tolist()]
fig_pl = px.bar(
agg_pl,
x=profit_col,
y=seg_col,
orientation="h",
title=f"Net Profit by {seg_col} (Top {top_n})",
)
fig_pl.update_traces(marker_color=colors)
fig_pl.update_layout(template="plotly_dark")
st.plotly_chart(fig_pl, use_container_width=True)
# Heatmap
st.subheader("🔥 Heatmap Analytics")
if country_col and category_col:
pivot = (
filtered_df.groupby([country_col, category_col], dropna=False)[revenue_col]
.sum()
.reset_index()
.pivot(index=country_col, columns=category_col, values=revenue_col)
)
fig6 = px.imshow(
pivot,
aspect="auto",
color_continuous_scale="Turbo",
title="Revenue Heatmap (Country × Category)",
)
fig6.update_layout(template="plotly_dark", height=520)
st.plotly_chart(fig6, use_container_width=True)
else:
st.info("Heatmap requires both Country and Product Category columns.")
# Insights
st.subheader("🧠 AI Style Business Insights")
best_country = None
best_category = None
best_age = None
if country_col:
country_data = (
filtered_df.groupby(country_col, dropna=False)[revenue_col]
.sum()
.reset_index(name="Revenue")
)
if not country_data.empty:
best_country = country_data.sort_values("Revenue", ascending=False).iloc[0][country_col]
if category_col:
category_data = (
filtered_df.groupby(category_col, dropna=False)[revenue_col]
.sum()
.reset_index(name="Revenue")
)
if not category_data.empty:
best_category = category_data.sort_values("Revenue", ascending=False).iloc[0][category_col]
if age_col:
age_data = (
filtered_df.groupby(age_col, dropna=False)[revenue_col]
.sum()
.reset_index(name="Revenue")
)
if not age_data.empty:
best_age = age_data.sort_values("Revenue", ascending=False).iloc[0][age_col]
# Render insights safely
insight_lines = []
if best_country is not None:
insight_lines.append(f"Top revenue country: <b>{best_country}</b>")
if best_category is not None:
insight_lines.append(f"Top revenue category: <b>{best_category}</b>")
if best_age is not None:
insight_lines.append(f"Top revenue age group: <b>{best_age}</b>")
if profit_col and profit_series is not None and len(insight_lines) == 0:
insight_lines.append("Adjust filters to generate insights.")
if insight_lines:
st.markdown(
"<div class=\"glass\"><b>Key Takeaways</b><br/>" + "<br/>".join(insight_lines) + "</div>",
unsafe_allow_html=True,
)
else:
st.info("No insight data available for the selected filters.")