private static bool CalculateLinearMarginBalanceInternal(Portfolio portfolio, bool[] zeros, double[,] sigma, double[] profit, double[] margin, PortfolioInput input, Vector[] balance) { int count = 0; Dictionary <int, int> map = new Dictionary <int, int>(); for (int index = 0; index < zeros.Length; ++index) { bool status = zeros[index]; if (!status) { map[map.Count] = index; ++count; } } if (0 == count) { return(true); // nothing to do } // create sub-matrix double[,] _sigma = new double[count, count]; double[] _profit = new double[count]; double[] _margin = new double[count]; for (int row = 0; row < count; ++row) { int r = map[row]; _profit[row] = profit[r]; _margin[row] = margin[r]; for (int column = 0; column < count; ++column) { int c = map[column]; _sigma[row, column] = sigma[r, c]; } } double[,] _balance = new double[balance.Length, count]; for (int row = 0; row < balance.Length; ++row) { int r = row; for (int column = 0; column < count; ++column) { int c = map[column]; _balance[row, column] = balance[row][c]; } } // calculate factor and check it double factor = NumericalMethods.Sqrt(_sigma.Maximum()); if (factor <= 0) { string st = string.Format("Runtime error: invalid factor = {0}", factor); throw new InvalidOperationException(st); } // normalize data NumericalMethods.Multiply(_sigma, 1 / factor / factor); NumericalMethods.Multiply(_profit, 1 / factor); // execute mathematica script MathArgs args = new MathArgs(); args.Add("$profit", _profit); args.Add("$reliability", input.Reliability); args.Add("$covariance", _sigma); args.Add("$loss", input.MaximumLoss / factor); args.Add("$profit", _profit); args.Add("$balance", _balance); args.Add("$margin", _margin); //args.Add("$margin", m); double marginThreshold = (input.InitialDeposit - input.MaximumLoss) / input.MarginLevelThreshold; args.Add("$marginThreshold", marginThreshold); MathResult output = MathematicaKernel.Execute(s_portfolioMarginBalance, args); double[] coefficients = (double[])output["result"]; double p = (double)output["profit"]; if (0 == p) { return(true); } // check results bool result = FastPositiveMinimalThreshold(zeros, input.MinimumCoefficientValue, count, map, coefficients); if (!result) { return(result); } // prepare results for (int index = 0; index < count; ++index) { portfolio.Coefficients[map[index]] = coefficients[index]; } portfolio.Profit = (double)output["profit"] * factor; portfolio.When = (double)output["when"]; return(result); }