Lesson 7 · Supply Chain Operations Analytics
Order-Level and Demand Analysis in Supply Chain Operations Analytics | Full Training
In this lesson, we will solve real-world order-level and demand analysis problems using Python. These types of problems help businesses manage inventory,…
- CourseSupply Chain Operations Analytics
- Lesson7 of 27
- Video19 min
- FormatJupyter notebook · 17 code cells
What you'll learn
- Core Data Concepts in Order and Demand Analysis
- Beginner Example 1: Loading Retail Demand Data
- Beginner Example 2: Loading Manufacturing Operations Data
- Beginner Example 3: Counting Unique Orders
- Intermediate Example 1: Daily Demand Time Series
- Intermediate Example 2: Most Demanded Products
- Intermediate Example 3: Analyzing Order Frequency by Country
- Advanced Example 1: Order Lead Time Analysis (Delivery Dataset)
Data
No separate download needed — the notebook creates or downloads everything it uses.
📓 Full notebook
Download .ipynbOrder-Level and Demand Analysis in Supply Chain Operations#
- In this lesson, we will solve real-world order-level and demand analysis problems using Python.
- These types of problems help businesses manage inventory, fulfill customer needs, and improve supply chain efficiency.
- Understanding demand patterns and order behaviors prevents stockouts and helps plan future operations.
- By the end, you will be able to analyze real datasets, spot demand trends, and extract essential supply chain metrics.
import pandas as pd
import numpy as np
import openml
import warnings
warnings.filterwarnings('ignore')
Core Data Concepts in Order and Demand Analysis#
- Supply chain datasets often record every order or line item, including date, product, quantity, and customer.
- Retail demand data tracks what was sold, when, and to whom.
- Operations datasets may include lead times, supplier info, or delivery performance.
- Beginners sometimes forget to check date consistency or misinterpret demand quantities.
- Aggregating at the wrong level (like mixing daily and monthly orders) is a common mistake.
- Clean, consistent timestamps and correct units are critical for good analysis.
Beginner Example 1: Loading Retail Demand Data#
- Let us explore a real-world online retail transactions dataset.
- We will look at the first few order records to see how demand data is organized.
url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/00502/online_retail_II.xlsx'
df = pd.read_excel(url, sheet_name='Year 2010-2011')
df['InvoiceDate'] = pd.to_datetime(df['InvoiceDate'])
print(df.shape)
print(df.head(3))
Beginner Example 2: Loading Manufacturing Operations Data#
- Not all supply chain analysis is retail.
- Here is an operations dataset from OpenML showing process-level order records.
dataset = openml.datasets.get_dataset(43900)
X, y, _, _ = dataset.get_data(dataset_format='dataframe')
df_ops = X.copy() if y is None else pd.concat([X, y], axis=1)
print(df_ops.shape)
print(df_ops.head(3))
Beginner Example 3: Counting Unique Orders#
- A basic analysis step is counting distinct orders over a period.
- Let us do this with the retail demand dataset.
unique_orders = df['Invoice'].nunique()
print('Number of unique orders:', unique_orders)
Intermediate Example 1: Daily Demand Time Series#
- Real supply chains monitor demand per day.
- We can group sales transactions by date to generate a daily demand curve.
daily_demand = df.groupby(df['InvoiceDate'].dt.date)['Quantity'].sum()
print(daily_demand.head())
Intermediate Example 2: Most Demanded Products#
- Knowing top sellers helps manage inventory and promotions.
- Let us find the most demanded product in our retail dataset.
top_product = df.groupby('Description')['Quantity'].sum().sort_values(ascending=False).head(1)
print('Most demanded product:')
print(top_product)
Intermediate Example 3: Analyzing Order Frequency by Country#
- Global distributors want to see which markets order most frequently.
- We will count orders by country in our retail dataset.
orders_country = df.groupby('Country')['Invoice'].nunique().sort_values(ascending=False)
print(orders_country.head())
Advanced Example 1: Order Lead Time Analysis (Delivery Dataset)#
- Meeting promised delivery dates is critical for customer satisfaction.
- We will analyze order lead times using real e-commerce order and delivery data.
olist_url = 'https://raw.githubusercontent.com/olist/work-at-olist-data/master/datasets/olist_orders_dataset.csv'
olist_df = pd.read_csv(olist_url)
olist_df['order_purchase_timestamp'] = pd.to_datetime(olist_df['order_purchase_timestamp'])
olist_df['order_delivered_customer_date'] = pd.to_datetime(olist_df['order_delivered_customer_date'])
olist_df['lead_time_days'] = (olist_df['order_delivered_customer_date'] - olist_df['order_purchase_timestamp']).dt.days
mean_lead_time = olist_df['lead_time_days'].mean()
print('Average lead time (days):', mean_lead_time)
Advanced Example 2: Detecting Demand Outliers#
- Sudden demand spikes could signal errors or special events.
- Let us flag unusually high daily demand days in the retail data.
Q1 = daily_demand.quantile(0.25)
Q3 = daily_demand.quantile(0.75)
IQR = Q3 - Q1
outlier_days = daily_demand[daily_demand > Q3 + 1.5 * IQR]
print('Unusually high demand days:')
print(outlier_days)
Advanced Example 3: Analyzing Demand Variability by Product#
- Highly variable demand skews safety stock calculations.
- Let us compute the standard deviation of demand by product.
prod_daily = df.groupby(['Description', df['InvoiceDate'].dt.date])['Quantity'].sum().reset_index()
var_by_prod = prod_daily.groupby('Description')['Quantity'].std().sort_values(ascending=False)
print('Top 5 most variable products by daily demand:')
print(var_by_prod.head())
Error Handling Example 1: Finding Missing Dates#
- Missing sales dates can impact trends and forecasts.
- Let us check for missing days in the daily demand time series.
all_days = pd.date_range(start=daily_demand.index.min(), end=daily_demand.index.max())
missing_days = all_days.difference(pd.to_datetime(daily_demand.index))
print('Number of missing sales days:', len(missing_days))
print('Missing dates:', missing_days[:5].strftime('%Y-%m-%d').tolist())
Error Handling Example 2: Preventing Incorrect Data Joins#
- Joining datasets on the wrong field can break analysis.
- Here is how to spot a mismatch in key fields.
# Example: matching orders from two sources by invoice - simulate mismatch
order_keys = set(df['Invoice'].astype(str).unique())
olist_keys = set(olist_df['order_id'].astype(str).unique())
join_overlap = order_keys & olist_keys
print('Number of matching order keys between datasets:', len(join_overlap))
Error Handling Example 3: Interpreting Negative or Null Values#
- Sometimes data has negative quantities or lead times.
- Let us scan for apparent errors in our order-level demand and delivery data.
neg_qty = df[df['Quantity'] < 0]
neg_lead = olist_df[olist_df['lead_time_days'] < 0]
print('Negative quantity rows:', neg_qty.shape[0])
print('Negative lead time rows:', neg_lead.shape[0])
Best Practices: Aggregate Demand by Time Period#
- Consistently aggregating by day, week, or month reduces errors.
- Here is how to safely sum demand by month in the retail dataset.
df['month'] = df['InvoiceDate'].dt.to_period('M')
monthly_demand = df.groupby('month')['Quantity'].sum()
print(monthly_demand.head())
Best Practices: Calculating Key Performance Indicators (KPIs)#
- KPIs such as fill rate, lead time, and order cycle time drive better decisions.
- Let us compute the percent of orders delivered within seven days.
on_time_pct = (olist_df['lead_time_days'] <= 7).mean() * 100
print(f'Percent of orders delivered within 7 days: {on_time_pct:.2f}%')
Mini End-to-End Problem: Demand Spike Alert#
- Let us solve a real scenario.
- Detect any week where retail demand is 50% higher than the prior week and alert operations managers.
df['week'] = df['InvoiceDate'].dt.to_period('W')
weekly_demand = df.groupby('week')['Quantity'].sum()
weekly_growth = weekly_demand.pct_change()
spike_weeks = weekly_growth[weekly_growth > 0.5].index.astype(str).tolist()
print('Weeks with demand spike alert:', spike_weeks)
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



