我试图计算两个数据列表的斜率。您可以使用SLOPE功能在EXCEL中轻松计算出来。 =SLOPE(A1:A100, B1:B100)
。我试图在C#WinForm中模仿这个功能。这是我的代码,它可以计算一些东西,但不能从Excel函数中获得正确的数字。请帮我在这里找到错误。非常感谢!
private double Getslope(List<double> ProductGrossExcessReturnOverRFR, List<double> primaryIndexExcessReturnOverRFR, int months, int go_back = 0)
{
double slope = 0;
double sumx = 0, sumy = 0, sumxy = 0, sumx2 = 0;
for (int i = ProductGrossExcessReturnOverRFR.Count - 1 - go_back; i > ProductGrossExcessReturnOverRFR.Count - (1 + months + go_back); i--)
{
sumxy += ProductGrossExcessReturnOverRFR[i] * primaryIndexExcessReturnOverRFR[i];
sumx += ProductGrossExcessReturnOverRFR[i];
sumy += primaryIndexExcessReturnOverRFR[i];
sumx2 += ProductGrossExcessReturnOverRFR[i] * ProductGrossExcessReturnOverRFR[i];
}
return slope = 1 / (((sumxy - sumx * sumy / months) / (sumx2 - sumx * sumx / months)));
}
测试数据:
{1.085231224, 2.335034309, 0.346667278}
和
如果使用{3.185231224,3.705034309 , -0.883332722}
函数在Excel中计算,=SLOPE
的斜率应为0.3373。但我的代码以某种方式产生0.47 ......
答案 0 :(得分:4)
我认为你的公式错了
根据Excel文档,SLOPE的公式是
另请注意,函数的第一个参数是y
值。
目前还不清楚goback
和months
的适用方式,但看起来可能会有效:
private double Getslope(List<double> ProductGrossExcessReturnOverRFR,
List<double> primaryIndexExcessReturnOverRFR,
int months,
int go_back = 0)
{
// calc # of items to skip
int skip = ProductGrossExcessReturnOverRFR.Count - go_back - months;
// get list of x's and y's
var ys = ProductGrossExcessReturnOverRFR.Skip(skip).Take(months);
var xs = primaryIndexExcessReturnOverRFR.Skip(skip).Take(months);
// "zip" xs and ys to make the sum of products easier
var xys = Enumerable.Zip(xs,ys, (x, y) => new {x = x, y = y});
double xbar = xs.Average();
double ybar = ys.Average();
double slope = xys.Sum(xy => (xy.x - xbar) * (xy.y - ybar)) / xs.Sum(x => (x - xbar)*(x - xbar));
return slope;
}