Sub topic 6
Measuring completion rate over a window
The current streak and the longest streak both depend on unbroken runs of days. They say nothing about a habit you do five days out of seven. This chapter adds a third metric, the completion rate, which is the share of days in a recent window on which you did the habit. It assumes you have the check-in log from the earlier chapters: a dictionary mapping each habit name to a set of date objects. You should also be comfortable with timedelta arithmetic and generator expressions.
Why a streak is not enough
Consider two people who both log a habit for a month.
- Person A does it every day for 10 days, misses 1 day, then does it 19 more days. Their current streak is 19 and their longest streak is 19.
- Person B does it on 28 of 30 days, missing one day in week two and one day in week four. Their current streak is 6 and their longest streak is 14.
Person B did the habit on more days than Person A did, yet the streak numbers make B look worse. A streak is brittle. One miss resets it to zero, even if you were consistent for months beforehand. The completion rate degrades gradually. One missed day in a 30-day window lowers it by about 3 percentage points, and it recovers as that day leaves the window.
The two kinds of metric answer different questions:
| Metric | Question it answers | Effect of one missed day |
|---|---|---|
| Current streak | How long have I gone without a break? | Drops to zero |
| Longest streak | What is my best unbroken run? | None, unless the miss splits a run |
| Completion rate | How often do I actually do it? | Small, temporary drop |
The definition
The completion rate over a window is:
completion rate = (days logged inside the window) / (days in the window)
A window is a fixed number of consecutive calendar days that ends on a chosen date. A 30-day window ending on 27 November covers 29 October through 27 November. Both ends are included. The window ends on a date you choose, usually today, and it extends backwards from there.
The basic function
Here is the function from the plan, with a small log to run it against.
from datetime import date, timedelta
def completion_rate(days, end, window=30):
start = end - timedelta(days=window - 1)
done = sum(1 for d in days if start <= d <= end)
return done / window
days = {date(2026, 11, d) for d in (1, 2, 3, 5, 6, 10, 11, 12, 13, 14, 20, 21, 25, 26, 27)}
end = date(2026, 11, 27)
print(f"{completion_rate(days, end, 30):.0%}") # 50%
print(f"{completion_rate(days, end, 7):.0%}") # 57%The log has 15 check-ins, all inside the 30-day window, so the rate is 15/30 = 50%. The 7-day window starts on 21 November and contains the 21st, 25th, 26th and 27th, so the rate is 4/7, which prints as 57%.
Why `window - 1`
The window includes the end date itself. A 7-day window ending on the 27th must start on the 21st, which is six days earlier, not seven. Using timedelta(days=window) would give you an 8-day window while still dividing by 7. That produces rates that can exceed 100%. This off-by-one error is the most common mistake in this function.
Why the upper bound matters
The condition is start <= d <= end, not just d >= start. The upper bound lets you ask about the past. If you compute the rate "as of" 15 November, check-ins after that date must not count. Without the upper bound, a historical rate would silently include later days.
It also protects you from a log that contains a future date, for example from a typo or a wrong system clock. The end bound ignores such dates for any end before them.
Why the denominator is the window, not the log
Do not divide by len(days). That gives the number of days you logged divided by itself, which is always 1. The denominator is the number of days you could have done the habit, and that is the window length. Days with no check-in count against you, which is the point of the metric.
Choosing the window length
The window length sets how fast the number reacts. A short window is responsive but noisy. A long window is stable but slow to show change.
| Window | Typical use | Behaviour |
|---|---|---|
| 7 days | Am I on track this week? | One miss changes the rate by 14 points |
| 30 days | Is the habit sticking? | One miss changes it by about 3 points |
| 90 days | Is this a lasting change? | Slow to react, hides recent slumps |
A 7-day window can only take eight values (0/7 to 7/7), so it looks jumpy. A 30-day window gives a smoother signal, so it is a sensible default. Show two windows side by side when you can, such as 7 and 30. If the 7-day rate is well below the 30-day rate, the habit is slipping now, even though the longer history looks fine.
Validating the inputs
The basic function has two silent failure modes. A window of 0 divides by zero. A negative window produces a start date after the end date, so the count is always 0 and the divisor is negative, which gives a rate of 0 or a negative number. Reject both explicitly:
from datetime import date, timedelta
def completion_rate(days, end, window=30):
if window < 1:
raise ValueError("window must be at least 1 day")
start = end - timedelta(days=window - 1)
done = sum(1 for d in days if start <= d <= end)
return done / window
try:
completion_rate({date(2026, 11, 27)}, date(2026, 11, 27), window=0)
except ValueError as error:
print(error) # window must be at least 1 dayRaising an error is better than returning 0.0 here. A rate of 0.0 means "you did nothing", and an invalid argument is a bug in the caller, not a fact about the habit.
A habit that is younger than the window
Suppose you started the habit on 20 November and logged it on the 20th, 21st, 25th, 26th and 27th. A 30-day window ending on the 27th gives 5/30, which is 17%. That figure is technically correct, but it is misleading. For 22 of those 30 days, the habit did not exist yet.
The fix is to let the window start no earlier than the habit's start date. Add an optional since argument and shrink the denominator to match:
from datetime import date, timedelta
def completion_rate(days, end, window=30, since=None):
if window < 1:
raise ValueError("window must be at least 1 day")
start = end - timedelta(days=window - 1)
if since is not None and since > start:
start = since
length = (end - start).days + 1
if length < 1:
return 0.0
done = sum(1 for d in days if start <= d <= end)
return done / length
days = {date(2026, 11, d) for d in (20, 21, 25, 26, 27)}
end = date(2026, 11, 27)
print(f"{completion_rate(days, end, 30):.1%}") # 16.7%
print(f"{completion_rate(days, end, 30, since=date(2026, 11, 20)):.1%}") # 62.5%With since, the window is 20 to 27 November. That is 8 days, with 5 logged, so the rate is 62.5%.
The length is computed as (end - start).days + 1. Subtracting two dates gives a timedelta, and the + 1 makes the count inclusive. The length < 1 check handles a since date later than end. In that case the habit had not started yet, so there are no days to measure.
Where does the start date come from?
You have two options, and each has a cost.
- Use
min(days), the first check-in. This needs no new data. The first day is always counted as done, which pushes the rate up slightly, and it hides any delay between deciding to start and the first check-in. - Store the start date with the habit. This is more accurate. It means changing the data model and the JSON file, which the earlier chapters keep as a plain mapping of names to dates.
For this tracker, min(days) is a reasonable choice. Be aware of the bias it introduces.
Rates over time
A single number tells you where you are now. To see the trend, compute the rate for several consecutive windows that do not overlap. Each window ends where the next one begins, one window length earlier.
from datetime import date, timedelta
def completion_rate(days, end, window=30):
if window < 1:
raise ValueError("window must be at least 1 day")
start = end - timedelta(days=window - 1)
done = sum(1 for d in days if start <= d <= end)
return done / window
def rolling_rates(days, end, window=7, periods=4):
results = []
for i in range(periods):
period_end = end - timedelta(days=i * window)
period_start = period_end - timedelta(days=window - 1)
results.append((period_start, period_end, completion_rate(days, period_end, window)))
return list(reversed(results)) # oldest first
days = {date(2026, 11, d) for d in (1, 2, 3, 5, 6, 10, 11, 12, 13, 14, 20, 21, 25, 26, 27)}
for start, end, rate in rolling_rates(days, date(2026, 11, 27)):
print(f"{start} to {end}: {rate:.0%}")The output is:
2026-10-31 to 2026-11-06: 71%
2026-11-07 to 2026-11-13: 57%
2026-11-14 to 2026-11-20: 29%
2026-11-21 to 2026-11-27: 57%The trend is clear. The habit was strong at the start, dipped in the third week, and recovered. A single 30-day rate of 50% would hide that. The list is reversed at the end so that it reads oldest first, like a timeline.
Edge cases to decide on
Should today count?
If you compute the rate at 9 a.m. and have not checked in yet, today is in the window as a miss. The rate is therefore a little low until you log. There are two reasonable choices:
- Use
end=date.today(). The number is honest about the present, but it dips every morning and recovers when you check in. - Use
end=date.today() - timedelta(days=1). The number only covers finished days, so it does not change during the day.
This is the same question as the "today is not logged yet" case in the streak calculation. The streak function resolves it by counting back from yesterday. For the rate, pick one convention and use it everywhere, so that the numbers on screen agree with each other.
Duplicates
Because check-ins are stored in a set, logging twice on one day still counts once. The rate can never exceed 100% because of repeated check-ins. This is a direct benefit of the data model chosen earlier. If you had used a list of dates, you would need to deduplicate before counting.
Performance
The function scans every logged date once, so it takes time proportional to the number of check-ins. For a habit logged daily over 10 years that is about 3,650 items, which is instant. If you ever needed the opposite, a fast check for a very large log and a small window, you could loop over the window days and test day in days. Set lookup is constant time, so that approach costs time proportional to the window length. At this scale, the simpler scan is the better choice.
Reading the number
A rate is only useful if you act on it, and that is the subject of a later chapter. For now, a few reading rules help:
- Compare the rate with your own goal, not with 100%. A habit you set for five days a week has a ceiling near 71%. Tracking that kind of habit properly is covered in the chapter on non-daily schedules.
- Look at the direction of change more than the level. A rate that moves from 40% to 55% across consecutive windows means more than a steady 60%.
- Treat a rate based on fewer than about 14 days as a rough hint, not a measurement.
Summary
- The completion rate is days logged in the window divided by window length. The window includes its end date, so it starts
window - 1days earlier. - Filter with both bounds,
start <= d <= end, so that historical queries and stray future dates behave correctly. - Divide by the window length, never by the number of check-ins.
- Reject windows shorter than 1 day, and shrink the window for habits younger than the window.
- Consecutive windows give a trend that a single rate hides.
Exercise
A habit's log contains the dates 1 to 10 November 2026 and 20 November 2026. What does completion_rate(days, date(2026, 11, 20), window=14) return? Give the start of the window and the fraction.
Show answer
The window starts on 7 November, because 20 November minus 13 days is 7 November. The logged dates inside the window are 7, 8, 9, 10 and 20 November, which is 5 dates. The result is 5/14, about 0.357, or 36%.
Exercise
A colleague writes start = end - timedelta(days=window) and keeps done / window. What goes wrong, and how would you see it in a test?
Show answer
The window then spans window + 1 days, but the divisor is still window. If every day in that span was logged, the function returns (window + 1) / window, which is above 1. A test that logs every day for 7 days and asks for a 7-day rate would return 8/7 instead of 1.0. The fix is timedelta(days=window - 1).
Exercise
A habit was started 5 days ago and has been done on every one of those 5 days. What do a plain 30-day rate and a rate using since return, and why is the second one more useful?
Show answer
The plain 30-day rate is 5/30, about 17%, even though you have done everything so far. With since set to the start date, the window is 5 days long and the rate is 5/5, or 100%. The second figure describes how well you did on the days the habit existed, so it does not penalize you for days before you started.