Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5/JS Chart with Moving Average

Question: How can a moving average line be calculated and plotted on a JS/HTML5 chart?

The closest example I can find is this website. Looking at its JS files, I cannot identify the plotting chart library. Upon closer inspection, it appears that the moving average was not calculated on the serverside but not the clientside.

Any suggestions appreciated!

enter image description here

like image 654
Nyxynyx Avatar asked Nov 14 '13 15:11

Nyxynyx


1 Answers

A more general and simple function would be this one:

function movingAvg(array, countBefore, countAfter) {
  if (countAfter == undefined) countAfter = 0;
  const result = [];
  for (let i = 0; i < array.length; i++) {
    const subArr = array.slice(Math.max(i - countBefore, 0), Math.min(i + countAfter + 1, array.length));
    const avg = subArr.reduce((a, b) => a + (isNaN(b) ? 0 : b), 0) / subArr.length;
    result.push(avg);
  }
  return result;
}

const myArr = [1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9];

//averages of 7 (i.e. 7 day moving average):
const avg7Before = movingAvg(myArr, 6); //6 before and the current
const avg7Middle = movingAvg(myArr, 3, 3); //3 before, 3 after, plus the current
const avg7After = movingAvg(myArr, 0, 6); //6 after plus the current


console.log('original:',...myArr.map(x => x.toFixed(1)));
console.log('7 before:',...avg7Before.map(x => x.toFixed(1)));
console.log('7 middle:',...avg7Middle.map(x => x.toFixed(1)));
console.log('7 after: ',...avg7After.map(x => x.toFixed(1)));
like image 65
Frank Orellana Avatar answered Oct 14 '22 00:10

Frank Orellana