MathGroup Archive 2008

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: time based moving average (and other newbie mathematica questions)

My first solution was very slow for a larger dataset.
The best, I can get for now is the function "ima" below.
It has not got the fearure to select the index for which the time-average will
be built :-(

In[1]:= data =
  Sort[({#1, Sqrt[#1] + Sin[Pi*#1]} & ) /@ RandomReal[{0, 100},

In[2]:= IntervalMovingAverage[dat_List, width_, index_: 1] :=
   If[index =!= 1, Sort, Identity][
     Mean /@
   Function[pos, Select[dat, pos[[index]] <= #1[[index]] <=
                 pos[[index]] + width & ]] /@ dat]

In[3]:= ima[dat_, width_] := Mean /@ Block[{lst = dat, k},
       Reap[While[Length[lst] > 0,
             Sow[Take[lst, k = 1; While[k <= Length[lst] &&
                       lst[[k, 1]] - lst[[1, 1]] <= width, k++];
        k - 1]];
              lst = Rest[lst]]][[2, 1]]]

In[4]:= (tst = (Timing[#1[data, 5]] & ) /@ {IntervalMovingAverage,
     ima})[[All, 1]]

Out[4]= {5.736359, 0.32802100000000056}

In[5]:= SameQ[tst[[All, 2]]]

Out[5]= True


falcon schrieb:
> 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

  • Prev by Date: Re: time based moving average (and other newbie mathematica questions)
  • Next by Date: Re: error region in parametric plot
  • Previous by thread: Re: time based moving average (and other newbie mathematica questions)
  • Next by thread: Mathematica vs Latex