Exponentially Smoothed Moving Averages in PHP

Wow, I’m a dumbass. While closing out tabs this morning, I found an article on Smoothing Time Series that actually explains this stuff in code terms instead of subscripted letters that made my eyes glaze over.

Looking back at the formula at the bottom of John Walker’s Exponentially smoothed moving averages page, it’s pretty clear how trivially easy the code is:


// Exponentially smoothed moving average function
function esma($in) {
  $out[0] = $in[0];
  for($i=1; $i<sizeof($in); $i++) {
    $out[$i] = $out[$i-1] + 0.1 * ($in[$i] - $out[$i-1]);
  }
  return $out;
}

Here’s an output comparing a 20-day simple moving average, a 20-day exponential moving average, and the exponentially smoothed moving average. You can see the latter two are almost identical. The advantage of the exponential averages are that they track from the first point (instead of the simple moving average’s offset). The exponentially smoothed average uses a smoothing constant, so it doesn’t depend on the a size window):

Also, here’s the source.