NOTE: This applies to JavaScript Stock Chart only. The code provided here can be modified to work on regular charts.
Normally JavaScript Stock Chart does not support automatically-calculated "moving average" graphs or other indicators. However, it's quite easy to add such functionality yourself.
Here's a code for "moving average": (it should be included after amstoock.js)
// MOVING AVERAGE PLUGIN FOR JAVASCRIPT STOCK CHARTS FROM AMCHARTS // AmCharts.averageGraphs = 0; AmCharts.addMovingAverage = function (dataSet, panel, field) { // update dataset var avgField = "avg"+AmCharts.averageGraphs; dataSet.fieldMappings.push({ fromField: avgField, toField: avgField}); // calculate moving average var fc = 0; var sum = 0; for (var i = 0; i < dataSet.dataProvider.length; i++) { var dp = dataSet.dataProvider[i]; if (dp[field] !== undefined) { sum += dp[field]; fc++; dp[avgField] = sum / fc; } } // create a graph var graph = new AmCharts.StockGraph(); graph.valueField = avgField; panel.addStockGraph(graph); // increment average graph count AmCharts.averageGraphs++; // return newly created StockGraph object return graph; }
Now, to add a moving average graph for some value in your data you just need to call AmCharts.addMovingAverage() function. It accepts the following parameters:
- dataSet: a reference to a DataSet object. So it must already be defined in your chart instantiation code.
- panel: a reference to StockPanel you want to add your moving average graph to.
- field: a field in your dataset's data provider that moving average will be calculated based on.
The function returns a StockGraph object. You can set it's title, color, and any other property the way you see fit.
It's best to call the method just before chart.write(). I.e.:
var avgGraph = AmCharts.addMovingAverage(dataSet, stockPanel1, "value"); avgGraph.useDataSetColors = false; avgGraph.color = "#ccffcc"; avgGraph.title = "Moving average";
Here's a working example: http://jsfiddle.net/amcharts/TuLpK/
Comments