# How can I incrementally calculate a time series average?

If I have a time series s, and if you'll pardon the pseudo code, such that

s = {t_i, v_i}


is there an easy way to calculate the series

{t_i, Mean[s[[t_0 ;; t_i]]}


As I say this is pseudo code. In reality s is a TimeSeries object

s = TimeSeries[v,{t}]


I can generate a new TimeSeries object using MovingAverage with ease, but that is not what I require. What I do require is to create a TimeSeries object which is at time t the mean of values in the initial time series having a timestamp less than or equal to t

I could code this up for a simple sequence, but given MovingAverage is supported I was hoping for something similar for this case.

• Maybe MovingAverage ? Apr 30, 2020 at 16:59

You may use Accumulateand TimeSeriesThread.

With

s = TimeSeries[{a, b, c}];


then

t = TimeSeriesThread[Apply[Divide], {Accumulate[s], Range@s["PathLength"]}];
t["Values"]


{ a , (a+b)/2 , (a+b+c)/3 }

Hope this helps.

I am confused on what is asked, so here are 2 alternatives

 s = {{0, 1}, {1, 2}, {2, 4}, {3, 8}, {4, 16}, {5, 32}};
{s[[#, 1]], Mean[s[[1 ;; #, 2]]]} & /@ Range[Length@s] // N or may be this is what is needed

{s[[#, 1]], Mean[s[[1 ;; #]]]} & /@ Range[Length@s] // N • for a time series modelled as a sequence of pairs your first suggestion is correct, but it is very inefficient. I need an efficient solution for a TimeSeries object.
– Nick
Apr 30, 2020 at 19:37

Perhaps you are looking for TimeSeriesWindow:

{#, Mean@TimeSeriesWindow[ts, {tmin, #}]} & /@ tvalues