Bar Info

Menu

Debugging

Menu

Derivatives

Menu

Matrix Handling

Menu

Price Rounding

Menu

Regression Lines

Menu

Statistics

Menu

User Tracking

Menu

Example Strategies

Menu

## Linear Regression

**Description:**

Calculate the bets fit linear regression line of a provided set of price values.

**Syntax:**

LinearRegression(List<T> y);

**Arguments:**

y: A list of inputs along the y axis of a chart.

**Notes:**

This method assumes the x axis increases in increments of 1.

` ````
```///
/// Calculates the best fit linear regression of a set of data.
///
/// The y values of the input data.
/// A list of the regression values from start to finish.
private List LinearRegression(List y)
{
// save input count to help performance
int n = y.Count;
List x = new List();
// set x total and y total
double xTotal = 0;
double yTotal = 0;
for (int i = 0; i < n; i++)
{
x.Add(i);
xTotal += i;
yTotal += y[i];
}
// save averages to calculate intercept
double xAvg = xTotal / n;
double yAvg = yTotal / n;
// save sum of slope numerator and denominator
double mNum = 0;
double mDen = 0;
for (int i = 0; i < n; i++)
{
mNum += (i - xAvg) * (y[i] - yAvg);
mDen += Math.Pow(i - xAvg, 2);
}
// calculate slope and intercept
double m = mNum / mDen;
double b = yAvg - m * xAvg;
// calculate regression line
List fx = new List();
for (int i = 0; i < n; i++)
fx.Add(m * x[i] + b);
/*
// calculates reliability of linear regression
double linRegrNum = 0;
double linRegrDen = 0;
for (int i = 0; i < n; i++)
{
linRegrNum += Math.Abs(Math.Pow(y[i] - (m * i + b), 2));
linRegrDen += Math.Abs(Math.Pow(y[i] - yAvg, 2));
}
double r2 = 1 - linRegrNum / linRegrDen;
*/
return fx;
}