鼎元C++量化程式码指标与函数模块系列之【方差(variance)、标准差(standard deviation,StandardDev)计算方法及调用方法】
1、头文件中声明变量:[code]double Variance(string period, string inst, int num);//方差计算公式变量
double StandardDev(string period, string inst, int num);//标准差计算公式变量
[/code]2、源文件核心公式程式码[code]
//方差计算公式
double test::Variance(string period, string inst, int num)
{
double ma = average(sPeriod, sInst, num);//中间均线
int key = 0;
double sumdev = 0;
double madev = 0;
if (mapK[period][inst].size() < num) return 0;
map<string, TKVALUE>::reverse_iterator it;
for (it = mapK[period][inst].rbegin(); it != mapK[period][inst].rend(); ++it)
{
sumdev += pow(it->second.dClose - ma, 2); //偏离平方加总
key++;
if (key >= num)break;
}
return sumdev / num;
}
//标准差计算公式
double test::StandardDev(string period, string inst, int num)
{
double value1;
if (mapK[period][inst].size() < num) return 0;
value1 = Variance(sPeriod, sInst, num);
return sqrt(value1);
}
[/code]3、调用方法:[code]
StandardDev(sPeriod, sInst, length)
[/code]
页:
[1]