Reputation: 129
I want to implement moving average in hightchart. Is there any option in highchart for this.
Like: I have series 10, 20, 30, 40, 50, 60, 70
and here the moving average would be 2
.
Then second series will generate on average values of series 1
like: 15, 35, 105
(taking average of each two datapoints)
And embedding this moving average series of series1
on the same chart.
Upvotes: 9
Views: 6663
Reputation: 412
If you want something more efficient than a for loop:
$('#buttonAddSeries').click(function() {
var series = chart.get('seriesId')
var yData = series.processedYData
var xData = series.processedXData
var data = [];
var period = 3;
/* sumForAverage initialised to sum of yData indexed between 0 and period */
var sumForAverage = yData.slice(0, period).reduce(function(prev, cur) {
return prev + cur;
});
/* Subset yData from period to end. */
yDataWindow = yData.slice(period, yData.length)
/* At each point add the new value and subtract yData[currentIndex]. */
yDataWindow.reduce(function(previousValue, currentValue, currentIndex) {
/* push each iteration to data */
data.push([xData[currentIndex + period], previousValue/period])
return previousValue + currentValue - yData[currentIndex]
/* sumForAverage is passed as starting value */
}, sumForAverage)
chart.addSeries({
name: 'Moving Average',
data: data
});
});
Example: JS Fiddle with data
Upvotes: 0
Reputation: 185
Moving averages are supported using the technical indicators plug-in found here
Here is a link to the JavaScript source that you'll need to include:
It is implemented by adding another series to the chart of type: 'trendline', algorithm: 'SMA' that refers to the relevant data series by id:
series : [
{
name: 'AAPL Stock Price',
type : 'line',
id: 'primary',
data : [100,101,105,107,104,105,106,104,...]
}, {
name: '15-day SMA',
linkedTo: 'primary',
showInLegend: true,
type: 'trendline',
algorithm: 'SMA',
periods: 15
}]
Here is a JSFiddle.
Upvotes: 4
Reputation: 848
These days there is a plugin for Highcharts with which you can add a SMA (Simple Moving Average).
See: http://www.highcharts.com/plugin-registry/single/16/technical-indicators
Upvotes: 4
Reputation: 657
you can calculate the moving average and add it like this:
$('#buttonAddSeries').click(function() {
var series = chart.series[0];
var data = [];
var period = 2;
var sumForAverage = 0;
var i;
for(i=0;i<series.data.length;i++) {
sumForAverage += series.data[i].y;
if(i<period) {
data.push(null);
} else {
sumForAverage -= series.data[i-period].y;
data.push([series.data[i].x, sumForAverage/period]);
}
}
chart.addSeries({
name: 'Moving Average',
data: data
});
});
You can use any number of points as the period, not only 2.
Upvotes: 6
Reputation: 14452
No, currently HighCharts does not do any data analysis like this. You would need to generate your own moving average and create that as its own series or plotLine/plotBand.
Upvotes: 4