The C # Implementation of EMA computing (c # Exponential Moving Average (EMA) indicator ),
Originally, the external source code (TechnicalAnalysisEngine src 1.25) internally calculates the EMA as follows:
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
};
It can be seen that such a calculation method is inconsistent with our traditional method and may not even produce results. After studying the EMA algorithm in the main software such as Cinda in China, we can use the following method to calculate the EMA. Paste the C # implementation method.
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 Values", result. Values. Count );
For (int I = 0; I <result. Values. Count; I ++ ){
Console. WriteLine ("ema = {1} in {0}", 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 ;}
}
// Configure //-------------------------------------------------------------------------------------------------------------------------------
/// <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;
}
}
}