Lesson 7.1Module 7: Smoothing and Granger causality45 minIntermediate
Smoothing: moving averages and loudness envelopes
Trailing, centred and exponential moving averages, and the price each one pays: delay, peeking at the future, or flattened peaks. Then see smoothing as a filter that deletes whole cycles, hear it muffle a sound, and use it to measure a song's loudness the way a meter does.
Every loudness meter, every "7-day average" on a streaming dashboard and every trend line in this course is a moving average of some kind. Smoothing looks harmless: it just removes the jitter. But every smoother makes choices about what counts as jitter, and those choices delay peaks, flatten them, and can delete patterns completely. This lesson compares the main moving averages on real streaming data, then shows that a moving average is a filter, the same thing as the tone control on an amplifier. You'll hear it muffle a sound, and use it to build the loudness envelope of a simulated song.
Set up
You need christmas_pageviews.csv (lesson 2.2).
import wave
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
SR = 22050
rng = np.random.default_rng(7)
def save_wav(name, x, sr=SR):
"""Save a numpy array as a 16-bit mono WAV file you can play (from lesson 1.2)."""
x = x / np.max(np.abs(x))
pcm = (x * 0.8 * 32767).astype(np.int16)
with wave.open(name, "wb") as f:
f.setnchannels(1)
f.setsampwidth(2)
f.setframerate(sr)
f.writeframes(pcm.tobytes())
views = pd.read_csv("christmas_pageviews.csv", index_col="date", parse_dates=True)["views"]
log_views = np.log(views)Three moving averages
A moving average replaces each value with the average of a window of values around it. There are three common designs:
- Trailing: the average of today and the previous 6 days. It uses only the past, so you can compute it in real time. This is the "7-day average" on most dashboards.
- Centred: the average of today, the 3 days before and the 3 days after. Lessons 2.2 and 3.1 used centred averages for the trend. It needs 3 days of the future, so it can't be computed for the most recent days.
- Exponential (EWMA, the exponentially weighted moving average): today's smoothed value is 30% of today's actual value plus 70% of yesterday's smoothed value. Recent days count most, and older days fade away gradually. Robert Brown (1956) and Charles Holt (1957) made it the basis of business forecasting. It needs only one number carried from day to day, which made it ideal for the punch-card computers of the 1950s, and it's still everywhere.
Let's apply all three to the Christmas peak of 2024. We smooth the log views, as usual for a series that spans this range.
smooth = pd.DataFrame({
"actual": log_views,
"trailing 7-day": log_views.rolling(7).mean(),
"centred 7-day": log_views.rolling(7, center=True).mean(),
"exponential (0.3)": log_views.ewm(alpha=0.3).mean(),
})
season = smooth["2024-12-01":"2025-01-10"]
print("Peak date and height, December 2024 season:")
for name in smooth:
print(f" {name:18s} {season[name].idxmax():%d %b} {np.exp(season[name].max()):7,.0f} views")
fig, ax = plt.subplots(figsize=(10, 3.8))
ax.plot(np.exp(season["actual"]), color="grey", linewidth=1, label="actual")
for name, colour in [("trailing 7-day", "C0"), ("centred 7-day", "C1"), ("exponential (0.3)", "C2")]:
ax.plot(np.exp(season[name]), color=colour, linewidth=2, label=name)
ax.axvline(pd.Timestamp("2024-12-25"), color="grey", linestyle=":")
ax.set_title("All I Want for Christmas Is You, December 2024", loc="left")
ax.set_ylabel("Daily views")
ax.legend(loc="upper left")
plt.show()The actual peak was 45,314 views on Christmas Day. Each smoother gets something wrong:
- The trailing average peaks on 26 December, a day late, and stays high for a week after real interest has collapsed, because it's still averaging the busy days before Christmas. On a dashboard, that's a week of looking stronger than you are.
- The centred average peaks on 23 December, two days early. It's on time for the build-up but, because Christmas Day is followed by a sudden drop, the window that centres on Christmas Day already includes the quiet days after it. A centred average puts smooth turning points in the right place; a cliff edge pulls it early.
- Both 7-day averages cut the peak to about 22,000, half its true height. That's the price of averaging: a one-day spike gets shared out over seven days.
- The exponential average peaks on the right day and keeps more of the height (25,887), because today's value carries 30% of the weight. But it never fully forgets: a spike's influence fades by 30% a day but never quite reaches zero.
None of these is "the" smooth version of the data. Each answers a different question, and each moves or shrinks the most interesting day of the year.
Smoothing deletes cycles
Lesson 4.4 found a weekly pattern in these views: weekends are about 3% higher than weekdays. What does smoothing do to it? Let's measure the weekly pattern before and after smoothing. To isolate it, we look at each day's distance from a 28-day centred average, which takes out the slow seasonal movement, and average those distances by weekday.
slow = log_views.rolling(28, center=True).mean()
weekday_names = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
def weekly_pattern(series):
gap = (series - slow).dropna()
return 100 * gap.groupby(gap.index.day_of_week).mean()
patterns = pd.DataFrame({
"unsmoothed": weekly_pattern(log_views),
"5-day average": weekly_pattern(log_views.rolling(5, center=True).mean()),
"7-day average": weekly_pattern(log_views.rolling(7, center=True).mean()),
})
patterns.index = weekday_names
print("Weekly pattern (% above or below the 28-day average):")
print(patterns.round(2).T.to_string())Before smoothing, the weekly pattern runs from 2.3% below average on Wednesdays to 3.4% above on Sundays. The 7-day average wipes it out completely: every weekday is within 0.04% of zero. The 5-day average only shrinks it, to a range of about −1.3% to +0.8%, and shuffles which days look high. A smoother can remove a cycle exactly, or leave a damaged copy of it behind, depending on whether its window matches the cycle.
Here's why. Any moving average can be described by how much of each cycle it lets through, a curve called its frequency response. (This is the spectrum idea from lesson 4.2, applied to a smoother instead of a series.) For an average of N equally weighted values, a cycle that repeats every P days survives with this share of its size:
gain = |sin(πN/P) / (N sin(π/P))|
period = np.linspace(2, 40, 1000) # cycle length, in days
def ma_gain(N, P):
return np.abs(np.sin(np.pi * N / P) / (N * np.sin(np.pi / P)))
fig, axes = plt.subplots(1, 2, figsize=(10, 3.4))
for N in (5, 7):
axes[0].plot(period, ma_gain(N, period), label=f"{N}-day average")
axes[0].axvline(7, color="grey", linestyle=":")
axes[0].set_xlabel("Cycle length (days)")
axes[0].set_ylabel("Share of the cycle kept")
axes[0].set_title("Moving averages on daily data", fontsize=10, loc="left")
axes[0].legend(fontsize=8)
freq = np.linspace(20, 5000, 2000) # pitch, in cycles per second (Hz)
for N in (5, 25):
axes[1].plot(freq, ma_gain(N, SR / freq), label=f"{N}-sample average")
axes[1].set_xlabel("Frequency (Hz)")
axes[1].set_title("The same maths on audio, 22,050 samples a second", fontsize=10, loc="left")
axes[1].legend(fontsize=8)
plt.tight_layout()
plt.show()
print(f"Share of a 7-day cycle kept: 5-day average {ma_gain(5, 7):.2f}, 7-day average {ma_gain(7, 7):.2f}")
print(f"Share of a 30-day cycle kept by the 7-day average: {ma_gain(7, 30):.2f}")The 7-day average keeps 0.00 of a 7-day cycle: every window of seven days contains exactly one of each weekday, so the weekly pattern cancels out perfectly. It also deletes cycles of 3.5 days, 7/3 days and so on, because seven days hold a whole number of those too. The 5-day average keeps 0.36 of the weekly cycle, which is why about a third of the pattern was left behind. Long, slow cycles pass through almost untouched: the 7-day average keeps 0.91 of a 30-day cycle. That's the sense in which a moving average is a low-pass filter: it passes slow (low-frequency) movements and blocks fast (high-frequency) ones.
The right-hand chart is the same formula with cycles measured in Hz instead of days. That's the link to sound: 220 Hz is a cycle every 100 samples, just as a weekly pattern is a cycle every 7 days.
Hearing a moving average
The right-hand chart says that averaging audio samples should cut the high frequencies: the brightness of a sound. Let's hear it. Here's a simulated chord of A minor (A, C and E), each note built from 20 harmonics, so it's bright and buzzy, followed by the same chord smoothed with a 5-sample and a 25-sample moving average:
t = np.arange(2 * SR) / SR
chord = sum(np.sin(2 * np.pi * h * f * t) / h
for f in (220.0, 261.6, 329.6) for h in range(1, 21)) * np.exp(-0.8 * t)
def moving_average(x, N):
return np.convolve(x, np.ones(N) / N, mode="same")
save_wav("chord.wav", chord)
save_wav("chord_avg5.wav", moving_average(chord, 5))
save_wav("chord_avg25.wav", moving_average(chord, 25))
for N in (5, 25):
kept = np.std(moving_average(chord, N)) / np.std(chord)
print(f"{N}-sample average: keeps {ma_gain(N, SR / 220):.2f} of the 220 Hz fundamental, "
f"{ma_gain(N, SR / 2200):.2f} of the 2,200 Hz harmonic; overall size {kept:.2f} of the original")The 5-sample average leaves the 220 Hz fundamental untouched and keeps 65% of the 2,200 Hz harmonic, so you hear only a slight dulling. The 25-sample average still keeps 90% of the fundamental, but only 13% of the 2,200 Hz harmonic, so the buzz goes and the chord sounds muffled. The notes are the same, and only the brightness has gone. Every tone control, every "low-pass" knob on a synthesiser, does this kind of averaging, usually with a better-shaped set of weights than a plain average (the ripples after the first zero in the chart are why engineers prefer other shapes).
The loudness envelope
Now the second half of the title. A sound wave swings above and below zero thousands of times a second, so its average is always about zero. To see how loud it is over time, take the RMS (root mean square): square the samples, take a moving average, and take the square root. Plot it in decibels, a log scale, and you have the sound's loudness envelope, the outline a meter shows.
Here's a simulated 16-second song section, with a kick drum on every beat at 120 BPM and the chord from above held underneath: 4 seconds of quiet intro, a louder verse, a loud chorus, and a 4-second fade-out.
song_len = 16
t = np.arange(song_len * SR) / SR
pad = sum(np.sin(2 * np.pi * h * f * t) / h for f in (220.0, 261.6, 329.6) for h in range(1, 9))
kick_t = np.arange(int(0.2 * SR)) / SR
kick = np.sin(2 * np.pi * (50 + 80 * np.exp(-25 * kick_t)) * kick_t) * np.exp(-15 * kick_t)
drums = np.zeros_like(t)
for beat in np.arange(0, song_len, 0.5):
i = int(beat * SR)
drums[i:i + len(kick)] += kick[:len(drums) - i]
level = np.select([t < 4, t < 8, t < 12], [0.1, 0.35, 1.0], default=1 - (t - 12) / 4) # intro, verse, chorus, fade
song = level * (0.15 * pad + drums)
save_wav("song.wav", song)
def rms_db(x, window_seconds):
N = int(window_seconds * SR)
power = np.convolve(x ** 2, np.ones(N) / N, mode="same")
return 10 * np.log10(power + 1e-10)
envelopes = {"10 ms": rms_db(song, 0.01), "400 ms": rms_db(song, 0.4), "3 s": rms_db(song, 3)}
verse, chorus = slice(5 * SR, 7 * SR), slice(9 * SR, 11 * SR) # the middle 2 seconds of each section
for name, env in envelopes.items():
ripple = np.percentile(env[chorus], 95) - np.percentile(env[chorus], 5)
step_up = np.median(env[chorus]) - np.median(env[verse])
print(f"{name:>6} window: ripple within the chorus {ripple:4.1f} dB, chorus louder than verse by {step_up:4.1f} dB")
print(f"The true step: the chorus is {1 / 0.35:.2f} times the verse's size, {20 * np.log10(1 / 0.35):.1f} dB")
fig, ax = plt.subplots(figsize=(10, 3.8))
step = 50 # plot every 50th sample, plenty for a chart
for (name, env), colour, width in zip(envelopes.items(), ["grey", "C0", "C1"], [0.6, 1.8, 2.4]):
ax.plot(t[::step], env[::step], color=colour, linewidth=width, label=f"{name} window")
for edge, label in [(0, "intro"), (4, "verse"), (8, "chorus"), (12, "fade")]:
ax.text(edge + 0.1, 1.02, label, transform=ax.get_xaxis_transform(), fontsize=9)
ax.axvline(edge, color="grey", linestyle=":", linewidth=0.8)
ax.set_ylim(-60, 5)
ax.set_xlabel("Time (seconds)")
ax.set_ylabel("Level (dB)")
ax.legend(loc="lower right")
plt.show()The chorus is 2.86 times the verse's size, which is 9.1 dB, and all three envelopes measure that step correctly: smoothing doesn't bias the level of a steady section. What changes is the detail:
- The 10 ms window is short enough to follow every kick drum: within the chorus, it ripples by 9.8 dB. That's the right scale for finding beats (lesson 6.1's onset envelope used 20 ms frames for the same reason).
- The 400 ms window ripples by only 2.4 dB, but still steps up sharply between sections. 400 ms is the "momentary loudness" window of the broadcast loudness standard (ITU-R BS.1770, used in Europe as EBU R 128), the meter engineers watch while mixing.
- The 3 s window ripples by just 0.4 dB, and its steps are rounded off: it starts climbing towards the verse about 1.5 seconds before the verse begins, because it's a centred average looking ahead, the same early turn we saw at Christmas. Three seconds is the standard's "short-term loudness". Streaming services go one step further and average over the whole track ("integrated loudness") to set their playback volume, which is why lesson 2.1's loudness war matters less on Spotify than it did on the radio.
The real standard also weights frequencies the way the ear hears them before averaging, which our simple RMS doesn't. But the core is the same: square, take a moving average, then convert to decibels.
Choosing a smoother
- Real time or after the event? If you need today's value today (a dashboard, a meter, a live forecast), use a trailing or exponential average, and accept the delay. For analysing the past, a centred average puts features in the right place.
- What do you want to delete? Match the window to the cycle: a 7-day window removes a weekly pattern exactly, a 12-month window a yearly one (that's why lesson 3.1's trend used 12 months).
- What do you want to keep? Every smoother flattens peaks. If the peak's height or timing is the question, smooth less, or not at all.
Key ideas
- Trailing averages use only the past but run late. Centred averages are on time but need the future. Exponential averages put the Christmas peak on the right day here, but never fully forget a spike.
- Every moving average flattens peaks: the 7-day averages cut the December 2024 peak to half its height.
- A moving average is a filter. An N-point average deletes cycles of length N, N/2, N/3 and so on, exactly. A 7-day average removes the weekday pattern; a 5-day average doesn't.
- On audio, a moving average is a low-pass filter: it removes high frequencies and muffles the sound.
- A loudness envelope is the RMS (the square root of a moving average of squared samples) in decibels. Its window decides what it shows: beats (10 ms), phrases (400 ms) or sections (3 s).
Try it yourself
- Change the exponential average's
alphafrom 0.3 to 0.1. What happens to its peak date and height? - Compute a 12-day trailing average of the Christmas views and find where it peaks in December 2024. How late is it?
- Use
ma_gainto find which cycles a 12-month moving average deletes on monthly data. Why is that useful for lesson 3.1's trend? - In the song, add a snare drum on beats 2 and 4. Which envelope window shows the change, and which doesn't?
Next lesson: Granger causality: does social-media buzz predict streams?
The course
Music as Data: Time Series with Python
1Music as a time series
2Seeing patterns
3Decomposition and stationarity
4Testing a time series
5Missing values
6Autocorrelation and forecasting
7Smoothing and Granger causality
8From time series to AI music