KatInterview

Detect and Remove Daily Revenue Outliers by Product

SQL & DataModel answer
MediumModel answerSQL & Datapandasoutlier-detectiondata-cleaning

Last 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:

columntypedescription
datestringcalendar date, e.g. "2023-01-01"
sku_idstringproduct identifier
unit_soldintunits sold
revenuefloatgross revenue in USD
promo_flagint1 if a promotion was active, 0 otherwise
store_idstringstore 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:

  1. Load and validate the raw data — parse dates, coerce revenue to numeric, and drop rows that are unusable (missing keys, negative revenue, duplicates).
  2. Aggregate to daily-per-product grain — sum revenue across stores so each row represents one product on one day.
  3. 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.
  4. Filter the flagged rows out into a cleaned dataset.
  5. 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_flag and 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.