Esempio n. 1
0
        /// <summary>
        /// The method looks for a stability region.
        /// threshold value = limitValue + sigmaCoefficient * sigma;
        /// </summary>
        /// <param name="data">can't be null</param>
        /// <param name="limitValue"></param>
        /// <param name="sigmaCoefficient">defines filter amplitude and direction; see threshold value calculation</param>
        /// <returns>
        /// true cells defines stability region
        /// false cells defines instability region
        /// </returns>
        public static bool[,] FindStabilityRegion(double[,] data, double sigmaFactor, BinaryFunction predicate, double limitValue = 1)
        {
            int rows    = data.GetLength(0);
            int columns = data.GetLength(1);

            List <double> deviations = new List <double>();

            for (int row = 0; row < rows; ++row)
            {
                for (int column = 0; column < columns; ++column)
                {
                    double value = data[row, column];
                    if (row - 1 >= 0)
                    {
                        double delta = data[row - 1, column] - value;
                        deviations.Add(delta);
                    }
                    if (row < rows - 1)
                    {
                        double delta = data[row + 1, column] - value;
                        deviations.Add(delta);
                    }
                    if (column - 1 >= 0)
                    {
                        double delta = data[row, column - 1] - value;
                        deviations.Add(delta);
                    }
                    if (column < columns - 1)
                    {
                        double delta = data[row, column + 1] - value;
                        deviations.Add(delta);
                    }
                }
            }
            double sigma = Statistics.CalculateSampleVariance(deviations.ToArray());

            sigma  = NumericalMethods.Sqrt(sigma);
            sigma *= sigmaFactor;
            double threshold = predicate(1, 0) ? (limitValue - sigma) : (limitValue + sigma);

            bool[,] result = new bool[rows, columns];

            for (int row = 0; row < rows; ++row)
            {
                for (int column = 0; column < columns; ++column)
                {
                    result[row, column] = predicate(data[row, column], threshold);
                }
            }

            double ry = NumericalMethods.Sqrt(rows);
            double rx = NumericalMethods.Sqrt(columns);
            int    r  = (int)Math.Min(rx, ry) - 1;

            for (int index = 0; index < r; ++index)
            {
                result = Morphology.Erosion(result);
            }
            return(result);
        }
Esempio n. 2
0
        public static Portfolio CalculateLinear(double[,] equity, double reliability, double maximumLoss, double minimumCoefficientValue)
        {
            CalculateLinearValidation(reliability, maximumLoss);
            double[,] deltaEquity = NumericalMethods.CalculateAbsoluteVariation(equity);

            double[,] sigma = Statistics.CalculateCovarianceMatrix(deltaEquity);
            double factor = NumericalMethods.Sqrt(sigma.Maximum());

            if (factor <= 0)
            {
                string st = string.Format("Runtime error: invalid factor = {0}", factor);
                throw new InvalidOperationException(st);
            }
            NumericalMethods.Multiply(deltaEquity, 1 / factor);
            double[] profit = Statistics.CalculateAverage(deltaEquity);
            sigma = Statistics.CalculateCovarianceMatrix(deltaEquity);

            MathArgs args = new MathArgs();

            args.Add("$profit", profit);
            args.Add("$reliability", reliability);
            args.Add("$covariance", sigma);
            args.Add("$loss", maximumLoss / factor);
            args.Add("$coefficient", minimumCoefficientValue);
            Dictionary <string, object> output = MathematicaKernel.Execute(s_portfolioDiscrete, args);
            Portfolio result = new Portfolio();

            result.Profit       = (double)output["profit"] * factor;
            result.When         = (double)output["when"];
            result.Coefficients = (double[])output["result"];
            return(result);
        }
Esempio n. 3
0
        public static Portfolio CalculateLinearFast(double[,] equity, double reliability, double maximumLoss, double minimumCoefficientValue)
        {
            CalculateLinearValidation(reliability, maximumLoss);

            double[,] deltaEquity = NumericalMethods.CalculateAbsoluteVariation(equity);
            double[,] sigma       = Statistics.CalculateCovarianceMatrix(deltaEquity);
            Log.Technical("sigma = ", MathFormatProvider.InputStringFromTable(sigma));
            double[] profit = Statistics.CalculateAverage(deltaEquity);
            Log.Technical("sigma = ", MathFormatProvider.InputStringFromData(profit));
            int n = profit.Length;

            Portfolio result = new Portfolio();

            result.Coefficients = new double[n];
            result.When         = double.NaN;
            bool[] zeros = new bool[n];

            bool status = false;

            do
            {
                status = CalculateLinearFastInternal(result, zeros, sigma, profit, reliability, maximumLoss, minimumCoefficientValue, FastAbsoluteMinimalThreshold);
            } while (!status);
            return(result);
        }
Esempio n. 4
0
        public static Portfolio CalculateLinearMarginBalance(PortfolioInput input, Vector[] balance)
        {
            CalculateLinearValidation(input.Reliability, input.MaximumLoss);

            if (input.InitialDeposit <= input.MaximumLoss)
            {
                string st = string.Format("Initial deposit = {0} should be more than maximum loss = {1}", input.InitialDeposit, input.MaximumLoss);
                throw new ArgumentException();
            }
            if (input.MarginLevelThreshold <= 0)
            {
                string st = string.Format("Margin level = {0}, but must be positive", input.MarginLevelThreshold);
                throw new ArgumentException();
            }

            double marginThreshold = (input.InitialDeposit - input.MaximumLoss) / input.MarginLevelThreshold;

            double[,] deltaEquity = NumericalMethods.CalculateAbsoluteVariation(input.Equity);
            double[,] sigma       = Statistics.CalculateCovarianceMatrix(deltaEquity);

            int count = sigma.GetLength(0);

            for (int i = 0; i < count; ++i)
            {
                for (int j = 1 + i; j < count; ++j)
                {
                    sigma[i, j] = 0;
                    sigma[j, i] = 0;
                }
            }
            double[] profit = Statistics.CalculateAverage(deltaEquity);

            Log.Technical("sigma = {0}", MathFormatProvider.InputStringFromTable(sigma));
            Log.Technical("profit = {0}", MathFormatProvider.InputStringFromData(profit));
            int n = profit.Length;

            double[] m = input.Margin.MaximumByRow();

            Portfolio result = new Portfolio();

            result.Coefficients = new double[n];
            result.When         = double.NaN;
            bool[] zeros = new bool[n];

            Vector[] _balance = new Vector[balance.Length - 1];
            for (int index = 1; index < balance.Length; ++index)
            {
                _balance[index - 1] = balance[index] - balance[0];
            }
            double[] margin = input.Margin.MaximumByRow();
            bool     status = false;

            do
            {
                status = CalculateLinearMarginBalanceInternal(result, zeros, sigma, profit, margin, input, _balance);
            } while (!status);
            return(result);
        }
Esempio n. 5
0
        public static bool[,] Erosion(bool[,] data, int row, int column)
        {
            int    rows    = data.GetLength(0);
            int    columns = data.GetLength(1);
            double ry      = NumericalMethods.Sqrt(rows);
            double rx      = NumericalMethods.Sqrt(columns);
            int    radius  = (int)Math.Min(rx, ry);

            bool[,] result = Erosion(data, row, column, radius);
            return(result);
        }
Esempio n. 6
0
        public static Portfolio CalculateLinearFast(double[,] equity, double[,] margin, double initialDeposit, double reliability, double maximumLoss,
                                                    double marginLevel, double minimumCoefficientValue)
        {
            CalculateLinearValidation(reliability, maximumLoss);

            if (maximumLoss <= 0)
            {
                string st = string.Format("maximumLoss = {0}, but must be positive", maximumLoss);
                throw new ArgumentException();
            }
            if (initialDeposit <= maximumLoss)
            {
                string st = string.Format("Initial deposit = {0} should be more than maximum loss = {1}", initialDeposit, maximumLoss);
                throw new ArgumentException();
            }
            if (marginLevel <= 0)
            {
                string st = string.Format("Margin level = {0}, but must be positive", marginLevel);
                throw new ArgumentException();
            }

            double marginThreshold = (initialDeposit - maximumLoss) / marginLevel;

            double[,] deltaEquity = NumericalMethods.CalculateAbsoluteVariation(equity);
            double[,] sigma       = Statistics.CalculateCovarianceMatrix(deltaEquity);
            double[] profit = Statistics.CalculateAverage(deltaEquity);

            Log.Technical("sigma = {0}", MathFormatProvider.InputStringFromTable(sigma));
            Log.Technical("profit = {0}", MathFormatProvider.InputStringFromData(profit));
            int n = profit.Length;

            double[] m = margin.MaximumByRow();

            Portfolio result = new Portfolio();

            result.Coefficients = new double[n];
            result.When         = double.NaN;
            bool[] zeros = new bool[n];


            bool status = false;

            do
            {
                status = CalculateLinearFastInternal(result, zeros, sigma, profit, m, reliability, maximumLoss, minimumCoefficientValue, marginThreshold);
            } while (!status);
            return(result);
        }
Esempio n. 7
0
        public static List <Pixel2> FindStabilityExtremums(double[,] data, double sigmaFactor, BinaryFunction predicate)
        {
            List <Pixel2> result = new List <Pixel2>();

            bool[,] region = FindStabilityRegion(data, sigmaFactor, predicate);

            for (; ;)
            {
                int  row    = -1;
                int  column = -1;
                bool status = NumericalMethods.FindConditionalExtremum(data, region, predicate, out row, out column);
                if (!status)
                {
                    break;
                }
                result.Add(new Pixel2(column, row));
                region = Morphology.Erosion(region, row, column);
            }
            return(result);
        }
Esempio n. 8
0
        private static bool CalculateLinearFastInternal(Portfolio portfolio, bool[] zeros, double[,] sigma, double[] profit, double[] margin, double reliability, double maximumLoss,
                                                        double minimumCoefficientValue, double marginThreshold)
        {
            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 < _profit.Length; ++row)
            {
                int r = map[row];
                _profit[row] = profit[r];
                _margin[row] = margin[r];
                for (int column = 0; column < _profit.Length; ++column)
                {
                    int c = map[column];
                    _sigma[row, column] = sigma[r, 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);
            NumericalMethods.Multiply(_margin, 1 / factor);

            MathArgs args = new MathArgs();

            args.Add("$profit", _profit);
            args.Add("$reliability", reliability);
            args.Add("$covariance", _sigma);
            args.Add("$loss", maximumLoss / factor);
            args.Add("$threshold", marginThreshold / factor);
            args.Add("$margin", _margin);

            Dictionary <string, object> output = MathematicaKernel.Execute(s_portfolioMargin, args);

            double[] coefficients = (double[])output["result"];
            // check results
            bool result = FastPositiveMinimalThreshold(zeros, 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);
        }