A LINQ Style Simple Moving Average Operator

Raw data series with extreme peaks and troughs can be difficult to interpret. One way to remove sudden spikes is by applying a simple moving average calculation. This article describes a simple moving average extension method with a LINQ style.

Implementing a Simple Moving Average

In the remainder of this article we will implement the simple moving average calculation. We'll create an extension method that operates in much the same way as the standard query operators of Language-Integrated Query (LINQ). This means that the method will accept data in any collection that implements IEnumerable<T> and will return data in another IEnumerable<T>. It will validate its arguments immediately but the calculations will be performed using deferred execution.

To begin, create a new console application project. Add a new class named, "SimpleMovingAverageExtensions" to the project. This will hold the extension method so needs to be a static class.

public static class SimpleMovingAverageExtensions
{
}

We can now add the public method that will be our extension method. This simply checks that the source data and the sample size are valid. If they are, the SimpleMovingAverageImpl method is called. This is the iterator that provides the deferred execution.

There are a number of ways that you could write the iterator. In this case we'll aim for readability. You might optimise the method for greater speed, should performance be a problem.

The method holds the sample in a generic Queue object. Initially the queue is empty. Each time a new value is read from the source sequence, it is added to the queue. The average of all of the items in the queue is calculated and returned. Once the queue has reached the desired sample size, an item is removed before a new one is added. This allows the sample to grow over the first few items but remain constant once the correct sample size is available.

Calling the Method

We can now try out the moving average calculation. Let's use the values from the year of sales data for our fictitious company. The code below initialises a sequence with the twelve values before calling the SimpleMovingAverage method. The sample size is five in this case. The results are zipped with the original values before being outputted to the console. You can see the results in the comments below. Note that the averages are formatted with two decimal places to make it easier to read the results.