financial/0000755000175000017500000000000011743631067014012 5ustar carandraugcarandraugfinancial/inst/0000755000175000017500000000000011743631067014767 5ustar carandraugcarandraugfinancial/inst/day.m0000644000175000017500000000174211743256035015724 0ustar carandraugcarandraug## Copyright (C) 2008 Bill Denney ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {dom =} day (Date) ## ## Returns the day of the month from a serial date number or a date ## string. ## ## @seealso{date, datevec, now, month, year} ## @end deftypefn function t = day (dates) t = datevec (dates); t = t (:,3); endfunction financial/inst/thirdwednesday.m0000644000175000017500000000425411743256035020166 0ustar carandraugcarandraug## Copyright (C) 2008 Bill Denney ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {[begindate, enddate]} = thirdwednesday (month, year) ## ## Find the third Wednesday of the month specified by the @var{month} ## and @var{year}. The @var{begindate} is the third Wednesday of the ## month, and the @var{enddate} is three months after that. Outputs are ## in the form of datenums. ## ## The third Wednesday is used for Eurodollar futures. ## ## @seealso{nweekdate, datenum} ## @end deftypefn function [wednesdays, enddate] = thirdwednesday (month, year) if nargin ~= 2 print_usage (); elseif ~ ((numel(year) == 1) || (numel(month) == 1) || ~isequal (size (month), size (year))) error("month and year must have the same size or one of them must be a scalar") endif if numel (year) == 1 sz = size (month); else sz = size (year); endif wednesdays = nweekdate (3, 4, year, month); dates = datevec (wednesdays); ## adjust the year when the date will wrap dates(:,1) += dates (:,2) > 9; ## adjust the month by three dates(:,2) = mod (dates(:,2) + 2, 12) + 1; enddate = reshape (datenum (dates), sz); endfunction ## Tests %!shared m, y, bt, et %! m = (1:12)'; %! y = 2008; %! bt = datenum(2008, m, [16;20;19;16;21;18;16;20;17;15;19;17]); %! et = datenum([2008*ones(9,1);2009*ones(3,1)], [4:12 1:3]', [16;20;19;16;21;18;16;20;17;15;19;17]); %!test %! [b e] = thirdwednesday (m, y); %! assert(b, bt) %! assert(e, et) %!test %! [b e] = thirdwednesday (m', y); %! assert(b, bt') %! assert(e, et') financial/inst/lweekdate.m0000644000175000017500000000242011743256035017106 0ustar carandraugcarandraug## Copyright (C) 2008 Bill Denney ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {last =} lweekdate (weekday, year, month, nextday) ## ## Returns the last occurrence of @var{weekday} from the @var{month} and ## @var{year}. If the optional @var{nextday} argument is given, then ## the week must also contain @var{nextday}. ## ## @seealso{eomdate, nweekdate, weekday} ## @end deftypefn function t = lweekdate (varargin) if nargin < 3 || nargin > 4 error ("3 or 4 input arguments are required") elseif nargin == 3 varargin{4} = 0; endif t = nweekdate ("lweekdate", varargin{:}); endfunction ## Tests are in nweekdate financial/inst/datesplit.m0000644000175000017500000003566511743274154017155 0ustar carandraugcarandraug## Copyright (C) 2001 Bill Denney ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {Y =} datesplit(date, P) ## @deftypefnx {Function File} {[Y,M,D,h,m,s] =} datesplit(date, P) ## Split a date string into the Year, Month, Day, hour, minute, and ## second. This routine tries to be as forgiving as possible to the ## date input while requiring that the date is not ambiguous. ## ## Anywhere possible where it would not be ambiguous, efforts were made ## to make times possible with seconds and AM/PM as optional. Also, ## along the same lines, where possible, commas were allowed with ## spaces, and the year/month/day separators were allowed as period (.), ## slash (/), and dash (-). Not all format possibilities are shown in ## the following table, but a date like @code{dd-mmm-yyyy HH:MM:SS} is ## parsed just as well as @code{d/mmm.yyyy, ,H:MM, AM}. ## ## Supported @code{date} formats include (the same as datestr): ## @multitable @columnfractions 0.1 0.45 0.45 ## @item @strong{Code} @tab @strong{Format} @tab @strong{Example} ## @item 0 @tab dd-mmm-yyyy HH:MM:SS @tab 07-Sep-2000 15:38:09 ## @item 1 @tab dd-mmm-yyyy @tab 07-Sep-2000 ## @item 2 @tab mm/dd/yy @tab 09/07/00 ## @item 3 @tab mmm @tab Sep ## @item 6 @tab mm/dd @tab 09/13 ## @item 10 @tab yyyy @tab 2000 ## @item 12 @tab mmmyy @tab Sep00 ## @item 13 @tab HH:MM:SS @tab 15:38:09 ## @item 14 @tab HH:MM:SS PM @tab 03:38:09 PM ## @item 15 @tab HH:MM @tab 15:38 ## @item 16 @tab HH:MM PM @tab 03:38 PM ## @item 17 @tab QQ-YY @tab Q3-00 ## @item 19 @tab dd/mm @tab 13/03 ## @item 20 @tab dd/mm/yy @tab 13/03/95 ## @item 21 @tab mmm.dd.yyyy HH:MM:SS @tab Mar.03.1962 13:53:06 ## @item 22 @tab mmm.dd.yyyy @tab Mar.03.1962 ## @item 23 @tab mm/dd/yyyy @tab 03/13/1962 ## @item 24 @tab dd/mm/yyyy @tab 12/03/1962 ## @item 25 @tab yy/mm/dd @tab 95/03/13 ## @item 26 @tab yyyy/mm/dd @tab 1995/03/13 ## @item 27 @tab QQ-YYYY @tab Q4-2132 ## @item 28 @tab mmmyyyy @tab Mar2047 ## @item 29 @tab yyyymmdd @tab 20470313 ## @item 30 @tab yyyymmddTHHMMSS @tab 20470313T132603 ## @item 31 @tab yyyy-mm-dd HH:MM:SS @tab 1047-03-13 13:26:03 ## @end multitable ## ## The parameter @code{P} is needed to convert date strings with 2 digit ## years into dates with 4 digit years. 2 digit years are assumed to be ## between @code{P} and @code{P+99}. If @code{P} is not given then the ## current year - 50 is used, so that dates are centered on the present. ## For birthdates, you would want @code{P} to be current year - 99. For ## appointments, you would want @code{P} to be current year. ## ## This function makes no strong attempt to verify the accuracy of the ## numbers that it returns in that it doesn't (currently) check to see ## that you're not trying to use the date Feb 30. When applicable, it ## tries to make your input work, though. It will try to determine if ## you're using the date "03/13/95" that the date is "March 13, 1995", ## but if there is doubt, datesplit will return an error instead of ## trying to guess the wrong value. ## ## @seealso{date,clock,now,datestr,datenum,calendar,weekday} ## @end deftypefn ## TODO: ## * Some formats are ambiguous. Allow the user to specify the format ## to remove ambiguity. ## * Validate the dates. ## * Possible bug (after dates are validated): There are times where ## the year is assumed, Feb 29 may be a valid date, but with the ## assumed year, it may become invalid. ## * Internationalize. Not all months use the English system. ## * Vectorize. That requires vectorization of regexp though... function [y, m, d, h, mi, s] = datesplit(ds, P) persistent warned = false; if (! warned) warned = true; warning ("Octave:deprecated-function", "`datesplit' has been deprecated in favor of `datevec' from Octave core. This function will be removed from future versions of the `financial' package"); endif if nargin < 2 P = []; endif today = datevec(now); if (isempty(P)) P = today(1)-50; endif global __month_names = ["Jan";"Feb";"Mar";"Apr";"May";"Jun";... "Jul";"Aug";"Sep";"Oct";"Nov";"Dec"]; global __day_names = ["Sun";"Mon";"Tue";"Wed";"Thu";"Fri";"Sat"]; global __time_names = ["AM";"PM"]; if (iscellstr(ds)) ds = ds{1}; endif ds = tolower(deblank(ds)); if (nargin < 1) error("datesplit: no input arguments"); elseif (nargin == 1) fmt = []; endif %% we have to determine the format, this could be error prone ## format 0 dd-mmm-yyyy HH:MM:SS e.g. 07-Sep-2000 15:38:09 [match, d, m, y, h, mi, s, ap] = \ of_regexp("^(3[01]|[0-2]?[0-9])[-./]([a-z]{3})[-./]([0-9]{4})[, ]+(2[0-3]|[01]?[0-9]):([0-5][0-9])(:[0-5][0-9]|)[, ]*([ap]m|)$", ds); ## format 21 mmm.dd.yyyy HH:MM:SS e.g. Mar.03.1962 13:53:06 if (isempty(match)) [match, m, d, y, h, mi, s, ap] = \ of_regexp("^([a-z]{3})[-./](3[01]|[0-2]?[0-9])[-./]([0-9]{4})[, ]+(2[0-3]|[01]?[0-9]):([0-5][0-9])(:[0-5][0-9]|)[, ]*([ap]m|)$", ds); endif ## format 31 yyyy-mm-dd HH:MM:SS e.g. 2004-03-13 13:26:03 if (isempty(match)) [match, y, m, d, h, mi, s, ap] = \ of_regexp("^([0-9]{4})[-./](1[012]|0?[0-9])[-./](3[01]|[0-2]?[0-9])[, ]+(2[0-3]|[01]?[0-9]):([0-5][0-9])(:[0-5][0-9]|)[, ]*([ap]m|)$", ds); endif ## format 30 yyyymmddTHHMMSS e.g. 20470313T132603 if (isempty(match)) [match, y, m, d, h, mi, s] = \ of_regexp("^([0-9]{4})(1[012]|0[0-9])(3[01]|[012][0-9])t(2[0-3]|[01][0-9])([0-5][0-9])([0-5][0-9])$", ds); ap = "NA"; endif ## format 13 HH:MM:SS e.g. 15:38:09 ## format 14 HH:MM:SS PM e.g. 03:38:09 PM ## format 15 HH:MM e.g. 15:38 ## format 16 HH:MM PM e.g. 03:38 PM if (isempty(match)) [match, h, mi, s, ap] = \ of_regexp("^(2[0-3]|[01]?[0-9]):([0-5][0-9])(:[0-5][0-9]|)[, ]*([ap]m|)$", ds); if (! isempty(match)) %% assume that it is as of today y = today(1); m = today(2); d = today(3); endif endif ## format 1 dd-mmm-yyyy e.g. 07-Sep-2000 if (isempty(match)) [match, d, m, y] = \ of_regexp("^(3[01]|[012]?[0-9])[-./]([a-z]{3})[-./]([0-9]{4})$", ds); if (! isempty(match)) %% assume the beginning of the day h = 0; mi = 0; s = 0; ap = "NA"; endif endif ## format 22 mmm.dd.yyyy e.g. Mar.03.1962 if (isempty(match)) [match, m, d, y] = \ of_regexp("^([a-z]{3})[-./](3[01]|[012]?[0-9])[-./]([0-9]{4})$", ds); if (! isempty(match)) %% assume the beginning of the day h = 0; mi = 0; s = 0; ap = "NA"; endif endif ## format 2 mm/dd/yy e.g. 09/07/00 ## format 23 mm/dd/yyyy e.g. 03/13/1962 ## format 20 dd/mm/yy e.g. 13/03/95 ## format 24 dd/mm/yyyy e.g. 12/03/1962 ## format 25 yy/mm/dd e.g. 95/03/13 ## format 26 yyyy/mm/dd e.g. 1995/03/13 if (isempty(match)) [match, d, m, y] = \ of_regexp("^([0-9]{1,2}|[0-9]{4})[-./](3[01]|[012]?[0-9])[-./]([0-9]{1,2}|[0-9]{4})$", ds); if (! isempty(match)) %% we have to determine if the date is unambiguous d = str2num(d); m = str2num(m); y = str2num(y); if ((y == 0) || (y > 31)) %% we've got the year correct if ((m > 12) && (d < 13)) %% we're operating on mm/dd/yyyy tmp = m; m = d; d = tmp; elseif ((m < 13) && (d > 12)) %% it's fine else %% it's ambiguous error(["datesplit: ambiguous date " ds]); endif elseif ((d == 0) || (d > 31)) %% the day and the year need to be switched tmp = y; y = d; d = tmp; else %% it's ambiguous error(["datesplit: ambiguous date " ds]); endif %% assume the beginning of the day h = 0; mi = 0; s = 0; ap = "NA"; endif endif ## format 29 yyyymmdd e.g. 20470313 if (isempty(match)) [match, y, m, d] = \ of_regexp("^([0-9]{4})(1[012]|0?[0-9])(3[01]|[012][0-9])$", ds); %% I've never seen a date that has the year first that was not %% yyyy/mm/dd, so I'm going to assume that it's unambiguous. if (! isempty(match)) %% assume the beginning of the day h = 0; mi = 0; s = 0; ap = "NA"; endif endif ## format 17 QQ-YY e.g. Q3-00 ## format 27 QQ-YYYY e.g. Q4-2132 if (isempty(match)) [match, q, y] = \ of_regexp("^q([1-4])[-./]([0-9]{2}|[0-9]{4})$", ds); if (! isempty(match)) %% Assume that it's the end of the quarter q = str2num(q); m = 3*q; dayopts = [31 30 30 31]; d = dayopts(q); %% assume the end of the day h = 23; mi = 59; s = 59; ap = "NA"; endif endif ## format 28 mmmyyyy e.g. Mar2047 ## format 12 mmmyy e.g. Sep00 if (isempty(match)) [match, m, y] = \ of_regexp("^([a-z]{3})([0-9]{2}|[0-9]{4})$", ds); if (! isempty(match)) %% assume the beginning of the month d = 1; h = 0; mi = 0; s = 0; ap = "NA"; endif endif ## format 6 mm/dd e.g. 09/07 ## format 19 dd/mm e.g. 13/03 if (isempty(match)) [match, m, d] = \ of_regexp("^(3[01]|[012]?[0-9])[-./](3[01]|[012][0-9])$", ds); if (! isempty(match)) m = str2num(m); d = str2num(d); %% we have to determine if the date is unambiguous if ((m > 12) && (d < 13)) %% we're operating on mm/dd/yyyy tmp = m; m = d; d = tmp; elseif ((m < 13) && (d > 12)) %% it's fine else %% it's ambiguous error(["datesplit: ambiguous date " ds]); endif %% assume this year and the beginning of the day y = today(1); h = 0; mi = 0; s = 0; ap = "NA"; endif endif ## format 10 yyyy e.g. 2000 if (isempty(match)) [match, y] = of_regexp("^([0-9]{4})$", ds); if (! isempty(match)) %% assume the beginning of the year m = 1; d = 1; h = 0; mi = 0; s = 0; ap = "NA"; endif endif ## format 3 mmm e.g. Sep if (isempty(match)) m = strmatch(ds, tolower(__month_names)); if (! isempty(m)) match = 1; %% assuming the beginning of the month, this year y = today(1); d = 1; h = 0; mi = 0; s = 0; ap = "NA"; endif endif ## format 8 ddd e.g. Thu %% People shouldn't use this function for something like this if (isempty(match)) %% you mean I did all that work, and you still didn't use a valid %% date? Darn you! error(["datesplit: Unknown date format " ds]); endif if (! isempty(match)) if isempty(s) s = 0; elseif (ischar(s) && (1 == findstr(s,":"))) s = s(2:3); endif if isempty(ap) ap = "NA"; endif endif %% start converting the date from characters to numbers if (ischar(y)) y = str2num(y); if (isempty(y)) error(["datesplit: Invalid year specification " y]); endif endif %% Handle Y2K issues... if (y < 100) y = y + 1900; if (y < P) y = y + 100; endif endif if (ischar(m)) m_num = str2num(m); if (isempty(m_num)) m = strmatch(m, tolower(__month_names)); else m = m_num; endif if (isempty(m)) error(["datesplit: Invalid month specification"]); endif endif if (ischar(d)) d = str2num(d); if (isempty(d)) error(["datesplit: Invalid day specification " d]); endif endif if (ischar(h)) h = str2num(h); if (isempty(h)) error(["datesplit: Invalid hour specification " h]); elseif ((ap(2) == "M") && (h > 12)) error(["datesplit: Invalid hour specification, AM or PM specified but" "hour is greater than 12."]); endif if (strcmpi(ap, "PM") && (h < 12)) h = h + 12; elseif (strcmpi(ap, "AM") && (h == 12)) h = 0; endif endif if (ischar(mi)) mi = str2num(mi); if (isempty(mi) || (mi > 59)) error(["datesplit: Invalid minute specification " mi]); endif endif if (ischar(s)) s = str2num(s); if (isempty(s) || (s > 59)) error(["datesplit: Invalid second specification " s]); endif endif if (nargout <= 1) y = [y, m, d, h, mi, s]; endif endfunction # wrapper around Octave's regexp # compatible with octave-forge's regexp function varargout = of_regexp(pattern,string) [S, E, TE, M, T, NM] = regexp(string,pattern); varargout{1} = S; # return sub-strings if match if (S) for i=2:nargout varargout{i} = T{1}{i-1}; end else for i=2:nargout varargout{i} = []; end end endfunction %!shared nowvec %! nowvec=datevec(now); % Some tests could fail around midnight! %!assert (datevec("07-Sep-2000 15:38:09"),[2000,9,7,15,38,9]); %!assert (datevec("07-Sep-2000"),[2000,9,7,0,0,0]); %!assert (datevec("1 Jan 2000"),[2000,1,1,0,0,0]); %!assert (datevec("Sep00"),[2000,9,1,0,0,0]); %!assert (datevec("15:38:09"),[nowvec(1:3),15,38,9]); %!assert (datevec("03:38:09 PM"),[nowvec(1:3),15,38,9]); %!assert (datevec("15:38"),[nowvec(1:3),15,38,0]); %!assert (datevec("3:38 PM"),[nowvec(1:3),15,38,0]); %!assert (datevec("03/13/1962"),[1962,3,13,0,0,0]); ## Ambiguous %!#assert (datevec("09/07/00"),[2000,9,7,0,0,0]); %!#assert (datevec("09/13"),[nowvec(1),9,13,0,0,0]); ## Not supported in octave version of datevec %!#assert (datevec("Sep"),[nowvec(1),9,1,0,0,0]); %!#assert (datevec("Q3-00"),[2000,9,30,23,59,59]); %!#assert (datevec("Q4-2132"),[2132,12,31,23,59,59]); ## This should be a standard string (without or without the time) %!assert (datevec("Mar.03.1962 13:53:06","mmm.dd.yyyy HH:MM:SS"),[1962,3,3,13,53,6]); ## No longer a predefined string to parse the date in octave version %!assert (datevec("1995/03/13","yyyy/mm/dd"),[1995,3,13,0,0,0]); %!assert (datevec("Mar2047","mmmyyyy"),[2047,3,1,0,0,0]); %!assert (datevec("20470313","yyyymmdd"),[2047,3,13,0,0,0]); %!assert (datevec("20470313T132603","yyyymmddTHHMMSS"),[2047,3,13,13,26,3]); %!assert (datevec("1047-03-13 13:26:03","yyyy-mm-dd HH:MM:SS"),[1047,3,13,13,26,3]); financial/inst/rate.m0000644000175000017500000000534211743301537016100 0ustar carandraugcarandraug## Copyright (C) 1995-1998, 2000, 2002, 2004-2007 Kurt Hornik ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {@var{r} =} rate (@var{n}, @var{p}, @var{v}) ## @deftypefnx {Function File} {@var{r} =} rate (@var{n}, @var{p}, @var{v}, @var{l}) ## @deftypefnx {Function File} {@var{r} =} rate (@var{n}, @var{p}, @var{v}, @var{l}, @var{method}) ## @deftypefnx {Function File} {@var{r} =} rate (@var{n}, @var{p}, @var{v}, @var{method}) ## Return the rate of return @var{r} on an investment of present value @var{v} ## which pays @var{p} in @var{n} consecutive periods. ## ## The optional argument @var{l} may be used to specify an additional ## lump-sum payment made at the end of @var{n} periods. ## ## The optional string argument @var{method} may be used to specify ## whether payments are made at the end (@code{"e"}, default) or at the ## beginning (@code{"b"}) of each period. ## @seealso{pv, pmt, nper, npv} ## @end deftypefn function r = rate (n, p, v, l = 0, m = "e") if (nargin < 3 || nargin > 5) print_usage (); elseif (!isnumeric (n) || !isscalar (n) || n <= 0) error ("number of consecutive periods `n' must be a positive scalar"); elseif (!isnumeric (p) || !isscalar (p)) error ("second argument `p' must be a numeric scalar"); elseif (!isnumeric (v) || !isscalar (v)) error ("present value `v' must be a numeric scalar"); ## the following checks is to allow using default value for `l' while specifying `m' elseif (nargin == 5) if (!isnumeric (l) || !isscalar (l)) error ("value of additional lump-sum payment `l' must be numeric scalar"); elseif (!ischar (m)) error ("`method' must be a string") endif elseif (nargin == 4) if (ischar (l)) m = l; l = 0; # default value for `l' again elseif (!isnumeric (l) || !isscalar (l)) error ("fourth argument must either be a numeric scalar for lump-sum payment `l' or a string for `method'"); endif endif if (!any (strcmpi (l, {"e","b"}))) error ("`method' must either be `e' or `b") endif f = @(x) pv (x, n, p, l, m) - v; r = fsolve (f, 0); endfunction financial/inst/lbusdate.m0000644000175000017500000000364111743256035016752 0ustar carandraugcarandraug## Copyright (C) 2008 Bill Denney ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {b =} lbusdate (year, month) ## @deftypefnx {Function File} {b =} lbusdate (year, month, holiday) ## @deftypefnx {Function File} {b =} lbusdate (year, month, holiday, weekend) ## ## Return the datenum of the last business day of the @var{year} and ## @var{month}. @var{holiday} is a vector of datenums that defines the ## holidays observed (the holidays function is used if not given). ## @var{weekend} defines the days of the week that should be considered ## weekends; [1 0 0 0 0 0 1] (default) indicates that Sunday and ## Saturday are holidays. ## ## If any of the optional inputs (@var{holiday}, @var{weekend}) are ## empty, then the default is used. ## ## @seealso{holidays, fbusdate, isbusday, busdate} ## @end deftypefn function rd = lbusdate (y, m, hol, wkend) rd = eomdate (y, m); if nargin < 3 hol = []; end if nargin < 4 wkend = []; elseif nargin < 3 || nargin > 4 print_usage (); endif ## Test from the day after the end of the month so that the ## last day of the month is captured. rd = busdate (rd+1, -1, hol, wkend); endfunction ## Tests ## A normal day %!assert(lbusdate(2008,4), datenum(2008,4,30)) ## A weekend %!assert(lbusdate(2008,5), datenum(2008,5,30)) financial/inst/irr.m0000644000175000017500000000256411743301537015744 0ustar carandraugcarandraug## Copyright (C) 1995-1998, 2000, 2002, 2004-2007 Kurt Hornik ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {} irr (@var{p}, @var{i}) ## Return the internal rate of return of a series of payments @var{p} ## from an initial investment @var{i} (i.e., the solution of ## @code{npv (r, p) = i}. If the second argument is omitted, a value of ## 0 is used. ## @seealso{npv, pv, rate} ## @end deftypefn function r = irr (p, i = 0) ## Check input if (nargin != 1 && nargin != 2) print_usage (); elseif (! (isvector (p))) error ("irr: p must be a vector"); elseif (! isscalar (i)) error ("irr: i must be a scalar"); endif ## Solve system f = @(x) npv (x, p) - i; r = fsolve (f, 0); endfunction financial/inst/datefind.m0000644000175000017500000000275611743256035016733 0ustar carandraugcarandraug## Copyright (C) 2008 Bill Denney ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {indices =} datefind (subset, superset, tol) ## ## Find any instances of the @code{subset} in the @code{superset} with ## the @code{tol}erance. @code{tol} is 0 by default. ## ## @seealso{date, datenum} ## @end deftypefn function idx = datefind (subset, superset, tol=0) if (nargin < 2 || nargin > 3) print_usage (); elseif ! isscalar (tol) error ("datefind: tol must be a scalar") endif idx = []; for i = 1:numel (superset) if any (subset(:) - tol <= superset(i) & superset(i) <= subset(:) + tol) idx(end+1, 1) = i; endif endfor endfunction ## Tests %!assert (datefind (datenum (1999, 7, [10;20]), datenum (1999, 7, 1:31)), [10;20]) %!assert (datefind (datenum (1999, 7, [10;20]), datenum (1999, 7, 1:31), 1), [9;10;11;19;20;21]) financial/inst/taxedrr.m0000644000175000017500000000247411743301537016621 0ustar carandraugcarandraug## Copyright (C) 2008 Bill Denney ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {@var{return} =} taxedrr (@var{pretaxreturn}, @var{taxrate}) ## Compute the taxed rate of @var{return} based on a @var{pretaxreturn} ## rate and a @var{taxrate}. ## @seealso{irr, effrr, nomrr, pvvar, xirr} ## @end deftypefn function rate = taxedrr (pretax, taxrate) if (nargin != 2) print_usage (); elseif (taxrate < 0 || taxrate > 1) error ("taxedrr: taxrate must be between 0 and 1") endif rate = pretax.*(1-taxrate); endfunction ## Tests %!assert (taxedrr (0.12, 0.30), 0.084, 10*eps) %!assert (taxedrr (0.12, 0), 0.12, 10*eps) %!assert (taxedrr (0.12, 1), 0, 10*eps) financial/inst/bolling.m0000644000175000017500000000474711743301537016603 0ustar carandraugcarandraug## Copyright (C) 2008 Bill Denney ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {} bolling (@var{asset}, @var{samples}) ## @deftypefnx {Function File} {} bolling (@var{asset}, @var{samples}, @var{alpha}) ## @deftypefnx {Function File} {} bolling (@var{asset}, @var{samples}, @var{alpha}, @var{width}) ## @deftypefnx {Function File} {[@var{movavg}, @var{upperband}, @var{lowerband}] =} bolling (@var{asset}, @var{samples}, ...) ## ## If no output is requested, plot the bollinger bands of the ## @var{asset}. If output is requested, return the values for the ## bollinger bands. If given, @var{alpha} is the weighting power of the ## moving average; 0 (default) is the simple moving average, see ## @code{movavg} for the full definition. @var{width} is the number of ## standard deviations to plot above and below the moving average ## (default: 2). ## ## @seealso{movavg, candle, dateaxis, highlow, pointfig} ## @end deftypefn function [varargout] = bolling (asset, samples, alpha, width) ## Check input and set the defaults if nargin < 2 || nargin > 4 print_usage (); elseif nargin < 3 alpha = 0; endif if nargin < 4 width = 2; endif if samples > length (asset) error ("Samples must be <= the length of the asset") endif ## the moving average and the standard deviation avg = movavg(asset, samples, samples, alpha); s = zeros(size(avg)); ## Assume that the standard deviation is constant for the first samples ## FIXME: is this what matlab assumes s(1:samples) = std (asset(1:samples)); for i = samples+1:length (asset) s(i) = std (asset(i - samples + 1:i)); endfor if nargout > 0 varargout{1} = avg; else plot((1:length(avg))', [avg(:), avg(:)+s(:), avg(:)-s(:)]); endif if nargout > 1 varargout{2} = avg + s; endif if nargout > 2 varargout{3} = avg - s; endif endfunction financial/inst/fv.m0000644000175000017500000000423411743301537015557 0ustar carandraugcarandraug## Copyright (C) 1995-1998, 2000, 2002, 2005-2007 Kurt Hornik ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {} fv (@var{r}, @var{n}, @var{p}, @var{l}, @var{method}) ## Return the future value at the end of period @var{n} of an investment ## which consists of @var{n} payments of @var{p} in each period, ## assuming an interest rate @var{r}. ## ## The optional argument @var{l} may be used to specify an ## additional lump-sum payment. ## ## The optional argument @var{method} may be used to specify whether the ## payments are made at the end (@code{"e"}, default) or at the ## beginning (@code{"b"}) of each period. ## ## Note that the rate @var{r} is specified as a fraction (i.e., 0.05, ## not 5 percent). ## @end deftypefn function v = fv (r, n, p, l, m) if (nargin < 3 || nargin > 5) print_usage (); endif if (! (isscalar (r) && r > -1)) error ("fv: r must be a scalar > -1"); elseif (! (isscalar (n) && n > 0)) error ("fv: n must be a positive scalar"); elseif (! isscalar (p)) error ("fv: p must be a scalar"); endif if (r != 0) v = p * ((1 + r)^n - 1) / r; else v = p * n; endif if (nargin > 3) if (nargin == 5) if (! ischar (m)) error ("fv: `method' must be a string"); endif elseif ischar (l) m = l; l = 0; else m = "e"; endif if strcmp (m, "b") v = v * (1 + r); endif if isscalar (l) v = v + fvl (r, n, l); else error ("fv: l must be a scalar"); endif endif endfunction financial/inst/npv.m0000644000175000017500000000407711743301537015754 0ustar carandraugcarandraug## Copyright (C) 1995-2000, 2002, 2004-2007 Kurt Hornik ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {} npv (@var{r}, @var{p}, @var{i}) ## Net present value of a series of payments. ## ## Returns the net present value of a series of irregular (i.e., not ## necessarily identical) payments @var{p} which occur at the ends of @var{n} ## consecutive periods. @var{r} specifies the one-period interest rates and ## can either be a scalar (constant rates) or a vector of the same ## length as @var{p}. ## ## The optional argument @var{i} may be used to specify an initial ## investment. ## ## Note that the rate @var{r} is specified as a fraction (i.e., 0.05, ## not 5 percent). ## @seealso{irr, pv} ## @end deftypefn function v = npv (r, p, i) if (nargin < 2 || nargin > 3) print_usage (); endif if (! (isvector (p))) error ("npv: p has to be a vector"); else n = length (p); p = reshape (p, 1, n); endif if (any (any (r <= -1))) error ("npv: all interest rates must be > -1"); endif if (isscalar (r)) d = 1 ./ (1 + r) .^ (0 : n); elseif (isvector (r) && (length (r) == n)) d = [1, (1 ./ cumprod (reshape (1 + r, 1, n)))]; else error ("npv: r must be a scalar or a vector of the same length as p"); endif if (nargin == 3) if (! isscalar (i)) error ("npv: I_0 must be a scalar"); endif else i = 0; endif p = [i, p]; v = sum (d .* p); endfunction financial/inst/isbusday.m0000644000175000017500000000503611743256035016772 0ustar carandraugcarandraug## Copyright (C) 2008 Bill Denney ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {r =} isbusday (refdate) ## @deftypefnx {Function File} {r =} isbusday (refdate, holiday) ## @deftypefnx {Function File} {r =} isbusday (refdate, holiday, weekend) ## ## Return true if the @var{refdate} is a business date @var{refdate}. ## @var{holiday} is a vector of datenums that defines the holidays ## observed (the holidays function is used if not given). @var{weekend} ## defines the days of the week that should be considered weekends; ## [1 0 0 0 0 0 1] (default) indicates that Sunday and Saturday are ## weekends. ## ## @seealso{holidays, lbusdate, busdate, fbusdate} ## @end deftypefn function mask = isbusday (rd, hol=[], wkend=[]) if ~ isnumeric (rd) rd = datenum (rd); endif if isempty (hol) ## Get all possible holidays that could affect the output. hol = holidays (min(rd), max(rd)); end if isempty (wkend) wkend = [1 0 0 0 0 0 1]; elseif numel (wkend) ~= 7 error ("wkend must have 7 elements") elseif nargin > 3 print_usage (); endif mask = reshape (wkend (weekday (rd)), size (rd)); if ~ isempty (hol) ## Is it a holiday? mask = mask | ismember(rd, hol); endif mask = ~mask; endfunction ## Tests ## A normal day %!assert(isbusday(datenum(2008,1,2)), true()) ## A holiday %!assert(isbusday(datenum(2008,1,1)), false()) %!assert(isbusday(datenum(2008,1,1), []), false()) ## A weekend %!assert(isbusday(datenum(2008,2,2)), false()) ## An alternate holiday %!assert(isbusday(datenum(2008,1,2), datenum(2008,1,2)), false()) ## An alternate weekend %!assert(isbusday(datenum(2008,1,2), [], zeros(1,7)), true()) %!assert(isbusday(datenum(2008,1,2), [], ones(1,7)), false()) ## A vector %!assert(isbusday([datenum(2008,1,2) datenum(2008,2,2)]), [true() false()]) ## A vector in the other direction %!assert(isbusday([datenum(2008,1,2);datenum(2008,2,2)]), [true();false()]) financial/inst/pointfig.m0000644000175000017500000000501711743301537016763 0ustar carandraugcarandraug## Copyright (C) 2008 Bill Denney ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {} pointfig (@var{asset}) ## ## Plot the point figure chart of an @var{asset}. Upward price ## movements are plotted as Xs and downward movements are plotted as Os. ## ## @seealso{bolling, candle, dateaxis, highlow, movavg} ## @end deftypefn function pointfig (asset) if nargin != 1 print_usage (); endif upmask = asset(2:end) > asset(1:end-1); # if the data is equal, it will not change the trend equalmask = asset(2:end) == asset(1:end-1); downmask = asset(2:end) < asset(1:end-1); lx = 0; ly = 0; direction = 0; up = zeros(0,2); down = zeros(0,2); for i = 1:length (upmask) if direction > 0 && (upmask(i) || equalmask(i)) ## moving in the same direction as previously: up ly += 1; up(end+1,:) = [lx ly]; elseif direction < 0 && (downmask(i) || equalmask(i)) ## moving in the same direction as previously: down ly -= 1; down(end+1,:) = [lx ly]; else ## moving in a different direction than previously lx += 1; if upmask(i) up(end+1,:) = [lx ly]; direction = 1; else down(end+1,:) = [lx ly]; direction = -1; endif endif endfor hstat = ishold(); hold("on"); plot(up(:,1), up(:,2), "x", "color", [0 0 1]); plot(down(:,1), down(:,2), "o", "color", [1 0 0]); if ! hstat hold("off"); endif endfunction ## Tests %!shared a %! a = [1 2 3 2 4 2 1]; %!test %! [s l] = movavg(a, 2, 4); %! assert(s, [1 1.5 2.5 2.5 3 3 1.5]) %! assert(l, [1 1.5 2 2 2.75 2.75 2.25]) %!test %! [s l] = movavg(a', 2, 4); %! assert(s, [1;1.5;2.5;2.5;3;3;1.5]) %! assert(l, [1;1.5;2;2;2.75;2.75;2.25]) %!test %! [s l] = movavg(a, 3, 4, 1); %! assert(s, [3 4.8 7 7 9.5 8 5.5]./3, 10*eps) %! assert(l, [1 11/7 20/9 2.2 3 2.7 2], 10*eps) financial/inst/pv.m0000644000175000017500000000430611743301537015571 0ustar carandraugcarandraug## Copyright (C) 1995-1996, 1998, 2000, 2002, 2004-2007 Kurt Hornik ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {} pv (@var{r}, @var{n}, @var{p}, @var{l}, @var{method}) ## Returns the present value of an investment that will pay off @var{p} for @var{n} ## consecutive periods, assuming an interest @var{r}. ## ## The optional argument @var{l} may be used to specify an additional ## lump-sum payment made at the end of @var{n} periods. ## ## The optional argument @var{method} may be used to specify whether ## payments are made at the end (@code{"e"}, default) or at the ## beginning (@code{"b"}) of each period. ## ## Note that the rate @var{r} is specified as a fraction (i.e., 0.05, ## not 5 percent). ## @seealso{pmt, nper, rate, npv} ## @end deftypefn function v = pv (r, n, p, l, m) if (nargin < 3 || nargin > 5) print_usage (); endif if (! (isscalar (r) && r > -1)) error ("pv: r must be a scalar > -1"); elseif (! (isscalar (n) && n > 0)) error ("pv: n must be a positive scalar"); elseif (! isscalar (p)) error ("pv: p must be a scalar"); endif if (r != 0) v = p * (1 - (1 + r)^(-n)) / r; else v = p * n; endif if (nargin > 3) if (nargin == 5) if (! ischar (m)) error ("pv: `method' must be a string"); endif elseif (ischar (l)) m = l; l = 0; else m = "e"; endif if (strcmp (m, "b")) v = v * (1 + r); endif if (isscalar (l)) v = v + pvl (r, n, l); else error ("pv: l must be a scalar"); endif endif endfunction financial/inst/posvolidx.m0000644000175000017500000000634411743301537017177 0ustar carandraugcarandraug## Copyright (C) 2008 Bill Denney ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {@var{pvi} =} posvolidx (@var{closeprice}, @var{vol}) ## @deftypefnx {Function File} {@var{pvi} =} posvolidx ([@var{closeprice} @var{vol}]) ## @deftypefnx {Function File} {@var{pvi} =} posvolidx (@var{closeprice}, @var{vol}, @var{initpvi}) ## @deftypefnx {Function File} {@var{pvi} =} posvolidx ([@var{closeprice} @var{vol}], @var{initpvi}) ## ## Compute the positive volume index of a security based on its closing ## price (@var{closeprice}) and @var{vol}ume. They may be given as ## separate arguments or as an nx2 matrix. If given, the @var{initpvi} ## is the starting value of the pvi (default: 100). ## ## The @var{pvi} will always be a column vector. ## ## @seealso{onbalvol, negvolidx} ## @end deftypefn function pvi = posvolidx (c, vol, initpvi) default_pvi = 100; pvi = zeros (length (c), 1); if isvector (c) if nargin < 2 ## a closing price was given without a volume print_usage (); elseif isscalar (vol) ## probably initpvi was given as the second argument print_usage (); elseif !isvector (vol) print_usage (); elseif length (c) != length (vol) error ("closeprice and vol must be the same length"); endif c = [c(:) vol(:)]; if nargin < 3 pvi(1) = default_pvi; else pvi(1) = initpvi; endif elseif size (c, 2) != 2 error ("If given as a matrix, c must have exactly two columns.") elseif size (c, 2) == 2 if nargin == 2 pvi(1) = vol; else pvi(1) = default_pvi; endif else print_usage (); endif ## Start doing the work for i = 2:size (c, 1) pvi(i) = pvi(i-1) + (c(i,2) > c(i-1,2))*pvi(i-1)*(c(i,1)-c(i-1,1))/c(i-1,1); endfor endfunction ## Tests %!shared c, v, pvia, pvib %! 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]; %! v = [10 12 23 25 34 12 32 15 15 34 54 12 86 45 32 76 89 13 28]; %! pvia = [100 100.7575758 101.0249554 101.9607843 104.0998217 104.0998217 103.4276318 103.4276318 103.4276318 105.7488389 106.1059477 106.1059477 108.242309 108.242309 108.242309 107.9734953 104.7029289 104.7029289 102.9290546]'; %! pvib = [5 5.037878788 5.051247772 5.098039216 5.204991087 5.204991087 5.171381588 5.171381588 5.171381588 5.287441943 5.305297383 5.305297383 5.412115451 5.412115451 5.412115451 5.398674767 5.235146444 5.235146444 5.14645273]'; %!assert(posvolidx(c, v), pvia, 1e-5) %!assert(posvolidx([c' v']), pvia, 1e-5) %!assert(posvolidx(c, v, 5), pvib, 1e-5) %!assert(posvolidx([c' v'], 5), pvib, 1e-5) financial/inst/cov2corr.m0000644000175000017500000000334711743301537016707 0ustar carandraugcarandraug## Copyright (C) 2011 Hong Yu ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {[@var{sigma}, @var{corr}] =} cov2corr (@var{cov}) ## Convert covariance @var{cov} from input to standard deviation @var{sigma} and ## correlation coefficients @var{corr}. ## ## @seealso{corr2cov, corrcoef, cov, std} ## @end deftypefn function [sigma, corr] = cov2corr (cov_m) if ( nargin != 1 ) print_usage (); elseif ( ndims (cov_m) != 2 || rows(cov_m) != columns(cov_m) ) error("covariances must be a NxN matrix"); endif sigma = diag(cov_m); if ( min(sigma) <= 0 ) error("covariance: must have all positive values along the diagonal") endif sigma = sqrt(sigma)'; corr = cov_m ./ ( sigma' * sigma ); endfunction %!demo %! cov = [ 0.25 -0.5; -0.5 4.0 ]; %! [ sigma, corr ] = cov2corr( cov ) %! %-------------------------------------------------- %! % Input covariance matrix, output standard deviations and correlation %! % matrix %!test %! cov = [ 0.25 -0.5; -0.5 4.0 ]; %! [sigma, corr] = cov2corr( cov ); %! assert( sigma, [0.5 2.0] ) %! assert( corr, [1.0 -0.5; -0.5 1.0] ); financial/inst/minute.m0000644000175000017500000000173211743256035016447 0ustar carandraugcarandraug## Copyright (C) 2008 Bill Denney ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {m =} minute (Date) ## ## Returns the minute from a serial date number or a date string. ## ## @seealso{date, datevec, now, hour, second} ## @end deftypefn function t = minute (dates) t = datevec (dates); t = t (:,6); endfunction financial/inst/pvl.m0000644000175000017500000000266611743301537015754 0ustar carandraugcarandraug## Copyright (C) 1995-1998, 2000, 2002, 2005-2007 Kurt Hornik ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {@var{v} =} pvl (@var{r}, @var{n}, @var{p}) ## Return the present value @var{v} of an investment that will pay off @var{p} ## in one lump sum at the end of @var{n} periods, given the interest ## rate @var{r}. ## ## Note that the rate @var{r} is specified as a fraction (i.e., 0.05, ## not 5 percent). ## @end deftypefn function v = pvl (r, n, p) if (nargin != 3) print_usage (); endif if (! (isscalar (r) && (r > -1))) error ("pvl: r has to be a scalar > -1"); elseif (! (isscalar (n) && n > 0)) error ("pvl: n has to be a positive scalar"); elseif (! isscalar (p)) error ("pvl: p has to be a scalar"); endif v = p / (1 + r)^n; endfunction financial/inst/yahoo.m0000644000175000017500000000320011743301537016253 0ustar carandraugcarandraug## Copyright (C) 2008 Bill Denney ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {@var{conn} =} yahoo () ## @deftypefnx {Function File} {@var{conn} =} yahoo (@var{URL}, @var{ipaddress}, @var{port}) ## ## Prepare a Yahoo connection for the fetch command to get Yahoo ## historical quote data. ## ## If given, the @var{URL} must be "http://quote.yahoo.com". The ## @var{ipaddress} and @var{port} is the proxy ipaddress and port. These ## parameters are currently ignored (with a warning if given). ## ## @seealso{fetch, google} ## @end deftypefn ## FIXME: Actually use the proxy info if given. function conn = yahoo (url="http://quote.yahoo.com", ipaddr="", port=[]) if ! strcmpi (url, "http://quote.yahoo.com") error ("url must be 'http://quote.yahoo.com'") elseif ! (isempty (ipaddr) && isempty (port)) warning ("Proxy information is currently ignored") endif conn.url = url; conn.ip = ipaddr; conn.port = port; endfunction financial/inst/nweekdate.m0000644000175000017500000001137111743256035017115 0ustar carandraugcarandraug## Copyright (C) 2008 Bill Denney ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {last =} nweekdate (n, weekday, year, month, nextday) ## ## Returns the @var{n}th occurrence of @var{weekday} from the ## @var{month} and @var{year}. If the optional @var{nextday} argument ## is given, then the week must also contain @var{nextday}. If @var{n} ## is greater than the number of occurrences of that day in the month, 0 ## is returned. ## ## @seealso{eomdate, lweekdate, weekday} ## @end deftypefn function t = nweekdate (varargin) if nargin < 4 || nargin > 5 error ("4 or 5 input arguments are required") elseif nargin == 4 varargin{5} = 0; endif ## special handling so that most of this code will not need to be ## duplicated in lweekdate do_lweekdate = is_lweekdate(varargin{1}); if do_lweekdate varargin{1} = 1; endif scale = cellfun (@numel, varargin); if ~ all (scale == 1 | scale == max(scale)); error("All inputs must be either scalars or have the same number of elements"); else ## make sure that the sizes are the same for any non-scalar inputs ind = find (scale > 1); if length(ind) > 1 for i = 2:length (ind) if ndims (varargin{ind(1)}) ~= ndims (varargin{ind(i)}) error("Mismatching dimensions on inputs %d and %d", ind(1), ind(i)); elseif ~ all (size (varargin{ind(1)}) == size (varargin{ind(i)})) error("The sizes of inputs %d and %d do not match", ind(1), ind(i)); endif endfor endif endif if max(scale) > 1 t = zeros (size (varargin{ind(1)})); for i = 1:numel (varargin{ind(1)}) args = cell(5,1); for j = 1:5 if isscalar (varargin{j}) args{j} = varargin{j}; else args{j} = varargin{j}(i); endif endfor if do_lweekdate args{1} = "lweekdate"; end t(i) = nweekdate (args{:}); endfor else ## Do the real work. n = varargin{1}; wd = varargin{2}; y = varargin{3}; mon = varargin{4}; nextday = varargin{5}; ## Find the day of the week for the last day of the mon. doml = eomday (y, mon); dowl = weekday (datenum (y, mon, doml)); ## Make sure that the day is in the weeks for the last then the ## first week. if (wd < nextday) || (dowl < wd) ## adjust the last day adjust = 7; else adjust = 0; endif dom = sort((doml - dowl + wd - adjust):-7:1); if nextday && (dom(1) <= wd - nextday) # adjust the first day dom(1) = []; endif if do_lweekdate t = datenum (y, mon, dom(end)); elseif n > length(dom) t = 0; else t = datenum (y, mon, dom(n)); end endif endfunction function v = is_lweekdate(v) if ischar(v) if strcmp (v, "lweekdate") v = true(); else error("Invalid input for n") endif else v = false(); endif endfunction # Tests for all calling options # Find the first Wednesday in Jan 2008 %!assert(nweekdate(1, 4, 2008, 1), datenum(2008, 1, 2)) # Find the second Wednesday in Jan 2008 %!assert(nweekdate(2, 4, 2008, 1), datenum(2008, 1, 9)) # Find the third Wednesday in Jan 2008 %!assert(nweekdate(3, 4, 2008, 1), datenum(2008, 1, 16)) # Find the fourth Wednesday in Jan 2008 %!assert(nweekdate(4, 4, 2008, 1), datenum(2008, 1, 23)) # Find the fifth Wednesday in Jan 2008 %!assert(nweekdate(5, 4, 2008, 1), datenum(2008, 1, 30)) # Find the sixth Wednesday in Jan 2008, it doesn't exist, so return 0 %!assert(nweekdate(6, 4, 2008, 1), 0) # Find the fifth Friday in Jan 2008, it doesn't exist, so return 0 %!assert(nweekdate(5, 6, 2008, 1), 0) # Find the first Wednesday in Jan 2008 in the same week as a Monday # WARNING: it is unclear from the Matlab docs if this should work or if # this should be called the second Wednesday in Jan 2008. %!assert(nweekdate(1, 4, 2008, 1, 2), datenum(2008, 1, 9)) # Find the fifth Wednesday in Jan 2008 in the same week as a Friday. # It doesn't exist, so return 0 %!assert(nweekdate(5, 4, 2008, 1, 6), 0) # Try vector arguments %!assert(nweekdate(1:6, 4, 2008, 1, 6), [datenum(2008, 1, 2:7:23), 0, 0]) # Try the lweekdate operation of this function: # Find the last Wednesday in Jan 2008 %!assert(nweekdate('lweekdate', 4, 2008, 1), datenum(2008, 1, 30)) # Find the last Wednesday in Jan 2008 with a Friday %!assert(nweekdate('lweekdate', 4, 2008, 1, 6), datenum(2008, 1, 23)) financial/inst/daysact.m0000644000175000017500000000454011743256035016576 0ustar carandraugcarandraug## Copyright (C) 2007 David Bateman ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {} daysact (@var{d1}) ## @deftypefnx {Function File} {} daysact (@var{d1}, @var{d2}) ## Calculates the number of days between two dates. If the second date is not ## given, calculate the number of days since 1-Jan-0000. The variables @var{d1} ## and @var{d2} can either be strings or an @var{n}-row string matrix. If both ## @var{d1} and @var{d2} are string matrices, then the number of rows must ## match. An example of the use of @code{daysact} is ## ## @example ## @group ## daysact ("01-Jan-2007", ["10-Jan-2007"; "23-Feb-2007"; "23-Jul-2007"]) ## @result{} 9 ## 53 ## 203 ## @end group ## @end example ## @seealso{datenum} ## @end deftypefn function days = daysact (d1, d2) if (nargin == 1) nr = size (d1, 1); if (nr != 1) days = zeros (nr,1); for i = 1 : nr days (i) = datenum (d1 (i,:)); endfor else days = datenum(d1); endif elseif (nargin == 2) nr1 = size (d1, 1); nr2 = size (d2, 1); if (nr1 != nr2 && nr1 != 1 && nr2 != 1) error ("daysact: size mismatch"); endif if (nr1 == 1 && nr2 == 1) days = datenum (d2) - datenum(d1); elseif (nr1 == 1) days = zeros (nr2, 1); for i = 1 : nr2 days(i) = datenum (d2 (i,:)) - datenum (d1); endfor elseif (nr2 == 1) days = zeros (nr1, 1); for i = 1 : nr1 days(i) = datenum (d2) - datenum (d1 (i,:)); endfor else days = zeros (nr1, 1); for i = 1 : nr1 days(i) = datenum (d2 (i, :)) - datenum (d1 (i,:)); endfor endif else print_usage(); endif endfunction %!assert (daysact ("01-Jan-2007", ["10-Jan-2007"; "23-Feb-2007"; "23-Jul-2007"]),[9;53;203]) financial/inst/llow.m0000644000175000017500000000360411743301537016121 0ustar carandraugcarandraug## Copyright (C) 2008 Bill Denney ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {@var{llv} =} llow (@var{data}) ## @deftypefnx {Function File} {@var{llv} =} llow (@var{data}, @var{nperiods}) ## @deftypefnx {Function File} {@var{llv} =} llow (@var{data}, @var{nperiods}, @var{dim}) ## ## Compute the lowest low value of @var{data} for the past ## @var{nperiods} (default: 14) across the dimension, @var{dim} ## (default: 1). ## ## @seealso{hhigh} ## @end deftypefn function llv = llow (data, nperiods = 14, dim = find (size (data) > 1, 1)) if nargin < 1 || nargin > 3 print_usage (); elseif ! isvector (data) ## FIXME error ("cannot yet handle more than one dimensional data") elseif dim > ndims (data) error ("dim cannot be greater than the number of dimensions in data"); endif sz = size (data); llv = data; for i = 1:sz(dim) llv(i) = min (data(max (i-nperiods+1, 1):i)); endfor endfunction ## Tests %!shared c, l %! 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 25]; %! l = [22.44 22.44 22.44 22.44 22.44 22.44 22.44 22.44 22.44 22.44 22.44 22.44 22.44 22.44 22.61 22.67 22.86 22.86 22.86 22.86]; %!assert(llow(c), l) %!assert(llow(c'), l') financial/inst/second.m0000644000175000017500000000173211743256035016421 0ustar carandraugcarandraug## Copyright (C) 2008 Bill Denney ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {s =} second (Date) ## ## Returns the second from a serial date number or a date string. ## ## @seealso{date, datevec, now, hour, minute} ## @end deftypefn function t = second (dates) t = datevec (dates); t = t (:,6); endfunction financial/inst/m2xdate.m0000644000175000017500000000504311743256035016511 0ustar carandraugcarandraug## Copyright (C) 2008 Bill Denney ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {exceldatenums =} m2xdate (datenums) ## @deftypefnx {Function File} {exceldatenums =} m2xdate (datenums, convention) ## @deftypefnx {Function File} {exceldatenums =} m2xdate (datenums, convention, "ExcelBug") ## ## Convert @var{datenums} from the internal date format to the format ## used by Microsoft Excel. If set to 0 (default, Excel for Windows), ## @var{convention} specifies to use the Excel 1900 convention where Jan ## 1, 1900 corresponds to Excel serial date number 1. If set to 1 ## (Excel for Mac), @var{convention} specifies to use the Excel 1904 ## convention where Jan 1, 1904 corresponds to Excel serial date number ## 0. ## ## Note that this does not take into account the Excel bug where 1900 is ## considered to be a leap year unless you give the "ExcelBug" option. ## ## Excel does not represent dates prior to 1 January 1900 using this ## format, so a warning will be issued if any dates preceed this date. ## ## @seealso{datenum, x2mdate} ## @end deftypefn function dates = m2xdate (dates, convention, excelbug) if nargin == 1 convention = 0; excelbug = false(); elseif nargin == 2 excelbug = false(); elseif nargin == 3 excelbug = strcmpi(excelbug, "ExcelBug"); else print_usage (); endif if convention == 0 adj = datenum(1900, 1, 1) - 2; elseif convention == 1 adj = datenum(1904, 1, 1); endif if excelbug datemask = (dates < datenum(1900, 3, 1)); dates(datemask) = dates(datemask) - 1; endif dates = dates - adj; if any (dates < 0) warning ("Negative date found, this will not work within MS Excel.") endif endfunction ## Tests %!assert(m2xdate(datenum(2008, 1, 1)), 39448) %!assert(m2xdate(datenum(2007:2008, 1, 1)), [39083 39448]) %!assert(m2xdate(datenum(1900, 1, 1)), 2) %!assert(m2xdate(datenum(1900, 1, 1), 0, "ExcelBug"), 1) %!assert(m2xdate(datenum(1904, 1, 1), 1), 0) financial/inst/cfdur.m0000644000175000017500000000376411743301537016256 0ustar carandraugcarandraug## Copyright (C) 2011 Hong Yu ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {[@var{dur}, @var{mod_dur}] =} cfdur (@var{cf}, @var{yield}) ## Calculate duration @var{dur} and modified duration @var{mod_dur}, from given ## fixed-paid cash flow @var{cf} and period yield @var{yield}. ## ## Reference: ## http://en.wikipedia.org/wiki/Bond_duration ## Using periodic compounding instead of continuous compounding. ## ## @seealso{cfconv} ## @end deftypefn function [dur, modDur] = cfdur (cf, yield) if ( nargin != 2 ) print_usage (); elseif ( ! isscalar(yield) ) error("input yield must be a scalar"); endif if ( rows(1) != 1 ) error("input cash flow must be a 1xN matrix"); endif v_idx = 1:columns(cf); t1 = (1+yield) .^ (-v_idx); t2 = v_idx .* t1; dur = (cf*t2') / (cf*t1'); modDur = dur / (1+yield); endfunction %!demo %! cf = [2.5 2.5 2.5 2.5 2.5 2.5 2.5 2.5 2.5 102.5]; %! yield = 0.025; %! [ duration, modDuration ] = cfdur( cf, yield ) %! %-------------------------------------------------- %! % Input cash flow and yield, output duration and modified duration %!test %! cf = [2.5 2.5 2.5 2.5 2.5 2.5 2.5 2.5 2.5 102.5]; %! [dur modDur] = cfdur( cf, 0.025 ); %! errVal1 = round(dur*(1e+4))*(1e-4) - 8.9709; %! errVal2 = round(modDur*(1e+4))*(1e-4) - 8.7521; %! assert( errVal1, 0 ) %! assert( errVal2, 0 ) financial/inst/fvl.m0000644000175000017500000000263211743301537015733 0ustar carandraugcarandraug## Copyright (C) 1995-1998, 2000, 2002, 2005-2007 Kurt Hornik ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {} fvl (@var{r}, @var{n}, @var{l}) ## Return the future value at the end of @var{n} periods of an initial ## lump sum investment @var{l}, given a per-period interest rate ## @var{r}. ## ## Note that the rate @var{r} is specified as a fraction (i.e., 0.05, ## not 5 percent). ## @end deftypefn function v = fvl (r, n, l) if (nargin != 3) print_usage (); endif if (! (isscalar (r) && r > -1)) error ("fvl: r has to be a scalar > -1"); elseif (! (isscalar (n) && n > 0)) error ("fvl: n has to be a positive scalar"); elseif (! isscalar (l)) error ("fvl: l has to be a scalar"); endif v = l * (1 + r)^n; endfunction financial/inst/cfconv.m0000644000175000017500000000354411743301537016425 0ustar carandraugcarandraug## Copyright (C) 2011 Hong Yu ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {@var{cfConv} =} cfconv (@var{cf}, @var{yield}) ## Calculate convexity @var{cfConv} from given fixed-paid cash flow @var{cf} and ## period yield @var{yield}. ## ## Reference: ## ## [1] http://thismatter.com/money/bonds/duration-convexity.htm ## ## [2] http://en.wikipedia.org/wiki/Bond_convexity ## ## @seealso{cfdur} ## @end deftypefn function [cfConv] = cfconv (cf, yield) if ( nargin != 2 ) print_usage (); elseif ( ! isscalar(yield) ) error("yield: must be scalar"); elseif ( rows(cf) != 1 ) error("Cash Flow: must be 1xN"); endif v_idx = 1:columns(cf); t1 = (1+yield) .^ (-v_idx); t2 = ((v_idx .^ 2) + v_idx) .* t1; cfConv = (cf*t2') / (cf*t1') / (1+yield) / (1+yield); endfunction %!demo %! cf = [2.5 2.5 2.5 2.5 2.5 2.5 2.5 2.5 2.5 102.5]; %! yield = 0.025; %! cfConv = cfconv( cf, yield ) %! %-------------------------------------------------- %! % Input cash flow and yield, output convexity %!test %! cf = [2.5 2.5 2.5 2.5 2.5 2.5 2.5 2.5 2.5 102.5]; %! cfConv = cfconv( cf, 0.025 ); %! errVal = round(cfConv*(1e+4))*(1e-4) - 90.4493; %! errVal = round(errVal*(1e+10)); %! assert(errVal, 0) financial/inst/today.m0000644000175000017500000000221111743256035016257 0ustar carandraugcarandraug## Copyright (C) 2008 Bill Denney ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {datenum =} today () ## Returns the current local date as the number of days since Jan 1, 0000. ## By this reckoning, Jan 1, 1970 is day number 719529. ## ## The returned number corresponds to 00:00:00 today. ## ## The returned value is also called a "serial date number" ## (see @code{datenum}). ## @seealso{clock, date, datenum, now} ## @end deftypefn function t = today () t = floor (now ()); endfunction financial/inst/pmt.m0000644000175000017500000000373011743301537015744 0ustar carandraugcarandraug## Copyright (C) 1995-1998, 2000-2002, 2004-2007 Kurt Hornik ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {} pmt (@var{r}, @var{n}, @var{a}, @var{l}, @var{method}) ## Return the amount of periodic payment necessary to amortize a loan ## of amount a with interest rate @var{r} in @var{n} periods. ## ## The optional argument @var{l} may be used to specify a terminal ## lump-sum payment. ## ## The optional argument @var{method} may be used to specify whether ## payments are made at the end (@var{"e"}, default) or at the beginning ## (@var{"b"}) of each period. ## @seealso{pv, nper, rate} ## @end deftypefn function p = pmt (r, n, a, l, m) if (nargin < 3 || nargin > 5) print_usage (); endif if (! (isscalar (r) && r > -1)) error ("pmt: rate must be a scalar > -1"); elseif (! (isscalar (n) && n > 0)) error ("pmt: n must be a positive scalar"); elseif (! (isscalar (a) && a > 0)) error ("pmt: a must be a positive scalar"); endif if (nargin == 5) if (! ischar (m)) error ("pmt: `method' must be a string"); endif elseif (nargin == 4) if (ischar (l)) m = l; l = 0; else m = "e"; endif else l = 0; m = "e"; endif p = r * (a - l * (1 + r)^(-n)) / (1 - (1 + r)^(-n)); if (strcmp (m, "b")) p = p / (1 + r); endif endfunction financial/inst/easter.m0000644000175000017500000000511011743274154016425 0ustar carandraugcarandraug## Copyright (C) 2008 Bill Denney ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {[m, d] =} easter (y) ## @deftypefnx {Function File} {datenum =} easter (y) ## ## Return the month (@var{m}) and day (@var{d}) of Easter in the ## Gregorial calendar on a given year or years. ## ## @seealso{holidays} ## @end deftypefn function varargout = easter (y) ## This uses the Meesus/Jones/Butcher Gregorian algorithm as described ## on http://en.wikipedia.org/wiki/Computus#Algorithms a = mod (y, 19); b = floor (y/100); c = mod (y, 100); d = floor (b/4); e = mod (b, 4); f = floor ((b + 8)/25); g = floor ((b - f + 1)/3); h = mod ((19*a+b-d-g+15), 30); i = floor (c/4); k = mod (c, 4); L = mod ((32 + 2*e + 2*i - h - k), 7); m = floor ((a + 11*h + 22*L)/451); mon = floor ((h + L - 7*m + 114)/31); day = 1 + mod ((h + L - 7*m + 114), 31); if nargout == 2 varargout = {mon(:), day(:)}; else varargout{1} = reshape (datenum (y(:), mon(:), day(:)), size (y)); end endfunction ## Tests ## Validate that it calculates the correct date for a decade %!assert(easter(1990), datenum(1990, 4, 15)) %!assert(easter(1991), datenum(1991, 3, 31)) %!assert(easter(1992), datenum(1992, 4, 19)) %!assert(easter(1993), datenum(1993, 4, 11)) %!assert(easter(1994), datenum(1994, 4, 3)) %!assert(easter(1995), datenum(1995, 4, 16)) %!assert(easter(1996), datenum(1996, 4, 7)) %!assert(easter(1997), datenum(1997, 3, 30)) %!assert(easter(1998), datenum(1998, 4, 12)) %!assert(easter(1999), datenum(1999, 4, 4)) ## Validate vector and matrix inputs %!assert(easter([2000 2001]), [datenum(2000, 4, 23) datenum(2001, 4, 15)]) %!assert(easter([2002;2003]), [datenum(2002, 3, 31);datenum(2003, 4, 20)]) %!assert(easter([2004 2005;2006 2007;2008 2009]), [datenum(2004, 4, 11) datenum(2005, 3, 27);datenum(2006, 4, 16) datenum(2007, 4, 8);datenum(2008, 3, 23) datenum(2009, 4, 12)]) %!assert(easter([2002;2003]), [datenum(2002, 3, 31);datenum(2003, 4, 20)]) financial/inst/eomdate.m0000644000175000017500000000253711743256035016570 0ustar carandraugcarandraug## Copyright (C) 2008 Bill Denney ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {@var{e} =} eomdate (@var{y}, @var{m}) ## Return the last day of the month @var{m} for the year @var{y} in ## datenum format. ## @seealso{datenum, datevec, weekday, eomday} ## @end deftypefn function e = eomdate (y, m) if (nargin != 2) print_usage (); endif d = eomday (y, m); e = datenum (y, m, d); endfunction ## Tests ## Leap years %!assert(eomdate(2008, 2), datenum(2008, 2, 29)) %!assert(eomdate(2007, 2), datenum(2007, 2, 28)) ## Vectors %!assert(eomdate([2008 2007], [3 4]), [datenum(2008, 3, 31) datenum(2007, 4, 30)]) %!assert(eomdate([2008;2007], [3;4]), [datenum(2008, 3, 31);datenum(2007, 4, 30)]) financial/inst/busdays.m0000644000175000017500000001230711743256035016620 0ustar carandraugcarandraug## Copyright (C) 2008 Bill Denney ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {@var{bdates} =} busdays (@var{sdate}, @var{edate}) ## @deftypefnx {Function File} {@var{bdates} =} busdays (@var{sdate}, @var{edate}, @var{bdmode}) ## @deftypefnx {Function File} {@var{bdates} =} busdays (@var{sdate}, @var{edate}, @var{bdmode}, @var{holvec}) ## Generate a list of business dates at the end of the periods defined ## between (including) @var{sdate} and @var{edate}. ## ## @var{sdate} is the starting date, @var{edate} is the ending date, ## both are in serial date format (see datenum). @var{bdmode} is the ## business day frequency ("daily", "weekly", "monthly", "quarterly", ## "semiannual", or "annual"); these can be abbreviated by the first ## letter and they may also use an integer corresponding to the order in ## the above list (i.e. "daily" = 1). @var{holvec} is an optional list ## of holidays. If the holidays are not given, then the holidays ## function is used. ## @seealso{holidays, busdate, lbusdate, isbusday, fbusdate, datenum} ## @end deftypefn function bd = busdays (sd, ed, mode=1, hol=[]) if nargin < 2 || nargin > 4 print_usage (); endif if ~isnumeric (sd) sd = datenum (sd); endif if ~isnumeric (ed) ed = datenum (ed); endif if ed < sd error ("busdays: the start date must be less than the end date") endif if isempty (hol) ## make the holidays take into account the whole ending year because ## the day may extend beyond the actual ending date edtmp = datevec (ed); edtmp(2:3) = [12 31]; hol = holidays (sd, datenum (edtmp)); endif ## Convert the mode to the numeric modestr = "dwmqsa"; if ischar (mode) mode = find (lower (mode(1)) == modestr); if isempty (mode) error ("busdays: mode must be one of '%s'", modestr) endif elseif isnumeric (mode) if mode < 1 || mode > length (modestr) error ("busdays: mode must be between 1 and %d", length (modestr)) endif else error ("busdays: mode must be a number or string") endif ## do the computation if mode == 1 ## daily bd = (sd:ed)'(isbusday (sd:ed, hol)); elseif mode < 6 if mode == 2 ## weekly make the start and end dates Fridays and then move back ## from there wd = weekday ([sd;ed]); d = [sd;ed] - wd + 7; ## there are generally not more than one week of holidays at a ## time, but the call to unique will make certain of that. bd = unique (busdate ([d(1):7:d(2)]', -1, hol)); else d = datevec ([sd:ed]); ## unique year and month list within the date range ym = unique (d(:,1:2), "rows"); if mode == 3 ## monthly, do nothing to the ym list elseif mode == 4 ## quarterly if mod (ym(end), 3) != 0 ## make the last month an end of quarter month ym(end) = ym(end) + 3 - mod (ym(end), 3); endif ym(mod (ym(:,2), 3) != 0, :) = []; elseif mode == 5 ## semi-annually if mod (ym(end), 6) != 0 ## make the last month an end of semi-annual month (6, 12) ym(end) = ym(end) + 6 - mod (ym(end), 6); endif ym(mod (ym(:,2), 6) != 0, :) = []; endif bd = lbusdate (ym(:,1), ym(:,2), hol); endif elseif mode == 6 ## annual d = datevec ([sd;ed]); bd = lbusdate ((d(1,1):d(2,1))', 12, hol); else ## this should have been caught before now error ("busdays: invalid mode") endif endfunction ## Tests %!assert (busdays (datenum (2008, 1, 1), datenum (2008, 1, 12)), datenum (2008, 1, [2;3;4;7;8;9;10;11])) %!assert (busdays (datenum (2008, 1, 1), datenum (2008, 1, 12), "d"), datenum (2008, 1, [2;3;4;7;8;9;10;11])) %!assert (busdays (datenum (2001, 1, 2), datenum (2001, 1, 9), "w"), datenum (2001, 1, [5;12])) %!assert (busdays (datenum (2008, 1, 1), datenum (2008, 1, 2), "m"), datenum (2008, 1, 31)) %!assert (busdays (datenum (2008, 1, 1), datenum (2010, 5, 2), "m"), lbusdate ([2008*ones(12,1);2009*ones(12,1);2010*ones(5,1)], [1:12 1:12 1:5]')) %!assert (busdays (datenum (2008, 1, 1), datenum (2008, 1, 2), "q"), datenum (2008, 3, 31)) %!assert (busdays (datenum (2008, 1, 1), datenum (2010, 5, 2), "q"), lbusdate ([2008*ones(4,1);2009*ones(4,1);2010*ones(2,1)], [3:3:12 3:3:12 3 6]')) %!assert (busdays (datenum (2008, 1, 1), datenum (2008, 1, 2), "s"), datenum (2008, 6, 30)) %!assert (busdays (datenum (2008, 1, 1), datenum (2010, 5, 2), "s"), lbusdate ([2008;2008;2009;2009;2010], [6 12 6 12 6]')) %!assert (busdays (datenum (2008, 1, 1), datenum (2011, 1, 2), "a"), datenum ([2008;2009;2010;2011], [12;12;12;12], [31;31;30;30])) financial/inst/highlow.m0000644000175000017500000000522111743301537016602 0ustar carandraugcarandraug## Copyright (C) 2008 Bill Denney ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {@var{h} =} highlow (@var{high}, @var{low}, @var{close}) ## @deftypefnx {Function File} {@var{h} =} highlow (@var{high}, @var{low}, @var{close}, @var{open}) ## @deftypefnx {Function File} {@var{h} =} highlow (@var{high}, @var{low}, @var{close}, @var{open}, @var{color}) ## ## Plot the @var{high}, @var{low}, and @var{close} of a security. The ## @var{close} is plotted as a tick to the right, and if @var{open} is ## given and non-empty, it is plotted as a tick to the left. The color ## can override the default color for the plot. ## ## @seealso{bolling, candle, dateaxis, movavg, pointfig} ## @end deftypefn function h = highlow (high, low, close, open = [], color) if nargin < 3 || nargin > 5 print_usage (); elseif nargin < 5 plotargs = {}; else plotargs = {"color", color}; endif if isempty (high) || isempty (low) || isempty (close) error ("high, low, and close may not be empty") elseif ~(isvector (high) && isvector (low) && isvector (close)) error ("high, low, and close must be vectors") elseif ( (numel (high) != numel (low)) || (numel (high) != numel (close)) ) error ("high, low, and close must have the same number of elements") elseif ( !isempty (open) && (numel (high) != numel (open)) ) error ("open must have the same number of elements as high, low, and close") endif holdstat = ishold (); ## h = hggroup (); ## plotargs(end+1:end+2) = {"parent", h}; hold on; x = (1:length(high)) + 0.5; x = reshape([x;x;nan(size(x))], [], 1); y = reshape([high(:)'; low(:)'; nan(1, length(high))], [], 1); plot(x, y, plotargs{:}); x = 1:length(high); x = reshape([x+0.5;x+1;nan(size(x))], [], 1); y = reshape([close(:)';close(:)';nan(1, length(close))], [], 1); plot(x, y, plotargs{:}); if ! isempty(open) x -= 0.5; y = reshape([open(:)';open(:)';nan(1, length(open))], [], 1); plot(x, y, plotargs{:}); endif if !holdstat hold off; endif endfunction financial/inst/nomrr.m0000644000175000017500000000222611743301537016300 0ustar carandraugcarandraug## Copyright (C) 2008 Bill Denney ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {@var{return} =} nomrr (@var{rate}, @var{numperiods}) ## Compute the nominal rate of return based on a effective @var{rate} ## over a number of periods, @var{numperiods}. ## @seealso{irr, effrr} ## @end deftypefn function rate = nomrr (rate, numperiods) if (nargin != 2) print_usage (); endif rate = numperiods.*((1+rate).^(1./numperiods) - 1); endfunction ## Tests %!assert (nomrr (0.0938, 12), 0.09, 0.00005) financial/inst/onbalvol.m0000644000175000017500000000365511743301537016766 0ustar carandraugcarandraug## Copyright (C) 2008 Bill Denney ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {@var{obv} =} onbalvol (@var{closeprice}, @var{vol}) ## @deftypefnx {Function File} {@var{obv} =} onbalvol ([@var{closeprice} @var{vol}]) ## ## Compute the on balance volume of a security based on its closing ## price (@var{closeprice}) and @var{vol}ume. They may be given as ## separate arguments or as an nx2 matrix. ## ## The output will be a column vector, and the first number in the ## output is always 0. ## ## @seealso{negvolidx, posvolidx} ## @end deftypefn function obv = onbalvol (c, vol) if nargin == 1 % do nothing elseif nargin == 2 c = [c(:) vol(:)]; else print_usage (); endif obv = zeros (size (c, 1), 1); for i = 2:size (c, 1) if c(i,1) > c(i-1,1) obv(i) = obv(i-1) + c(i,2); elseif c(i,1) < c(i-1,1) obv(i) = obv(i-1) - c(i,2); else obv(i) = obv(i-1); endif endfor endfunction ## Tests %!shared c, v, obv %! 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]; %! v = [10 12 23 25 34 12 32 15 15 34 54 12 86 45 32 76 89 13 28]; %! obv = [0 12 35 60 94 82 50 35 50 84 138 150 236 281 249 173 84 97 69]'; %!assert(onbalvol(c, v), obv) %!assert(onbalvol([c' v']), obv) financial/inst/months.m0000644000175000017500000000436411743301537016460 0ustar carandraugcarandraug## Copyright (C) 2008 Bill Denney ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {mos =} months (startdate, enddate) ## @deftypefnx {Function File} {mos =} months (startdate, enddate, endmonthflag) ## ## Return the number of whole months between @var{startdate} and ## @var{enddate}. @var{endmonthflag} defaults to 1. ## ## If @var{endmonthflag} is true, then if both the @var{startdate} and ## the @var{enddate} are end of month dates and @var{enddate} has fewer ## days in the month than @var{startdate}, @var{endmonthflag} = 1 treats ## @var{enddate} as the end of a month, but @var{endmonthflag} = 0 does ## not. ## ## @seealso{yeardays, yearfrac} ## @end deftypefn function mos = months (startdate, enddate, endmonthflag = 1) if (nargin < 2 || nargin > 3) print_usage (); endif s = datevec (startdate); e = datevec (enddate); s_eom = (s(:,3) == eomday(s(:,1), s(:,2))); e_eom = (e(:,3) == eomday(e(:,1), e(:,2))); ## Handle the end of the month correctly dayadj = ((s(:,3) > e(:,3)) & endmonthflag & s_eom & e_eom); mos = 12*(e(:,1) - s(:,1)) + (e(:,2) - s(:,2)) - (s(:,3) > e(:,3)) + dayadj; endfunction ## Tests %!assert(months('may 31 2004', 'jun 30 2004'), 1) %!assert(months({'may 31 2004' 'may 30 2004'}, 'jun 30 2004'), [1;1]) %!assert(months('may 31 2004', 'jun 30 2004', 1), 1) %!assert(months({'may 31 2004' 'may 30 2004'}, 'jun 30 2004', 1), [1;1]) %!assert(months('may 31 2004', 'jun 30 2004', 0), 0) %!assert(months({'may 31 2004' 'may 30 2004'}, 'jun 30 2004', 0), [0;1]) %!assert(months('jun 30 2005', 'june 30 2006'), 12) %!assert(months('jun 30 2005', 'june 29 2006'), 11) financial/inst/fetch.m0000644000175000017500000001201311743301537016227 0ustar carandraugcarandraug## Copyright (C) 2008 Bill Denney ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {@var{data} =} fetch (@var{conn}, @var{symbol}) ## @deftypefnx {@var{data} =} fetch (@dots{}, @var{fields}) ## @deftypefnx {@var{data} =} fetch (@dots{}, @var{date}) ## @deftypefnx {@var{data} =} fetch (@dots{}, @var{fromdate}, @var{todate}) ## @deftypefnx {@var{data} =} fetch (@dots{}, @var{period}) ## @deftypefnx {[@var{data}, @var{fields}] =} fetch (@dots{}) ## ## Download stock data from a connection. ## ## @var{fields} are the data fields to download and must come from the ## set ## @itemize @bullet ## @item "Symbol" ## @item "Last" ## @item "Date" ## @item "Time" ## @item "Change" ## @item "Open" ## @item "High", ## @item "Low" ## @item "Volume" ## @end itemize ## ## As an output, @var{fields} may be different than your request. This ## is because there is mapping of field names from the data source to ## the output, and what is returned is the source mapping to allow ## validation. ## ## @var{date} is the date string or datenum for the requested data. If ## you enter today's date, you will get yesterday's data. @var{fromdate} ## and @var{todate} allow you to specify a date range for the data. ## ## @var{period} (default: "d") allows you to select the period for the ## data which can be any of the below as long as they are supported by ## the associated backend. ## @itemize @bullet ## @item 'd': daily ## @item 'w': weekly ## @item 'm': monthly (Yahoo only) ## @item 'v': dividends (Yahoo only) ## @end itemize ## ## @seealso{yahoo, google} ## @end deftypefn ## FIXME: Actually use the proxy info if given in the connection. ## FIXME: Do not ignore the fields input. function [data fields] = fetch (conn=[], symbol="", varargin) fields = {"Symbol", "Last", "Date", "Time", "Change", "Open", ... "High", "Low", "Volume"}; fromdate = []; todate = []; period = "d"; firstdate = datenum (1900, 1, 1); lastdate = today (); if isempty (conn) ## By default, use yahoo now since it's the only connection ## currently available. conn = yahoo (); endif if isempty (symbol) error ("The ticker symbol must be given") elseif ! ischar (symbol) error ("The symbol must be either a string") endif for i = 1:numel (varargin) if ischar (varargin{i}) && (length (varargin{i}) == 1) period = varargin{i}; elseif iscellstr (varargin{i}) || ischar (varargin{i}) ## if it's a character and it's a valid date, make it into our ## dates if ischar (varargin{i}) thisdate = []; try thisdate = datenum (varargin{i}); if isempty (fromdate) fromdate = thisdate; endif todate = thisdate; end_try_catch endif if isempty (thisdate) fields = varargin{i}; warning ("Fields are currently ignored and all data is returned") endif thisdate = []; elseif isnumeric (varargin{i}) ## it must be our dates if isempty (fromdate) fromdate = varargin{i}; endif todate = varargin{i}; else error ("Invalid input for argument %d", i + 2) endif endfor if isempty (fromdate) fromdate = firstdate; todate = lastdate; endif if strcmpi (conn.url, "http://quote.yahoo.com") [data fields] = fetch_yahoo (conn, symbol, fromdate, todate, period); elseif strcmpi (conn.url, "http://finance.google.com") [data fields] = fetch_google (conn, symbol, fromdate, todate, period); else error ("Unrecgonized connection type") endif endfunction %!shared fgood, dgood %! fgood = {"Date", "Open", "High", "Low", "Close", "Volume", "Adj Close"}; %! dgood = [732501,34.77,34.87,34.25,34.62,15515400,34.62; %! 732500,33.87,34.77,33.72,34.63,16354300,34.63; %! 732499,34.64,34.97,34.03,34.12,13585700,34.12; %! 732498,34.25,35.08,34.20,34.60,16086700,34.60; %! 732494,34.76,34.85,34.22,34.44,9861600,34.44]; %!test %! [d f] = fetch(yahoo(), "yhoo", "01-Jul-2005", "10-Jul-2005"); %! assert(d, dgood, eps); %! assert(f, fgood, eps); ## The test below fails because yahoo gives a different volume on 732498 ##%!xtest ##%! [d f] = fetch(yahoo(), "yhoo", "01-Jul-2005", "10-Jul-2005", "w"); ##%! assert(d, dgood(4:5,:), eps); ##%! assert(f, fgood, eps); financial/inst/fbusdate.m0000644000175000017500000000374511743256035016751 0ustar carandraugcarandraug## Copyright (C) 2008 Bill Denney ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {b =} fbusdate (year, month) ## @deftypefnx {Function File} {b =} fbusdate (year, month, holiday) ## @deftypefnx {Function File} {b =} fbusdate (year, month, holiday, weekend) ## ## Return the datenum of the first business day of the @var{year} and ## @var{month}. @var{holiday} is a vector of datenums that defines the ## holidays observed (the holidays function is used if not given). ## @var{weekend} defines the days of the week that should be considered ## weekends; [1 0 0 0 0 0 1] (default) indicates that Sunday and ## Saturday are holidays. ## ## If any of the optional inputs (@var{holiday}, @var{weekend}) are ## empty, then the default is used. ## ## @seealso{holidays, lbusdate, isbusday, busdate} ## @end deftypefn function rd = fbusdate (y, m, hol, wkend) rd = datenum (y, m, 1); if nargin < 3 hol = []; end if nargin < 4 wkend = []; elseif nargin < 3 || nargin > 4 print_usage (); endif ## Test from the day before the beginning of the month so that the ## first day of the month is captured. rd = busdate (rd-1, 1, hol, wkend); endfunction ## Tests ## A normal day %!assert(fbusdate(2008,2), datenum(2008,2,1)) ## A holiday %!assert(fbusdate(2008,1), datenum(2008,1,2)) ## A weekend %!assert(fbusdate(2008,3), datenum(2008,3,3)) financial/inst/negvolidx.m0000644000175000017500000000624011743301537017142 0ustar carandraugcarandraug## Copyright (C) 2008 Bill Denney ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {@var{nvi} =} negvolidx (@var{closeprice}, @var{vol}) ## @deftypefnx {Function File} {@var{nvi} =} negvolidx ([@var{closeprice} @var{vol}]) ## @deftypefnx {Function File} {@var{nvi} =} negvolidx (@var{closeprice}, @var{vol}, @var{initnvi}) ## @deftypefnx {Function File} {@var{nvi} =} negvolidx ([@var{closeprice} @var{vol}], @var{initnvi}) ## ## Compute the negative volume index of a security based on its closing ## price (@var{closeprice}) and @var{vol}ume. They may be given as ## separate arguments or as an nx2 matrix. If given, the @var{initnvi} ## is the starting value of the nvi (default: 100). ## ## The @var{nvi} will always be a column vector. ## ## @seealso{onbalvol, posvolidx} ## @end deftypefn function nvi = negvolidx (c, vol, initnvi) default_nvi = 100; nvi = zeros (length (c), 1); if isvector (c) if nargin < 2 ## a closing price was given without a volume print_usage (); elseif isscalar (vol) ## probably initnvi was given as the second argument print_usage (); elseif !isvector (vol) print_usage (); elseif length (c) != length (vol) error ("closeprice and vol must be the same length"); endif c = [c(:) vol(:)]; if nargin < 3 nvi(1) = default_nvi; else nvi(1) = initnvi; endif elseif size (c, 2) != 2 error ("If given as a matrix, c must have exactly two columns.") elseif size (c, 2) == 2 if nargin == 2 nvi(1) = vol; else nvi(1) = default_nvi; endif else print_usage (); endif ## Start doing the work for i = 2:size (c, 1) nvi(i) = nvi(i-1) + (c(i,2) < c(i-1,2))*nvi(i-1)*(c(i,1)-c(i-1,1))/c(i-1,1); endfor endfunction ## Tests %!shared c, v, nvia, nvib %! 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]; %! v = [10 12 23 25 34 12 32 15 15 34 54 12 86 45 32 76 89 13 28]; %! nvia = [100 100 100 100 100 99.44349315 99.44349315 98.49559157 98.49559157 98.49559157 98.49559157 98.78565011 98.78565011 100.7353669 98.13574451 98.13574451 98.13574451 99.14355704 99.14355704]'; %! nvib = [5 5 5 5 5 4.972174658 4.972174658 4.924779578 4.924779578 4.924779578 4.924779578 4.939282505 4.939282505 5.036768344 4.906787226 4.906787226 4.906787226 4.957177852 4.957177852]'; %!assert(negvolidx(c, v), nvia, 1e-5) %!assert(negvolidx([c' v']), nvia, 1e-5) %!assert(negvolidx(c, v, 5), nvib, 1e-5) %!assert(negvolidx([c' v'], 5), nvib, 1e-5) financial/inst/mirr.m0000644000175000017500000000325111743301537016113 0ustar carandraugcarandraug## Copyright (C) 2008 Bill Denney ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {@var{return} =} mirr (@var{cashflow}, @var{finrate}, @var{reinvestrate}) ## Compute the modified internal rate of return. ## Take periodic @var{cashflow}s as a vector and the finance rate, ## @var{finrate}, for negative cash flows and a reinvestment rate, ## @var{reinvestrate}, for positive cash flows. ## @seealso{irr, effrr, nomrr, pvvar, xirr} ## @end deftypefn ## Algorithm from ## http://en.wikipedia.org/wiki/Modified_Internal_Rate_of_Return function rate = mirr (flow, finrate, reinvestrate) if (nargin != 3) print_usage (); endif posflow = zeros (size (flow)); negflow = zeros (size (flow)); mask = flow >= 0; posflow(mask) = flow(mask); negflow(!mask) = flow(!mask); n = numel (flow); rate = (-npv (reinvestrate, posflow)*(1+reinvestrate)^n/ (npv (finrate, negflow)*(1+finrate)))^(1/(n-1))-1; endfunction ## Tests %!assert (mirr ([-100000 20000 -10000 30000 38000 50000], 0.09, 0.12), 0.0832, 0.00005) financial/inst/rsindex.m0000644000175000017500000000421511743301537016617 0ustar carandraugcarandraug## Copyright (C) 2008 Bill Denney ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {@var{rsi} =} rsindex (@var{closeprice}) ## @deftypefnx {Function File} {@var{rsi} =} rsindex (@var{closeprice}, @var{nperiods}) ## ## Compute the relative strength index (RSI) of an asset from the vector ## of closing prices (@var{closeprice}). @var{nperiods} defines the ## number of periods that the rsi should be calculated for ## (default: 14). ## ## The beginning of the @var{rsi} is padded with nans to match the size ## of @var{closeprice}. ## ## @end deftypefn function rsi = rsindex (cl, n = 14) if nargin < 1 || nargin > 2 print_usage (); elseif n > length(cl) error ("nperiods must be <= the length of closeprice") elseif ! isvector (cl) error ("closeprice must be a vector") endif diff = cl(2:end) - cl(1:end-1); rsi = nan (size (cl)); for i = n:length (cl) changes = diff(i-n+1:i-1); downs = changes < 0; ups = changes > 0; if isempty (downs) ## prevent division by zero rsi(i) = 100; elseif isempty (ups) rsi(i) = 0; else ups = sum(changes(ups)); downs = -sum(changes(downs)); rsi(i) = 100*(1-1/(1+ups/downs)); endif endfor endfunction ## Tests %!shared c, r %! 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]; %! r = [nan(1, 13) 85.1190 70.235 68.6684 55.6322 53.0414 49.7717]; %!assert(rsindex(c), r, 0.0001) %!assert(rsindex(c'), r', 0.0001) financial/inst/yeardays.m0000644000175000017500000000565311743256035016775 0ustar carandraugcarandraug## Copyright (C) 2008 Bill Denney ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {@var{d} =} yeardays (@var{y}) ## @deftypefnx {Function File} {@var{d} =} yeardays (@var{y}, @var{b}) ## Return the number of days in the year @var{y} with an optional basis ## @var{b}. ## ## Valid bases ## @itemize @bullet ## @item 0 ## actual/actual (default) ## @item 1 ## 30/360 (SIA) ## @item 2 ## actual/360 ## @item 3 ## actual/365 ## @item 4 ## 30/360 (PSA) ## @item 5 ## 30/360 (IDSA) ## @item 6 ## 30/360 (European) ## @item 7 ## actual/365 (Japanese) ## @item 8 ## actual/actual (ISMA) ## @item 9 ## actual/360 (ISMA) ## @item 10 ## actual/365 (ISMA) ## @item 11 ## 30/360E (ISMA) ## @end itemize ## @seealso{days365, days360, daysact, daysdif} ## @end deftypefn function d = yeardays (y, basis) if (nargin == 1) basis = 0; elseif (nargin != 2) print_usage (); endif if isscalar (y) d = zeros (size (basis)); elseif isscalar (basis) ## the rest of the code is much simpler if you can be sure that ## basis is a matrix if y is a matrix basis = basis * ones (size (y)); d = zeros (size (y)); else if ndims (y) == ndims (basis) if ~ all (size (y) == size (basis)) error ("year and basis must be the same size or one must be a scalar"); else d = zeros (size (y)); endif else error ("year and basis must be the same size or one must be a scalar.") endif endif bact = ismember (basis(:), [0 8]); b360 = ismember (basis(:), [1 2 4 5 6 9 11]); b365 = ismember (basis(:), [3 7 10]); badbasismask = ~ (bact | b360 | b365); if any (badbasismask) badbasis = unique (basis(badbasismask)); error ("Unsupported basis: %g\n", badbasis) endif d(bact) = 365 + (eomday(y(bact), 2) == 29); d(b360) = 360; d(b365) = 365; endfunction ## Tests %!assert(yeardays(2000), 366) %!assert(yeardays(2001), 365) %!assert(yeardays(2000:2004), [366 365 365 365 366]) %!assert(yeardays(2000, 0), 366) %!assert(yeardays(2000, 1), 360) %!assert(yeardays(2000, 2), 360) %!assert(yeardays(2000, 3), 365) %!assert(yeardays(2000, 4), 360) %!assert(yeardays(2000, 5), 360) %!assert(yeardays(2000, 6), 360) %!assert(yeardays(2000, 7), 365) %!assert(yeardays(2000, 8), 366) %!assert(yeardays(2000, 9), 360) %!assert(yeardays(2000, 10), 365) %!assert(yeardays(2000, 11), 360) financial/inst/nper.m0000644000175000017500000000417611743301537016115 0ustar carandraugcarandraug## Copyright (C) 1995-1998, 2000, 2002, 2004-2007 Kurt Hornik ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {} nper (@var{r}, @var{p}, @var{a}, @var{l}, @var{method}) ## Return the number of regular payments of @var{p} necessary to ## amortize @var{a} loan of amount @var{a} and interest @var{r}. ## ## The optional argument @var{l} may be used to specify an additional ## lump-sum payment of @var{l} made at the end of the amortization time. ## ## The optional argument @var{method} may be used to specify whether ## payments are made at the end (@var{"e"}, default) or at the beginning ## (@var{"b"}) of each period. ## ## Note that the rate @var{r} is specified as a fraction (i.e., 0.05, ## not 5 percent). ## @seealso{pv, pmt, rate, npv} ## @end deftypefn function n = nper (r, p, a, l, m) if (nargin < 3 || nargin > 5) print_usage (); endif if (! (isscalar (r) && r > -1)) error ("nper: r must be a scalar > -1"); elseif (! isscalar (p)) error ("nper: p must be a scalar"); elseif (! isscalar (a)) error ("nper: a must be a scalar"); endif if (nargin == 5) if (! ischar (m)) error ("nper: `method' must be a string"); endif elseif (nargin == 4) if (ischar (l)) m = l; l = 0; else m = "e"; endif else m = "e"; l = 0; endif if (strcmp (m, "b")) p = p * (1 + r); endif q = (p - r * a) / (p - r * l); if (q > 0) n = - log (q) / log (1 + r); else n = Inf; endif endfunction financial/inst/holidays.m0000644000175000017500000000641611743256035016766 0ustar carandraugcarandraug## Copyright (C) 2008 Bill Denney ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {h =} holidays (startdate, enddate) ## ## Return a vector of datenums that were holidays between ## @var{startdate} and @var{enddate}, inclusive. These holidays are ## trading holidays observed by the NYSE according to its rule 51.10. It ## does not take into account the exceptions for "unusual business ## conditions" or for additional days that have been called as holidays ## for one-time purposes. ## ## The complete list can be found at ## http://www.chronos-st.org/NYSE_Observed_Holidays-1885-Present.html ## ## @seealso{busdate, lbusdate, isbusday, fbusdate} ## @end deftypefn function hol = holidays (sd, ed) sd = datenum (datevec (sd)); ed = datenum (datevec (ed)); ## just get the start and end years and generate all holidays in that range yrs = year(sd):year(ed); hol = []; ## New Year's Day tmphol = datenum (yrs, 1, 1); hol = [hol; tmphol(:)]; ## Martin Luther King Day, the third Monday in January tmphol = nweekdate (3, 2, yrs, 1); hol = [hol; tmphol(:)]; ## Washington's Birthday, the third Monday in February tmphol = nweekdate (3, 2, yrs, 2); hol = [hol; tmphol(:)]; ## Good Friday tmphol = easter (yrs) - 2; hol = [hol; tmphol(:)]; ## Memorial Day, the last Monday in May tmphol = lweekdate (2, yrs, 5); hol = [hol; tmphol(:)]; ## Independence Day, July 4 tmphol = datenum (yrs, 7, 4); hol = [hol; tmphol(:)]; ## Labor Day, the first Monday in September tmphol = nweekdate (1, 2, yrs, 9); hol = [hol; tmphol(:)]; ## Thanksgiving Day, the fourth Thursday in November tmphol = nweekdate (4, 5, yrs, 11); hol = [hol; tmphol(:)]; ## Christmas Day tmphol = datenum (yrs, 12, 25); hol = [hol; tmphol(:)]; ## Adjust for Saturdays and Sundays wd = weekday (hol); if any (wd == 1) hol(wd == 1) = hol(wd == 1) + 1; endif if any (wd == 7) hol(wd == 7) = hol(wd == 7) - 1; endif ## Trim out the days that are not in the date range hol(hol > ed | hol < sd) = []; hol = sort (hol); endfunction ## Tests %!assert(holidays(datenum(2008,1,1), datenum(2008,12,31)), datenum(2008*ones(9,1), [1;1;2;3;5;7;9;11;12], [1;21;18;21;26;4;1;27;25])) ## Test Independence day observing on a Monday (July 5) and Christmas ## observing on a Friday (Dec 24) %!assert(holidays(datenum(2004,1,1), datenum(2004,12,31)), datenum(2004*ones(9,1), [1;1;2;4;5;7;9;11;12], [1;19;16;9;31;5;6;25;24])) %!assert(holidays(datenum(2008,3,5), datenum(2008,3,8)), zeros(0,1)) %!assert(holidays(datenum(2008,3,5), datenum(2008,3,5)), zeros(0,1)) %!assert(holidays(datenum(2008,1,1), datenum(2008,1,1)), datenum(2008,1,1)) financial/inst/month.m0000644000175000017500000000174411743256035016276 0ustar carandraugcarandraug## Copyright (C) 2008 Bill Denney ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {mon =} month (Date) ## ## Returns the day of the month from a serial date number or a date ## string. ## ## @seealso{date, datevec, now, day, year} ## @end deftypefn function t = month (dates) t = datevec (dates); t = t (:,2); endfunction financial/inst/year.m0000644000175000017500000000172211743256035016105 0ustar carandraugcarandraug## Copyright (C) 2008 Bill Denney ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {y =} year (Date) ## ## Returns the year from a serial date number or a date string. ## ## @seealso{date, datevec, now, day, month} ## @end deftypefn function t = year (dates) t = datevec (dates); t = t (:,1); endfunction financial/inst/dateaxis.m0000644000175000017500000000557611743301537016760 0ustar carandraugcarandraug## Copyright (C) 2008 Bill Denney ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {} dateaxis () ## @deftypefnx {Function File} {} dateaxis (@var{ax}) ## @deftypefnx {Function File} {} dateaxis (@var{ax}, @var{dateform}) ## @deftypefnx {Function File} {} dateaxis (@var{ax}, @var{dateform}, @var{startdate}) ## @deftypefnx {Function File} {} dateaxis (@var{h}, ...) ## ## Convert the current axis tick labels (or the axis handle @var{h}) to ## a date format. The axis given by @var{ax} ("x", "y", or "z") will be ## changed; the default is "x". The date format, @var{dateform}, used ## will be either auto-determined or an integer corresponding to the ## date formats in datestr. If @var{startdate} is given, then the first ## tick value on the given axis is assumed to be that date. ## ## @seealso{bolling, candle, highlow, movavg, pointfig} ## @end deftypefn function dateaxis (varargin) ## defaults h = []; ax = "x"; dateform = []; startdate = []; ## check inputs if nargin > 0 if ishandle(varargin{1}) h = varargin{1}; varargin(1) = []; endif if length(varargin) > 0 ax = varargin{1}; endif if length(varargin) > 1 dateform = varargin{2}; endif if length(varargin) > 2 startdate = varargin{3}; if ischar(startdate) startdate = datenum(startdate); elseif !isnumeric(startdate) error ("dateaxis: startdate must be either a datenum or numeric") endif endif if length(varargin) > 3 print_usage (); endif endif if (isempty (h)) h = gca (); endif if isempty(dateform) r = range(get(h, [ax "lim"])); if r < 10/60/24 ## minutes and seconds dateform = 13; elseif r < 2 ## hours dateform = 15; elseif r < 15 ## days dateform = 8; elseif r < 365 ## months dateform = 6; elseif r < 90*12 ## quarters dateform = 27; else ## years dateform = 10; endif endif ticks = get (h, [ax "tick"]); if (!isempty (startdate)) ticks = ticks - ticks(1) + startdate; endif ticks = datestr(ticks, dateform); ticks = mat2cell(ticks, ones(size(ticks,1),1), size(ticks,2)); set (h, [ax "ticklabel"], ticks); endfunction financial/inst/google.m0000644000175000017500000000322011743301537016412 0ustar carandraugcarandraug## Copyright (C) 2008 Bill Denney ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {@var{conn} =} google () ## @deftypefnx {Function File} {@var{conn} =} google (@var{URL}, @var{ipaddress}, @var{port}) ## ## Prepare a Google connection for the fetch command to get Google ## historical quote data. ## ## If given, the @var{URL} must be "http://finance.google.com". The ## @var{ipaddress} and @var{port} is the proxy ipaddress and port. These ## parameters are currently ignored (with a warning if given). ## ## @seealso{fetch, yahoo} ## @end deftypefn ## FIXME: Actually use the proxy info if given. function conn = google (url="http://finance.google.com", ipaddr="", port=[]) if ! strcmpi (url, "http://finance.google.com") error ("url must be 'http://finance.google.com'") elseif ! (isempty (ipaddr) && isempty (port)) warning ("Proxy information is currently ignored") endif conn.url = url; conn.ip = ipaddr; conn.port = port; endfunction financial/inst/vol.m0000644000175000017500000000407111743301537015743 0ustar carandraugcarandraug## Copyright (C) 1995-1998, 2000, 2002, 2005-2007 Friedrich Leisch ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {@var{volat} =} vol (@var{x}, @var{m}, @var{n}) ## Return the volatility @var{volat} of each column of the input matrix @var{x}. ## ## The number of data sets per period is given by @var{m} (e.g. the ## number of data per year if you want to compute the volatility per ## year). The optional parameter @var{n} gives the number of past ## periods used for computation, if it is omitted, a value of 1 is used. ## ## If @var{t} is the number of rows of @var{x}, @code{vol} returns the ## volatility from @code{n*m} to @var{t}. ## ## @end deftypefn function retval = vol (X, m, n) if (nargin < 2) print_usage (); endif [xr, xc] = size (X); if (nargin > 2) if (n * m > xr) error ("vol: I need more data!"); endif else n = 1; if (n * m > xr) error ("vol: I need more data!"); endif endif U = zeros (xr - 1, xc); if (all (X)) U = X ((2 : xr), :) ./ X((1 : (xr-1)), :); else error ("vol: zero element in X"); endif U = log(U); U = U - ones (xr - 1, 1) * sum (U) / (xr - 1); retval = zeros (xr - n * m, xc); retval(1, :) = sumsq (U((1 : n*m), :)); for i = 2 : (xr - n * m) retval(i, :) = retval(i - 1, :) ... - U(i - 1, :).^2 + U(i + n * m - 1, :).^2; endfor retval = sqrt (retval * m / (n * m - 1)); endfunction financial/inst/effrr.m0000644000175000017500000000221711743301537016247 0ustar carandraugcarandraug## Copyright (C) 2008 Bill Denney ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {@var{return} =} effrr (@var{rate}, @var{numperiods}) ## Compute the effective rate of return based on a nominal @var{rate} ## over a number of periods, @var{numperiods}. ## @seealso{irr, nomrr} ## @end deftypefn function rate = effrr (rate, numperiods) if (nargin != 2) print_usage (); endif rate = (1+rate./numperiods).^numperiods - 1; endfunction ## Tests %!assert (effrr (0.09, 12), 0.0938, 0.00005) financial/inst/private/0000755000175000017500000000000011743631067016441 5ustar carandraugcarandraugfinancial/inst/private/fetch_yahoo.m0000644000175000017500000000723211743301537021107 0ustar carandraugcarandraug## Copyright (C) 2008 Bill Denney ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {[@var{data} @var{fields}] =} ## fetch_yahoo (@var{conn}, @var{symbol}, @var{fromdate}, @var{todate}, @var{period}) ## ## Download stock data from yahoo. (Helper for fetch.) ## ## @var{fields} are the data fields returned by Yahoo. ## ## @var{fromdate} and @var{todate} is the date datenum for the requested ## date range. If you enter today's date, you will get yesterday's ## data. ## ## @var{period} (default: "d") allows you to select the period for the ## data which can be any of ## @itemize @bullet ## @item 'd': daily ## @item 'w': weekly ## @item 'm': monthly ## @item 'v': dividends ## @end itemize ## ## @seealso{yahoo, fetch} ## @end deftypefn ## FIXME: Actually use the proxy info if given in the connection. ## FIXME: Do not ignore the fields input. function [data fields] = fetch_yahoo (conn=[], symbol="", fromdate, todate, period="d") if strcmpi (conn.url, "http://quote.yahoo.com") fromdate = datevec (fromdate); todate = datevec (todate); geturl = sprintf (["http://ichart.finance.yahoo.com/table.csv" ... "?s=%s&d=%d&e=%d&f=%d&g=%s&a=%d&b=%d&c=%d&" ... "ignore=.csv"], symbol, todate(2)-1, todate(3), todate(1), period, fromdate(2)-1, fromdate(3), fromdate(1)); ## FIXME: This would be more efficient if csv2cell could work on ## strings instead of files. [f, success, msg] = urlwrite (geturl, tmpnam ()); if ! success error ("Could not write Yahoo data to tmp file:\n%s", msg) endif d = csv2cell (f); unlink(f); ## Pull off the header fields = d(1,:); d(1,:) = []; dates = strvcat (d(:,1)); dates = datenum(str2num(dates(:,1:4)), str2num(dates(:,6:7)), str2num(dates(:,9:10))); data = [dates, cell2mat(d(:,2:end))]; else error ("Non-yahoo connection passed to yahoo fetch") endif endfunction %!shared fgood, dgood %! fgood = {"Date", "Open", "High", "Low", "Close", "Volume", "Adj Close"}; %! dgood = [732501,34.77,34.87,34.25,34.62,15515400,34.62; %! 732500,33.87,34.77,33.72,34.63,16354300,34.63; %! 732499,34.64,34.97,34.03,34.12,13585700,34.12; %! 732498,34.25,35.08,34.20,34.60,16086700,34.60; %! 732494,34.76,34.85,34.22,34.44,9861600,34.44]; %!test %! [d f] = fetch_yahoo (yahoo(), "yhoo", 732494, 732501, "d"); %! assert(d, dgood, eps); %! assert(f, fgood, eps); ## test that the automatic period works %!test %! [d f] = fetch_yahoo (yahoo(), "yhoo", 732494, 732501); %! assert(d, dgood, eps); %! assert(f, fgood, eps); ## The test below fails because yahoo gives a different volume on 732498 ##%!xtest ##%! [d f] = fetch(yahoo(), "yhoo", "01-Jul-2005", "10-Jul-2005", "w"); ##%! assert(d, dgood(4:5,:), eps); ##%! assert(f, fgood, eps); financial/inst/private/fetch_google.m0000644000175000017500000001001111743301537021231 0ustar carandraugcarandraug## Copyright (C) 2008 Bill Denney ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {[@var{data} @var{fields}] =} ## fetch_google (@var{conn}, @var{symbol}, @var{fromdate}, @var{todate}, @var{period}) ## ## Download stock data from google. (Helper for fetch.) ## ## @var{fields} are the data fields returned by Google. ## ## @var{fromdate} and @var{todate} is the date datenum for the requested ## date range. If you enter today's date, you will get yesterday's ## data. ## ## @var{period} (default: "d") allows you to select the period for the ## data which can be any of ## @itemize @bullet ## @item 'd': daily ## @item 'w': weekly ## @end itemize ## ## @seealso{google, fetch} ## @end deftypefn ## FIXME: Actually use the proxy info if given in the connection. ## FIXME: Do not ignore the fields input. function [data fields] = fetch_google (conn=[], symbol="", fromdate, todate, period="d") periods = struct("d", "daily", "w", "weekly"); if strcmpi (conn.url, "http://finance.google.com") fromdatestr = datestr (fromdate); todatestr = datestr (todate); ## http://finance.google.com/finance/historical?q=T&startdate=Sep+1%2C+2007&enddate=Aug+31%2C+2008&histperiod=weekly&output=csv geturl = sprintf (["http://finance.google.com/finance/" ... "historical?" ... "q=%s&startdate=%s&enddate=%s&" ... "histperiod=%s&output=csv"], symbol, fromdatestr, todatestr, periods.(period)); ## FIXME: This would be more efficient if csv2cell could work on ## strings instead of files. [f, success, msg] = urlwrite (geturl, tmpnam ()); if ! success error (["Could not write Google data to tmp file:" ... "\n%s\nURL was:\n%s"], msg, geturl) endif d = csv2cell (f); d{1,1} = d{1,1}(4:end); # Remove byte order mark (BOM) unlink(f); ## Pull off the header fields = d(1,:); d(1,:) = []; ## Put the dates into datenum format data = [datenum(datevec(d(:,1), "dd-mmm-yy")), \ cell2mat(d(:,2:end))]; ## Note that google appears to have an off-by-one error in ## returning historical data, so make sure that we only return the ## requested data and not what Google sent. data((data(:,1) < fromdate) | (data(:,1) > todate), :) = []; else error ("Non-google connection passed to google fetch") endif endfunction %!shared fgood, dgood, wgood %! fgood = {"Date", "Open", "High", "Low", "Close", "Volume"}; %! dgood = [732501,34.77,34.87,34.25,34.62,15296900; %! 732500,33.87,34.77,33.72,34.63,16265900; %! 732499,34.64,34.97,34.03,34.12,13451500; %! 732498,34.25,35.08,34.20,34.60,15845100; %! 732494,34.76,34.85,34.22,34.44,9740300]; %! wgood = [732501,34.25,35.08,33.72,34.62,60859400; %! 732494,35.88,36.24,34.22,34.44,67132100]; %!test %! [d f] = fetch_google (google(), "yhoo", 732494, 732501, "d"); %! assert(d, dgood, eps); %! assert(f, fgood, eps); ## test that the automatic period works %!test %! [d f] = fetch_google (google(), "yhoo", 732494, 732501); %! assert(d, dgood, eps); %! assert(f, fgood, eps); ## Test that weekly works %!test %! [d f] = fetch_google (google(), "yhoo", 732494, 732501, "w"); %! assert(d, wgood, eps); %! assert(f, fgood, eps); financial/inst/busdate.m0000644000175000017500000001013611743256035016573 0ustar carandraugcarandraug## Copyright (C) 2008 Bill Denney ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {b =} busdate (refdate) ## @deftypefnx {Function File} {b =} busdate (refdate, direction) ## @deftypefnx {Function File} {b =} busdate (refdate, direction, holiday) ## @deftypefnx {Function File} {b =} busdate (refdate, direction, holiday, weekend) ## ## Return the datenum of the next or previous business day from ## @var{refdate}. @var{direction} indicates the next day (default) if 1 ## and the previous day if -1. @var{holiday} is a vector of datenums ## that defines the holidays observed (the holidays function is used if ## not given). @var{weekend} defines the days of the week that should ## be considered weekends; [1 0 0 0 0 0 1] (default) indicates that ## Sunday and Saturday are holidays. ## ## If any of the optional inputs (@var{direction}, @var{holiday}, ## @var{weekend}) are empty, then the default is used. ## ## @seealso{holidays, lbusdate, isbusday, fbusdate} ## @end deftypefn function rd = busdate (rd, d, hol, wkend) if ~isnumeric (rd) rd = datenum ( rd); endif if nargin < 2 || isempty (d) d = 1; elseif ~ all (abs (d) == 1) ## People could use other numbers to skip days, but that is not ## supported. error ("directions must all be either 1 or -1.") endif if nargin < 3 hol = []; end if nargin < 4 wkend = []; elseif nargin > 4 print_usage (); endif rd += d; mask = ~isbusday (rd, hol, wkend); while any (mask) ## Only recompute for the days that are not yet business days if isscalar (d) rd(mask) += d; else rd(mask) += d(mask); endif mask(mask) = ~isbusday (rd(mask), hol, wkend); endwhile endfunction ## Tests ## A normal day %!assert(busdate(datenum(2008,1,2)), datenum(2008,1,3)) ## A holiday %!assert(busdate(datenum(2007,12,31)), datenum(2008,1,2)) ## Go over a weekend and start in a weekend %!assert(busdate(datenum(2007,1,5)), datenum(2007,1,8)) %!assert(busdate(datenum(2007,1,6)), datenum(2007,1,8)) ## Backward %!assert(busdate(datenum(2008,1,3), -1), datenum(2008,1,2)) ## Backward holiday %!assert(busdate(datenum(2008,1,2), -1), datenum(2007,12,31)) ## Backward with alternate holidays %!assert(busdate(datenum(2008,1,2), -1, datenum(2007,1,1):datenum(2008,1,1)), datenum(2006,12,29)) ## Multiple dates in both orientations %!assert(busdate([datenum(2008,1,2) datenum(2007,1,1)]), [datenum(2008,1,3) datenum(2007,1,2)]) %!assert(busdate([datenum(2008,1,2) datenum(2007,1,1)], [1 1]), [datenum(2008,1,3) datenum(2007,1,2)]) %!assert(busdate([datenum(2008,1,2) datenum(2007,1,1)], 1), [datenum(2008,1,3) datenum(2007,1,2)]) %!assert(busdate([datenum(2008,1,2);datenum(2007,1,1)], [1;1]), [datenum(2008,1,3);datenum(2007,1,2)]) ## Multiple dates with opposite directions holidays and weekends %!assert(busdate([datenum(2008,1,2);datenum(2007,1,2)], [1;-1]), [datenum(2008,1,3);datenum(2006,12,29)]) ## Alternate weekends %!assert(busdate(datenum(2008,1,2), 1, holidays(datenum(2008,1,1), datenum(2008,1,31)), [1 0 0 0 0 0 0]), datenum(2008,1,3)) %!assert(busdate(datenum(2008,1,4), 1, holidays(datenum(2008,1,1), datenum(2008,1,31)), [1 0 0 0 0 0 0]), datenum(2008,1,5)) %!assert(busdate(datenum(2008,1,5), 1, holidays(datenum(2008,1,1), datenum(2008,1,31)), [1 0 0 0 0 0 0]), datenum(2008,1,7)) %!assert(busdate(datenum(2008,1,6), 1, holidays(datenum(2008,1,1), datenum(2008,1,31)), [1 0 0 0 0 0 0]), datenum(2008,1,7)) %!assert(busdate(datenum(2008,1,1), 1, holidays(datenum(2008,1,1), datenum(2008,1,31)), [1 1 1 1 1 1 0]), datenum(2008,1,5)) financial/inst/hhigh.m0000644000175000017500000000360711743630324016235 0ustar carandraugcarandraug## Copyright (C) 2008 Bill Denney ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {@var{hhv} =} hhigh (@var{data}) ## @deftypefnx {Function File} {@var{hhv} =} hhigh (@var{data}, @var{nperiods}) ## @deftypefnx {Function File} {@var{hhv} =} hhigh (@var{data}, @var{nperiods}, @var{dim}) ## ## Compute the highest high value of @var{data} for the past ## @var{nperiods} (default: 14) across the dimension, @var{dim} ## (default: 1). ## ## @seealso{llow} ## @end deftypefn function hhv = hhigh (data, nperiods = 14, dim = find (size (data) > 1, 1)) if nargin < 1 || nargin > 3 print_usage (); elseif ! isvector (data) ## FIXME error ("cannot yet handle more than one dimensional data") endif if dim > ndims (data) error ("dim cannot be greater than the number of dimensions in data"); endif sz = size (data); hhv = data; for i = 1:sz(dim) hhv(i) = max (data(max (i-nperiods+1, 1):i)); endfor endfunction ## Tests %!shared c, h %! 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 25]; %! h = [22.44 22.61 22.67 22.88 23.36 23.36 23.36 23.36 23.36 23.69 23.77 23.84 24.32 24.8 24.8 24.8 24.8 24.8 24.8 25]; %!assert(hhigh(c), h) %!assert(hhigh(c'), h') financial/inst/hour.m0000644000175000017500000000172611743256035016126 0ustar carandraugcarandraug## Copyright (C) 2008 Bill Denney ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {h =} hour (Date) ## ## Returns the hour from a serial date number or a date string. ## ## @seealso{date, datevec, now, minute, second} ## @end deftypefn function t = hour (dates) t = datevec (dates); t = t (:,4); endfunction financial/inst/movavg.m0000644000175000017500000000640011743301537016440 0ustar carandraugcarandraug## Copyright (C) 2008 Bill Denney ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {} movavg (@var{asset}, @var{lead}, @var{lag}) ## @deftypefnx {Function File} {} movavg (@var{asset}, @var{lead}, @var{lag}, @var{alpha}) ## @deftypefnx {Function File} {[@var{short}, @var{long}] =} movavg (@var{asset}, @var{lead}, @var{lag}, @var{alpha}) ## ## Calculate the @var{lead}ing and @var{lag}ging moving average of an ## @var{asset}. If given, @var{alpha} is the weighting power of the ## delay; 0 (default) is the simple moving average, 0.5 would be the ## square root weighted moving average, 1 would be linear, 2 would be ## squared, ..., and 'e' is the exponential moving average. ## ## If no output is requested the data is plotted. The plots are drawn ## in the following order: asset, lag, lead. If output is requested, no ## plot is generated. ## ## @seealso{bolling, candle, dateaxis, highlow, pointfig} ## @end deftypefn function [varargout] = movavg (asset, lead, lag, alpha = 0) if nargin < 3 || nargin > 4 print_usage (); endif if lead > lag error ("lead must be <= lag") elseif ischar (alpha) if ! strcmpi (alpha, "e") error ("alpha must be 'e' if it is a char"); endif elseif ! isnumeric (alpha) error ("alpha must be numeric or 'e'") endif ## Compute the weights if ischar (alpha) lead = exp(1:lead); lag = exp(1:lag); else lead = (1:lead).^alpha; lag = (1:lag).^alpha; endif ## Adjust the weights to equal 1 lead = lead / sum (lead); lag = lag / sum (lag); short = asset; long = asset; for i = 1:length (asset) if i < length (lead) ## Compute the run-in period r = length (lead) - i + 1:length(lead); short(i) = dot (asset(1:i), lead(r))./sum (lead(r)); else short(i) = dot (asset(i - length(lead) + 1:i), lead); endif if i < length (lag) r = length (lag) - i + 1:length(lag); long(i) = dot (asset(1:i), lag(r))./sum (lag(r)); else long(i) = dot (asset(i - length(lag) + 1:i), lag); endif endfor if nargout > 0 varargout{1} = short; else plot((1:length(asset))', [asset(:), long(:), short(:)]); endif if nargout > 1 varargout{2} = long; endif endfunction ## Tests %!shared a %! a = [1 2 3 2 4 2 1]; %!test %! [s l] = movavg(a, 2, 4); %! assert(s, [1 1.5 2.5 2.5 3 3 1.5]) %! assert(l, [1 1.5 2 2 2.75 2.75 2.25]) %!test %! [s l] = movavg(a', 2, 4); %! assert(s, [1;1.5;2.5;2.5;3;3;1.5]) %! assert(l, [1;1.5;2;2;2.75;2.75;2.25]) %!test %! [s l] = movavg(a, 3, 4, 1); %! assert(s, [3 4.8 7 7 9.5 8 5.5]./3, 10*eps) %! assert(l, [1 11/7 20/9 2.2 3 2.7 2], 10*eps) financial/inst/corr2cov.m0000644000175000017500000000364111743301537016704 0ustar carandraugcarandraug## Copyright (C) 2011 Hong Yu ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {@var{cov} =} corr2cov (@var{sigma}, @var{corr}) ## Convert standard deviation @var{sigma} and correlation coefficients @var{corr} ## to covariance @var{cov}. ## ## Note that the rate @var{r} is specified as a fraction (i.e., 0.05, ## not 5 percent). ## @seealso{corrcoef, cov, cov2corr, std} ## @end deftypefn function ret = corr2cov (sigma, corr) if ( nargin != 2 ) print_usage (); elseif ( rows(corr) != columns(corr) || ndims(corr) != 2 ) error("correlation coefficients must be a NxN matrix"); elseif ( rows(sigma) != 1 || ndims(sigma) != 2 ) error("sigma must be a 1xN vector (single row) with the standard deviation values"); elseif ( columns(sigma) < columns(1) ) error("sigma: must be 1xN \ncorr: must be NxN"); endif sigma = sigma(:); ret = corr .* (sigma * sigma'); endfunction %!demo %! sigma = [ 0.5 2.0 ]; %! corr = [ 1.0 -0.5; -0.5 1.0 ]; %! cov = corr2cov( sigma, corr ) %! %-------------------------------------------------- %! % Input standard deviations and correlation matrix, output covariance %! % matrix %!test %! sigma = [0.5 2.0]; %! corr = [1.0 -0.5; -0.5 1.0]; %! cov = corr2cov( sigma, corr ); %! assert( cov, [ 0.25 -0.5; -0.5 4.0 ] ) financial/inst/x2mdate.m0000644000175000017500000000503111743256035016506 0ustar carandraugcarandraug## Copyright (C) 2008 Bill Denney ## ## This program is free software; you can redistribute it and/or modify it under ## the terms of the GNU General Public License as published by the Free Software ## Foundation; either version 3 of the License, or (at your option) any later ## version. ## ## This program is distributed in the hope that it will be useful, but WITHOUT ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License along with ## this program; if not, see . ## -*- texinfo -*- ## @deftypefn {Function File} {datenums =} x2mdate (exceldatenums) ## @deftypefnx {Function File} {datenums =} x2mdate (exceldatenums, convention) ## @deftypefnx {Function File} {datenums =} x2mdate (exceldatenums, convention, "ExcelBug") ## ## Convert @var{datenums} from the Microsoft Excel date format to the ## format used by @code{datenum}. If set to 0 (default, Excel for ## Windows), @var{convention} specifies to use the Excel 1900 convention ## where Jan 1, 1900 corresponds to Excel serial date number 1. If set ## to 1 (Excel for Mac), @var{convention} specifies to use the Excel ## 1904 convention where Jan 1, 1904 corresponds to Excel serial date ## number 0. ## ## Note that this does not take into account the Excel bug where 1900 is ## considered to be a leap year unless you give the "ExcelBug" option. ## ## Excel does not represent dates prior to 1 January 1900 using this ## format, so a warning will be issued if any dates preceed this date. ## ## @seealso{datenum, x2mdate} ## @end deftypefn function dates = x2mdate (dates, convention, excelbug) if nargin == 1 convention = 0; excelbug = false(); elseif nargin == 2 excelbug = false(); elseif nargin == 3 excelbug = strcmpi(excelbug, "ExcelBug"); else print_usage (); endif if any (dates < 0) warning ("Negative date found, this will not work within MS Excel.") endif if convention == 0 adj = datenum(1900, 1, 1) - 2; elseif convention == 1 adj = datenum(1904, 1, 1); endif if excelbug datemask = (dates < 61); dates(datemask) = dates(datemask) + 1; endif dates = dates + adj; endfunction ## Tests %!assert(x2mdate(39448), datenum(2008, 1, 1)) %!assert(x2mdate([39083 39448]), datenum(2007:2008, 1, 1)) %!assert(x2mdate(2), datenum(1900, 1, 1)) %!assert(x2mdate(1, 0, "ExcelBug"), datenum(1900, 1, 1)) %!assert(x2mdate(0, 1), datenum(1904, 1, 1)) financial/NEWS0000644000175000017500000000314611743277056014521 0ustar carandraugcarandraugSummary of important user-visible changes for financial 0.4.0: ------------------------------------------------------------------- ** The following functions are new at financial 0.4.0: cfconv cfdur corr2cov cov2corr ** The following functions have been imported from the time package which has been removed (it is now simply a dummy package that lists the financial package as its single dependency): busdate busdays datefind datesplit day daysact easter eomdate fbusdate holidays hour isbusday lbusdate lweekdate m2xdate minute month months nweekdate second thirdwednesday today x2mdate year yeardays ** The following functions were made private (`fetch' should be used directly instead): __fetch_google__ __fetch_yahoo__ ** The function `datesplit' (just imported from the time package) has been deprecated in favour of `datevec' from Octave-core. ** The functions `rate' and `irr' should now be compatible with new releases of octave. ** The function `fetch' should now work properly when using google finnance to adapt to the UTF-8 file received. ** The function `dateaxis' should no longer enter in debug mode at the end of its call. ** The package is now dependent on the io package (version 1.0.18 or later) since the functions that it depended of from miscellaneous package have been moved to io. ** Package is no longer automatically loaded. financial/INDEX0000644000175000017500000000077111743274154014611 0ustar carandraugcarandraugfinancial >> Financial Financial cfconv cfdur corr2cov cov2corr effrr fetch fvl fv google hhigh irr llow mirr movavg negvolidx nomrr nper npv onbalvol pmt posvolidx pvl pv rate rsindex taxedrr vol yahoo Plot bolling dateaxis highlow pointfig Time busdate busdays datefind datesplit day daysact easter eomdate fbusdate holidays hour isbusday lbusdate lweekdate m2xdate minute month months nweekdate second thirdwednesday today x2mdate yeardays year financial/DESCRIPTION0000644000175000017500000000063011743631012015505 0ustar carandraugcarandraugName: financial Version: 0.4.0 Date: 2012-04-18 Author: Bill Denney , Kurt Hornik Maintainer: Octave-Forge community Title: Financial Description: Financial manipulation, plotting functions and additional date manipulation tools. Depends: octave (>= 3.0.1), io (>= 1.0.18) Autoload: no License: GPLv3+ Url: http://octave.sf.net financial/COPYING0000644000175000017500000010451311743301537015045 0ustar carandraugcarandraug GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read .