Lesson 58 · Python for Retail E-commerce Analytics
Retail Sales Forecasting Case Study Training with Python for E-commerce Analytics
We will solve a real-world retail sales forecasting problem using Python. Forecasting future sales helps businesses plan inventory, marketing campaigns, and…
- CoursePython for Retail E-commerce Analytics
- Lesson58 of 43
- Video18 min
- FormatJupyter notebook · 15 code cells
What you'll learn
- Core Concepts in Retail Sales Analytics
- Beginner Example 1: Calculate Total Sales Revenue
- Beginner Example 2: Identify Top-Selling Products
- Beginner Example 3: Daily Sales Revenue Trend
- Intermediate Example 1: Average Order Value (AOV)
- Intermediate Example 2: Customer Analysis Who Are the Biggest Buyers?
- Intermediate Example 3: Category Performance with Synthetic Product Catalog
- Advanced Example 1: Weekly Sales Forecasting with a Simple Model
Data
No separate download needed — the notebook creates or downloads everything it uses.
📓 Full notebook
Download .ipynbRetail Sales Forecasting Case Study#
- We will solve a real-world retail sales forecasting problem using Python.
- Forecasting future sales helps businesses plan inventory, marketing campaigns, and staffing.
- Accurate forecasts lead to better stock management, fewer lost sales, and higher profits.
- By the end, you will learn to explore sales data, identify sales patterns, and build forecasting insights.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
Core Concepts in Retail Sales Analytics#
- Retail datasets record each product sale, customer, date, quantity, and price.
- Common metrics: sales revenue, units sold, average transaction value.
- Grouping data by product, customer, or date reveals valuable patterns.
- Beginners often forget to multiply quantity by price for total revenue.
- Time is essential: trends can shift with seasons, holidays, or promotions.
# Loading UCI Online Retail Transactions dataset for sales analysis
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 1: Calculate Total Sales Revenue#
- Calculate total revenue by multiplying quantity and price for each line item.
- Sum this value across all transactions to get total sales.
df['LineRevenue'] = df['Quantity'] * df['Price']
total_revenue = df['LineRevenue'].sum()
print(f"Total sales revenue: {total_revenue:,.2f}")
Beginner Example 2: Identify Top-Selling Products#
- Group sales by product, summing revenue for each item.
- Find the products with the highest total revenue.
top_products = df.groupby('Description')['LineRevenue'].sum().sort_values(ascending=False).head(5)
print('Top 5 products by revenue:')
print(top_products)
Beginner Example 3: Daily Sales Revenue Trend#
- Sum daily total revenue over time.
- Visualize to spot trends and volatility.
daily_revenue = df.groupby(df['InvoiceDate'].dt.date)['LineRevenue'].sum()
daily_revenue.plot(figsize=(12,5))
plt.title('Daily Sales Revenue Trend')
plt.ylabel('Revenue (GBP)')
plt.xlabel('Date')
plt.tight_layout()
plt.show()
Intermediate Example 1: Average Order Value (AOV)#
- Calculate AOV by dividing total revenue by number of unique invoices.
- A higher AOV often means more efficient sales and higher profitability.
n_invoices = df['Invoice'].nunique()
aov = total_revenue / n_invoices
print(f"Average Order Value (AOV): {aov:,.2f}")
Intermediate Example 2: Customer Analysis Who Are the Biggest Buyers?#
- Group sales by customer, summing their total purchases.
- Identify the customers who spend the most.
customer_sales = df.groupby('Customer ID')['LineRevenue'].sum().sort_values(ascending=False).head(5)
print('Top 5 customers by spend:')
print(customer_sales)
Intermediate Example 3: Category Performance with Synthetic Product Catalog#
- Use a synthetic catalog to assign categories and analyze revenue by category.
- Find which categories drive the highest sales.
np.random.seed(42)
categories = ['Electronics','Clothing','Home','Sports','Beauty']
product_ids = df['StockCode'].drop_duplicates().sample(100, random_state=42)
product_categories = np.random.choice(categories, 100)
synthetic_catalog = pd.DataFrame({'StockCode': product_ids.values, 'Category': product_categories})
df_cat = df.merge(synthetic_catalog, on='StockCode', how='left')
cat_sales = df_cat.groupby('Category')['LineRevenue'].sum().sort_values(ascending=False)
print('Revenue by product category (synthetic):')
print(cat_sales)
Advanced Example 1: Weekly Sales Forecasting with a Simple Model#
- Aggregate sales by week to see longer patterns.
- Use previous weeks' sales as a naive baseline forecast.
weekly_revenue = df.groupby(df['InvoiceDate'].dt.to_period('W'))['LineRevenue'].sum()
forecast = weekly_revenue.shift(1)
actual_vs_forecast = pd.DataFrame({'Actual': weekly_revenue, 'Forecast': forecast})
print(actual_vs_forecast.tail())
Advanced Example 2: Visualizing Actual vs Forecasted Sales#
- Plot both actual and forecasted weekly sales to evaluate forecasting accuracy.
- Spot where the forecast lags or spikes unexpectedly.
actual_vs_forecast.plot(figsize=(12,5), marker='o')
plt.title('Weekly Actual vs. Forecasted Sales Revenue')
plt.ylabel('Revenue (GBP)')
plt.xlabel('Week')
plt.legend(['Actual', 'Forecast'])
plt.tight_layout()
plt.show()
Advanced Example 3: Handle Missing Values in Sales Data#
- Missing prices or quantities can produce incorrect totals.
- Fill missing values or drop invalid rows for accurate analysis.
missing = df[['Quantity', 'Price']].isnull().sum()
print('Missing values in Quantity and Price:')
print(missing)
df_clean = df.dropna(subset=['Quantity','Price'])
print(f'After cleaning: {df_clean.shape[0]} rows')
Error Example 1: Incorrect Revenue Calculation#
- Multiplying only price or only quantity leads to wrong results.
- Always check the formula for total revenue.
wrong_revenue = df['Price'].sum()
print(f"Incorrect revenue calculation (price sum only): {wrong_revenue:,.2f}")
Error Example 2: Wrong Grouping for Category Sales#
- Grouping by wrong column can give misleading results.
- Always group by logical business keys (category, customer, product).
wrong_group = df_cat.groupby('Invoice')['LineRevenue'].sum().head(3)
print('Grouping by Invoice shows sales per transaction, not per category:')
print(wrong_group)
Best Practices for Reliable Retail Sales Analytics#
- Always check for missing values and outliers.
- Double-check your formulas and groupings.
- Use multiple time periods (day, week, month) for sales trends.
- Segment customers and products for deeper insights.
- Test different forecasting methods, even simple ones.
- Document every step for stakeholder transparency.
Practice: End-to-End Problem Find Top 3 Products with Most Seasonal Uplift#
- Calculate average monthly revenue for each product.
- Find products with largest difference between peak and lowest month.
- Recommend these to be prioritized for seasonal campaigns.
df['Month'] = df['InvoiceDate'].dt.to_period('M')
monthly_prod_rev = df.groupby(['Description','Month'])['LineRevenue'].sum().reset_index()
pivot = monthly_prod_rev.pivot(index='Description', columns='Month', values='LineRevenue').fillna(0)
peak_diff = pivot.max(axis=1) - pivot.min(axis=1)
top_seasonal = peak_diff.sort_values(ascending=False).head(3)
print('Top 3 products with largest seasonal revenue shifts:')
print(top_seasonal)
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



