# [R] algebra/moving average question - NOTHING TO DO WITH R

Deepayan Sarkar deepayan.sarkar at gmail.com
Fri Jul 6 23:01:02 CEST 2007

On 7/6/07, Leeds, Mark (IED) <Mark.Leeds at morganstanley.com> wrote:
> This has ABSOLUTELY nothing to do with R but I was hoping that someone
> might know because there are obviously a lot of very bright people on
> this list.
>
> Suppose I had a time series of data and at each point in time t, I was
> calculating x bar + plus minus sigma where x bar was based on a
> moving window of size n and so was sigma.
>
> So, if I was at time t , then x bar t plus minus sigma_t would be based
> on the values of x_t-n+1 through x_t.
>
> This is the hard part : Is there a way to back out what the next
> value(s), x_t+1 would have to be in order to for that value to
> be either
>
> greater than  x bar_t+1 plus Z*sigma_t+1
>
> or
>
> less than  x bar_t+1 plus minus Z*sigma_t+1.
>
> where Z is whatever constant ?
>
> I started to try to figure this out but the data window changes and the
> x bar is in the formula for sigma so the algebra got overwhelming but I
> was never an algebra whiz. thanks.

Here's one approach:

Define

T1(t, n) = \sum_{k=t-n+1}^t X_k
T2(t, n) = \sum_{k=t-n+1}^t {X_k}^2

Then, dropping the dependence on (t, n),

xbar = T1 / n
sigma^2 = (T2 - T1^2 / n) / (n-1)

The bounds you want are

X_{t+1} = xbar(t + 1, n) +/- Z sigma(t + 1, n)

Note that

T1(t + 1, n) = T1(t, n - 1) + X_{t+1}
T2(t + 1, n) = T2(t, n - 1) + {X_{t+1}}^2

This should give you a quadratic equation for X_{t+1}.  If my
calculations are correct (they may not be, so you should check), this
equation is

Ax^2 + Bx + C = 0, where

A = (n-1)^3 - Z^2 * n * (n-1)
B = -2 * (Z^2 * n + (n-1)^2) * T1(t, n-1)
C = (Z^2 * n + n - 1) * T1(t, n-1)^2 - Z^2 * n^2 * T2(t, n-1)

Hope this helps,
-Deepayan