# Q-33: A rolling mean and a band

Data-Driven Athletics tutorial · Week 11 · Chapter 11 · about 15 min · workflow steps: Statistics, Visualize

Web page: https://apopt.com/course/tutorials/q33-rolling-band/ · Data: https://apopt.com/data/tutorials/q33-rolling-band/

## The decision

An athlete's morning heart rate has been high for a few days. Before saying anything, decide
whether the week as a whole sits outside the athlete's usual range, or only a few mornings do.
This is training information, not a medical assessment.

## The raw data

- `raw/morning_hr_simulated.csv`: SIMULATED: 42 mornings of resting heart rate with a 4 bpm rise after day 35, and the book's own 7-day rolling mean (`roll7`) to check against Book example data, Chapter 11 (`book/ch11-statistics/data/morning_hr.csv`, made by `code/morning_hr.py` with a fixed seed). Simulated, not a recording.

One morning's heart rate says little: it moves by a few beats a minute from day to day with
no change in you. Two tools from Chapter 11 make a daily series readable. A **band** is your
usual range, the mean plus or minus one standard deviation of a baseline period. A
**rolling mean** is the mean of the last seven days, recomputed each day; it smooths the
day-to-day noise and reacts a little late.

The file is the book's **simulated** six weeks of morning heart rate (Section 11.8). In the
simulation the true level rises by 4 beats a minute after day 35, so you know what the tools
should find.

### A baseline band from the first four weeks

*Predict first:* Your guess for the baseline mean, in beats per minute?

```python
import pandas as pd

hr = pd.read_csv("raw/morning_hr_simulated.csv", index_col="day")["hr"]
base = hr.loc[1:28]                                   # four weeks before anything changed
lo, hi = base.mean() - base.std(), base.mean() + base.std()
print(f"{len(hr)} mornings; baseline mean {base.mean():.1f} bpm, band {lo:.1f} to {hi:.1f}")
print(f"baseline mornings outside the band: {int(((base < lo) | (base > hi)).sum())} of 28")
```

Output:

```
42 mornings; baseline mean 51.3 bpm, band 49.2 to 53.4
baseline mornings outside the band: 12 of 28
```

Twelve of 28 ordinary mornings fall outside a band of one standard deviation. For normal
scatter you expect about a third outside; with day-to-day memory in the series (a high
morning tends to follow a high morning) runs outside are common. One morning above the band
is not news.

### A trailing seven-day mean

*Predict first:* In the last week the true level is 4 bpm higher. How many of those seven mornings will sit above the band?

```python
roll = hr.rolling(7).mean()                           # days d-6 to d: past only
check = pd.read_csv("raw/morning_hr_simulated.csv", index_col="day")["roll7"]
print(f"largest difference from the book's column: {(roll - check).abs().max():.3f} bpm")
print(f"7-day mean on day 35 {roll[35]:.1f}, on day 42 {roll[42]:.1f}")
print(f"mornings above the band in the last week: {int((hr.loc[36:] > hi).sum())} of 7")
print(f"7-day mean above the band from day {int(roll[roll > hi].index.min())}")
```

Output:

```
largest difference from the book's column: 0.004 bpm
7-day mean on day 35 49.9, on day 42 53.5
mornings above the band in the last week: 3 of 7
7-day mean above the band from day 42
```

Only three of the seven high mornings clear the band. The rolling mean climbs every day of
the week, from 49.9 to 53.5, and ends above the band on day 42: the band says "watch", the
rolling mean says "the week as a whole has moved". Use `rolling(7)` (the last seven days), not `rolling(7, center=True)`: a
centered window uses days that have not happened yet, which a tracker cannot do and a
forecast must not do (Section 11.8.1).

### The chart

```python
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(6.4, 3.2))
ax.axhspan(lo, hi, color="0.88", lw=0, label="usual range (days 1-28)")
ax.plot(hr.index, hr, "o", mfc="white", mec="0.35", ms=4, label="each morning")
ax.plot(roll.index, roll, "-", color="black", lw=1.8, label="7-day rolling mean")
ax.axvline(35.5, color="0.4", ls="--", lw=1)
ax.set(xlabel="day", ylabel="morning heart rate (bpm)",
       title="The weekly mean shows the rise that single mornings blur")
ax.legend(loc="upper left", fontsize=8)
plt.tight_layout()
```

![Six weeks of simulated morning heart rate as open circles, a shaded band from 49.2 to 53.4 bpm, and a solid line for the 7-day rolling mean that rises above the band in the last week.](https://apopt.com/course/tutorials/q33-rolling-band/c05-1.png)

**For the athlete:** "Your morning heart rate this week averaged about 2 beats a minute above
your usual level; that is training information, not a diagnosis, so tell us how you are
sleeping and we will look again next week."

## Action card

- **Finding:** The last week's mean rose about 2 bpm and reached the top of the usual range; single mornings did not show it clearly.
- **Evidence:** The 7-day mean rose from 49.9 to 53.5 bpm, above a band of 49.2 to 53.4; only 3 of 7 mornings were above it.
- **Sure:** Moderate. One week above the band; the next week decides.
- **Action:** Ask about sleep, illness and training load; change nothing else yet.
- **Retest:** Look at the 7-day mean again in one week.

---
Text CC BY 4.0, code MIT. IRSRI Sports Research Institute.
