[SciPy-user] moving average, moving standard deviation, etc...
palazzol at comcast.net
Sun Dec 24 06:46:08 CST 2006
The technique I've seen involves keeping some intermediate variables,
and subtracting off the oldest value while adding on the newest. At
each timestep then, you just update the variables and recalculate the
xsum += (x[i] - x[i-window_size])
x2sum += (x[i]*x[i] - x[i-window_size]*x[i-window_size])
average = xsum/window_size
stdev_squared = (x2sum - xsum*xsum)/window_size
stdev = sqrt(stdev_squared)
If you want the "sample" stdev, you can compute it directly, or use:
stdev_sample_squared = window_size*stdev_squared/(window_size-1)
stdev_sample = sqrt(stdev_squared)
Don't get me started on this though... IMHO it's usually a waste of time.
Matt Knox wrote:
> Does anyone know of a slick way to calculate a simple moving average and/or moving standard deviation? And when I say slick, I mean loop-free way, because it would be fairly easy to code a looping way of doing it, it would just be really slow.
> To be more specific, when I say moving standard deviation, I mean for example...
> if A is a 1-dimensional array with 100 elements, and I'm using a window size of 10, then the result at index 10 would be A[0:10].std(), the result at index 11 would be A[1:11].std() , etc...
> And similarly for moving average, and so forth. Is their a general way to do these kind of things? Or would it have to be a special case for each type of calculation to avoid looping?
> Any help is greatly appreciated. Thanks in advance,
> - Matt
> SciPy-user mailing list
> SciPy-user at scipy.org
More information about the SciPy-user