Serving the Quantitative Finance Community

 
User avatar
banthony
Topic Author
Posts: 0
Joined: June 22nd, 2010, 1:50 pm

Quick question regarding linear regression

January 4th, 2011, 5:21 pm

Hello,I'm working with the following C# code to calculate the linear regression for a time series, and I can't figure out how to do it without an intercept. If anyone has any suggestions I would appreciate it a ton.Thankspublic Regression(double[] dblList1, double[] dblList2) { double xAvg = 0; double yAvg = 0; int x = 0; foreach (double dblValue1 in dblList1) { xAvg += dblValue1; yAvg += dblList2[x]; x += 1; } xAvg = xAvg / dblList1.Length; yAvg = yAvg / dblList1.Length; double v1 = 0; double v2 = 0; x = 0; //double[] cTemp = new double[dblList1.Length]; foreach (double dblValue1 in dblList1) { v1 += (dblValue1 - xAvg) * (dblList2[x] - yAvg); v2 += Math.Pow(dblValue1 - xAvg, 2); //cTemp[x] = (v1 / v2) * (dblValue1) + (yAvg - (v1 / v2) * xAvg); x += 1; } a = v1 / v2; b = yAvg - a * xAvg; //b = 0; double[] cTemp = new double[dblList1.Length]; x = 0; foreach (double dblValue1 in dblList1) { cTemp[x] = a * (dblValue1) + b; x += 1; } c = cTemp; printOut = "y = ax + b" + crLf; printOut += "a = " + Math.Round(a, 2) + ", the slope of the trend line." + crLf; printOut += "b = " + Math.Round(b, 2) + ", the intercept of the trend line." + crLf; }
 
User avatar
quantinenergies
Posts: 0
Joined: April 28th, 2009, 1:42 pm

Quick question regarding linear regression

January 4th, 2011, 9:41 pm

I am not absolutely sure that I understand what you are asking for. However, I think that you want to estimate b in y = bx + eps. In that case you just need to change your formula for b to b = sum(x_n*y_n)/sum(x_n^2). It is just playing with your v1 and v2 (no averages).Good luck
Last edited by quantinenergies on January 3rd, 2011, 11:00 pm, edited 1 time in total.
 
User avatar
tags
Posts: 3631
Joined: February 21st, 2010, 12:58 pm

Quick question regarding linear regression

January 4th, 2011, 9:55 pm

Quoteand I can't figure out how to do it without an interceptit's not clear to me want you want to get.do you want your code to find a trend line of the form y = bx ?
 
User avatar
banthony
Topic Author
Posts: 0
Joined: June 22nd, 2010, 1:50 pm

Quick question regarding linear regression

January 5th, 2011, 3:49 am

Hi,Thanks for the responses. What I'm trying to do is recreate the following R code in C#:var <- lm(x ~ y + 0)The "+0" in the command forces a zero intercept. My current code will return the same results as if I excluded the "+ 0", but I can't figure out the rest.Thanks.
 
User avatar
quantmeh
Posts: 0
Joined: April 6th, 2007, 1:39 pm

Quick question regarding linear regression

January 5th, 2011, 1:08 pm

if you literally converted R code, you'd have much shorter code.beta = sum(xy)/sum(x^2)