Topic 1: Python Essentials

Introduction to Business Analytics — HKUST

Prof. Xuhu Wan

Why Python for Business?

Python Is the Language of Data

Why it matters

“Coding is not just for tech people — it is for anyone who wants to run a competitive company in the 21st century.”

— Mary Callahan Erdoes, JPMorgan

  • 📈 #1 language in data science and finance
  • 🤖 Powers AI: TensorFlow, PyTorch, LangChain
  • 💼 Required by Goldman Sachs, JP Morgan, McKinsey
  • 🎓 Most taught in top business schools

Data Science Language Popularity 2025

Language Share
Python 31%
JavaScript 24%
Java 17%
R 12%
SQL 8%

What We Build This Course

Course workflow:

🐍 Python Essentials → 📋 Data Processing → 📈 Linear Regression → 🧩 Clustering

Topic 1 Topic 2 Topic 3 Topic 4
Python Essentials Data Processing Linear Regression Clustering

Key takeaway

Today (Topic 1): Lists, NumPy arrays, and pandas Series — the three containers you will use every day.

Setting Up

Learning Goals

  • ✓ Install external Python packages with pip
  • ✓ Import libraries and understand aliases (pd, np, plt)
  • ✓ Know what each core library does

Core libraries

  • 🐍 NumPy — arrays & math
  • 📋 Pandas — data frames
  • 📊 Matplotlib — charts
  • 📚 isom2600 — course data

Installing Packages with pip

Why it matters

Python comes with basics, but for data analysis we need extra toolboxes (packages). Think of pip as an app store for Python.

# Install the course package (run once per Colab session)
!pip install isom2600 --quiet
  • On Google Colab: install at the top of every notebook
  • On local Anaconda: install once in terminal, then import

Importing Modules

A module is like a toolbox — you import the tools you need.

import numpy as np       # Math & arrays
import pandas as pd      # DataFrames & Series
import matplotlib.pyplot as plt  # Charts
import isom2600          # Course data
  • np — NumPy (arrays, random numbers, math)
  • pd — Pandas (Series, DataFrames, stats)
  • plt — Matplotlib (line, bar, scatter plots)

Lists — Your First Data Container

Learning Goals

  • ✓ Create lists and understand heterogeneous types
  • ✓ Use indexing and slicing to access elements
  • ✓ Apply key list methods: append, remove, len, sort

stock_tickers

[0] [1] [2] [3]
AAPL GOOG TSLA NVDA
  • .append() — add
  • .remove() — delete
  • .sort() — order

What Is a List?

A list stores an ordered collection of items — numbers, strings, anything.

Why it matters

In business, lists represent portfolios, product catalogs, customer IDs, and survey responses.

Business Use Cases

  • 📈 Portfolio of stocks
  • 📦 Product catalog
  • 👥 Customer IDs
  • 📋 Survey responses

Indexing and Slicing

Python counts from 0 (zero-indexed). Negative indices count from the end.

index 0 index 1 index 2 index 3
AAPL GOOG TSLA NVDA
-4 -3 -2 -1

Key List Methods

Key takeaway

.append() adds, .remove() deletes, len() counts, .sort() orders (use reverse=True for descending).

Try It! — Lists

Try it!

Given monthly sales figures:

sales = [12000, 15000, 8000, 22000, 18000, 9000]

  1. What was the sales in month 3? (Hint: zero-indexed!)
  2. What were the sales in the last 2 months?
  3. Add 25000 as next month’s sales
  4. What is the total number of months now?

List Comprehension — Doing More with Less

Learning Goals

  • ✓ Write plain list comprehensions to transform data
  • ✓ Write filtered comprehensions to select data
  • ✓ Write conditional comprehensions for if/else logic

For-loop: 4 lines of code

vs.

Comprehension: 1 line

  • [expr for item in list]
  • [expr for item if cond]
  • [A if c else B for item]

Plain Comprehension

Business problem: Apply a 10% price increase to all products.

Key takeaway

Pattern: [expression for item in list]

Filtered Comprehension

Business problem: Show only premium products (price > 150).

Key takeaway

Pattern: [expression for item in list if condition]

The output list can be shorter than the input — items are filtered out.

Conditional Comprehension

Business problem: Generate Buy/Sell signals based on price.

Key takeaway

Pattern: [A if cond else B for item in list]

Output always has the same length as input — every item gets a value.

Try it!

Classify exam scores: scores = [88, 45, 72, 95, 61]

Output "Pass" if score \(\geq\) 60, else "Fail".

Nested Conditional Comprehension

Business problem: Assign letter grades based on score thresholds.

Key takeaway

You can chain if/else inside a comprehension. Read left to right: first condition checked first.

Important

Avoid nesting more than 2–3 conditions — beyond that, use a helper function for readability.

From List to pandas Series — The Power-Up

Learning Goals

  • ✓ Understand why lists are limited for data analysis
  • ✓ Create a pandas Series from a list
  • ✓ Use Series attributes: .dtype, .shape, .index, .name

📋 List (no math, no stats, no plots)

pd.Series(list)

📊 pd.Series (math ✓ stats ✓ plots ✓)

Why Lists Aren’t Enough

Why it matters

Lists are general-purpose containers. For data analysis — math, statistics, plotting — we need something more powerful.

List vs. pd.Series

Operation List Series
prices + 10
.mean()
.max()
.plot()

Convert to pandas Series

Key takeaway

pd.Series(list) converts a plain list into a powerful data object with built-in math, statistics, and plotting.

List → Series

List Series (with index)
100 Mon : 100
102 Tue : 102
98 Wed : 98
105 Thu : 105
101 Fri : 101

Series Attributes

Attributes (no parentheses)

Describe the data: .dtype, .shape, .index, .name

Methods (with parentheses)

Compute on the data: .mean(), .max(), .plot()

pandas Series Methods

Learning Goals

  • ✓ Compute descriptive statistics with one method call
  • ✓ Use .value_counts() and .sort_values()
  • ✓ Create quick plots directly from a Series
  • .describe() — full summary
  • .value_counts() — categories
  • .sort_values() — rank
  • .plot() / .hist() — visualize

ISOM 2500 Recap — Descriptive Statistics

Central tendency (typical value):

  • .mean() — numerical, outlier-affected
  • .median() — numerical, robust
  • .mode() — categorical & numerical

Variation:

  • .std() — standard deviation
  • IQR: .quantile(.75) - .quantile(.25)

Sample vs. population std:

\[s = \sqrt{\frac{\sum_{i=1}^{n}(x_i - \bar{x})^2}{n-1}}\]

aapl.std()        # sample (ddof=1, default)
aapl.std(ddof=0)  # population

ddof=1 uses \(n{-}1\) (Bessel’s correction).

Descriptive Statistics in Action

import isom2600
aapl = isom2600.data.getStock("AAPL")["Close"].squeeze().squeeze()

print(aapl.mean())      # Average price
print(aapl.median())    # Median price
print(aapl.std())       # Volatility (sample std)
print(aapl.min())       # Lowest price
print(aapl.max())       # Highest price

# Interquartile range
iqr = aapl.quantile(0.75) - aapl.quantile(0.25)

print(aapl.describe())  # Full summary in one call!

Why it matters

.describe() gives you count, mean, std, min, 25%, 50%, 75%, max — the complete “profile” of your data in one line.

.value_counts() and .sort_values()

Quick Plots from a Series

import isom2600
aapl = isom2600.data.getStock("AAPL")["Close"].squeeze()
# .squeeze() converts a one-column DataFrame to a Series

aapl.plot()            # Line chart (default)
aapl.hist(bins=30)     # Histogram
aapl.plot(kind="bar")  # Bar chart

Key takeaway

pandas integrates with matplotlib. One method call = one chart. Customize with figsize, color, title.

Conceptual line chart: AAPL price trending upward over days. One line of code: aapl.plot().

NumPy Essentials

Learning Goals

  • ✓ Understand element-wise operations with NumPy arrays
  • ✓ Generate random numbers for simulation

Broadcasting: array * 2

Input 1 2 3
× 2 2 4 6

List *2 would repeat the list instead!

NumPy Array vs. List

Key takeaway

NumPy arrays support element-wise math (broadcasting), just like pd.Series — but without a named index.

List ×2 ✗ → repeats list

[100,102,...,100,102,...]

Array ×2 ✓ → each doubled

[200,204,196,210,202]

Random Numbers — Simulate Stock Returns

Syntax: np.random.normal(μ, σ, n) — draw n samples from \(\mathcal{N}(\mu,\,\sigma^2)\)

Key takeaway

Each call gives different random draws. The sample mean/std will be close to \(\mu\)/\(\sigma\) but not exact.

Matplotlib and Statistical Graphing

Learning Goals

  • ✓ Create line plots, histograms, and scatter plots with matplotlib
  • ✓ Customize plots: title, labels, color, linestyle
  • ✓ Build multi-panel figures with plt.subplots()

Two Ways to Plot: plt vs. Series Methods

Way 1: plt (matplotlib directly)

# You supply x and y explicitly
plt.plot(days, price, color="blue")
plt.hist(returns, bins=30)
plt.scatter(x, y)
  • Works with any data: lists, arrays, Series
  • You control every detail
  • Need to pass both x and y

Way 2: Series methods

# Series knows its own index and values
aapl.plot(color="blue")
aapl.hist(bins=30)
aapl.plot(kind="bar")
  • Only works with pandas Series/DataFrame
  • Index auto-used as x-axis
  • Shorter — great for quick exploration

Key takeaway

Use Series methods for quick exploration. Use plt when you need full control or non-pandas data.

Line Plot — Price Over Time

Key takeaway

Key params: color, linewidth, linestyle, marker, label.

Histogram — Distribution Profile

Why it matters

Histograms reveal shape: is the return symmetric? Are there fat tails?

Scatter Plot — Bivariate Association

Key takeaway

Scatter plots reveal the direction and strength of association between two variables.

Figure Object and Subplots

Key takeaway

plt.subplots(r, c) returns a grid of Axes objects. Always call plt.tight_layout() to prevent overlap.

Plotting with Series Methods

import isom2600
import pandas as pd
import matplotlib.pyplot as plt

aapl = isom2600.data.getStock("AAPL")["Close"].squeeze()
fig, axes = plt.subplots(1, 3, figsize=(15, 4))

aapl.plot(ax=axes[0], title="Price", color="steelblue")
aapl.hist(ax=axes[1], bins=25, color="coral")
axes[1].set_title("Distribution")

stats_s = pd.Series({"Mean": aapl.mean(),
    "Median": aapl.median(), "Std": aapl.std()})
stats_s.plot(kind="bar", ax=axes[2], color="seagreen")
plt.tight_layout(); plt.show()

Key takeaway

Series methods (.plot(), .hist()) accept ax= to place them in subplots. No need to pass x and y separately.

Try It! — Matplotlib

Try it!

  1. Generate 300 normal random returns: np.random.normal(0.001, 0.02, 300). Plot the histogram. Add a vertical dashed line at the mean.
  2. Simulate two correlated assets (market and stock). Create a scatter plot. Add axis labels and a title.
  3. Create a \(1 \times 2\) subplot: line chart on the left, boxplot on the right. Use plt.tight_layout().

SciPy for Business Statistics

Learning Goals

  • ✓ Compute cumulative probabilities: \(P(X < x)\)
  • ✓ Find critical values: \(P(X < ?) = p\)
  • ✓ Apply to business problems: VaR and hypothesis testing

SciPy Stats — CDF and PPF

CDF: value → probability

Given \(x=10\), the shaded area under the normal density to the left of 10 = 84.1%.

PPF: probability → value

Given probability 5%, the \(x\)-value that cuts off the left 5% of the distribution is \(x = 4.71\).

Key takeaway

.cdf(x): value → probability \(\longleftrightarrow\) .ppf(p): probability → value

Business Application: Value at Risk and Hypothesis Testing

Normal density with the left-tail 5% region shaded — the VaR is the cutoff \(x\) such that \(P(X < \text{VaR}) = 5\%\).

Key takeaway

VaR: “Worst outcome at 95% confidence.” Standard in risk management.

Putting It All Together — Mini Project

Mini Project: Portfolio Analyzer

Build a Portfolio Analyzer using everything you learned today.

Mini Project: Visualize and Classify

Key takeaway

This mini project combines lists, comprehensions, f-strings, pd.Series, and matplotlib — all in one workflow.

Takeaway — When to Use What?

Property List pd.Series np.array
Mixed types
Element-wise math
Built-in stats
Named index
One-liner plots
Fastest math

Key takeaway

Rule of thumb: Start with a list for raw data. Convert to pd.Series for analysis. In this course, we mostly use pd.Series for data work. We only use np.array for generating random samples (e.g., np.random.normal()).