title: How to calculate cumulative moving average in Python/SQLAlchemy/Flask
body: <p>I'll give some context so it makes sense. I'm capturing Customer Ratings for Products in a table (Rating) and want to be able to return a Cumulative Moving Average of the ratings based on time.</p>
  
  <p>A basic example follows taking a rating per day:</p>
  
  <pre><code>02 FEB - Rating: 5 - Cum Avg: 5
  03 FEB - Rating: 4 - Cum Avg: (5+4)/2 = 4.5
  04 FEB - Rating: 1 - Cum Avg: (5+4+1)/3 = 3.3
  05 FEB - Rating: 5 - Cum Avg: (5+4+1+5)/4 = 3.75
  Etc...
  </code></pre>
  
  <p>I'm trying to think of an approach that won't scale horribly. </p>
  
  <p>My current idea is to have a function that is tripped when a row is inserted into the Rating table that works out the Cum Avg based on the previous row for that product</p>
  
  <p>So the fields would be something like:</p>
  
  <pre><code>TABLE: Rating
  | RatingId | DateTime | ProdId | RatingVal | RatingCnt | CumAvg |
  </code></pre>
  
  <p>But this seems like a fairly dodgy way to store the data.</p>
  
  <p>What would be the (or any) way to accomplish this? If I was to use the 'trigger' of sorts, how do you go about doing that in SQLAlchemy?</p>
  
  <p>Any and all advice appreciated!</p>