How is LinRegSlope() calculated?


Why are the following two formulas not giving me exactly the same answer? What am I missing?

How is LinRegSlope calculated?

periods = Param("Periods", 25, 1, 200, 1 );

LRSlope = LinRegSlope( C, periods ) / Ref(C,-periods);
LRSlopeCalc = ((LinearReg( close, periods) - Ref(LinearReg( close, periods), -periods)) / periods ) / Ref(C,-periods);

Plot( LRSlope, "LRSlope", ColorGreen, styleLine ); // right one
Plot( LRSlopeCalc, "SlopeCalc", ColorRed, styleLine );

I am trying to do the following:

"Calculate the vertical difference between the beginning and ending values of a 25 period close regression line, and divide it by the horizontal change (25 days). That’s the slope of the regression line for that 25-day period. Divide that slope by the beginning value of the line, and you will make your indicator price-independent."

Many thanks,

You are missing Math 101. Your formula is wrong. The internet is wide and open LinRegSlope is described precisely in Wikipedia. Really, Google is your friend.
Also take Excel and do the same and you will get the same result.

Copy paste this code

Plot( C, "Price", colorDefault );

period = 20;

Plot( LinearReg( C, period ), "LR", colorBlue );

bi = BarIndex();
sbi = SelectedValue( bi );

b = SelectedValue( LinRegIntercept( C, period ) );
a = SelectedValue( LinRegSlope( C, period ) );

x = bi - sbi;

ll = a * ( x + period - 1 ) + b;

ll = IIf( x >= - period && x <= 0, ll, Null );

Plot( ll, "Line", colorRed, styleThick );

then click on chart and move the vertical line with cursor, then you will see that the moving LinearRegression is an END POINT of estimate of slope and intercept at period bars. And that it changes on every bar. You will clearly see that only END POINT is on the LR line. Once you understand you will know why your formula is incorrect.



Wow…that is brilliant demonstration of linear regression…

So LinearReg( C, period ) is the moving LinearRegression end point.

and ((LinearReg( C, periods) - Ref(LinearReg( C, periods), -periods)) / periods ) ; is the slope of the moving LinearRegression end point line not the slope of the regression line ending at that point.

Thank you very much


Tomasz Sir really very helpful

Question for Tomasz on this: Since the "price values" in the "Line" are known by AmiBroker, and they are known for each price bar in the "Line Period", is it possible to retrieve those values and use them in a formula? For example, if the price value of Line at close > the price value of Line at close 20 periods ago, then the slope of the line is positive. Can this be made into a formula? I tried using SelectedValue but didn't have much success.