3

我正在尝试计算两个数据列表的斜率。您可以使用 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)));
}

测试数据:如果您在 Excel 中使用函数计算
{1.085231224, 2.335034309, 0.346667278},则斜率应为 0.3373。但是我的代码以某种方式产生了 0.47 ......
{3.185231224,3.705034309 , -0.883332722}=SLOPE

4

1 回答 1

5

我认为你的公式是错误的

根据 Excel 文档,SLOPE 的公式为

另请注意,该函数的第一个参数是y值。

目前尚不清楚如何应用gobackmonths看起来这可能有效:

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;
}
于 2013-11-14T20:44:55.130 回答