What is the fastest library/algorithm for calculating simple moving average? I wrote my own, but it takes too long on 330 000 items decimal dataset.
You don't need to keep a running queue. Just pick the latest new entry to the window and drop off the older entry. Notice that this only uses one loop and no extra storage other than a sum.
// n is the window for your Simple Moving Average
public List GetMovingAverages(List prices, int n)
{
var movingAverages = new double[prices.Count];
var runningTotal = 0.0d;
for (int i = 0; i < prices.Count; ++i)
{
runningTotal += prices[i].Value;
if( i - n >= 0) {
var lost = prices[i - n].Value;
runningTotal -= lost;
movingAverages[i] = runningTotal / n;
}
}
return movingAverages.ToList();
}