Detect and Remove Daily Revenue Outliers by Product
SQL & DataModel answerLast updated
Build a pandas pipeline that aggregates raw sales records, flags per-product outliers using IQR or Z-score, then plots the distribution before and after cleaning.
Daily Revenue Outlier Detection
You receive a raw daily sales table with the following schema:
| column | type | description |
|---|---|---|
date | string | calendar date, e.g. "2023-01-01" |
sku_id | string | product identifier |
unit_sold | int | units sold |
revenue | float | gross revenue in USD |
promo_flag | int | 1 if a promotion was active, 0 otherwise |
store_id | string | store identifier |
Sample rows:
date sku_id unit_sold revenue promo_flag store_id
2023-01-01 A123 120 2400.00 1 S01
2023-01-02 A123 80 1600.00 0 S01
2023-01-01 B456 200 3000.00 1 S02
2023-01-02 B456 50 750.00 0 S02
Your task
Using Python with pandas, matplotlib, and seaborn:
- Load and validate the raw data — parse dates, coerce revenue to numeric, and drop rows that are unusable (missing keys, negative revenue, duplicates).
- Aggregate to daily-per-product grain — sum revenue across stores so each row represents one product on one day.
- Flag outliers per product using either the IQR fence rule or the Z-score rule. Do not apply a single global threshold across all products.
- Filter the flagged rows out into a cleaned dataset.
- Plot histograms of daily revenue per product, before and after cleaning, using shared bin edges so the two charts are directly comparable.
What a complete answer covers
- Why per-product thresholds matter (not global)
- The IQR method and why it is more robust than the standard Z-score on skewed revenue data
- At least one edge case: small groups, zero variance, or the interaction between
promo_flagand outlier detection - Working, readable Python code for the full pipeline
- A brief note on time and space complexity
Hints
Hint 1
Before detecting outliers, aggregate revenue by (sku_id, date) — a single SKU sold across multiple stores appears on multiple rows in the raw table, which inflates the value if you forget to sum first.
Hint 2
Use groupby(...).transform(...) to compute per-SKU IQR fences and attach them back as columns. That lets you add an is_outlier flag without losing any rows, so you can audit exactly what was removed before you filter.
Hint 3
Revenue is right-skewed and products operate on very different scales — a day that looks extreme for a small SKU is routine for a large one. Check whether flagged rows coincide with promo_flag=1 before deleting them; a promotion spike is signal, not noise.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is not the statistics — it is the sequencing. Do each step in the right order, keep intermediate results auditable, and the rest follows naturally.
Step 1 — Load and validate
Parse date with errors="coerce" and revenue with errors="coerce", then drop rows where either is NaN. Also drop exact duplicates and rows with negative revenue (returns or data-entry errors). Doing this first prevents corrupted values from distorting quartile calculations later.
Step 2 — Aggregate to the right grain
The raw table is at (date, sku_id, store_id) grain. The question asks for daily revenue per product, so you need (date, sku_id) grain. Use groupby(["sku_id", "date"]).agg(...) to sum revenue and units, and take the max of promo_flag (any store running a promo counts as a promo day).
Skipping this step is the most common mistake. If a product is sold in 10 stores, one data-entry spike in one store inflates the row for that store only — once you aggregate, it is dampened by the other nine. Detecting before aggregating mixes store-level noise with product-level signal.
Step 3 — Flag outliers per product, not globally
Product A might average $2,000/day; Product B might average $50/day. A global fence derived from both combined would flag every normal day of Product A and miss genuine spikes for Product B.
IQR rule (recommended): for each product, compute Q1, Q3, IQR = Q3 − Q1, then mark a day as an outlier if its revenue falls below Q1 − 1.5·IQR or above Q3 + 1.5·IQR. Quartiles are robust — a handful of extreme values barely move them, so the fences do not collapse toward the anomalies.
Why not standard Z-score? When revenue is right-skewed, a single massive spike inflates the mean and standard deviation. That inflated σ can pull the extreme point's own z-score below the threshold — the masking effect. IQR fences are immune to this.
If you want a score-based method, use the modified Z-score instead: 0.6745 · (x − median) / MAD > 3.5. It uses the median and median absolute deviation, both robust estimators.
Add a boolean is_outlier column rather than dropping rows immediately. This keeps the step reversible and lets you inspect what was flagged before committing to removal.
Step 4 — Business sanity check
Before deleting anything, cross-reference with promo_flag. A revenue spike on a promotion day is expected behavior, not a data error. A strong candidate says: "I'd report flagged promo days to the business rather than silently dropping them." One clean approach is to flag outliers separately within promo and non-promo subgroups.
Step 5 — Plot before and after
Compute shared bin edges from the full dataset with np.histogram_bin_edges, then use those same edges for both the pre- and post-cleaning histograms. Without shared bins, the x-axes shift after removal and the comparison is misleading.
Edge cases
- Tiny groups: IQR on 2 data points is mathematically defined but practically meaningless. Require a minimum number of observations (e.g., 4) and skip flagging for products below that threshold.
- Zero variance: if a product has identical revenue every day, IQR = 0 and the fences collapse to a single point. Treat zero-IQR groups as having no outliers rather than flagging everything.
- Do not iterate: running the IQR filter repeatedly until nothing remains is not standard practice. Apply it once with a documented multiplier
k(default 1.5).
Complexity
- Time: O(n log n) — dominated by the groupby sort and per-group quantile computation; flagging and filtering are O(n).
- Space: O(n) for the aggregated frame and the threshold columns.
Python solution
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# ── 1. Load & validate ──────────────────────────────────────────────────────
def load_sales(path_or_df) -> pd.DataFrame:
df = (path_or_df.copy()
if isinstance(path_or_df, pd.DataFrame)
else pd.read_csv(path_or_df))
df["date"] = pd.to_datetime(df["date"], errors="coerce")
df["revenue"] = pd.to_numeric(df["revenue"], errors="coerce")
df = df.dropna(subset=["date", "sku_id", "revenue"]).drop_duplicates()
return df[df["revenue"] >= 0].reset_index(drop=True)
# ── 2. Aggregate to (sku_id, date) grain ───────────────────────────────────
def aggregate_daily(df: pd.DataFrame) -> pd.DataFrame:
return (
df.groupby(["sku_id", "date"], as_index=False)
.agg(
revenue=("revenue", "sum"),
units_sold=("unit_sold", "sum"),
promo_flag=("promo_flag", "max"), # any store on promo → 1
)
)
# ── 3. Flag outliers per product using IQR ─────────────────────────────────
def flag_outliers_iqr(
daily: pd.DataFrame,
value_col: str = "revenue",
group_col: str = "sku_id",
k: float = 1.5,
min_obs: int = 4,
) -> pd.DataFrame:
out = daily.copy()
g = out.groupby(group_col)[value_col]
q1 = g.transform(lambda s: s.quantile(0.25))
q3 = g.transform(lambda s: s.quantile(0.75))
iqr = q3 - q1
out["lower"] = q1 - k * iqr
out["upper"] = q3 + k * iqr
enough_data = g.transform("size") >= min_obs
nonzero_iqr = iqr > 0
out["is_outlier"] = (
enough_data
& nonzero_iqr
& ((out[value_col] < out["lower"]) | (out[value_col] > out["upper"]))
)
return out
# ── 4. (Optional) Z-score variant ──────────────────────────────────────────
def flag_outliers_zscore(
daily: pd.DataFrame,
value_col: str = "revenue",
group_col: str = "sku_id",
threshold: float = 3.0,
min_obs: int = 4,
) -> pd.DataFrame:
out = daily.copy()
g = out.groupby(group_col)[value_col]
mean = g.transform("mean")
std = g.transform("std") # sample std (ddof=1)
out["z"] = (out[value_col] - mean) / std.replace(0, np.nan)
enough_data = g.transform("size") >= min_obs
out["is_outlier"] = enough_data & (out["z"].abs() > threshold)
# NaN z-scores (zero std) evaluate to False — treated as non-outliers
return out
# ── 5. Plot before / after on shared bins ──────────────────────────────────
def plot_before_after(
flagged: pd.DataFrame,
value_col: str = "revenue",
hue: str = "sku_id",
bins: int = 30,
) -> pd.DataFrame:
clean = flagged[~flagged["is_outlier"]].copy()
edges = np.histogram_bin_edges(flagged[value_col], bins=bins)
fig, axes = plt.subplots(1, 2, figsize=(13, 4.5), sharex=True, sharey=True)
for ax, data, label in [
(axes[0], flagged, f"Before (n={len(flagged)})"),
(axes[1], clean, f"After (n={len(clean)}, "
f"{flagged['is_outlier'].sum()} removed)"),
]:
sns.histplot(data, x=value_col, hue=hue, bins=edges,
element="step", alpha=0.45, ax=ax)
ax.set_title(label)
ax.set_xlabel("Daily revenue per SKU (USD)")
plt.tight_layout()
plt.show()
return clean
# ── Demo ───────────────────────────────────────────────────────────────────
if __name__ == "__main__":
rng = np.random.default_rng(42)
dates = pd.date_range("2023-01-01", periods=90)
rows = []
for sku, store, base, price in [
("A123", "S01", 100, 20.0),
("B456", "S02", 150, 15.0),
]:
units = rng.poisson(base, len(dates))
promo = rng.random(len(dates)) < 0.10
units = np.where(promo, (units * 1.3).astype(int), units)
for d, u, p in zip(dates, units, promo):
rows.append([d, sku, int(u), u * price, int(p), store])
raw = pd.DataFrame(
rows, columns=["date", "sku_id", "unit_sold", "revenue", "promo_flag", "store_id"]
)
# Inject two data-entry style spikes
raw.loc[[5, 120], "revenue"] *= 8
daily = aggregate_daily(load_sales(raw))
flagged = flag_outliers_iqr(daily)
print(flagged[flagged["is_outlier"]][
["sku_id", "date", "revenue", "lower", "upper", "promo_flag"]
])
clean = plot_before_after(flagged)
Common mistakes to avoid
- Detecting outliers on the raw (store-level) table instead of the aggregated (product-day) table.
- Using a single global threshold across products with very different revenue scales.
- Dropping rows immediately without an auditable flag column.
- Plotting before and after with different bin edges, making the change look larger or smaller than it is.
- Iterating the outlier filter until convergence — one pass with a documented
kis the standard.