首页 > 代码库 > 计算一个序列的移动平均线序列的模板,可实现均线的均线
计算一个序列的移动平均线序列的模板,可实现均线的均线
#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;
//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);//均线的均线的均线
计算一个序列的移动平均线序列的模板,可实现均线的均线
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。