Computing the [[wp:Moving_average#Simple_moving_average|simple moving average]] of a series of numbers.

;Task

Create a [[wp:Stateful|stateful]] function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far.

{{task heading|Description}}

A simple moving average is a method for computing an average of a stream of numbers by only averaging the last &nbsp; P &nbsp; numbers from the stream, &nbsp; where &nbsp; P &nbsp; is known as the period. 

It can be implemented by calling an initialing routine with &nbsp; P &nbsp; as its argument, &nbsp; I(P), &nbsp; which should then return a routine that when called with individual, successive members of a stream of numbers, computes the mean of (up to), the last &nbsp; P &nbsp; of them, lets call this &nbsp; SMA().

The word &nbsp; ''stateful'' &nbsp; in the task description refers to the need for &nbsp; SMA() &nbsp; to remember certain information between calls to it:
* &nbsp; The period, &nbsp; P
* &nbsp; An ordered container of at least the last &nbsp; P &nbsp; numbers from each of its individual calls.

<br>
''Stateful'' &nbsp;  also means that successive calls to &nbsp; I(), &nbsp; the initializer, &nbsp; should return separate routines that do &nbsp; ''not'' &nbsp; share saved state so they could be used on two independent streams of data.

Pseudo-code for an implementation of &nbsp; SMA &nbsp; is:
<pre>
function SMA(number: N):
    stateful integer: P
    stateful list:    stream
    number:           average

    stream.append_last(N)
    if stream.length() > P:
        # Only average the last P elements of the stream
        stream.delete_first()
    if stream.length() == 0:
        average = 0
    else:    
        average = sum( stream.values() ) / stream.length()
    return average
</pre>

{{task heading|See also}}

{{Related tasks/Statistical measures}}

<hr>

