title: Implementing Exponential Moving Average in C++
body: <p>I am developing a small trading robot as an exercise. He receives stock prices day after day (represented as iterations).</p>
  
  <p>Here's what my <code>Trade</code> class looks like:</p>
  
  <pre><code>class   Trade
  {
  private:
    int                   capital_;
    int                   days_; // Total number of days of available stock prices                                       
    int                   daysInTrading_; // Increments as days go by.                                                   
    std::list&lt;int&gt;        stockPrices_; // Contains stock prices day after day.                                          
    int                   currentStock_; // Current stock we are dealing with.                                           
    int                   lastStock_; // Last stock dealt with                                                           
    int                   trend_; // Either {-1; 0; 1} depending on the trend.                                           
    int                   numOfStocks_; // Number of stocks in our possession
    int                   EMA_; // Exponential Moving Average                                                            
    int                   lastEMA_; // Last EMA                                                                          
  
  public:
      // functions
  };
  </code></pre>
  
  <p>As you can see from my last two attributes, I wish to implement an Exponential Moving Average as part of a Trend Following Algorithm.</p>
  
  <p>But I think I didn't quite understand how to implement it; here's my <code>calcEMA</code> function that simply calculates the <code>EMA</code>:</p>
  
  <pre><code>int     Trade::calcEMA()
  {
    return ((this-&gt;currentStock_ - this-&gt;lastEMA_
             * (2/(this-&gt;daysInTrading_ + 1)))
            + this-&gt;lastEMA_);
  }
  </code></pre>
  
  <p>But when my stock values (passed in a file) are like such:</p>
  
  <pre><code>1000, 1100, 1200, 1300, 1400, 1500, 1400, 1300, 1200, 1100, 1000
  </code></pre>
  
  <p>As to make sure my EMA makes sense, and well... it does not !</p>
  
  <p>Where did I go wrong on the operation?</p>
  
  <p>Aditionally, what value should I give <code>lastEMA</code> if it's the first time I call <code>calcEMA</code>?</p>