#include "stdev.hh"
#include <algorithm>
#include <cassert>

namespace AI {

STDEV::STDEV(int period) :
    SimpleIndicator(period)
{
    assert(period >= 2);
}

void STDEV::operator()(double value)
{
    buffer_.pop_back();
    buffer_.push_front(value);
}

double STDEV::operator()() const
{
    double average =
        std::accumulate(buffer_.begin(), buffer_.end(), 0.0) / buffer_.size();

    double sqSum = 0.0;

    for (auto value : buffer_)
        sqSum += (value - average) * (value - average);

    return sqrt(sqSum / (buffer_.size() - 1));
}

void STDEV::clear()
{
    clearBuffer();
}

}
