SmartQuant Discussion
http://www.smartquant.com/forums/

Autocorrelation
http://www.smartquant.com/forums/viewtopic.php?f=86&t=14684
Page 1 of 1

Author:  azuric [ Fri Jan 27, 2017 9:25 am ]
Post subject:  Autocorrelation

Hi I am trying to reverse engineer your autocorrelation for my live system but having trouble with the code:

using something like this:

https://upload.wikimedia.org/math/6/d/a ... 18bb8a.png

leading to:

Code:
        public double GetAverage(List<double> data, int len)
        {
            if (len == 0)
                throw new Exception("No data");

            double sum = 0;

            for (int i = data.Count - len; i < data.Count; i++)
                sum += data[i];

            return sum / Convert.ToDouble(len);
        }

        public double GetAverage2(List<double> data, int len)
        {
            if (len == 0)
                throw new Exception("No data");

            double sum = 0;

            for (int i = data.Count - len-1; i < data.Count-1; i++)
                sum += data[i];

            return sum / Convert.ToDouble(len);
        }


        public double GetVariance(List<double> data, int len)
        {
            // Get average
            double avg = GetAverage(data, len);

            double sum = 0;

            for (int i = data.Count - len; i < data.Count; i++)
                sum += System.Math.Pow((data[i] - avg), 2);

            return sum / Convert.ToDouble(len);
        }

        public double GetVariance2(List<double> data, int len)
        {
            // Get average
            double avg = GetAverage2(data, len);

            double sum = 0;

            for (int i = data.Count - len-1; i < data.Count-1; i++)
                sum += System.Math.Pow((data[i] - avg), 2);

            return sum / Convert.ToDouble(len);
        }

        public double GetStdev(List<double> data, int len)
        {
            return Math.Sqrt(GetVariance(data, len));
        }

        public double GetStdev2(List<double> data, int len)
        {
            return Math.Sqrt(GetVariance2(data, len));
        }

        public double GetCorrelation(List<double> x, int len)
        {
            double avgX = GetAverage(x, len);
            double stdevX = GetStdev(x, len);
            double avgY = GetAverage2(x, len);
            double stdevY = GetStdev2(x, len);
            double covXY = 0;
            double pearson = 0;

            for (int i = x.Count - len; i < x.Count; i++)
                covXY += (x[i] - avgX) * (x[i-1] - avgY);
            covXY /= len;
            pearson = covXY / (stdevX * stdevY);
            return pearson;
        }


Can you show me where I am going wrong?

Page 1 of 1 All times are UTC + 3 hours
Powered by phpBB® Forum Software © phpBB Group
https://www.phpbb.com/