Time series minima and maxima

• To: mathgroup at smc.vnet.net
• Subject: [mg115906] Time series minima and maxima
• From: Jagra <jagra24891 at mypacks.net>
• Date: Tue, 25 Jan 2011 04:21:49 -0500 (EST)

```Working on some code to find minima and maxima of time series data I
came across this earlier discussion on the forum:

In it, Ray Koopman posted a neat way to do it, but I have some
questions about what I need to do next.

I took Ray's code and wrapped it in a function:

findMinimaMaxima[data_, window_] := With[{k = window}, minmaxdata[[k + Flatten[Position[Partition[data[[All, 2]], 2 k + 1, 1],
x_List /; x[[k + 1]] < Min[Delete[x, k + 1]] || [[k + 1]] >
Max[Delete[x, k + 1]]]]]]]

The findMinimaMaxima[] function has a window parameter, which I hoped
would enable the function to look further left and right and thereby
identify fewer minima and maxima, but more major ones (relative to the
length of the window).
I grab some time series data using FinancialData, strip off the
associated date fields and replaced them with integer positions to
make things easier to debug:

data = FinancialData["SPY", {"May 1, 2006", "Jan. 21, 2011"}][[All,
2]];data = Transpose[{Range[Length@data], data}];

Now.

minimamaxima = findMinimaMaxima[data, 50];
ListLinePlot[{data, minimamaxima}, Joined -> True, ImageSize -> 500]

When you look at the plot, you'll see that with a 50 interval window
(and probably almost any other lengths) and data from "SPY" some
problems appear.

(Note: You can run a couple of other instruments to see things that
move up and down different ways at different times.  Try "GLD" or
"TLT")

Two minor problems.  The function doesn't identify the first point as
either a minima or maxima and it doesn't identify what one would
expect to be the last minima or maxima.

More important, one would want the function to return a list which
alternates between minima and maxima, but the chart shows that a
couple of times, it returns 2 minima in a row or 2 maxima in a row.
In some case it might return even more.  So, clearly expanding the
window left and right more than the original value of 2 the Ray used
introduces some problems.

I first thought to add some code to get rid of the extra point after
the calculation, but everything I thought of seemed clumsy and drifted
away from the clarity of Ray's  original solution.

I haven't downloaded Mathematica 8 yet.  Any chance it has a way to do
this sort of thing?  This relates to data compression too I think, in
getting rid of the extraneous data.

Thanks in advance for any suggestions or directions pursue.

```

• Prev by Date: Re: adding a keyboard shortcut for double brackets
• Next by Date: Re: Plot works in Mathematca 7 but not in Mathematica 8
• Previous by thread: Re: Recursive function
• Next by thread: Re: Time series minima and maxima