title: How to efficiently calculate a moving Standard Deviation
body: <p>Below you can see my C# method to calculate Bollinger Bands for each point (moving average, up band, down band).</p>
  
  <p>As you can see this method uses 2 for loops to calculate the moving standard deviation using the moving average. It used to contain an additional loop to calculate the moving average over the last n periods. This one I could remove by adding the new point value to total_average at the beginning of the loop and removing the i - n point value at the end of the loop.</p>
  
  <p>My question now is basically: Can I remove the remaining inner loop in a similar way I managed with the moving average?</p>
  
  <pre><code>    public static void AddBollingerBands(SortedList&lt;DateTime, Dictionary&lt;string, double&gt;&gt; data, int period, int factor)
      {
          double total_average = 0;
  
          for (int i = 0; i &lt; data.Count(); i++)
          {
              total_average += data.Values[i]["close"];
  
              if (i &gt;= period - 1)
              {
                  double total_bollinger = 0;
                  double average = total_average / period;
  
                  for (int x = i; x &gt; (i - period); x--)
                  {
                      total_bollinger += Math.Pow(data.Values[x]["close"] - average, 2);
                  }
  
                  double stdev = Math.Sqrt(total_bollinger / period);
  
                  data.Values[i]["bollinger_average"] = average;
                  data.Values[i]["bollinger_top"] = average + factor * stdev;
                  data.Values[i]["bollinger_bottom"] = average - factor * stdev;
  
                  total_average -= data.Values[i - period + 1]["close"];
              }
          }
      }
  </code></pre>