#pragma once
//write by 陈墨仙 20150718
//功能:计算序列的移动平均线,并返回序列
template<class T>class funcMa
{
public:
funcMa(){lastTick = 0;};
~funcMa(){};
void clear()
{
t.clear();
t.swap(vector<T>(t));
lastTick = 0;
}
vector<T> Caculate(vector<T> p,int N,int direction)
{
int size = p.size() -1;
if (size <= 0)
{
return t;
}
//vector<double> tSum;
if (direction == 1)
{
for (;size > lastTick; size--)
{
T sum = 0;
T ma = 0;
if(N > size)
{
N = size + 1;
}
for (int i = size; i > size - N; i--)
{
sum += p[i];
}
ma = sum/N;
//tSum.push_back(sum);
t.push_back(ma);
}
lastTick = size + 1;
}
else
{
for (int i = lastTick; i<=size; i++)
{
T sum = 0;
T ma =0;
int temp = N;
if(temp > i)
temp = i + 1;
for(int j = i; j > i - temp; j--)
{
sum+=p[j];
}
ma = sum/temp;
t.push_back(ma);
}
lastTick = size + 1;
}
return t;
}
private:
int lastTick;
vector<T> t;
};
源码下载地址:http://download.csdn.net/detail/corivsky/8916855
该代码的优点是。仅仅要不clear,就不会反复计算移动平均序列,当传入序列增大时。他会在原有基础上计算传入序列新增的数值。
用法:
static funcMa<double> ma60;
static funcMa<double> ma2;
static funcMa<double> ma22;
static vector<double> C;//收盘价序列
vector<double> ma60temp = ma60.Caculate(C,N*2,0);//收盘价的均线序列
vector<double> ma2temp = ma2.Caculate(ma60temp,M1*2,0);//均线的均线
vector<double> ma22temp =ma22.Caculate(ma2temp,M2*2,0);//均线的均线的均线