1 ## Copyright (C) 2008 Bill Denney <bill@denney.ws>
3 ## This program is free software; you can redistribute it and/or modify it under
4 ## the terms of the GNU General Public License as published by the Free Software
5 ## Foundation; either version 3 of the License, or (at your option) any later
8 ## This program is distributed in the hope that it will be useful, but WITHOUT
9 ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10 ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
13 ## You should have received a copy of the GNU General Public License along with
14 ## this program; if not, see <http://www.gnu.org/licenses/>.
17 ## @deftypefn {Function File} {} movavg (@var{asset}, @var{lead}, @var{lag})
18 ## @deftypefnx {Function File} {} movavg (@var{asset}, @var{lead}, @var{lag}, @var{alpha})
19 ## @deftypefnx {Function File} {[@var{short}, @var{long}] =} movavg (@var{asset}, @var{lead}, @var{lag}, @var{alpha})
21 ## Calculate the @var{lead}ing and @var{lag}ging moving average of an
22 ## @var{asset}. If given, @var{alpha} is the weighting power of the
23 ## delay; 0 (default) is the simple moving average, 0.5 would be the
24 ## square root weighted moving average, 1 would be linear, 2 would be
25 ## squared, ..., and 'e' is the exponential moving average.
27 ## If no output is requested the data is plotted. The plots are drawn
28 ## in the following order: asset, lag, lead. If output is requested, no
31 ## @seealso{bolling, candle, dateaxis, highlow, pointfig}
34 function [varargout] = movavg (asset, lead, lag, alpha = 0)
36 if nargin < 3 || nargin > 4
41 error ("lead must be <= lag")
43 if ! strcmpi (alpha, "e")
44 error ("alpha must be 'e' if it is a char");
46 elseif ! isnumeric (alpha)
47 error ("alpha must be numeric or 'e'")
50 ## Compute the weights
55 lead = (1:lead).^alpha;
58 ## Adjust the weights to equal 1
59 lead = lead / sum (lead);
60 lag = lag / sum (lag);
64 for i = 1:length (asset)
66 ## Compute the run-in period
67 r = length (lead) - i + 1:length(lead);
68 short(i) = dot (asset(1:i), lead(r))./sum (lead(r));
70 short(i) = dot (asset(i - length(lead) + 1:i), lead);
73 r = length (lag) - i + 1:length(lag);
74 long(i) = dot (asset(1:i), lag(r))./sum (lag(r));
76 long(i) = dot (asset(i - length(lag) + 1:i), lag);
83 plot((1:length(asset))', [asset(:), long(:), short(:)]);
93 %! a = [1 2 3 2 4 2 1];
95 %! [s l] = movavg(a, 2, 4);
96 %! assert(s, [1 1.5 2.5 2.5 3 3 1.5])
97 %! assert(l, [1 1.5 2 2 2.75 2.75 2.25])
99 %! [s l] = movavg(a', 2, 4);
100 %! assert(s, [1;1.5;2.5;2.5;3;3;1.5])
101 %! assert(l, [1;1.5;2;2;2.75;2.75;2.25])
103 %! [s l] = movavg(a, 3, 4, 1);
104 %! assert(s, [3 4.8 7 7 9.5 8 5.5]./3, 10*eps)
105 %! assert(l, [1 11/7 20/9 2.2 3 2.7 2], 10*eps)