Moving Average Practice Problem
This data science coding problem helps you practice Array Manipulation, moving average, and implementation skills. Read the problem statement, write your solution, and strengthen your understanding of Array Manipulation.
- Problem ID: 59
- Problem key: 59-moving-average
- URL: https://datacrack.app/solve/59-moving-average
- Difficulty: medium
- Topic: Array Manipulation
- Module: NumPy Foundations
Problem Statement
# 🧩 Moving Average
---
### 🎯 Goal
The **moving average** (rolling mean) smooths time-series data by averaging over a sliding window. It is used in stock price analysis, signal processing, sensor data smoothing, and monitoring ML training loss curves. This problem teaches `np.convolve`, a fast NumPy approach for simple windowed operations like moving averages.
---
### 🔍 The Moving Average
For window size `w`, the moving average at position `i` is:
$$
MA_i = \frac{x_{i-w+1} + x_{i-w+2} + \cdots + x_i}{w}
$$
For `data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]` and `window = 3`:
```
Position 2: (1+2+3)/3 = 2.0
Position 3: (2+3+4)/3 = 3.0
...
```
Output has `len(data) - window + 1` elements.
---
### 💻 Task
Implement `moving_average(data, window)` using `np.convolve`.
---
### 📥 Input
- `data`: list of numbers
- `window`: int — window size (≥ 1, ≤ len(data))
### 📤 Output
- List of moving averages (length = `len(data) - window + 1`)
---
### 🧩 Starter Code
```python
import numpy as np
def moving_average(data, window):
"""
Compute the moving average with the given window size.
Args:
data (list): Time-series data
window (int): Number of points to average over
Returns:
list: Moving averages
"""
arr = np.array(data, dtype=float)
# 🧠 Hint: Create a kernel of ones divided by window:
# kernel = np.ones(window) / window
# 🧠 Then use np.convolve(arr, kernel, mode='valid')
# mode='valid' only returns values where the window fully overlaps
pass
```
---
### 💡 Example
```python
moving_average([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3)
# Expected: [2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]
```
---
### 🔑 Key Concepts
- `np.convolve(arr, kernel, mode='valid')` — slides the kernel over the data
- Kernel for moving average: `np.ones(window) / window`
- `mode='valid'` — output only where the window fits entirely (no edge padding)Starter Code
import numpy as np
def moving_average(data, window):
"""
Compute the moving average with the given window size.
Args:
data (list): Time-series data
window (int): Number of points to average over
Returns:
list: Moving averages
"""
arr = np.array(data, dtype=float)
# 🧠 Hint: Create a kernel of ones divided by window:
# kernel = np.ones(window) / window
# 🧠 Then use np.convolve(arr, kernel, mode='valid')
# mode='valid' only returns values where the window fully overlaps
pass