]> Creatis software - CreaPhase.git/blob - octave_packages/financial-0.4.0/cfdur.m
Add a useful package (from Source forge) for octave
[CreaPhase.git] / octave_packages / financial-0.4.0 / cfdur.m
1 ## Copyright (C) 2011 Hong Yu <hyu0401@hotmail.com>
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{dur}, @var{mod_dur}] =} cfdur (@var{cf}, @var{yield})
18 ## Calculate duration @var{dur} and modified duration @var{mod_dur}, from given
19 ## fixed-paid cash flow @var{cf} and period yield @var{yield}.
20 ##
21 ## Reference:
22 ## http://en.wikipedia.org/wiki/Bond_duration
23 ## Using periodic compounding instead of continuous compounding.
24 ##
25 ## @seealso{cfconv}
26 ## @end deftypefn
27
28 function [dur, modDur] = cfdur (cf, yield)
29
30   if ( nargin != 2 )
31     print_usage ();
32   elseif ( ! isscalar(yield) )
33     error("input yield must be a scalar");
34   endif
35
36   if ( rows(1) != 1 )
37     error("input cash flow must be a 1xN matrix");
38   endif
39
40   v_idx   = 1:columns(cf);
41   t1      = (1+yield) .^ (-v_idx);
42   t2      = v_idx .* t1;
43
44   dur     = (cf*t2') / (cf*t1');
45   modDur  = dur / (1+yield);
46
47 endfunction
48
49 %!demo
50 %! cf = [2.5 2.5 2.5 2.5 2.5 2.5 2.5 2.5 2.5 102.5];
51 %! yield = 0.025;
52 %! [ duration, modDuration ] = cfdur( cf, yield )
53 %! %--------------------------------------------------
54 %! % Input cash flow and yield, output duration and modified duration
55
56 %!test
57 %! cf = [2.5 2.5 2.5 2.5 2.5 2.5 2.5 2.5 2.5 102.5];
58 %! [dur modDur] = cfdur( cf, 0.025 );
59 %! errVal1 = round(dur*(1e+4))*(1e-4) - 8.9709;
60 %! errVal2 = round(modDur*(1e+4))*(1e-4) - 8.7521;
61 %! assert( errVal1, 0 )
62 %! assert( errVal2, 0 )