Tuesday, September 1, 2020

Calculate Exponential Moving Average EMA

    Decimal CalculateExponentialMovingAverage(DateTime day, int numDays)

        {

            Decimal factor = 2.0M / (1.0M + (Decimal)numDays);

            DateTime firstDay = GetDateXPeriodsAgo(day, numDays);

            Decimal total = CalculateMovingAverage(firstDay, numDays);


            DateTime workingDay;

            for (int i = numDays; i >= 0; i--)

            {

                workingDay = GetDateXPeriodsAgo(day, i);

                foreach (StockInfo data in _stockData)

                {

                    if (data.Date == workingDay)

                    {

                        total = (total * (1.0M - factor)) + (data.ClosingPrice * factor);

                    }

                }

            }

            return total;

        }

No comments:

Post a Comment