EMA CrossOver Trading Strategy
var simpleMovingAVG = function(dataObjArray, timePeriods){
var sum = 0;
var result = false;
try{
for(var i=timePeriods-1;i>-1;i--){
sum += dataObjArray[i].data;
}
result = (parseFloat(sum) / parseFloat(timePeriods));
//console.log('SMA Result : ' + result);
} catch(err) {
result = false;
console.log("SMA Error : " + err);
}
return result;
};
var exponentialMovingAVG= function(dataObjArray, focusPriceIndex, timePeriods){
var result = false;
try {
// Smoothing factor
var alpha = parseFloat(2.0 / (1 + timePeriods));
if(focusPriceIndex < dataObjArray.length){
if(focusPriceIndex > timePeriods-1){
if(focusPriceIndex-1 > -1){
exponentialMovingAVG(dataObjArray, (focusPriceIndex-1), timePeriods);
//console.log('prevEMA#' + (focusPriceIndex-1) + ' : ' + dataObjArray[focusPriceIndex-1].ema);
dataObjArray[focusPriceIndex].ema = (dataObjArray[focusPriceIndex].data * alpha) + (dataObjArray[focusPriceIndex-1].ema * (1 - alpha));
//console.log('EMA ' + dataObjArray[focusPriceIndex].date + ' : ' + dataObjArray[focusPriceIndex].ema);
focusPriceIndex -= 1;
}
} else if(focusPriceIndex == timePeriods - 1){
var sma = simpleMovingAVG(dataObjArray, timePeriods);
if(sma!=false) {
dataObjArray[focusPriceIndex].ema = sma;
result = sma;
} else {
dataObjArray[focusPriceIndex].ema = 0;
}
}
}
} catch(err) {
result = false;
console.log("EMA Error : " + err);
}
return result;
};
var prices = [
{date:'2010-03-24', data:22.27, ema:null},
{date:'2010-03-25', data:22.19, ema:null},
{date:'2010-03-26', data:22.08, ema:null},
{date:'2010-03-29', data:22.17, ema:null},
{date:'2010-03-30', data:22.18, ema:null},
{date:'2010-03-31', data:22.13, ema:null},
{date:'2010-04-01', data:22.23, ema:null},
{date:'2010-04-05', data:22.43, ema:null},
{date:'2010-04-06', data:22.24, ema:null},
{date:'2010-04-07', data:22.29, ema:null},
{date:'2010-04-08', data:22.15, ema:null},
{date:'2010-04-09', data:22.39, ema:null},
{date:'2010-04-12', data:22.38, ema:null},
{date:'2010-04-13', data:22.61, ema:null},
{date:'2010-04-14', data:23.36, ema:null},
{date:'2010-04-15', data:24.05, ema:null},
{date:'2010-04-16', data:23.75, ema:null},
{date:'2010-04-19', data:23.83, ema:null},
{date:'2010-04-20', data:23.95, ema:null},
{date:'2010-04-21', data:23.63, ema:null},
{date:'2010-04-22', data:23.82, ema:null},
{date:'2010-04-23', data:23.87, ema:null},
{date:'2010-04-26', data:23.65, ema:null},
{date:'2010-04-27', data:23.19, ema:null},
{date:'2010-04-28', data:23.10, ema:null},
{date:'2010-04-29', data:23.33, ema:null},
{date:'2010-04-30', data:22.68, ema:null},
{date:'2010-05-03', data:23.10, ema:null},
{date:'2010-05-04', data:22.40, ema:null},
{date:'2010-05-05', data:22.17, ema:null}
];
exponentialMovingAVG(prices, 29, 10);
console.log(prices);
Sources:
github.com/patharanordev/ema
www.investopedia.com/terms/e/ema.asp