       Re: time based moving average (and other newbie mathematica

• To: mathgroup at smc.vnet.net
• Subject: [mg92847] Re: time based moving average (and other newbie mathematica
• From: Mark Fisher <particlefilter at gmail.com>
• Date: Wed, 15 Oct 2008 05:36:25 -0400 (EDT)
• References: <gcn496\$751\$1@smc.vnet.net> <gcv7m8\$e6i\$1@smc.vnet.net>

```On Oct 13, 6:25 am, Mark Fisher <particlefil... at gmail.com> wrote:
> On Oct 10, 4:37 am, falcon <shahb... at gmail.com> wrote:
>
>
>
> > Hi,
> > I see that Mathematica provides a couple of moving average functions.
> > As far as I can tell, they are based on the number of elements in an
> > array.  Is there a function for doing moving average based on time?
> > In other words, if I pass in intra-day data containing prices, times
> > (up to a millisecond) and some other fields, can I get Mathematica to
> > to give me a 5 minute moving average rather than moving average of the
> > last 100 trades?  Obviously this five minute window may contain any
> > number of elements.
>
> > Secondly, along the same idea, I have a file with a large number of
> > stocks.  They are all mixed in (the file is in chronological order).
> > Is there an sql type 'group by' command that lets me see moving
> > averages for each stock?
>
> > Third, if I'm able to get moving average for each stock in the list,
> > can I plot all of them in one command (I guess this technique is
> > called "small multiples" in charting vernacular). Obviously I will
> > only have 20 or 30 stocks.
>
> > Thanks
>
> Following up on my previous post, this version is faster:
>
> MovingTimeAverage =
>         Compile[{{data, _Real, 2}, {lag, _Real, 0}},
>         Module[{j = 1},
>         Table[
>                 While[data[[i, 1]] - data[[j, 1]] > lag, =
j++];
>                 {data[[i, 1]], Mean[data[[j ;; i, 2]]]},
>                         {i, Length[data]}]
>         ]]
>
> It didn't occur to me right away to put the two pieces together.
>
> --Mark

In a private communication, Daniel Lichtblau sent me a yet faster
version. It uses of Accumulate[] as part of a faster way to compute
the mean, by differencing the accumulated values and avoiding the
repeated calls to Mean[].

MovingTimeAverage =
Compile[{{data, _Real, 2}, {lag, _Real, 0}},
Module[{
j = 1,
d2 = Prepend[Accumulate[data[[All, 2]]], 0]
},
Table[
While[data[[i, 1]] - data[[j, 1]] > lag, j++];
{data[[i, 1]], (d2[[i + 1]] - d2[[j]])/(i + 1 - j)},
{i, Length[data]}]
]]

--Mark

```

• Prev by Date: Re: Solve vs. NSolve
• Next by Date: Re: Re: Nested If
• Previous by thread: Re: time based moving average (and other newbie mathematica
• Next by thread: Exclude O[] from Series[] for Solve[] in Mathematica