-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
200 lines (172 loc) · 8.92 KB
/
Copy pathapp.py
File metadata and controls
200 lines (172 loc) · 8.92 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
import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import seaborn as sns
# ── Page config ──────────────────────────────────────────────────────────────
st.set_page_config(
page_title="Superstore Sales Analytics",
page_icon="📊",
layout="wide",
)
# ── Global style ─────────────────────────────────────────────────────────────
PALETTE = ["#4C9BE8", "#E8834C", "#4CE882", "#E84C6B", "#A04CE8", "#E8D14C"]
sns.set_theme(style="darkgrid", palette=PALETTE)
plt.rcParams.update({
"figure.facecolor": "#0e1117",
"axes.facecolor": "#262730",
"axes.labelcolor": "#ccc",
"xtick.color": "#ccc",
"ytick.color": "#ccc",
"text.color": "#eee",
"grid.color": "#3a3a4a",
})
# ── Load data ─────────────────────────────────────────────────────────────────
@st.cache_data
def load_data():
for enc in ("windows-1252", "latin-1", "utf-8"):
try:
df = pd.read_csv("Superstore.csv", encoding=enc)
break
except UnicodeDecodeError:
continue
df["Order Date"] = pd.to_datetime(df["Order Date"], errors="coerce")
df["Ship Date"] = pd.to_datetime(df["Ship Date"], errors="coerce")
df["Year"] = df["Order Date"].dt.year
df["Month"] = df["Order Date"].dt.month
df["YearMonth"] = df["Order Date"].dt.to_period("M").astype(str)
df["Profit Margin %"] = (df["Profit"] / df["Sales"].replace(0, pd.NA) * 100).round(2)
return df
df = load_data()
# ── Sidebar Filters ───────────────────────────────────────────────────────────
st.sidebar.image("https://img.icons8.com/color/96/combo-chart--v2.png", width=60)
st.sidebar.title("Filters")
years = sorted(df["Year"].dropna().unique().astype(int))
sel_years = st.sidebar.multiselect("Year", years, default=years)
regions = sorted(df["Region"].dropna().unique())
sel_regions = st.sidebar.multiselect("Region", regions, default=regions)
categories = sorted(df["Category"].dropna().unique())
sel_cats = st.sidebar.multiselect("Category", categories, default=categories)
# Apply filters
mask = (
df["Year"].isin(sel_years) &
df["Region"].isin(sel_regions) &
df["Category"].isin(sel_cats)
)
fdf = df[mask]
st.sidebar.divider()
st.sidebar.caption(f"Showing **{len(fdf):,}** of **{len(df):,}** rows")
# ── Header ────────────────────────────────────────────────────────────────────
st.title("📊 Superstore Sales Analytics")
st.markdown("An interactive end-to-end analytics dashboard built with Python & Streamlit.")
st.divider()
# ── KPI Row ───────────────────────────────────────────────────────────────────
total_sales = fdf["Sales"].sum()
total_profit = fdf["Profit"].sum()
total_orders = fdf["Order ID"].nunique()
avg_order_val = total_sales / total_orders if total_orders else 0
profit_margin = (total_profit / total_sales * 100) if total_sales else 0
k1, k2, k3, k4, k5 = st.columns(5)
k1.metric("💰 Total Sales", f"${total_sales:,.0f}")
k2.metric("📈 Total Profit", f"${total_profit:,.0f}")
k3.metric("🛒 Total Orders", f"{total_orders:,}")
k4.metric("🧾 Avg. Order Value", f"${avg_order_val:,.0f}")
k5.metric("📊 Profit Margin", f"{profit_margin:.1f}%")
st.divider()
# ─── Helper: chart wrapper ────────────────────────────────────────────────────
def show_chart(fig):
fig.tight_layout()
st.pyplot(fig)
plt.close(fig)
# ── Chart 1: Monthly Sales Trend ──────────────────────────────────────────────
st.subheader("📅 Monthly Sales Trend")
if not fdf.empty:
trend = fdf.groupby("YearMonth")["Sales"].sum().reset_index()
trend["Sales_K"] = trend["Sales"] / 1000
fig, ax = plt.subplots(figsize=(14, 4))
ax.fill_between(trend["YearMonth"], trend["Sales_K"], alpha=0.15, color=PALETTE[0])
ax.plot(trend["YearMonth"], trend["Sales_K"], marker="o", ms=4,
color=PALETTE[0], linewidth=2)
ax.set_xlabel("Month")
ax.set_ylabel("Sales ($ thousands)")
ax.yaxis.set_major_formatter(mticker.FuncFormatter(lambda x, _: f"${x:.0f}K"))
# Reduce x-tick clutter
step = max(1, len(trend) // 12)
ax.set_xticks(range(0, len(trend), step))
ax.set_xticklabels(trend["YearMonth"].iloc[::step], rotation=45, ha="right", fontsize=8)
show_chart(fig)
else:
st.info("No data available for the selected filters.")
st.divider()
# ── Charts Row 2: Category & Region ──────────────────────────────────────────
col_a, col_b = st.columns(2)
with col_a:
st.subheader("🗂️ Sales & Profit by Category")
if not fdf.empty:
cat = fdf.groupby("Category")[["Sales", "Profit"]].sum().reset_index()
cat_melted = cat.melt(id_vars="Category", var_name="Metric", value_name="Amount")
fig, ax = plt.subplots(figsize=(6, 4))
sns.barplot(data=cat_melted, x="Category", y="Amount", hue="Metric",
ax=ax, palette=[PALETTE[0], PALETTE[2]])
ax.set_xlabel("")
ax.yaxis.set_major_formatter(mticker.FuncFormatter(lambda x, _: f"${x/1000:.0f}K"))
ax.legend(facecolor="#262730", edgecolor="none")
show_chart(fig)
with col_b:
st.subheader("🌍 Sales by Region")
if not fdf.empty:
reg = fdf.groupby("Region")["Sales"].sum().reset_index().sort_values("Sales", ascending=False)
fig, ax = plt.subplots(figsize=(6, 4))
bars = sns.barplot(data=reg, x="Region", y="Sales", ax=ax,
hue="Region", legend=False, palette=PALETTE)
ax.yaxis.set_major_formatter(mticker.FuncFormatter(lambda x, _: f"${x/1000:.0f}K"))
ax.set_xlabel("")
show_chart(fig)
st.divider()
# ── Charts Row 3: Sub-Category & Segment ──────────────────────────────────────
col_c, col_d = st.columns(2)
with col_c:
st.subheader("📦 Profit by Sub-Category")
if not fdf.empty:
sub = (fdf.groupby("Sub-Category")["Profit"].sum()
.reset_index()
.sort_values("Profit", ascending=True))
colors = [PALETTE[2] if v >= 0 else PALETTE[3] for v in sub["Profit"]]
fig, ax = plt.subplots(figsize=(6, 6))
ax.barh(sub["Sub-Category"], sub["Profit"], color=colors)
ax.axvline(0, color="#ccc", linewidth=0.8)
ax.xaxis.set_major_formatter(mticker.FuncFormatter(lambda x, _: f"${x/1000:.0f}K"))
ax.set_xlabel("Profit ($)")
show_chart(fig)
with col_d:
st.subheader("👤 Sales Share by Customer Segment")
if not fdf.empty:
seg = fdf.groupby("Segment")["Sales"].sum()
fig, ax = plt.subplots(figsize=(6, 6))
wedges, texts, autotexts = ax.pie(
seg.values,
labels=seg.index,
autopct="%1.1f%%",
colors=PALETTE[:len(seg)],
startangle=90,
wedgeprops=dict(linewidth=2, edgecolor="#0e1117"),
)
for t in texts + autotexts:
t.set_color("#eee")
ax.set_facecolor("#0e1117")
show_chart(fig)
st.divider()
# ── Raw Data Explorer ──────────────────────────────────────────────────────────
with st.expander("🔍 Explore Raw Data", expanded=False):
cols_to_show = ["Order ID", "Order Date", "Customer Name", "Segment",
"Region", "Category", "Sub-Category", "Product Name",
"Sales", "Quantity", "Discount", "Profit", "Profit Margin %"]
existing = [c for c in cols_to_show if c in fdf.columns]
st.dataframe(
fdf[existing].sort_values("Order Date", ascending=False).reset_index(drop=True),
use_container_width=True,
height=350,
)
csv = fdf[existing].to_csv(index=False).encode("utf-8")
st.download_button("⬇️ Download Filtered Data as CSV", csv, "filtered_superstore.csv", "text/csv")
st.caption("Data: Superstore Sales Dataset | Built with Python, Pandas & Streamlit")