# CS-16: Forecast next week, and beat "same as last week"

Data-Driven Athletics tutorial · Week 11 · Chapter 11 · about 60 min · workflow steps: Gather, Statistics, Visualize, Cleanse, Features, Split

Web page: https://apopt.com/course/tutorials/cs16-forecast-load/ · Data: https://apopt.com/data/tutorials/cs16-forecast-load/

## The decision

A coach plans next week's training and wants to know how much training load this athlete is
likely to carry, with a range, before deciding whether to add or remove a session. A forecast is
only worth using if it beats "same as last week". This is training information, not medical
advice.

## Predict first

A regression on last week's load, the week before, and the mean of the last four weeks is tested on the final 52 weeks against "same as last week". Which wins, and by how much?

## The raw data

- `raw/sessions_fit.csv`: 693 activity summaries (running, elliptical, swimming, cycling, hiking and others), June 2024 to November 2026, as FIT session fields in the watch's own names and units (seconds, meters, UTC start plus an offset) Activity summaries from a COROS Training Hub archive of an adult male athlete in his mid-40s, published in the course case file (`athletes/jh/coros-history/`). GPS positions, per-second records and identifiers were removed before publication.

| Field | Meaning | Unit | Range | Missing |
|---|---|---|---|---|
| start_time | start of the activity | ISO 8601 UTC (ends in Z) | 2024-06-28 to 2026-11-28 | none |
| utc_offset_h | local clock minus UTC at the start | h | −7 to +3 (mostly −6 and −7) | none |
| sport | sport as the watch labels it | text | running, fitness_equipment, swimming, cycling, hiking, generic, walking, training | none |
| total_timer_time | timer time with pauses excluded (the moving time) | s | 1.83 to 28 676 | none |
| total_distance | distance | m | 0 to 21 859 | blank or 0 on 91 rows, mostly elliptical and indoor bike |
| avg_heart_rate | average heart rate (wrist) | beats/min | 67 to 188 | blank on 6 activities |
| max_heart_rate | highest heart rate in the activity | beats/min | 81 to 209 | blank on 5 activities |

What is wrong with it: times are in seconds and distances in meters, and the start is in UTC
with the local offset in a separate column (travel moves it from −7 to +3 hours). Four
activities last under a minute (aborted starts, one a 0.2-minute "run" with no distance). Six
have no average heart rate, so their load cannot be computed as recorded; three of them are
real sessions, including a 37-minute run. The highest wrist reading on a run, 209 bpm, is
probably the sensor locking onto cadence, so HRmax is taken as the 99th percentile, 202 bpm.
The export starts on a Friday, so the first week is partial. Five weeks, all over the December
holidays, have nothing recorded; they are kept as zero, which assumes the watch was not simply
left at home.

A coach planning next week's training wants a number for the load the athlete is likely to
carry, with a range. Any forecast has to beat the simplest one there is: **same as last week**,
the **persistence baseline** (Section 11.8.1). If it cannot, use persistence and say so.

The data are two and a half years of activity summaries from one GPS watch with a wrist heart
sensor, worn by an adult male athlete in his mid-40s who mostly runs, and also swims, uses an
elliptical, rides and hikes. Load here is the case file's **training load**: moving minutes
times (average heart rate / HRmax) squared, summed over every activity in a week, in arbitrary
units (AU). A 50-minute run at 80% of HRmax adds 50 × 0.8² = 32 AU. This is training
information, not medical advice.

### Step 1 · Gather

The file is the watch's own FIT session summary, one row per activity, in the watch's units:
times in seconds, distances in meters, and the start time in UTC with a separate offset to the
local clock.

*Predict first:* The export spans about two and a half years. How many weeks is that?

```python
import numpy as np
import pandas as pd

raw = pd.read_csv("raw/sessions_fit.csv")
utc = pd.to_datetime(raw["start_time"]).dt.tz_localize(None)
act = pd.DataFrame({
    "start": utc + pd.to_timedelta(raw["utc_offset_h"], unit="h"),   # local clock
    "sport": raw["sport"],
    "minutes": raw["total_timer_time"] / 60,                         # s -> min, pauses excluded
    "km": raw["total_distance"] / 1000,                              # m -> km
    "avg_hr": raw["avg_heart_rate"], "max_hr": raw["max_heart_rate"]})
print(act["sport"].value_counts().to_string())
span = act["start"].max() - act["start"].min()
print("from", act["start"].min().date(), "to", act["start"].max().date(), f"({span.days / 7:.0f} weeks)")
print("hours from UTC:", raw["utc_offset_h"].value_counts().to_dict())
```

Output:

```
sport
running              497
fitness_equipment     73
swimming              67
cycling               19
hiking                13
generic               13
walking               10
training               1
from 2024-06-28 to 2026-11-28 (126 weeks)
hours from UTC: {-6.0: 465, -7.0: 191, 3.0: 16, -4.0: 14, -5.0: 7}
```

Most activities are on a clock six or seven hours behind UTC (summer and winter time); the
others are travel. Using the offset the watch stored keeps a 6 a.m. run in the right day.

### Step 2 · Statistics

Profile the activities before summing anything. Look at the shortest ones, the heart rates the
load depends on, and the day of the week.

*Predict first:* What is the highest heart rate you expect the watch to report on a run?

```python
print(act.groupby("sport")[["minutes", "avg_hr"]].median().round(0).to_string())
print("activities without average heart rate:", act["avg_hr"].isna().sum())
print(act.nsmallest(5, "minutes")[["start", "sport", "minutes", "km"]].round(2).to_string(index=False))
runs = act[act["sport"] == "running"]
HRMAX = float(np.percentile(runs["max_hr"].dropna(), 99, method="lower"))
print(f"run max HR: highest {runs['max_hr'].max():.0f}, 99th percentile {HRMAX:.0f} bpm")
print("runs by weekday:", runs["start"].dt.day_name().str[:3].value_counts().to_dict())
```

Output:

```
                   minutes  avg_hr
sport                             
cycling               53.0   129.0
fitness_equipment     50.0   129.0
generic               45.0   140.0
hiking                55.0   110.0
running               48.0   157.0
swimming              55.0   123.0
training              24.0   120.0
walking               26.0   101.0
activities without average heart rate: 6
              start             sport  minutes   km
2026-07-24 18:02:17          swimming     0.03  NaN
2025-09-27 19:43:38           running     0.04  NaN
2024-07-12 18:25:34           running     0.21 0.00
2026-07-02 20:33:24 fitness_equipment     0.96  NaN
2025-07-24 07:53:12           running     1.67 0.24
run max HR: highest 209, 99th percentile 202 bpm
runs by weekday: {'Fri': 108, 'Sat': 107, 'Mon': 103, 'Wed': 100, 'Tue': 41, 'Thu': 37, 'Sun': 1}
```

Four activities last under a minute: aborted starts, one of them a 0.2-minute run with no
distance. Six have no average heart rate, so their load cannot be computed as recorded. The
highest wrist reading on a run, 209 bpm, is probably the sensor locking onto cadence; the case
file uses the 99th percentile, 202 bpm, as a stand-in for HRmax (not a tested maximum). The
athlete ran on a Sunday once in two and a half years, so a Monday-to-Sunday week is a natural
unit, and the last week of the export, which ends on a Saturday, is complete.

### Step 3 · Visualize

Compute each activity's load, sum it by week starting on Monday, and keep every week between
the first and the last, including weeks with nothing recorded.

```python
import matplotlib.dates
import matplotlib.pyplot as plt

act["load"] = act["minutes"] * (act["avg_hr"] / HRMAX) ** 2
monday = act["start"].dt.normalize() - pd.to_timedelta(act["start"].dt.day_of_week, unit="D")
raw_week = act.groupby(monday)["load"].sum()                      # missing HR counts as 0 here
weeks = pd.date_range(raw_week.index.min(), raw_week.index.max(), freq="7D")
raw_week = raw_week.reindex(weeks, fill_value=0)                  # empty weeks stay in, as 0
fig, ax = plt.subplots(figsize=(6.6, 3.0))
ax.plot(raw_week.index, raw_week, "o-", ms=2.5, color="black", lw=0.8)
ax.set(xlabel="week (starting Monday)", ylabel="training load per week (AU)",
       title="Raw weekly load: breaks each December and a few big weeks")
ax.xaxis.set_major_locator(matplotlib.dates.YearLocator())
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%Y"))
plt.tight_layout()
print(f"{len(raw_week)} weeks, {(raw_week == 0).sum()} with nothing recorded; "
      f"median {raw_week.median():.0f} AU, largest {raw_week.max():.0f} AU")
```

Output:

```
127 weeks, 5 with nothing recorded; median 149 AU, largest 248 AU
```

![Weekly training load from mid-2024 to late 2026. Most weeks lie between 100 and 200 AU; it drops to zero for two or three weeks in each December, with shorter dips at other times; the largest week, in July 2024, is near 250.](https://apopt.com/course/tutorials/cs16-forecast-load/c05-1.png)

All five empty weeks fall over the December holidays; shorter dips come at other times. The
watch recorded everything the athlete did, swims and hikes included, for two and a half years,
so a week with nothing on it is most likely a week without training, and it stays in the series
as **zero**. That is an assumption, and you should name it: if the watch had been left at home,
those zeros would teach the model a rest that never happened. The largest week, in July 2024,
holds an eight-hour hike. It is real load and stays.

### Step 4 · Cleanse

Rules, written before the forecast is fitted, with a change log:

1. Drop activities shorter than one minute (aborted starts).
2. Fill a missing average heart rate with the median of the same sport, so a 37-minute run
   does not count as zero load.
3. Drop the first week: the export starts on a Friday, so that week is partial.

```python
import os

log = []
short = act["minutes"] < 1
log.append({"rule": "shorter than 1 min", "changed": int(short.sum()), "left": int((~short).sum())})
keep = act[~short].copy()
gap = keep["avg_hr"].isna()
keep["avg_hr"] = keep["avg_hr"].fillna(keep.groupby("sport")["avg_hr"].transform("median"))
log.append({"rule": "average HR filled by sport", "changed": int(gap.sum()), "left": len(keep)})
keep["load"] = keep["minutes"] * (keep["avg_hr"] / HRMAX) ** 2
week = keep.groupby(monday[keep.index])["load"].sum().reindex(weeks, fill_value=0)
week = week.iloc[1:]                                              # first week is partial
log.append({"rule": "partial first week dropped", "changed": 1, "left": len(week)})
os.makedirs("clean", exist_ok=True)
pd.DataFrame(log).to_csv("clean/change_log.csv", index=False)
week.round(1).rename("load_au").to_csv("clean/weekly_load.csv", index_label="week_start")
print(pd.DataFrame(log).to_string(index=False))
print(f"{len(week)} weeks, {(week == 0).sum()} at zero; median {week.median():.0f} AU, largest {week.max():.0f} AU")
```

Output:

```
                      rule  changed  left
        shorter than 1 min        4   689
average HR filled by sport        3   689
partial first week dropped        1   126
126 weeks, 5 at zero; median 149 AU, largest 248 AU
```

### Step 5 · Features from the past only

Three features, each built only from weeks before the one being forecast:

* `lag1`, last week's load, and `lag2`, the week before;
* `mean4`, the mean of the four weeks before, **shifted by one week before averaging**, so the
  week being forecast is never inside its own feature.

The first four weeks lack a full history and cannot be used.

*Predict first:* How strongly does last week's load go with this week's, as a correlation from 0 to 1?

```python
f = pd.DataFrame({"y": week, "lag1": week.shift(1), "lag2": week.shift(2),
                  "mean4": week.shift(1).rolling(4).mean()})
usable = f.dropna()
print(f"{len(week)} weeks; {len(usable)} have all three features")
print(usable.head(3).round(0).to_string())
print("correlation of each feature with the week's load:",
      usable.corr()["y"].drop("y").round(2).to_dict())
```

Output:

```
126 weeks; 122 have all three features
                y   lag1   lag2  mean4
2024-07-29  133.0   68.0  248.0  130.0
2024-08-05  142.0  133.0   68.0  146.0
2024-08-12   55.0  142.0  133.0  148.0
correlation of each feature with the week's load: {'lag1': 0.64, 'lag2': 0.36, 'mean4': 0.46}
```

Last week goes with this week (correlation 0.64): this athlete's training comes in blocks, so a
big week tends to follow a big week. That is exactly the pattern persistence uses, which makes
it a hard baseline to beat.

### Step 8 · Split by time and compare with persistence

The test set is the last 52 usable weeks, one full year from December 2025; the model learns
only from the 70 weeks before them. A random split would let it learn from weeks after the one
it predicts. Every method is scored by its mean absolute error (MAE) on the same test weeks.

A small gain in MAE can be luck. To check, take the gain week by week (persistence's miss minus
the model's), then **bootstrap** it: draw 52 test weeks at random with replacement, average,
and repeat 2000 times. If the middle 90% of those averages includes zero, the test year cannot
tell the two methods apart.

*Predict first:* Will the regression on lags beat "same as last week"?

```python
from sklearn.linear_model import LinearRegression

X = ["lag1", "lag2", "mean4"]
train, test = usable.iloc[:-52], usable.iloc[-52:]          # chronological split
lin = LinearRegression().fit(train[X], train["y"])
pred = {"persistence (last week)": test["lag1"], "mean of last 4 weeks": test["mean4"],
        "training-weeks mean": pd.Series(train["y"].mean(), index=test.index),
        "linear on lags": pd.Series(lin.predict(test[X]), index=test.index)}
centered = week.rolling(5, center=True, min_periods=3).mean()           # uses the future!
pred["centered 5-week mean (leaks)"] = centered.loc[test.index]
print(f"train {len(train)} weeks ({train.index[0].date()} to {train.index[-1].date()}), test {len(test)}")
for name, p in pred.items():
    print(f"{name:30s} MAE {(test['y'] - p).abs().mean():5.1f} AU")
gain = (test["y"] - test["lag1"]).abs() - (test["y"] - pred["linear on lags"]).abs()
rng = np.random.default_rng(0)                              # resample test weeks: is the gain real?
boot = [rng.choice(gain, len(gain)).mean() for _ in range(2000)]
print(f"linear closer than persistence in {(gain > 0).sum()} of {len(test)} test weeks; mean gain "
      f"{gain.mean():.1f} AU, 90% bootstrap interval {np.percentile(boot, 5):.1f} to {np.percentile(boot, 95):.1f}")
print("coefficients:", {k: round(float(v), 2) for k, v in zip(X, lin.coef_)}, "intercept", round(float(lin.intercept_), 1))
```

Output:

```
train 70 weeks (2024-07-29 to 2025-11-24), test 52
persistence (last week)        MAE  38.4 AU
mean of last 4 weeks           MAE  45.0 AU
training-weeks mean            MAE  46.7 AU
linear on lags                 MAE  36.4 AU
centered 5-week mean (leaks)   MAE  28.0 AU
linear closer than persistence in 28 of 52 test weeks; mean gain 2.0 AU, 90% bootstrap interval -2.3 to 6.0
coefficients: {'lag1': 0.62, 'lag2': 0.09, 'mean4': -0.0} intercept 39.1
```

The regression beats persistence by 2.0 AU a week (36.4 against 38.4), and it was closer in 28
of the 52 weeks. That is not much. The bootstrap interval for the gain runs from -2.3 to +6.0 AU
and includes zero, so the test year cannot tell the regression from "same as last week". Look
at what it learned: most of its weight is on last week (0.62) plus a constant, so it is
persistence pulled part of the way toward the usual week. The training mean and the 4-week
mean, which ignore last week or dilute it, do clearly worse. The centered mean scores best of
all and is useless: it uses the two weeks *after* the week it "predicts".

### Step 3 again · The forecast against the weeks it predicted

```python
fig, ax = plt.subplots(figsize=(6.6, 3.2))
ax.plot(test.index, test["y"], "o", color="black", ms=4, label="recorded")
ax.plot(test.index, pred["persistence (last week)"], "--", color="0.35", drawstyle="steps-mid", label="same as last week")
ax.plot(test.index, pred["linear on lags"], "-", color="0.55", lw=2, label="linear on lags")
ax.set(xlabel="week (starting Monday)", ylabel="training load per week (AU)",
       title="The regression is persistence, pulled toward the middle", ylim=(0, 300))
ax.legend(fontsize=8, loc="upper center", ncol=3)
fig.autofmt_xdate()
plt.tight_layout()
```

![The 52 test weeks of training load as black dots, the persistence forecast as a dashed step line one week behind, and the regression forecast as a solid gray line that follows persistence but stays closer to the middle. Both miss most at the December break and the dips in May and September.](https://apopt.com/course/tutorials/cs16-forecast-load/c13-1.png)

Both forecasts are one week late at every turn: neither sees the December break or the dips in
May and September coming, and both forecast a low week right after each one ends. In between,
the regression follows persistence but sags below it in the big weeks of late 2026, because it
pulls toward the usual week of the training period, which was lighter. A model that only knows
past totals cannot know about a holiday or a planned taper; the coach can, and should overrule
the number in those weeks.

### Step 8 again · Next week, with a range

Persistence was not clearly beaten, so use it, and say so: it is simpler, and anyone can check
it. The range comes from persistence's own test-week errors: the middle 80% of them, added to
the forecast.

*Predict first:* Your forecast for next week's load, in AU, before you run this?

```python
err = test["y"] - test["lag1"]
lo, hi = np.percentile(err, [10, 90])
fc = week.iloc[-1]                                          # persistence: same as last week
final = LinearRegression().fit(usable[X], usable["y"])
nxt = pd.DataFrame({"lag1": [week.iloc[-1]], "lag2": [week.iloc[-2]], "mean4": [week.iloc[-4:].mean()]})
print(f"last four weeks: {week.iloc[-4:].round(0).tolist()} AU")
print(f"week starting {(week.index[-1] + pd.Timedelta(days=7)).date()}: forecast {fc:.0f} AU, "
      f"80% range {fc + lo:.0f} to {fc + hi:.0f} AU")
print(f"the regression would say {final.predict(nxt)[0]:.0f} AU")
```

Output:

```
last four weeks: [217.0, 220.0, 173.0, 217.0] AU
week starting 2026-11-30: forecast 217 AU, 80% range 159 to 276 AU
the regression would say 191 AU
```

The range is wide, about 60 AU on each side, because one athlete's weeks are variable and 52
test weeks are a short history of errors. The regression gives a lower number, 191 AU, because
it pulls a big week back toward the usual week; on the test year that habit was worth too
little to trust. The number is a planning guide for the coach, not a target: it says what this
athlete is likely to do next, not what he should do.

## How good is the number?

The test set is a full year, 52 weeks. The regression's MAE (36.4 AU) is 2.0 AU better than
persistence (38.4 AU), it was closer in 28 of 52 weeks, and a bootstrap of the week-by-week gain
gives a 90% interval of −2.3 to +6.0 AU: no clear win. Both methods are one week late at every
break and dip, which is where most of their error is. The training mean (46.7 AU) and the
4-week mean (45.0 AU) are clearly worse, because last week matters (correlation 0.64). The leak
check is the centered 5-week mean: it "scores" 28.0 AU because it uses the weeks after the one
it forecasts. The 80% range comes from 52 persistence errors and is itself rough.

## Track it

The record gets a weekly row when you track load: `date` (the Monday that starts the week),
`test=watch-week`, `metric=training_load_au`, `value`, `unit=AU`, `device` (the watch),
`protocol_version` (the HRmax used, here 202 bpm), `note` (a week with nothing recorded is added
as zero only if you know it was a week without training; note why).

## With your own data

Export your own activity summaries from your watch's account (most makers offer a download of
all activities, often as FIT files). Put each start on your local clock, compute moving minutes
times (average heart rate / your HRmax) squared for each activity, and run this notebook from
Step 3 on your weekly sums. Decide, and write down, whether an empty week was rest or a watch
left at home.

## The same method in another field

Forecasting demand for a plant or a power grid starts the same way: the naive "same as last
period" forecast is the benchmark every model must beat on a chronological split, and inputs
must come from the past only. The Machine Learning for Engineers page on
[ARX time-series models](https://apmonitor.com/pds/index.php/Main/ARXTimeSeries) builds the
same kind of model from past outputs and inputs.

## Acknowledgements

The activity summaries come from a COROS Training Hub archive, published in the course case file (`athletes/jh/coros-history/`).

## Action card

- **Finding:** Next week's load is best forecast as last week's; a regression on recent weeks did not do clearly better.
- **Evidence:** On 52 test weeks, persistence missed by 38.4 AU on average and the regression by 36.4 AU; the gain's 90% bootstrap interval, −2.3 to +6.0 AU, includes zero.
- **Sure:** Moderate: one athlete, one test year, and an 80% range of 159 to 276 AU around the forecast.
- **Action:** Plan the week starting 30 November 2026 around 217 AU, about last week, expect anything from 159 to 276, and overrule the number yourself for holidays or a planned easy week.
- **Retest:** Score persistence and the regression again after 13 more weeks, with the same bootstrap check.

## Challenge: A second load series

Repeat the forecast with a different weekly series: running kilometers per week from the same
export, or your own watch export if you have a year or more.

1. Write the cleaning rules (what is not a run, how a week is defined, what an empty week means) before you fit anything.
2. Build `lag1`, `lag2` and a trailing `mean4` from the past only, and count the weeks lost at the start.
3. Split by time with the last 52 usable weeks as the test set, and compare persistence, the training mean, the 4-week mean and a regression on lags.
4. Count the test weeks in which your best method beats persistence, and bootstrap the gain.
5. Give next week's forecast with an 80% range from the test errors, in one sentence for a coach.

Deliverables:

- a notebook that runs top to bottom
- a table of MAE by method on the same test weeks
- one sentence for the coach with the forecast and its range

## References

- Hyndman, R. J., and Athanasopoulos, G. *Forecasting: Principles and Practice*, 3rd ed. OTexts. [Some simple forecasting methods](https://otexts.com/fpp3/simple-methods.html) (the naïve method as a benchmark).
- Chapter 11 of *Data-Driven Athletics*: Splitting by athlete and by day; Time Series; A forecast has to beat "same as last week".

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