]> Creatis software - CreaPhase.git/blob - octave_packages/financial-0.4.0/rsindex.m
Add a useful package (from Source forge) for octave
[CreaPhase.git] / octave_packages / financial-0.4.0 / rsindex.m
1 ## Copyright (C) 2008 Bill Denney <bill@denney.ws>
2 ##
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
6 ## version.
7 ##
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
11 ## details.
12 ##
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/>.
15
16 ## -*- texinfo -*-
17 ## @deftypefn {Function File} {@var{rsi} =} rsindex (@var{closeprice})
18 ## @deftypefnx {Function File} {@var{rsi} =} rsindex (@var{closeprice}, @var{nperiods})
19 ##
20 ## Compute the relative strength index (RSI) of an asset from the vector
21 ## of closing prices (@var{closeprice}).  @var{nperiods} defines the
22 ## number of periods that the rsi should be calculated for 
23 ## (default: 14).
24 ##
25 ## The beginning of the @var{rsi} is padded with nans to match the size
26 ## of @var{closeprice}.
27 ##
28 ## @end deftypefn
29
30 function rsi = rsindex (cl, n = 14)
31
32   if nargin < 1 || nargin > 2
33     print_usage ();
34   elseif n > length(cl)
35     error ("nperiods must be <= the length of closeprice")
36   elseif ! isvector (cl)
37     error ("closeprice must be a vector")
38   endif
39
40   diff = cl(2:end) - cl(1:end-1);
41   rsi  = nan (size (cl));
42
43   for i = n:length (cl)
44     changes = diff(i-n+1:i-1);
45     downs   = changes < 0;
46     ups     = changes > 0;
47     if isempty (downs)
48       ## prevent division by zero
49       rsi(i) = 100;
50     elseif isempty (ups)
51       rsi(i) = 0;
52     else
53       ups    = sum(changes(ups));
54       downs  = -sum(changes(downs));
55       rsi(i) = 100*(1-1/(1+ups/downs));
56     endif
57   endfor
58
59 endfunction
60
61 ## Tests
62 %!shared c, r
63 %! c = [22.44 22.61 22.67 22.88 23.36 23.23 23.08 22.86 23.17 23.69 23.77 23.84 24.32 24.8 24.16 24.1 23.37 23.61 23.21];
64 %! r = [nan(1, 13) 85.1190 70.235 68.6684 55.6322 53.0414 49.7717];
65 %!assert(rsindex(c), r, 0.0001)
66 %!assert(rsindex(c'), r', 0.0001)