Is there a way I can do time series calculation, such as a moving
average in list comprehension syntax? I'm new to python but it looks
like list comprehension's 'head' can only work at a value at a time. I
also tried using the reduce function and passed in my list and another
function which calculates a moving average outside the list comp. ...
but I'm not clear how to do it. Any ideas? Thanks.
Something like:
AVELEN = 5
DATA = [ 2, 4, 5, 1, 6, 6, 3, 2, 6, 3,
2, 3, 3, 5, 6, 6, 5, 4, 3, 6,
1, 4, 3, 4, 1, 6, 6, 5, 6, 5,
5, 6, 5, 3, 3, 5, 1, 4, 1, 3,
2, 5, 5, 4, 2, 5, 5, 2, 2, 4,
1, 3, 5, 1, 4, 1, 1, 3, 3, 6 ]
moving = [ sum(DATA[x-AVELEN:x]) / float(AVELEN)
for x in xrange(AVELEN, len(DATA) + 1) ]
print moving
....
[3.6000000000000001, 4.4000000000000004, 4.2000000000000002,
3.6000000000000001, 4.5999999999999996, 4.0, 3.2000000000000002,
3.2000000000000002, 3.3999999999999999, 3.2000000000000002,
3.7999999999999998, 4.5999999999999996, 5.0, 5.2000000000000002,
4.7999999999999998, 4.7999999999999998, 3.7999999999999998,
3.6000000000000001, 3.3999999999999999, 3.6000000000000001,
2.6000000000000001, 3.6000000000000001, 4.0, 4.4000000000000004,
4.7999999999999998, 5.5999999999999996, 5.4000000000000004,
5.4000000000000004, 5.4000000000000004, 4.7999999999999998,
4.4000000000000004, 4.4000000000000004, 3.3999999999999999,
3.2000000000000002, 2.7999999999999998, 2.7999999999999998,
2.2000000000000002, 3.0, 3.2000000000000002, 3.7999999999999998,
3.6000000000000001, 4.2000000000000002, 4.2000000000000002,
3.6000000000000001, 3.2000000000000002, 3.6000000000000001,
2.7999999999999998, 2.3999999999999999, 3.0, 2.7999999999999998,
2.7999999999999998, 2.7999999999999998, 2.3999999999999999, 2.0,
2.3999999999999999, 2.7999999999999998]
{Note: I've not actually validated the results -- the first and last
seem right... }
--