python-movingaverage icon indicating copy to clipboard operation
python-movingaverage copied to clipboard

Function for computing a moving average of data.

Written by Sean Reifschneider [email protected] Released into the Public Domain 2011-02-05

Module to compute the moving average of a list. For example:

from movingaverage import movingaverage print list(movingaverage([1,2,3,4,5,6], 3))

[2,3,4,5]

NOTE: Another option is the "stats" pacakge, which is currently (Feb 2011) in early development. The author of that package says that it includes several moving average functions. I haven't used it, because I didn't find out about it until after I wrote this. For more information see: http://pypi.python.org/pypi/stats/

movingaverage(data, subset_size, data_is_list = None, avoid_fp_drift = True)

Return the moving averages of the data, with a window size of subset_size. subset_size must be an integer greater than 0 and less than the length of the input data, or a ValueError will be raised.

data_is_list can be used to tune the algorithm for list or iteratable as an input. The default value, None will auto-detect this. The algorithm used if data is a list is almost twice as fast as if it is an iteratable.

avoid_fp_drift, if True (the default) sums every sub-set rather than keeping a "rolling sum" (which may be subject to floating-point drift). While more correct, it is also dramatically slower for subset sizes much larger than 20.

NOTE: You really should consider setting avoid_fp_drift = False unless you are dealing with very small numbers (say, far smaller than 0.00001) or require extreme accuracy at the cost of execution time. For subset_size < 20, the performance difference is very small.