I’m looking to implement an exponentially weighted moving average with a sliding window using data that I am pulling from a large data set.
The code works but the results are definitely not what they should be and I can’t seem to figure out why. Here is my code and please give me good detail as to what I am exactly doing wrong:
for(unsigned int i = window; i< close_price.size(); i++)
{
double tmp3;
double tmp4;
for(int j = 0; j < window; j++)
{
tmp3 += pow(lambda,j) * pow(close_price[i-j], 2);
tmp4 += pow(close_price[i-j], 2);
if(j == window-1)
{
double temp = (1-lambda) * (pow(close_price[window], 2) + tmp3);
ewma.push_back( sqrt(temp) );
sma.push_back( tmp4/window );
}
tmp3 = 0;
tmp4 = 0;
}
}
Basically the problem is that tmp3 and tmp4 are not initialized, so tmp3+=blah has undefined result.
The way I see your code now, it should look something like this:
Explanation: there is no need for the extra if within the for loop, as j’s last value will be
window-1anyway, tmp3 and tmp4 are to be initialized at every i-loop start. The type of size() issize_tnot unsigned int, if any.