Chapter 2 · Section 8 practice
Rolling and Cumulative Methods
Work from question 1 to 10. Edit your Python box, click Run Code, review the result, then click Submit attempt. Reference answers unlock after all ten attempts are submitted. This records completion, not correctness. Each box runs independently. Progress is saved in this browser.
1. A moving mean
Warm-up. Print the three-observation rolling means as a list.
Write your answer, then run it.
2. Recent total
Warm-up. Print the final three-observation rolling sum.
Write your answer, then run it.
3. Early windows
Warm-up. Print rolling means with window 3 and min_periods=1.
Write your answer, then run it.
4. Cumulative sales
Build your skills. Print cumulative sales as a list.
Write your answer, then run it.
5. Running record
Build your skills. Print the running maximum of these sales.
Write your answer, then run it.
6. Combined growth
Build your skills. Print the combined return of +10% and −10%, rounded to two decimals.
Write your answer, then run it.
7. Rows or calendar days
Build your skills. For November 5, print the three-row mean and three-day mean.
Write your answer, then run it.
8. Plot a moving average
Challenge. Plot the original sales and their three-observation mean with a legend, title, and both axis labels.
Write your answer, then run it.
9. Growth from complete prices
Challenge. Calculate cumulative return from the first price and print rounded values. Use price / first price − 1.
Write your answer, then run it.
10. Choose the right accumulation
Challenge. Print the final three-observation sum, total since the start, and running minimum.
Write your answer, then run it.
Reference answers are locked until all 10 attempts are submitted.
1. A moving mean
import pandas as pd
sales = pd.Series([100, 200, 300, 400, 500])
print(list(sales.rolling(3).mean()))Expected output
[nan, nan, 200.0, 300.0, 400.0]Two initial windows are incomplete.
2. Recent total
import pandas as pd
sales = pd.Series([100, 200, 300, 400, 500])
print(sales.rolling(3).sum().iloc[-1])Expected output
1200.0The final window includes 300, 400, and 500.
3. Early windows
import pandas as pd
sales = pd.Series([100, 200, 300, 400])
print(list(sales.rolling(3, min_periods=1).mean()))Expected output
[100.0, 150.0, 200.0, 300.0]Early averages use fewer than three observations.
4. Cumulative sales
import pandas as pd
sales = pd.Series([100, 200, 300, 400])
print(list(sales.cumsum()))Expected output
[100, 300, 600, 1000]Each result retains all observations from the start.
5. Running record
import pandas as pd
sales = pd.Series([100, 80, 120, 90])
print(list(sales.cummax()))Expected output
[100, 100, 120, 120]The running record remains 120 when the final observation falls to 90.
6. Combined growth
import pandas as pd
returns = pd.Series([0.10, -0.10])
combined = (1 + returns).cumprod() - 1
print(round(combined.iloc[-1], 2))Expected output
-0.01Compounding gives -1%, not zero.
7. Rows or calendar days
import pandas as pd
sales = pd.Series(
[100.0, 200.0, 300.0, 400.0],
index=pd.to_datetime(["2026-11-01", "2026-11-02", "2026-11-05", "2026-11-06"]),
)
print(sales.rolling(3).mean().loc["2026-11-05"])
print(sales.rolling("3D").mean().loc["2026-11-05"])Expected output
200.0
300.0The default three-day window excludes the observation exactly at its left boundary.
8. Plot a moving average
import pandas as pd
sales = pd.Series([100, 200, 300, 400, 500])
import matplotlib.pyplot as plt
plt.rcParams.update({"font.size": 11})
ax = sales.plot(marker="o", label="Sales", color="#2a3f5c", figsize=(6, 3))
sales.rolling(3).mean().plot(ax=ax, label="Mean3", color="#008080")
ax.set(title="Sales and recent average", xlabel="Observation position", ylabel="Sales (HKD)")
ax.legend()
print("Moving-average chart created.")
plt.tight_layout()
plt.show()Expected output
Moving-average chart created.The moving curve begins only when the full window is available.
9. Growth from complete prices
import pandas as pd
prices = pd.Series([100.0, 110.0, 99.0, 108.9], name="Price")
print(list((prices / prices.iloc[0] - 1).round(3)))Expected output
[0.0, 0.1, -0.01, 0.089]This direct price-ratio calculation checks the compounded path.
10. Choose the right accumulation
import pandas as pd
sales = pd.Series([100, 200, 300, 400, 500])
print(sales.rolling(3).sum().iloc[-1])
print(sales.cumsum().iloc[-1])
print(sales.cummin().iloc[-1])Expected output
1200.0
1500
100Recent total, accumulated total, and historical minimum are different measures.