你的位置:首页 > ASP.net教程

[ASP.net教程]EMA计算的C#实现(c# Exponential Moving Average (EMA) indicator )


原来国外有个源码(TechnicalAnalysisEngine src 1.25)内部对EMA的计算是:

var copyInputValues = input.ToList();

for (int i = period; i < copyInputValues.Count; i++)
{
var resultValue = (copyInputValues[i] - returnValues.Last()) * multiplier + returnValues.Last();

returnValues.Add(resultValue);
}

var result = new EMAResult()
{
Values = returnValues,
StartIndexOffset = period - 1
};

可以明显看出,这样的计算方式与我们传统的不一致,甚至可能无法得出结果。经过对国内通达信等主力软件内的EMA算法研究得出用一下方法可以实现对EMA的计算。贴上C#的实现方法。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace myEMA
{
public class myEMA
{

static void Main(string[] args)
{
double[] arr;
arr = new double[5]{2077,2077,2078,2083,2082};
List<double> dd=new List<double>(){2077,2077,2077,2078,2083,2082};

//EMAResult du= ;
var result=EMA(dd,5);
Console.WriteLine("{0}个result的值",result.Values.Count);

for(int i=0;i<result.Values.Count;i++ ){
Console.WriteLine("第{0}的ema={1}",i,result.Values[i]);
}
Console.WriteLine("emaR={0}",result.EmaR );
}
/// <summary>
/// Contains calculation results for EMA indicator
/// </summary>
public class EMAResult
{
public List<double> Values { get; set; }
public int StartIndexOffset { get; set; }
public double EmaR { get; set; }

}

//-------------------------------------------------------------------------------------------------------------------------------

/// <summary>
/// Calculates Exponential Moving Average (EMA) indicator
/// </summary>
/// <param name="input">Input signal</param>
/// <param name="period">Number of periods</param>
/// <returns>Object containing operation results</returns>
public static EMAResult EMA(IEnumerable<double> input, int period)
{
var returnValues = new List<double>();

double multiplier = (2.0 / (period + 1));
//double initialSMA = input.Take(period).Average();

//returnValues.Add(initialSMA);

var copyInputValues = input.ToList();

int j=0;
for (int i = copyInputValues.Count-period; i < copyInputValues.Count; i++)
{
if(j<1)
{
var resultValue =copyInputValues[i];
returnValues.Add(resultValue);
}
else
{
var resultValue = (copyInputValues[i]*multiplier )+(1- multiplier)* returnValues.Last();
returnValues.Add(resultValue);
}
j++;


}

var result = new EMAResult()
{
EmaR=returnValues.Last(),
Values = returnValues,
StartIndexOffset = period - 1
};

return result;
}

 


}
}