標籤:
原來國外有個源碼(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;
}
}
}
EMA計算的C#實現(c# Exponential Moving Average (EMA) indicator )