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.

Easy Python 3.9+ Aug 9, 2026 Algorithms & data structures 12 views 0 copies

Python code

22 lines
Python 3.9+
from 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

stdout
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

  1. Use a fixed-size list and modulo index for a circular buffer implementation
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.