Py.Cafe

stichbury/

megastore-sales-profit-exploration

MegaStore Sales and Profit Exploration

DocsPricing
  • app.py
  • requirements.txt
app.py
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
############ Imports ##############
import vizro.plotly.express as px
import vizro.tables as vt
import vizro.models as vm
from vizro.models.types import capture
from vizro import Vizro
import pandas as pd
from vizro.managers import data_manager
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import vizro.plotly.express as px
from vizro.models.types import capture


####### Function definitions ######
@capture("graph")
def customer_segment_chart(data_frame):
    # Aggregate by customer segment and product category
    segment_data = (
        data_frame.groupby(["Customer Segment", "Product Category"])
        .agg({"Sales": "sum", "Profit": "sum"})
        .reset_index()
    )

    # Create sunburst
    fig = go.Figure(
        go.Sunburst(
            labels=segment_data["Product Category"],
            parents=segment_data["Customer Segment"],
            values=segment_data["Sales"],
            hovertemplate="<b>%{label}</b><br>"
            + "Customer Segment: %{parent}<br>"
            + "Sales: $%{value:,.0f}<br>"
            + "Profit: $%{customdata:,.0f}<br>"
            + "<extra></extra>",
            customdata=segment_data["Profit"],
            maxdepth=2,
            insidetextorientation="radial",
        )
    )

    # Update layout
    fig.update_layout(margin=dict(t=20, l=0, r=0, b=0))

    return fig


@capture("graph")
def geographic_sales_chart(data_frame):
    # Aggregate by continent and region
    geo_data = (
        data_frame.groupby(["Continent", "Region"])
        .agg({"Sales": "sum", "Profit": "sum"})
        .reset_index()
    )

    # Create treemap
    fig = go.Figure(
        go.Treemap(
            labels=geo_data["Region"],
            parents=geo_data["Continent"],
            values=geo_data["Sales"],
            text=geo_data["Region"],
            textinfo="label+value",
            hovertemplate="<b>%{label}</b><br>"
            + "Continent: %{parent}<br>"
            + "Sales: $%{value:,.0f}<br>"
            + "Profit: $%{customdata:,.0f}<br>"
            + "<extra></extra>",
            customdata=geo_data["Profit"],
            textfont_size=12,
            pathbar_visible=False,
        )
    )

    # Update layout
    fig.update_layout(margin=dict(t=20, l=0, r=0, b=0))

    return fig


@capture("graph")
def sales_profit_timeline(data_frame):
    # Convert Order Date to datetime and extract year-month
    df = data_frame.copy()
    df["Order Date"] = pd.to_datetime(df["Order Date"])
    df["Year_Month"] = df["Order Date"].dt.to_period("M")

    # Aggregate by month
    monthly_data = (
        df.groupby("Year_Month").agg({"Sales": "sum", "Profit": "sum"}).reset_index()
    )

    # Convert Period to string for plotting
    monthly_data["Year_Month"] = monthly_data["Year_Month"].astype(str)

    # Create subplot with secondary y-axis
    fig = make_subplots(
        specs=[[{"secondary_y": True}]],
        subplot_titles=["Sales and Profit Trends Over Time"],
    )

    # Add Sales trace
    fig.add_trace(
        go.Scatter(
            x=monthly_data["Year_Month"],
            y=monthly_data["Sales"],
            mode="lines+markers",
            name="Sales",
            line=dict(color="#1f77b4", width=2),
            hovertemplate="<b>Sales</b><br>"
            + "Month: %{x}<br>"
            + "Sales: $%{y:,.0f}<br>"
            + "<extra></extra>",
        ),
        secondary_y=False,
    )

    # Add Profit trace
    fig.add_trace(
        go.Scatter(
            x=monthly_data["Year_Month"],
            y=monthly_data["Profit"],
            mode="lines+markers",
            name="Profit",
            line=dict(color="#ff7f0e", width=2),
            hovertemplate="<b>Profit</b><br>"
            + "Month: %{x}<br>"
            + "Profit: $%{y:,.0f}<br>"
            + "<extra></extra>",
        ),
        secondary_y=True,
    )

    # Update layout
    fig.update_layout(
        xaxis_title="Time Period",
        hovermode="x unified",
        legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1),
    )

    # Update y-axes
    fig.update_yaxes(title_text="Sales ($)", secondary_y=False)
    fig.update_yaxes(title_text="Profit ($)", secondary_y=True)

    return fig


@capture("graph")
def category_performance_chart(data_frame):
    # Aggregate by product category
    category_data = (
        data_frame.groupby("Product Category")
        .agg({"Sales": "sum", "Profit": "sum", "Order Quantity": "sum"})
        .reset_index()
    )

    # Create figure
    fig = go.Figure()

    # Add Sales bars
    fig.add_trace(
        go.Bar(
            name="Sales",
            x=category_data["Product Category"],
            y=category_data["Sales"],
            marker_color="#1f77b4",
            hovertemplate="<b>%{x}</b><br>"
            + "Sales: $%{y:,.0f}<br>"
            + "<extra></extra>",
        )
    )

    # Add Profit bars
    fig.add_trace(
        go.Bar(
            name="Profit",
            x=category_data["Product Category"],
            y=category_data["Profit"],
            marker_color="#ff7f0e",
            hovertemplate="<b>%{x}</b><br>"
            + "Profit: $%{y:,.0f}<br>"
            + "<extra></extra>",
        )
    )

    # Update layout
    fig.update_layout(
        barmode="group",
        xaxis_title="Product Category",
        yaxis_title="Amount ($)",
        legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1),
    )

    return fig


####### Data Manager Settings #####
data_manager["megastore_data"] = pd.read_excel(
    "https://raw.githubusercontent.com/stichbury/vizro_projects/main/Megastore/MegastoreData.xlsx"
)

########### Model code ############
model = vm.Dashboard(
    pages=[
        vm.Page(
            id="home",
            components=[
                vm.Card(
                    type="card",
                    text="## Overview\nExplore the complete MegaStore dataset with summary statistics and raw data.",
                    href="/overview",
                ),
                vm.Card(
                    type="card",
                    text="## Distribution Analysis\nAnalyze the distribution of numeric columns with interactive histograms.",
                    href="/distribution",
                ),
                vm.Card(
                    type="card",
                    text="## Advanced Analysis\nDeep dive into business insights with custom visualizations.",
                    href="/advanced",
                ),
            ],
            title="Home",
        ),
        vm.Page(
            id="overview",
            components=[
                vm.Text(
                    type="text",
                    text="## MegaStore Dataset Summary\n\nThis dataset contains **16,798 records** of sales data from a global retail store with the following key characteristics:\n\n- **Geographic Coverage**: Sales across North America, Europe, and Asia\n- **Product Categories**: Office Supplies, Furniture, and Technology\n- **Customer Segments**: Corporate, Consumer, and Small Business\n- **Time Period**: Sales data spanning multiple years\n- **Key Metrics**: Sales, Profit, Discount, Shipping Cost, and more\n\nThe dataset includes both transactional details and customer information, making it ideal for comprehensive business analysis.",
                ),
                vm.AgGrid(
                    type="ag_grid",
                    figure=vt.dash_ag_grid(
                        data_frame="megastore_data",
                        dashGridOptions={"pagination": True, "paginationPageSize": 20},
                    ),
                    title="Raw Data",
                ),
            ],
            title="Overview",
        ),
        vm.Page(
            id="distribution",
            components=[
                vm.Graph(
                    id="hist_chart",
                    type="graph",
                    figure=px.histogram(
                        data_frame="megastore_data", x="Sales", nbins=50
                    ),
                    title="Distribution Analysis",
                )
            ],
            title="Distribution Analysis",
            controls=[
                vm.Parameter(
                    type="parameter",
                    targets=["hist_chart.x"],
                    selector=vm.Dropdown(
                        type="dropdown",
                        options=[
                            "Sales",
                            "Profit",
                            "Discount",
                            "Order Quantity",
                            "Unit Price",
                            "Shipping Cost",
                            "Product Base Margin",
                        ],
                        value="Sales",
                    ),
                ),
                vm.Filter(
                    type="filter",
                    column="Product Category",
                    targets=["hist_chart"],
                    selector=vm.Dropdown(type="dropdown", multi=True),
                ),
                vm.Filter(
                    type="filter",
                    column="Customer Segment",
                    targets=["hist_chart"],
                    selector=vm.Dropdown(type="dropdown", multi=True),
                ),
                vm.Filter(
                    type="filter",
                    column="Continent",
                    targets=["hist_chart"],
                    selector=vm.Dropdown(type="dropdown", multi=True),
                ),
                vm.Filter(
                    type="filter",
                    column="Order Priority",
                    targets=["hist_chart"],
                    selector=vm.Dropdown(type="dropdown", multi=True),
                ),
            ],
        ),
        vm.Page(
            id="advanced",
            components=[
                vm.Graph(
                    id="sales_profit_time",
                    type="graph",
                    figure=sales_profit_timeline(data_frame="megastore_data"),
                    title="Sales and Profit Trends Over Time",
                ),
                vm.Graph(
                    id="category_performance",
                    type="graph",
                    figure=category_performance_chart(data_frame="megastore_data"),
                    title="Product Category Performance",
                ),
                vm.Graph(
                    id="geographic_sales",
                    type="graph",
                    figure=geographic_sales_chart(data_frame="megastore_data"),
                    title="Geographic Sales Distribution",
                ),
                vm.Graph(
                    id="customer_segment",
                    type="graph",
                    figure=customer_segment_chart(data_frame="megastore_data"),
                    title="Customer Segment Analysis",
                ),
            ],
            title="Advanced Analysis",
            layout=vm.Grid(type="grid", grid=[[0, 1], [2, 3]]),
        ),
    ],
    theme="vizro_dark",
    navigation=vm.Navigation(
        pages=["home", "overview", "distribution", "advanced"],
        nav_selector=vm.NavBar(
            type="nav_bar",
            items=[
                vm.NavLink(pages=["home"], label="Home", icon="home"),
                vm.NavLink(pages=["overview"], label="Overview", icon="info"),
                vm.NavLink(
                    pages=["distribution"], label="Distribution", icon="bar_chart"
                ),
                vm.NavLink(pages=["advanced"], label="Advanced", icon="trending_up"),
            ],
        ),
    ),
    title="MegaStore Analytics Dashboard",
)

Vizro().build(model).run()