private static double getOverallStatValue(SwapsSummaryRow v, DateTime date_)
    {
      var stats = v.Instrument.Stats.RollingStats;

      var instrumentValues = stats.GetValues(date_);

      if (instrumentValues == null)
      {
        Logger.Error(
          string.Format("could not get stats for date '{0}' on instrument '{1}'", date_.ToString("dd-MMM-yyyy"), v.Inst),
          typeof(RatesHelperMethods));

        return 0d;
      }

      var contributions = Singleton<CentralSwitches>.Instance.StatContributions;

      double statValue = 0d;

      foreach (var contribution in contributions)
      {
        var handlingType = PossibleStatColumns.First(x => x.Item1 == contribution.Field).Item2;

        switch (handlingType)
        {
          case StatContributionType.Value:
            {
              statValue += (contribution.Allocation * instrumentValues[(int)contribution.Field]);
            }
            break;
          case StatContributionType.PercentileAbs:
            {
              statValue += (contribution.Allocation * (Math.Abs(instrumentValues[(int)contribution.Field] - 0.5d) * 2d));
            }
            break;
          case StatContributionType.Carry:
            {
              var cry = instrumentValues[(int)contribution.Field];
              var lvlP = instrumentValues[(int)StatCols.Values_Percentile_1Y];

              statValue += (contribution.Allocation *
                            (Sign(lvlP - 0.5d) * -Sign(cry) * Math.Abs(cry)));
            }
            break;
        }
      }

      return statValue;
    }
 public static void RebuildOverallStat(SwapsSummaryRow v)
 {
   v.CombStat = getOverallStatValue(v, v.Instrument.Stats.RollingStats.Dates.Last());
 }
    public static DatedDataCollectionGen<double> GetHistoricalStatSeries(SwapsSummaryRow row_)
    {
      if (row_ == null) return null;

      var con = row_.Instrument.Stats.RollingStats;

      var values = new double[con.Dates.Count];

      for (int i = 0; i < values.Length; ++i)
      {
        values[i] = getOverallStatValue(row_, con.Dates[i]);
      }

      return new DatedDataCollectionGen<double>(con.Dates.ToArray(), values);
    }
    public static Instrument GetRegressionCandidate(SwapsSummaryRow instrument_, RegressionCandidate candidateType_)
    {
      string curve = instrument_.GetInstrument().CurveName;
      
      // for the futures curves, the regressor is the swap curve
      switch (curve)
      {
        case CurveNames.EDCurve:
          curve = CurveNames.USD3M;
          break;
        case CurveNames.ERCurve:
          curve = CurveNames.EUR6M;
          break;
        case CurveNames.L_Curve:
          curve = CurveNames.GBP6M;
          break;
      }

      //if (instrument_.Inst.Contains("USD") || instrument_.Inst.Contains(CurveNames.EDCurve))
      //  curve = CurveNames.USD3M;
      //else if (instrument_.Inst.Contains("EUR") || instrument_.Inst.Contains(CurveNames.ERCurve) )
      //  curve = CurveNames.EUR6M;
      //else if (instrument_.Inst.Contains("GBP") || instrument_.Inst.Contains(CurveNames.L_Curve) )
      //  curve = CurveNames.GBP6M;
      //else if (instrument_.Inst.Contains("JPY"))
      //  curve = CurveNames.JPY6M;
      //else if (instrument_.Inst.Contains("CAD"))
      //  curve = CurveNames.CAD6M;
      //else
      //  throw new NotSupportedException("Need to implement for unknown curve");

      Instrument ret = null;

      switch (candidateType_)
      {
        case RegressionCandidate.Bonds2s:
        {
          ret = xYyY.Get(curve, 0, 2);
        }
          break;
        case RegressionCandidate.Bonds5s:
        {
          ret = xYyY.Get(curve, 0, 5);
        }
          break;
        case RegressionCandidate.Bonds10s:
        {
          ret = xYyY.Get(curve, 0, 10);
        }
          break;
        case RegressionCandidate.Bonds30s:
          {
            ret = xYyY.Get(curve, 0, 30);
          }
          break;
        case RegressionCandidate.TwosFives:
        {
          ret = CurveSwap.Get(curve, PointDef.Create(0, 5), PointDef.Create(0, 2));
        }
          break;
        case RegressionCandidate.TwosTens:
        {
          ret = CurveSwap.Get(curve, PointDef.Create(0, 10), PointDef.Create(0, 2));
        }
          break;
        case RegressionCandidate.FivesTens:
        {
          ret = CurveSwap.Get(curve, PointDef.Create(0, 10), PointDef.Create(0, 5));
        }
          break;
        case RegressionCandidate.FivesThirties:
        {
          ret = CurveSwap.Get(curve, PointDef.Create(0, 30), PointDef.Create(0, 5));
        }
          break;
        case RegressionCandidate.TensThirties:
        {
          ret = CurveSwap.Get(curve, PointDef.Create(0, 30), PointDef.Create(0, 10));
        }
          break;
        case RegressionCandidate.TwosFivesTens:
        {
          ret = ButterflySwap.Get(curve, PointDef.Create(0, 2), PointDef.Create(0, 5),
            PointDef.Create(0, 10));
        }
          break;
        case RegressionCandidate.FivesSevensTens:
        {
          ret = ButterflySwap.Get(curve, PointDef.Create(0, 5), PointDef.Create(0, 7),
            PointDef.Create(0, 10));
        }
          break;
        case RegressionCandidate.FivesTensThirties:
        {
          ret = ButterflySwap.Get(curve, PointDef.Create(0, 5), PointDef.Create(0, 10),
            PointDef.Create(0, 30));
        }
          break;
        default:
        {
          throw new NotSupportedException(string.Format("{0} regressionCandidate not yet implemented.", candidateType_));
        }
      }

      return ret;
    }
    public static void UpdateThisWithCentralOptions(SwapsSummaryRow summaryRow_)
    {
      try
      {
        var lin = DoRegression(summaryRow_,
          GetRegressionCandidate(summaryRow_, Singleton<CentralSwitches>.Instance.RegressionArgs.Dependent),
          Singleton<CentralSwitches>.Instance.RegressionArgs.NumberOfDays, true);

        if (lin != null)
        {
          //summaryRow_.Beta = lin.ParameterEstimates[1].Value;
          summaryRow_.SetRegressionREsiduals(new DatedDataCollectionGen<double>(summaryRow_.Instrument.A_Prices.Dates.SliceLast(Singleton<CentralSwitches>.Instance.RegressionArgs.NumberOfDays),
            lin.Residuals.ToArray()));
          var anova = new NMathStats.LinearRegressionAnova(lin);
          summaryRow_.RSquared = anova.RSquared;
        }
      }
      catch (Exception e)
      {
        Logger.Error(string.Format("Error updating regression stats for {0}", summaryRow_.ToString()),
          typeof (RegressionHelper), e);
      }
    }
    public static void ShowRegression(SwapsSummaryRow row_)
    {
      var regARgs = Singleton<CentralSwitches>.Instance.RegressionArgs;

      var regressionCandidate = GetRegressionCandidate(instrument_: row_,
        candidateType_: regARgs.Dependent);

      var title = string.Format("{0} =  beta ({1}) + c", row_.Inst, regressionCandidate.ToString());

      ReturnsEval.RegressionsAnalysis analysis = new RegressionsAnalysis(title);

      analysis.Dependent = new RegressionsDataSeriesWrapper(row_.Instrument.A_Prices, 0);
      analysis.AddIndependentSeries(regressionCandidate.A_Prices, 0, regressionCandidate.ToString());
      analysis.AddIntercept = true;
      analysis.WindowLength = Singleton<CentralSwitches>.Instance.RegressionArgs.NumberOfDays;
      analysis.Evaluate();

      ReturnsEvalDisplay.RegressionResultsDisplay rd = new RegressionResultsDisplay();
      rd.Bind(analysis);

      SI.Controls.LookFeel.ProcessControl(rd);
      var form = rd.DisplayInShowForm(title);
      form.Icon = SI.Controls.Util.BmpToIcon(RatesSpreadResources.keyImage);

    }
    public static NMathStats.LinearRegression DoRegression(SwapsSummaryRow summaryRow_, Instrument regressAgainstThis_, int numDays_ = 252, bool withIntercept_=true)
    {
      var ys = summaryRow_.GetRawStatSeries(StatCols.Values);

      if (ys.Length < numDays_)
        return null;

      ys = ys.GetEndValues(numDays_);

      var xs = regressAgainstThis_.A_Prices.Data.Slice(regressAgainstThis_.A_Prices.Length - numDays_, numDays_);

      NMathCore.DoubleVector yV = new NMathCore.DoubleVector(ys.Data);
      NMathCore.DoubleMatrix matrix = new NMathCore.DoubleMatrix(xs.ToColumn());

      var lin = new NMathStats.LinearRegression(obs: yV, A: matrix, addIntercept: withIntercept_);

      return lin;
    }