File Name: LinearRegressionCalc.efs
Description:
Example formula for demonstrating the Linear Regression calculations.
Formula Parameters:
nLength: 10
Notes:
The green circles highlight the price series the regression line is based on for visual reference.
Download File:
LinearRegressionCalc.efs
EFS Code:
Description:
Example formula for demonstrating the Linear Regression calculations.
Formula Parameters:
nLength: 10
Notes:
The green circles highlight the price series the regression line is based on for visual reference.
Download File:
LinearRegressionCalc.efs
EFS Code:
PHP Code:
/*********************************
Provided By : eSignal. (c) Copyright 2004
*********************************/
function preMain() {
setPriceStudy(true);
setStudyTitle("Linear Regression ");
setShowCursorLabel(false);
}
var aY = null;
var c = null;
function main(nLength) {
var nState = getBarState();
var nIndex = getCurrentBarIndex();
var i = 0;
if (nLength == null) nLength = 10;
if (aY == null) aY = new Array(nLength);
if (nState == BARSTATE_NEWBAR && c != null) {
aY.pop();
aY.unshift(c);
}
c = close();
aY[0] = c;
if (nState == BARSTATE_NEWBAR) {
if (aY[nLength-1] != null) {
i = 1;
for (i = 1; i < nLength; ++i) {
drawShapeRelative(-i, aY[i], Shape.CIRCLE, null, Color.lime, null, "dot"+i);
}
}
}
if (aY[0] != null) {
drawShapeRelative(0, aY[0], Shape.CIRCLE, null, Color.lime, null, "dot0");
}
// y = Ax + B;
// A = SUM( (x-xAVG)*(y-yAVG) ) / SUM( (x-xAVG)^2 )
// A = slope
// B = yAVG - (A*xAVG);
if (aY[nLength-1] != null) {
var xSum = 0;
var ySum = 0;
i = 0;
for (i = 0; i < nLength; ++i) {
xSum += i;
ySum += aY[i];
}
var xAvg = xSum/nLength;
var yAvg = ySum/nLength;
var aSum1 = 0;
var aSum2 = 0;
i = 0;
for (i = 0; i < nLength; ++i) {
aSum1 += (i-xAvg) * (aY[i]-yAvg);
aSum2 += (i-xAvg)*(i-xAvg);
}
var A = (aSum1 / aSum2);
var B = yAvg - (A*xAvg);
//debugPrintln(nIndex + " Slope: " + -A.toFixed(4) + " Y-intercept: " + B.toFixed(4));
drawLineRelative(0, B, -(nLength-1), (A*(nLength-1)) + B, PS_SOLID, 2, Color.red, "reg");
}
return;
}