help-octave
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

RE: vectorized moving average?


From: Tim Rueth
Subject: RE: vectorized moving average?
Date: Wed, 12 May 2010 16:35:15 -0700

Your filter code below works just fine when compared to what I had been doing, except for a number of initial days, due to what values are assumed in negative time.  I had been using the following code:
 
# "ndays" is the number of days to be used when computing the exponential moving average of "data" (data is a column vector)
 data = "" ndays, 1); data];   # repeat data(1) ndays times at the beginning of data for negative time values
 alpha = 2/(ndays+1);
 n = length(data);
 avg = zeros(n,1);
 avg(1) = data(1);
 for i = 2 : n
     ao = avg(i-1);
     avg(i) = ao + alpha*(data(i) - ao);
 endfor
 
# trim off run-in period for negative time values
   long_ma = long_ma(lma_days+1 : end);
For small values of ndays, the number of initial days where there's a discrepancy with your filter() implementation is minimal, but for larger values of ndays, the number of initial days of discrepancy grows (obviously, due to the nature of an exponential MA having a long-tail memory).  Note, I add similar negative time values to the front of the vector when using filter() as well.  I'm just not sure what is the convention when it comes to calculating exponential moving averages for points in "data" where "ndays" reaches back into negative time.  Thanks again.
 


From: address@hidden [mailto:address@hidden On Behalf Of James Sherman Jr.
Sent: Tuesday, May 11, 2010 2:06 PM
To: address@hidden
Cc: Octave-ML
Subject: Re: vectorized moving average?

Well, if you want to use the formula found in Wikipedia exponential moving average, its not as you explain it, because an exponential moving average is fundamentally different than n-day weighted average because it has an infinite "memory" or from my EE background, it has an infinite impulse response.  (I don't know what your background is).

But don't fear!  The filter command can handle this as well (quite easily in fact).  You just need to use the equation found in in the wikipedia article that shows (let s_t be the sum at time t, and x_t be the value at time t), then

s_t = s_(t-1) + alpha*(x_t - s_(t-1))
or rearranged, it looks like
s_t = alpha*x_t - (alpha - 1)*s_(t-1)

so comparing those values to what filter expects, we get:
b = alpha;
a = [1, alpha-1];
s = filter(b, a, x);

I'm not 100% I haven't made a mistake here, but this is the general gist of things.

Hope this helps.

On Tue, May 11, 2010 at 4:28 PM, Tim Rueth <address@hidden> wrote:
> Yep, worked great, thanks!
>
> Now, I just have to figure out how to do an exponential MA using filter().
> (I think movavg() has a bug in it for the exponential case, where alpha =
> 'e'.)
>
> --Tim

reply via email to

[Prev in Thread] Current Thread [Next in Thread]