JSFiddle - React, Tailwind, and code Playground
by GeekStocks
HTML
<div id='msg'></div>
JavaScript
// quote data example
var qt = [
{d:'2012-01-23',o: 10.01,h: 10.31,l: 10.01,c:10.20},
{d:'2012-01-24',o: 9.95,h: 10.06,l: 9.89,c:10.30},
{d:'2012-01-25',o: 10.01,h: 10.31,l: 10.31,c:10.40},
{d:'2012-01-26',o: 10.01,h: 10.31,l: 10.41,c:10.50},
{d:'2012-01-27',o: 10.01,h: 10.31,l: 10.51,c:10.60},
{d:'2012-01-28',o: 10.01,h: 10.31,l: 10.60,c:10.70},
{d:'2012-01-29',o: 10.01,h: 10.31,l: 10.70,c:10.80},
{d:'2012-01-30',o: 10.01,h: 10.31,l: 10.01,c:10.90},
{d:'2012-01-31',o: 10.01,h: 10.31,l: 10.01,c:11.00}
];
var str = "";
var sma_a = 0; // init the accumulator
var days = 2; // the number of periods in our sma
// compute sma
for(var i = 0; i < qt.length; i++) {
// make sure we start with the proper day
if(i < days) {
qt[i].sma3 = '-1';
sma_a += qt[i].c; // accumulate the close
} else {
sma_a -= qt[i-days].c; // remove the oldest
sma_a += qt[i].c; // add the newest
qt[i].sma3 = Math.round(sma_a / days * 100) / 100
str += qt[i].d + ": " + qt[i].sma3 + "<br>";
}
}
$("#msg").html(str);
// now demo the array idea for use with wma's
var wma = [];
var accum_m = 0, accum_v = 0, multiplier = 0;
// load the array with
for(var i = 0; i < qt.length; i++) {
// make sure we start with the proper day
if(i < days) {
qt[i].wma3 = '-1';
wma.push({d: qt[i].d, c: qt[i].c}); // add the new day to the last element position of the array
} else {
wma.shift(); // remove the oldest
wma.push({d: qt[i].d, c: qt[i].c}); // add the newest
// compute the value by accumulating the product and multipliers used
accum_m = 0; accum_v = 0; multiplier = 0;
for(var d = 0; d < wma.length; d++) {
multiplier = d + 1; // need one based, not zero
accum_m += multiplier;
accum_v += (wma[d].c * multiplier);
console.log(wma[d].c + " x " + multiplier + " = " + wma[d].c *...