Editor

Compute Moving Averages

Advanced · Write the code · from Time Series: Detect Trends and Anomalies in Business Data

From the lesson: Step 2: Calculate Moving Averages

Raw daily data is noisy. A moving average smooths the data by averaging each point with its neighbors. A 7-day moving average is especially useful for business data because it evens out the weekly cycle, revealing the underlying trend.

Read this part of the lesson

Using the DataFrame from Step 1, add two new columns:

1. ma_7 - 7-day rolling mean of sales.

2. ma_30 - 30-day rolling mean of sales.

Then print: (1) the first row where ma_7 is not NaN (use df.dropna(subset=['ma_7']).head(1)), (2) the last 5 rows showing sales, ma_7, and ma_30, and (3) "7-day MA range: $X.XX to $Y.XX" using min/max of ma_7 (excluding NaN).

import pandas as pd
import numpy as np
np.random.seed(42)
dates = pd.date_range('2024-01-01', periods=90, freq='D')
base = 1000 + np.arange(90) * 5
weekend_boost = np.where(dates.dayofweek >= 5, 200, 0)
noise = np.random.normal(0, 80, 90)
sales = np.maximum(base + weekend_boost + noise, 0)
df = pd.DataFrame({'sales': np.round(sales, 2)}, index=dates)
df.index.name = 'date'
# Add moving averages and print results

More Time Series exercises

All Python exercises · 50 practice problems · Practical Projects quiz