A Yardstick That Moves With the Minute

Anomaly DetectionMedium+20 XP+20

A Yardstick That Moves With the Minute

A ticketing website counts sign-in attempts every minute. A sudden burst can mean a bot is guessing passwords. A sudden drop can mean the sign-in page is broken.

The count drifts up and down through the day, so one fixed fence would ring at every busy hour and sleep through a quiet one, the problem from Anomalies in Time Series. Instead, each minute is judged against the minutes just before it:

  • The baseline for minute iii is the window counts just before it: readings[i - window] up to and including readings[i - 1]. Minute iii is not part of its own baseline.
  • The baseline's mean μ\muμ is the expected level. Its standard deviation σ\sigmaσ, the population version (divide by window), is the yardstick.
  • The minute's score is
zi=xi−μσz_i = \frac{x_i - \mu}{\sigma}zi​=σxi​−μ​
  • Minute iii is flagged when ∣zi∣>|z_i| >∣zi​∣> threshold. Surprises count in both directions.

The first window minutes have no full baseline, so they are never scored or flagged.

Task: write rolling_z_alerts(readings, window, threshold) returning a list of (i, z) tuples, one per flagged minute, in time order, with z rounded to 4 decimal places. You may assume no baseline has a standard deviation of 0.

Examples

readings = [52, 48, 50, 51, 49, 50, 47, 75, 50, 51, 49, 52, 50, 48, 21, 50]
window = 5
threshold = 3
returns [(7, 18.8726), (14, -20.5061)]
readings = [61, 58, 60, 63, 59, 62, 60, 12, 30, 58, 61]
window = 6
threshold = 3
returns [(7, -28.4368)]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run