Rolling window average on streaming data
Question
Numbers arrive one at a time. Describe how to maintain the average of the most recent values efficiently as each new number arrives.
Short answer
Keep a running sum and a circular buffer of the last values. On each arrival add the new value to the sum, subtract the value it overwrites in the buffer, and divide by (or by the count so far during warm-up). Each update is time with memory, versus per update if you re-sum the window; periodically recompute the sum to limit floating-point drift.
Adapted from Zhou, A Practical Guide to Quantitative Finance Interviews, sec. 7.1 Algorithms, 'Moving average', p.173; question and answer rewritten by SelfMadeQuant.com.
See the hint and the full worked solution in the question bank (free account).
Open the worked solution