Tyche Trading

Linear Regression

Bar Info

Debugging

Derivatives

Matrix Handling

Price Rounding

Regression Lines

Statistics

User Tracking

Example Strategies

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.

				
					/// <summary>
/// Calculates the best fit linear regression of a set of data.
/// </summary>
/// <param name="y"> The y values of the input data. </param>
/// <returns> A list of the regression values from start to finish. </returns>
private List<double> LinearRegression(List<double> y)
{
	// save input count to help performance
	int n = y.Count;

	List<double> x = new List<double>();

	// 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<double> fx = new List<double>();
	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;
}