#include "rsi.hh"
#include <cassert>

namespace AI {

RSI::RSI(int period) :
    previous_(0.0), positiveSMA_(period), negativeSMA_(period)
{
    assert(period >= 2);
}

void RSI::operator()(double value)
{
    double diff = value - previous_;

    positiveSMA_(diff > 0 ? diff : 0.0);
    negativeSMA_(diff < 0 ? -diff : 0.0);

    previous_ = value;
}

double RSI::operator()() const
{
    if (negativeSMA_() == 0.0)
        return 100.0;

    double RS = positiveSMA_() / negativeSMA_();
    return 100.0 - 100.0 / (1.0 + RS);
}

void RSI::clear()
{
    positiveSMA_.clear();
    negativeSMA_.clear();
}

}
