How to Implement a Moving Average from a Data Stream in Python
Implement a MovingAverage class using a deque and running sum to compute the average of the last k values from a continuous data stream.
Python code
22 linesfrom collections import deque
class MovingAverage:
def __init__(self, size):
self.size = size
self.queue = deque()
self.window_sum = 0
def next(self, val):
self.queue.append(val)
self.window_sum += val
if len(self.queue) > self.size:
self.window_sum -= self.queue.popleft()
return self.window_sum / len(self.queue)
if __name__ == "__main__":
ma = MovingAverage(3)
for value in [1, 10, 3, 5]:
print(f"next({value}) -> {ma.next(value)}")
Output
next(1) -> 1.0
next(10) -> 5.5
next(3) -> 4.666666666666667
next(5) -> 6.0
How it works
The deque from the collections module maintains the sliding window of the last size elements. A running window_sum tracks the total of the window, so each new value only requires an O(1) add and, when the window is full, an O(1) removal via popleft(). The average is computed by dividing window_sum by the current window length. This approach avoids repeatedly summing the whole window, keeping each next() call constant time regardless of size. The deque replaces the head element automatically once the window exceeds the limit.
Common mistakes
- Using a list with `pop(0)` which is O(n) per removal, making the solution O(n) per call
- Forgetting to handle the window not being full yet, dividing by `size` instead of current length
- Overshooting the window size by not checking `len(queue) > size` before popping
Variations
- Use a fixed-size list and modulo index for a circular buffer implementation
- Use `queue.Queue` for thread-safe streaming, though slower for this simple case
Real-world use cases
- Computing a rolling average of sensor readings in an IoT monitoring service.
- Calculating short-term trends from user click rates or latency metrics.
- Building a simple technical indicator for stock price analysis in a trading bot.
Sponsored
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.