示例#1
0
        public int CompareTo(MathArgs other)
        {
            int result = Count.CompareTo(other.Count);

            if (0 != result)
            {
                return(result);
            }
            Enumerator itThis  = GetEnumerator();
            Enumerator itOther = other.GetEnumerator();

            for (; itThis.MoveNext() && itOther.MoveNext();)
            {
                result = itThis.Current.Key.CompareTo(itOther.Current.Key);
                if (0 != result)
                {
                    return(result);
                }
                result = itThis.Current.Value.CompareTo(itOther.Current.Value);
                if (0 != result)
                {
                    return(result);
                }
            }
            return(result);
        }
示例#2
0
        public void Clear()
        {
            MathArgs args = new MathArgs();

            args["$name"] = m_name;
            MathematicaKernel.Execute(s_clear, args);
        }
示例#3
0
 private long UpdateID(long id, MathArgs args)
 {
     m_id2args.Remove(id);
     ++m_lastUsedID;
     m_id2args.Add(m_lastUsedID, args);
     return(m_lastUsedID);
 }
示例#4
0
        private void AddResult(MathArgs args, MathResult result)
        {
            if (m_args2entry.ContainsKey(args))
            {
                return;
            }
            while (m_id2args.Count >= m_capacity)
            {
                SortedDictionary <long, MathArgs> .Enumerator it = m_id2args.GetEnumerator();
                it.MoveNext();
                m_args2entry.Remove(it.Current.Value);
                m_id2args.Remove(it.Current.Key);
            }
            ++m_lastUsedID;
            Entry entry = new Entry(result, m_lastUsedID);

            m_args2entry.Add(args, entry);
            try
            {
                m_id2args.Add(m_lastUsedID, args);
            }
            catch (System.Exception)
            {
                m_args2entry.Remove(args);
                throw;
            }
        }
示例#5
0
        public static Interval CalculateConfidenceInterval(double[] data, double confidenceLevel)
        {
            if ((confidenceLevel <= 0) || (confidenceLevel >= 1))
            {
                string st = string.Format("Confidence level = {0}, but must be more than 0 and less than 1", confidenceLevel);
                throw new ArgumentException(st);
            }
            double average;
            double s2 = CalculateSampleVarianceAndAverage(data, out average);

            MathArgs args = new MathArgs();

            args.Add("$level", confidenceLevel);
            args.Add("$freedom", data.Length - 1);

            MathResult answer = s_confidenceIntervalCache.LookFor(args);

            if (null == answer)
            {
                answer = MathematicaKernel.Execute(s_confidenceInterval, args);
                s_confidenceIntervalCache.Add(args, answer);
            }
            double deviation = (double)answer["deviation"];
            double k         = Math.Sqrt(s2 / data.Length);

            deviation *= k;
            double minimum = average - deviation;
            double maximum = average + deviation;

            return(new Interval(minimum, maximum));
        }
示例#6
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);
        }
示例#7
0
 public static MathResult Execute(string script, MathArgs args)
 {
     foreach (var element in args)
     {
         string pattern = string.Format(@"\{0}\b", element.Key);
         script = Regex.Replace(script, pattern, element.Value);
     }
     return(s_instance.Execute(script));
 }
示例#8
0
 public void Add(MathArgs args, MathResult result)
 {
     if (null == args)
     {
         throw new NullReferenceException("args cannot be null");
     }
     if (null == result)
     {
         throw new NullReferenceException("result cannot be null");
     }
     lock (m_synchronizer)
     {
         AddResult(args, result);
     }
 }
示例#9
0
        public MathResult LookFor(MathArgs args)
        {
            Entry entry = null;

            lock (m_synchronizer)
            {
                m_args2entry.TryGetValue(args, out entry);
                if (null != entry)
                {
                    entry.ID = UpdateID(entry.ID, args);
                    return(entry.Result);
                }
                else
                {
                    return(null);
                }
            }
        }
示例#10
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);
        }