Py.Cafe

huong-li-nguyen/

vizro-executive-stock-analysis

Executive Stock Performance Analysis

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
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
# Vizro is an open-source toolkit for creating modular data visualization applications.
# check out https://github.com/mckinsey/vizro for more info about Vizro
# and checkout https://vizro.readthedocs.io/en/stable/ for documentation.

import vizro.plotly.express as px
import vizro.models as vm
from vizro.models.types import capture
import plotly.graph_objects as go
import numpy as np
import pandas as pd

from vizro.managers import data_manager

data_manager["gapminder"] = px.data.gapminder()
data_manager["stocks"] = px.data.stocks()


####### Function definitions ######
@capture("graph")
def revenue_trend(data_frame):
    """
    Creates a professional line chart with area fill showing revenue trend over time.
    The chart displays the average of all stock values as total revenue.
    """
    # Create a copy to avoid modifying original data
    df = data_frame.copy()

    # Convert date column to datetime
    df["date"] = pd.to_datetime(df["date"])

    # Convert stock columns to numeric (they are currently strings)
    stock_columns = ["GOOG", "AAPL", "AMZN", "FB", "NFLX", "MSFT"]
    for col in stock_columns:
        df[col] = pd.to_numeric(df[col], errors="coerce")

    # Calculate average of all stock values as total revenue
    df["total_revenue"] = df[stock_columns].mean(axis=1)

    # Sort by date
    df = df.sort_values("date")

    # Create figure
    fig = go.Figure()

    # Add area fill
    fig.add_trace(
        go.Scatter(
            x=df["date"],
            y=df["total_revenue"],
            mode="lines+markers",
            name="Total Revenue",
            line=dict(
                color="#1f77b4", width=3, shape="spline", smoothing=1.3  # Smooth line
            ),
            marker=dict(
                size=8,
                color="#1f77b4",
                symbol="circle",
                line=dict(color="white", width=2),
            ),
            fill="tozeroy",
            fillcolor="rgba(31, 119, 180, 0.2)",
            hovertemplate="<b>Date</b>: %{x|%Y-%m-%d}<br><b>Revenue</b>: %{y:.4f}<extra></extra>",
        )
    )

    # Update layout with professional styling for executive dashboard
    fig.update_layout(
        title={
            "text": "<b>Revenue Trend Analysis</b>",
            "x": 0.5,
            "xanchor": "center",
            "font": {"size": 24, "color": "#2c3e50", "family": "Arial Black"},
        },
        xaxis=dict(
            title="<b>Date</b>",
            titlefont=dict(size=14, color="#2c3e50", family="Arial"),
            showgrid=True,
            gridcolor="rgba(220, 220, 220, 0.5)",
            showline=True,
            linewidth=2,
            linecolor="#2c3e50",
            mirror=True,
            tickfont=dict(size=11, color="#2c3e50"),
        ),
        yaxis=dict(
            title="<b>Average Stock Value (Total Revenue)</b>",
            titlefont=dict(size=14, color="#2c3e50", family="Arial"),
            showgrid=True,
            gridcolor="rgba(220, 220, 220, 0.5)",
            showline=True,
            linewidth=2,
            linecolor="#2c3e50",
            mirror=True,
            tickfont=dict(size=11, color="#2c3e50"),
            tickformat=".4f",
        ),
        plot_bgcolor="white",
        paper_bgcolor="#f8f9fa",
        hovermode="x unified",
        hoverlabel=dict(bgcolor="white", font_size=12, font_family="Arial"),
        showlegend=True,
        legend=dict(
            orientation="h",
            yanchor="bottom",
            y=1.02,
            xanchor="right",
            x=1,
            font=dict(size=12, color="#2c3e50"),
        ),
        margin=dict(l=80, r=40, t=100, b=80),
        height=500,
    )

    return fig


@capture("graph")
def monthly_variance(data_frame):
    """
    Creates a waterfall chart showing monthly performance variance for stocks.
    Displays monthly changes with bars indicating positive and negative variances from baseline.
    """
    # Create a copy of the dataframe
    df = data_frame.copy()

    # Convert date column to datetime
    df["date"] = pd.to_datetime(df["date"])

    # Convert stock columns to float
    stock_columns = ["GOOG", "AAPL", "AMZN", "FB", "NFLX", "MSFT"]
    for col in stock_columns:
        df[col] = pd.to_numeric(df[col], errors="coerce")

    # Sort by date
    df = df.sort_values("date").reset_index(drop=True)

    # Calculate portfolio average performance
    df["portfolio_avg"] = df[stock_columns].mean(axis=1)

    # Calculate monthly variance (change from previous period)
    df["variance"] = df["portfolio_avg"].diff()
    df["variance_pct"] = df["variance"] * 100  # Convert to percentage points

    # Prepare data for waterfall chart
    dates = df["date"].dt.strftime("%Y-%m-%d").tolist()

    # Create measure types: relative for changes, total for cumulative
    measure = ["absolute"] + ["relative"] * (len(df) - 1)

    # Values for waterfall
    values = [df["portfolio_avg"].iloc[0]] + df["variance"].iloc[1:].tolist()

    # Text labels showing percentage change
    text_labels = ["Baseline: {:.2f}".format(df["portfolio_avg"].iloc[0])]
    for i in range(1, len(df)):
        var_pct = df["variance_pct"].iloc[i]
        text_labels.append(
            "{:+.2f}%".format(var_pct) if not pd.isna(var_pct) else "0.00%"
        )

    # Create waterfall chart
    fig = go.Figure(
        go.Waterfall(
            name="Portfolio Performance",
            orientation="v",
            measure=measure,
            x=dates,
            y=values,
            text=text_labels,
            textposition="outside",
            connector={"line": {"color": "rgb(63, 63, 63)", "width": 2}},
            increasing={"marker": {"color": "green"}},
            decreasing={"marker": {"color": "red"}},
            totals={"marker": {"color": "blue"}},
        )
    )

    # Update layout for executive presentation
    fig.update_layout(
        title={
            "text": "Monthly Portfolio Performance Variance<br><sub>Average Performance Across All Stocks</sub>",
            "x": 0.5,
            "xanchor": "center",
            "font": {"size": 20, "color": "#2c3e50"},
        },
        xaxis={
            "title": "Date",
            "tickangle": -45,
            "showgrid": True,
            "gridcolor": "#e0e0e0",
        },
        yaxis={
            "title": "Normalized Performance Index",
            "showgrid": True,
            "gridcolor": "#e0e0e0",
            "zeroline": True,
            "zerolinecolor": "#000000",
            "zerolinewidth": 2,
        },
        plot_bgcolor="white",
        paper_bgcolor="white",
        font={"family": "Arial, sans-serif", "size": 12},
        showlegend=False,
        height=600,
        margin={"t": 100, "b": 100, "l": 80, "r": 80},
    )

    return fig


@capture("graph")
def revenue_by_segment(data_frame):
    """
    Creates a horizontal bar chart showing total values by stock ticker (business segment).
    Bars are sorted by value in descending order with a professional color scheme.
    """
    # Get stock columns (exclude date column)
    stock_columns = [col for col in data_frame.columns if col != "date"]

    # Convert stock columns to numeric (they are stored as strings)
    totals = []
    for col in stock_columns:
        # Convert to numeric and sum
        total = pd.to_numeric(data_frame[col], errors="coerce").sum()
        totals.append(total)

    # Create DataFrame for plotting
    chart_data = pd.DataFrame({"Segment": stock_columns, "Total_Value": totals})

    # Sort by total value descending
    chart_data = chart_data.sort_values(
        "Total_Value", ascending=True
    )  # ascending=True for horizontal bars (bottom to top)

    # Professional color scheme - blues and grays suitable for executive presentations
    colors = ["#1f77b4", "#4292c6", "#6baed6", "#9ecae1", "#c6dbef", "#deebf7"]

    # Create horizontal bar chart
    fig = go.Figure()

    fig.add_trace(
        go.Bar(
            y=chart_data["Segment"],
            x=chart_data["Total_Value"],
            orientation="h",
            marker=dict(
                color=colors[: len(chart_data)],
                line=dict(color="rgba(255, 255, 255, 0.5)", width=1),
            ),
            text=chart_data["Total_Value"].round(2),
            textposition="auto",
            textfont=dict(size=11, color="white", family="Arial"),
        )
    )

    # Update layout for professional appearance
    fig.update_layout(
        title=dict(
            text="Revenue by Business Segment",
            font=dict(size=20, family="Arial", color="#2c3e50"),
            x=0.5,
            xanchor="center",
        ),
        xaxis=dict(
            title="Total Value",
            titlefont=dict(size=14, family="Arial", color="#2c3e50"),
            showgrid=True,
            gridcolor="rgba(200, 200, 200, 0.3)",
            zeroline=True,
        ),
        yaxis=dict(
            title="Stock Ticker",
            titlefont=dict(size=14, family="Arial", color="#2c3e50"),
            showgrid=False,
        ),
        plot_bgcolor="white",
        paper_bgcolor="white",
        font=dict(family="Arial", size=12, color="#2c3e50"),
        height=500,
        margin=dict(l=100, r=50, t=80, b=60),
        showlegend=False,
    )

    return fig


@capture("graph")
def performance_gauge(data_frame):
    """
    Creates a gauge chart showing year-to-date performance vs target.
    Calculates the average growth rate across all stocks and displays it as a percentage.
    """
    # Create a copy to avoid modifying original data
    df = data_frame.copy()

    # Convert date column to datetime
    df["date"] = pd.to_datetime(df["date"])

    # Convert stock columns to numeric
    stock_columns = ["GOOG", "AAPL", "AMZN", "FB", "NFLX", "MSFT"]
    for col in stock_columns:
        df[col] = pd.to_numeric(df[col], errors="coerce")

    # Sort by date
    df = df.sort_values("date")

    # Calculate growth rate for each stock (latest value / earliest value - 1)
    growth_rates = []
    for col in stock_columns:
        earliest_value = df[col].iloc[0]
        latest_value = df[col].iloc[-1]
        if (
            earliest_value != 0
            and not pd.isna(earliest_value)
            and not pd.isna(latest_value)
        ):
            growth_rate = ((latest_value / earliest_value) - 1) * 100
            growth_rates.append(growth_rate)

    # Calculate average growth rate
    avg_growth_rate = np.mean(growth_rates) if growth_rates else 0

    # Define target (assuming 10% growth target)
    target = 10

    # Create gauge chart
    fig = go.Figure(
        go.Indicator(
            mode="gauge+number+delta",
            value=avg_growth_rate,
            domain={"x": [0, 1], "y": [0, 1]},
            # title={"text": "Year-to-Date Performance vs Target", "font": {"size": 24}},
            delta={"reference": target, "suffix": "%", "valueformat": ".2f"},
            number={"suffix": "%", "valueformat": ".2f"},
            gauge={
                "axis": {"range": [None, 50], "ticksuffix": "%"},
                "bar": {"color": "darkblue"},
                "steps": [
                    {
                        "range": [0, 5],
                        "color": "rgba(255, 0, 0, 0.3)",
                    },  # Red zone: Below target
                    {
                        "range": [5, 15],
                        "color": "rgba(255, 255, 0, 0.3)",
                    },  # Yellow zone: On target
                    {
                        "range": [15, 50],
                        "color": "rgba(0, 255, 0, 0.3)",
                    },  # Green zone: Above target
                ],
                "threshold": {
                    "line": {"color": "red", "width": 4},
                    "thickness": 0.75,
                    "value": target,
                },
            },
        )
    )

    fig.update_layout(
        height=400, margin=dict(l=20, r=20, t=80, b=20), font={"size": 14}
    )

    return fig


####### Data Manager Settings #####
#######!!! UNCOMMENT BELOW !!!#####


########### Model code ############
model = vm.Dashboard(
    id="executive-dashboard",
    pages=[
        vm.Page(
            id="financial-overview",
            components=[
                vm.Card(
                    id="revenue-kpi",
                    type="card",
                    text="### Total Revenue\n# $2.4B\n**↑ 12.5%** vs prior year",
                ),
                vm.Card(
                    id="profit-kpi",
                    type="card",
                    text="### Operating Margin\n# 23.8%\n**↑ 1.2pp** vs prior year",
                ),
                vm.Card(
                    id="efficiency-kpi",
                    type="card",
                    text="### EBITDA\n# $567M\n**↑ 15.3%** vs prior year",
                ),
                vm.Graph(
                    id="revenue-trend-chart",
                    type="graph",
                    figure=revenue_trend(data_frame="stocks"),
                ),
                vm.Graph(
                    id="segment-performance",
                    type="graph",
                    figure=revenue_by_segment(
                        data_frame="stocks"
                    ),
                ),
                vm.Graph(
                    id="monthly-variance-chart",
                    type="graph",
                    figure=monthly_variance(
                        data_frame="stocks"
                    ),
                ),
            ],
            title="Financial Overview",
            layout=vm.Grid(
                id="20fa3325", type="grid", grid=[[0], [1], [2], [3], [4], [5]]
            ),
        ),
        vm.Page(
            id="operations-overview",
            components=[
                vm.Card(
                    id="capacity-kpi",
                    type="card",
                    text="### Capacity Utilization\n# 87.4%\n**↑ 3.2%** vs target",
                ),
                vm.Card(
                    id="efficiency-ops-kpi",
                    type="card",
                    text="### Operational Efficiency\n# 94.2%\n**On Target** (>90%)",
                ),
                vm.Card(
                    id="incidents-kpi",
                    type="card",
                    text="### Safety Score\n# 98.1%\n**↑ 0.4%** vs prior period",
                ),
                vm.Graph(
                    id="performance-gauge-chart",
                    type="graph",
                    figure=performance_gauge(
                        data_frame="stocks"
                    ),
                ),
                vm.Graph(
                    id="regional-performance",
                    type="graph",
                    figure=px.bar(
                        data_frame="gapminder",
                        x="continent",
                        y="gdpPercap",
                        color="continent",
                        title="Regional Performance (GDP per Capita)",
                    ),
                ),
            ],
            title="Operations & Performance",
            layout=vm.Grid(id="664cab67", type="grid", grid=[[0], [1], [2], [3], [4]]),
        ),
        vm.Page(
            id="strategic-initiatives",
            components=[
                vm.Card(
                    id="initiatives-status",
                    type="card",
                    text="## Strategic Initiatives Status\n\n### On Track: 12 projects\n### At Risk: 3 projects  \n### Delayed: 1 project\n\n**Overall Portfolio Health:** 75% Green",
                ),
                vm.Card(
                    id="key-risks",
                    type="card",
                    text="## Key Risks & Mitigations\n\n**Supply Chain**: Medium Risk - Diversification underway\n\n**Talent Retention**: Low Risk - Programs implemented\n\n**Market Volatility**: Medium Risk - Monitoring closely",
                ),
                vm.Graph(
                    id="initiative-timeline",
                    type="graph",
                    figure=px.scatter(
                        data_frame="gapminder",
                        x="year",
                        y="lifeExp",
                        color="continent",
                        size="pop",
                        title="Strategic Initiative Progress Timeline",
                    ),
                ),
            ],
            title="Strategic Initiatives",
            layout=vm.Grid(id="75dbe666", type="grid", grid=[[0], [1], [2]]),
        ),
    ],
    title="Executive Dashboard - FY2024",
)

from vizro import Vizro

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