没写过这类函数,来此求助:
一、SMA(X,N,M)的函数算法:
SMA(X,N,M),求X的N日移动平均,M为权重。
算法: 若Y=SMA(X,N,M)
则 Y=[M*X+(N-M)*Y')/N,其中Y'表示上一周期Y值,N必须大于M。二、EMA(X,N)的函数算法:
EMA(X,N),求X的N日指数平滑移动平均。
算法:若Y=EMA(X,N)
则Y=[2*X+(N-1)*Y']/(N+1),其中Y'表示上一周期Y值。假设有一数组:decimal[] X=new decimal[100];
如何编写这两个函数,可以实现把X代入函数后,可以实现求出X[0]到X[99]的SMA和EMA的Y值。
还有一个细节就是:如果设定的N值为5天,那么无法求出X[96]到X[99]的Y值,直接返回值为0。谢谢!!!
一、SMA(X,N,M)的函数算法:
SMA(X,N,M),求X的N日移动平均,M为权重。
算法: 若Y=SMA(X,N,M)
则 Y=[M*X+(N-M)*Y')/N,其中Y'表示上一周期Y值,N必须大于M。二、EMA(X,N)的函数算法:
EMA(X,N),求X的N日指数平滑移动平均。
算法:若Y=EMA(X,N)
则Y=[2*X+(N-1)*Y']/(N+1),其中Y'表示上一周期Y值。假设有一数组:decimal[] X=new decimal[100];
如何编写这两个函数,可以实现把X代入函数后,可以实现求出X[0]到X[99]的SMA和EMA的Y值。
还有一个细节就是:如果设定的N值为5天,那么无法求出X[96]到X[99]的Y值,直接返回值为0。谢谢!!!
delegate int[] mv(int[] source, int count);
private void button1_Click(object sender, EventArgs e)
{
int[] source =new int[] { 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10 }; arraryEleOp 加减权 = (s, f) => {
List<int> res = new List<int>(); for (int i = 0; i < s.Length; i++)
{
res.Add(s[i] + f(i));
}
return res.ToArray();
}; mv 移动平均 = (s, count) =>
{
List<int> res = new List<int>();
for (int i = 0; i < s.Length - count + 1; i++)
{
ArraySegment<int> t = new ArraySegment<int>(s, i, count);
res.Add(avg(t));
}
return res.ToArray(); };
var res1 =加减权(
移动平均(
加减权(
移动平均(source, 5), i => source[i])
, 5)
, i => -移动平均(source, 5)[i]
);
}
//计算均值
private int avg(ArraySegment<int> source)
{
int res = 0;
for (int i = source.Offset; i < source.Offset + source.Count; i++)
{
res += source.Array[i];
}
return res / source.Count;
}