{_xLinRegSlope - exponential linear regression slope by Alex Matulich 4/24/2004 Copyright (c) 2004 by Unicorn Research Corporation. All rights reserved. This function calculates a linear regression slope using exponential moving averages as the summation terms in the slope formula. A simple average multiplied by the number of elements equals the sum, so we can calcuate the regression slope using simple averages. However, if we replace the simple averages in the computation by exponential averages, the resulting slope magnitude turns out larger by a factor of 3N/(N+1), where N is the number of elements, therefore we must divide the result by this correction factor (this simple correction was actually a lot of work to figure out). The correction factor will give perfect results for regions of perfectly constant slopes, but for noisy data like markets, the response time of the exponential average will make the SWINGS in slope magnitude appear smaller than the actual regression slope, but the slope will be smoother in areas of fairly constant slope.} Inputs: yvalue(NumericRef), {value of regression line to return} Price(NumericSeries), {Y values to fit a regression line} Len(NumericSimple); {Len need NOT be an integer} Variables: nn(0), n(0), sumX(0), sumY(0), sumXY(0), sumX2(0), w(0), denom(0), correction(0), xslope(0); if Len <> nn or CurrentBar = 1 then begin {initializations} nn = Len; {keep track of when Len changes} n = (nn-1)*0.75 + 1; {lag correction} sumX = 0.5 * n * (n-1); {sum of x values from 0 to n-1} sumX2 = (n-1)*n*(2*n-1)/6; {sum of x^2 from 0 to n-1} sumY = Price * n; {initialize sum of Y values} sumXY = sumX*Price; {initialize sum of X*Y values} w = 2 / (n + 1); {exponential weighting factor} correction = (n+1) / (3*n); {amplitude correction factor} end else begin {calculate sum of Y values and sum of X*Y values} sumY = w*Price*n + (1-w)*sumY[1]; sumXY = Price*(n-1) + sumXY[1]*(n-2)/n; end; denom = n*sumX2 - sumX*sumX; {denominator of slope formula} if denom < 0.0001 then denom = 0.0001; xslope = correction * n*(n*sumXY - sumX*sumY) / denom; yvalue = sumY/n + xslope * n/2; _xLinRegSlope = xslope;