#Indicator
'**************************************************************
'*   R-Squared Indicator (RSquared.txt)
'*     by Jeremy Williams
'*	   Oct. 11, 2007
'*
'*	Adapted from Technical Analysis of Stocks and Commodities
'*     December 2007
'*
'*  Summary: 
'*
'*      This indicator measures the quality of the trend, by 
'* 	evaluating how well the data is fit by a  simple linear 
'*  regression line. Values of R-Squared near 1 indicate the
'*  is virtually linear, while low values near zero indicate
'*  poorer trending conditions. Note: RSquared values do not
'*  reflect the direction of the trend. Another indicator(s)
'*  such as Linear Regression Slope (LNREG_SLOPE) should be 
'*  used. For more information see "Confiming Price Trend" in  
'*  the December 2007 issue of Technical Analysis of Stocks and 
'*  Commodities.
'*
'*  Parameters:
'*
'*  Periods -  Specifies the number of periods used for the 
'*				linear regression calculation.
'*					
'************************************************************** 

#Param	"Periods" , 20

Dim myStdDev		As Single
Dim myLnRegSlope	As Single
Dim myMultiplier	As Single
Dim myR				As Single
Dim myRR			As Single

' The algorithm presented here, uses the linear regression slope
' and standard deviation to determine the R^2 value using the
' formula:
'
' R^2 = (slope * SDx / SDy)^2
'
' Since the x values (time samples) are evenly spaced, SDx is constant,
' and given by the value: myMultiplier.


myMultiplier = SQRT((Periods+1)*(Periods-1)/12)
myLnRegSlope = LNREG_SLOPE(Periods)
myStdDev	 = STD(Periods)
myR			 = myMultiplier*myLnRegSlope/myStdDev
myRR		 = myR*myR

' Plot R^2 in its own pane (values always between 0 and 1)
SetScales(0,1)
Plot("RSquared", myRR)

' Return the value calculated by the indicator
Return myRR