"""Reproduce every figure in https://fawadhs.dev/blog/stockout-prevention-automated-alerts-ecommerce Data: Online Retail II, UC Irvine Machine Learning Repository (CC BY 4.0) https://archive.ics.uci.edu/dataset/502/online+retail+ii Download the zip, unzip it, and pass the path of online_retail_II.xlsx: pip install pandas openpyxl python stockout-alerts-analysis.py online_retail_II.xlsx Reading the xlsx takes about a minute. Checked with pandas 3.0.5 on 15 November 2026. """ import sys import pandas as pd # The three functions below are the ones printed in the post. def daily_rates(orders: pd.DataFrame, end: str, days: int = 28) -> pd.DataFrame: """Average units sold per day, and the spread, for each SKU over the last `days` days. `orders` has one row per order line: sku, date, quantity (cancellations negative).""" first = pd.Timestamp(end) - pd.Timedelta(days=days - 1) calendar = pd.date_range(first, periods=days, freq="D") window = orders[(orders.date >= first) & (orders.date < calendar[-1] + pd.Timedelta(days=1))] daily = ( window.assign(day=window.date.dt.normalize()) .groupby(["sku", "day"]).quantity.sum() .unstack(fill_value=0) .reindex(columns=calendar, fill_value=0) # days with no sales count as zero ) return pd.DataFrame({"per_day": daily.mean(axis=1), "sd": daily.std(axis=1)}) def reorder_point(per_day: float, sd: float, lead_days: int, z: float = 1.645) -> float: """Demand during the supplier's lead time, plus safety stock (z = 1.645 for 95%).""" return per_day * lead_days + z * sd * lead_days ** 0.5 def stock_status(on_hand: int, on_order: int, per_day: float, rop: float) -> dict: cover = on_hand / per_day if per_day > 0 else float("inf") if on_hand <= 0: status = "out" elif on_hand + on_order <= rop: status = "reorder" else: status = "ok" return {"status": status, "days_of_cover": round(cover, 1)} LEAD_DAYS = 14 # an illustration: the dataset has no supplier data def main(path: str) -> None: raw = pd.concat( pd.read_excel(path, sheet_name=None, dtype={"StockCode": str, "Invoice": str}).values(), ignore_index=True, ) print(f"order lines in the file: {len(raw)}") # Product lines only (stock codes start with five digits; this drops postage, fees and # manual adjustments), positive prices. Cancellations ("C" invoices) stay in as negative # quantities, so every figure below is net of cancelled orders. lines = raw[raw.StockCode.str.match(r"^\d{5}") & (raw.Price > 0)] orders = lines.rename(columns={"StockCode": "sku", "InvoiceDate": "date", "Quantity": "quantity"}) name = lines.groupby("StockCode").Description.agg(lambda s: s.mode().iat[0]) # 1. What a 10-unit threshold means, 1 Jan to 30 Nov 2011 (334 calendar days). period = orders[(orders.date >= "2011-01-01") & (orders.date < "2011-12-01")] rates = daily_rates(period, end="2011-11-30", days=334) rates = rates[rates.per_day > 0].sort_values("per_day", ascending=False) cover = 10 / rates.per_day print(f"\nproducts with net sales: {len(rates)}") for q, label in [(0.1, "fastest 10%"), (0.25, "fastest 25%"), (0.5, "median"), (0.75, "slowest 25%"), (0.9, "slowest 10%")]: print(f" 10 units = {cover.quantile(q):.1f} days of stock at the {label} boundary") print(f" share at 1 day or less: {(cover <= 1).mean():.1%}; at 30 days or more: {(cover >= 30).mean():.1%}") best = rates.index[0] print(f" best seller {best} {name[best]}: {rates.per_day.iloc[0]:.2f} a day; " f"10 units = {10 / rates.per_day.iloc[0] * 24:.1f} hours of average sales") # 2. Seasonality: November against February. month = period.date.dt.month units = period.groupby(month).quantity.sum() print(f"\nunits sold, November / February: {units[11] / units[2]:.2f}") daily = (period.assign(day=period.date.dt.normalize()) .groupby(["sku", "day"]).quantity.sum().unstack(fill_value=0) .reindex(columns=pd.date_range("2011-01-01", "2011-11-30"), fill_value=0)) feb = daily.loc[:, daily.columns.month == 2].mean(axis=1) nov = daily.loc[:, daily.columns.month == 11].mean(axis=1) both = (feb > 0) & (nov > 0) doubled = (nov[both] / feb[both] >= 2) print(f"products selling in both months: {both.sum()}; at least twice as fast in November: " f"{doubled.sum()} ({doubled.mean():.1%})") # 3. The paper chain kit and the magazine rack, 28-day rates and reorder points. for sku, end in [("22086", "2011-02-28"), ("22086", "2011-11-30"), ("22781", "2011-11-30")]: r = daily_rates(orders[orders.sku == sku], end=end).iloc[0] rop = reorder_point(r.per_day, r.sd, LEAD_DAYS) print(f"{sku} {name[sku]}, 28 days to {end}: {r.per_day:.1f} a day, " f"reorder point {rop:.0f} with a {LEAD_DAYS}-day lead time") # 4. Lumpy demand: largest single order line against average daily sales, top 50 sellers. top50 = rates.index[:50] sold = period[period.sku.isin(top50) & ~period.Invoice.str.startswith("C")] ratio = sold.groupby("sku").quantity.max() / rates.per_day[top50] print(f"\ntop 50: largest order line is a median {ratio.median():.1f} times average daily sales") # 5. The cancelled jar order, and what counting it would do. jars = raw[(raw.StockCode == "23166") & (raw.Quantity.abs() > 1000)] print(jars[["Invoice", "Quantity", "InvoiceDate", "Customer ID"]].to_string(index=False)) gross = period[~period.Invoice.str.startswith("C") & (period.quantity > 0)] print("top seller if cancellations are ignored:", gross.groupby("sku").quantity.sum().idxmax()) # 6. The status function on two made-up stock positions (an illustration, not data). print("\n", stock_status(0, 0, 1.0, 5.0), stock_status(40, 0, 2.0, 30.0)) if __name__ == "__main__": main(sys.argv[1])