summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorSébastien Villemot <sebastien@debian.org>2018-11-18 07:33:19 -0200
committerSébastien Villemot <sebastien@debian.org>2018-11-18 07:33:19 -0200
commitc56f67e8601f9a06855cf57498babd26e93e2b2c (patch)
treee1cbb778b68f640cc49f2f1d4bbd5b850af3d9ba
Import octave-financial_0.5.3.orig.tar.gz
[dgit import orig octave-financial_0.5.3.orig.tar.gz]
-rw-r--r--COPYING674
-rw-r--r--DESCRIPTION12
-rw-r--r--INDEX89
-rw-r--r--NEWS126
-rw-r--r--inst/@diffusion/diffusion.m84
-rw-r--r--inst/@diffusion/display.m38
-rw-r--r--inst/@diffusion/subsasgn.m47
-rw-r--r--inst/@diffusion/subsref.m43
-rw-r--r--inst/@drift/display.m38
-rw-r--r--inst/@drift/drift.m88
-rw-r--r--inst/@drift/subsasgn.m47
-rw-r--r--inst/@drift/subsref.m43
-rw-r--r--inst/@sde/display.m43
-rw-r--r--inst/@sde/sde.m170
-rw-r--r--inst/@sde/simByEuler.m447
-rw-r--r--inst/@sde/simulate.m83
-rw-r--r--inst/@sde/subsasgn.m77
-rw-r--r--inst/@sde/subsref.m35
-rw-r--r--inst/binprice.m150
-rw-r--r--inst/blkimpv.m73
-rw-r--r--inst/blkprice.m59
-rw-r--r--inst/blsdelta.m72
-rw-r--r--inst/blsgamma.m66
-rw-r--r--inst/blsimpv.m170
-rw-r--r--inst/blslambda.m85
-rw-r--r--inst/blsprice.m81
-rw-r--r--inst/blsrho.m74
-rw-r--r--inst/blstheta.m82
-rw-r--r--inst/blsvega.m66
-rw-r--r--inst/bm.m47
-rw-r--r--inst/bolling.m81
-rw-r--r--inst/busdate.m97
-rw-r--r--inst/busdays.m127
-rw-r--r--inst/candle.m319
-rw-r--r--inst/cev.m49
-rw-r--r--inst/cfconv.m60
-rw-r--r--inst/cfdur.m62
-rw-r--r--inst/cir.m64
-rw-r--r--inst/corr2cov.m55
-rw-r--r--inst/cov2corr.m53
-rw-r--r--inst/dateaxis.m101
-rw-r--r--inst/datefind.m44
-rw-r--r--inst/day.m41
-rw-r--r--inst/daysact.m53
-rw-r--r--inst/easter.m69
-rw-r--r--inst/effrr.m34
-rw-r--r--inst/eomdate.m40
-rw-r--r--inst/fbusdate.m58
-rw-r--r--inst/fv.m74
-rw-r--r--inst/fvl.m42
-rw-r--r--inst/gbm.m58
-rw-r--r--inst/heston.m81
-rw-r--r--inst/hhigh.m54
-rw-r--r--inst/highlow.m71
-rw-r--r--inst/holidays.m176
-rw-r--r--inst/hour.m41
-rw-r--r--inst/hwv.m49
-rw-r--r--inst/irr.m39
-rw-r--r--inst/isbusday.m72
-rw-r--r--inst/lbusdate.m56
-rw-r--r--inst/llow.m52
-rw-r--r--inst/lweekdate.m37
-rw-r--r--inst/m2xdate.m74
-rw-r--r--inst/macd.m87
-rw-r--r--inst/minute.m41
-rw-r--r--inst/mirr.m48
-rw-r--r--inst/month.m46
-rw-r--r--inst/months.m58
-rw-r--r--inst/movavg.m105
-rw-r--r--inst/negvolidx.m82
-rw-r--r--inst/nomrr.m34
-rw-r--r--inst/nper.m75
-rw-r--r--inst/npv.m69
-rw-r--r--inst/nweekdate.m152
-rw-r--r--inst/onbalvol.m59
-rw-r--r--inst/opprofit.m65
-rw-r--r--inst/pmt.m66
-rw-r--r--inst/pointfig.m88
-rw-r--r--inst/posvolidx.m82
-rw-r--r--inst/private/blscheck.m64
-rw-r--r--inst/private/fetch.m157
-rw-r--r--inst/private/fetch_google.m87
-rw-r--r--inst/private/fetch_yahoo.m81
-rw-r--r--inst/private/google.m44
-rw-r--r--inst/private/sdenvars.m49
-rw-r--r--inst/private/yahoo.m44
-rw-r--r--inst/pv.m74
-rw-r--r--inst/pvl.m42
-rw-r--r--inst/rate.m67
-rw-r--r--inst/renko.m124
-rw-r--r--inst/rsindex.m66
-rw-r--r--inst/sdeddo.m57
-rw-r--r--inst/sdeld.m49
-rw-r--r--inst/sdemrd.m85
-rw-r--r--inst/second.m41
-rw-r--r--inst/taxedrr.m38
-rw-r--r--inst/thirdwednesday.m68
-rw-r--r--inst/today.m32
-rw-r--r--inst/vol.m70
-rw-r--r--inst/weeknum.m126
-rw-r--r--inst/x2mdate.m75
-rw-r--r--inst/year.m55
-rw-r--r--inst/yeardays.m111
103 files changed, 8455 insertions, 0 deletions
diff --git a/COPYING b/COPYING
new file mode 100644
index 0000000..94a9ed0
--- /dev/null
+++ b/COPYING
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ 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.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ 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 <http://www.gnu.org/licenses/>.
+
+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:
+
+ <program> Copyright (C) <year> <name of author>
+ 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
+<http://www.gnu.org/licenses/>.
+
+ 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
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
diff --git a/DESCRIPTION b/DESCRIPTION
new file mode 100644
index 0000000..fa552a2
--- /dev/null
+++ b/DESCRIPTION
@@ -0,0 +1,12 @@
+Name: financial
+Version: 0.5.3
+Date: 2018-10-22
+Author: Bill Denney, Kurt Hornik
+Maintainer: Parsiad Azimzadeh <parsiad.azimzadeh@gmail.com>
+Title: Financial
+Description: Monte Carlo simulation, options pricing routines, financial
+ manipulation, plotting functions and additional date manipulation tools.
+Depends: octave (>= 4.4.0), io (>= 2.4.11), statistics (>= 1.4.0)
+Autoload: no
+License: GPLv3+
+Url: http://octave.sf.net
diff --git a/INDEX b/INDEX
new file mode 100644
index 0000000..f41d545
--- /dev/null
+++ b/INDEX
@@ -0,0 +1,89 @@
+financial >> Financial
+Financial
+ cfconv
+ cfdur
+ corr2cov
+ cov2corr
+ effrr
+ fvl
+ fv
+ hhigh
+ irr
+ llow
+ macd
+ mirr
+ movavg
+ negvolidx
+ nomrr
+ nper
+ npv
+ onbalvol
+ pmt
+ posvolidx
+ pvl
+ pv
+ rate
+ rsindex
+ taxedrr
+ vol
+Chart Financial Data
+ bolling
+ candle
+ dateaxis
+ highlow
+ pointfig
+ renko
+Price and Analyze Financial Instruments
+ binprice
+ blkimpv
+ blkprice
+ blsdelta
+ blsgamma
+ blsimpv
+ blslambda
+ blsprice
+ blsrho
+ blstheta
+ blsvega
+ opprofit
+Stochastic Differential Equation (SDE) Models
+ @diffusion/diffusion
+ @drift/drift
+ @sde/sde
+ @sde/simByEuler
+ @sde/simulate
+ sdeddo
+ sdeld
+ sdemrd
+ bm
+ cev
+ cir
+ gbm
+ heston
+ hwv
+Time
+ busdate
+ busdays
+ datefind
+ day
+ daysact
+ easter
+ eomdate
+ fbusdate
+ holidays
+ hour
+ isbusday
+ lbusdate
+ lweekdate
+ m2xdate
+ minute
+ month
+ months
+ nweekdate
+ second
+ thirdwednesday
+ today
+ weeknum
+ x2mdate
+ yeardays
+ year
diff --git a/NEWS b/NEWS
new file mode 100644
index 0000000..9c39ae0
--- /dev/null
+++ b/NEWS
@@ -0,0 +1,126 @@
+Summary of important user-visible changes for financial 0.5.3:
+--------------------------------------------------------------
+
+ ** Due to Google retiring the option to download financial
+ data, the `fetch` function has been removed entirely.
+
+Summary of important user-visible changes for financial 0.5.1:
+--------------------------------------------------------------
+
+ ** The following functions are new:
+
+ candle
+
+ ** A bug in the `fetch` function that broke retrieving
+ financial data from Google is now fixed.
+
+ ** Due to Yahoo retiring the option to download financial
+ data, Yahoo support in the `fetch` function has now been
+ removed.
+
+
+Summary of important user-visible changes for financial 0.5.0:
+--------------------------------------------------------------
+
+ ** The following classes for Monte Carlo methods are new (see
+ `help @sde/simulate` for example usage):
+
+ @sde
+ @drift
+ @diffusion
+
+ ** The following functions are new:
+
+ binprice
+ blkimpv
+ blkprice
+ blsdelta
+ blsgamma
+ blsimpv
+ blslambda
+ blsprice
+ blsrho
+ blstheta
+ blsvega
+ bm
+ cev
+ cir
+ gbm
+ heston
+ hwv
+ macd
+ opprofit
+ renko
+ sdeddo
+ sdeld
+ sdemrd
+ weeknum
+
+ ** `isbusday' has been fixed to accept non-integer values.
+
+ ** `holidays' has been changed to include past dates where the NYSE
+ was closed due to exceptional reasons.
+
+ ** `holidays' has been fixed to not count New Year's holidays when it
+ falls on a Saturday (Saturday holidays should be shifted to the
+ previous Friday except when it crosses a calendar year).
+
+ ** The function month now also returns a string with the 3 letter
+ abbreviation of the month number. The functions, year, month, day,
+ hour, minute, and second, all accept an optional input argument
+ to specify the format of an input date string.
+
+ ** The period option of `fetch' no longer accepts weekly when using
+ Google as the backend (Google Finance no longer supports weekly
+ historical prices).
+
+ ** The following functions had minor bug fixes unlikely to create
+ different results from previous versions:
+
+ rate
+
+ ** The function datesplit() has been deprecated in the previous release
+ of the Financial package and have now been removed.
+
+
+Summary 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.
diff --git a/inst/@diffusion/diffusion.m b/inst/@diffusion/diffusion.m
new file mode 100644
index 0000000..15529fb
--- /dev/null
+++ b/inst/@diffusion/diffusion.m
@@ -0,0 +1,84 @@
+## Copyright (C) 2015 Parsiad Azimzadeh <parsiad.azimzadeh@gmail.com>
+##
+## This program is free software; you can redistribute it and/or modify it under
+## the terms of the GNU Lesser 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 Lesser General Public License
+## for more details.
+##
+## You should have received a copy of the GNU Lesser General Public License
+## along with this program; if not, see <http://www.gnu.org/licenses/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function File} {@var{DiffusionRate} =} diffusion (@var{Alpha}, @var{Sigma})
+## Creates an object to represent the diffusion rate of a stochastic
+## differential equation (SDE).
+##
+## @center @var{DiffusionRate}(t, X_t) = diag(X_t.^Alpha(t)) * V(t)
+## @center dX_t = DriftRate(t, X_t)dt + @var{DiffusionRate}(t, X_t)dW_t.
+##
+## @itemize
+## @item (X_t) is an NVARS-dimensional process;
+## @item (W_t) is an NBROWNS-dimensional Wiener process.
+## @end itemize
+##
+## @itemize
+## @item
+## Variable: @var{Alpha} An NVARS-by-1 vector or a function. As a function,
+## @var{Alpha} returns an NVARS-by-1 vector and has either exactly one input
+## (time: @var{Alpha}(t)) or exactly two inputs (time and space:
+## @var{Alpha}(t, X_t)).
+## @item
+## Variable: @var{Sigma} An NVARS-by-NBROWNS matrix or a function. As a
+## function, @var{Sigma} returns an NVARS-by-NBROWNS matrix and has either
+## exactly one input (time: @var{Sigma}(t)) or exactly two inputs (time and
+## space: @var{Sigma}(t, X_t)).
+## @end itemize
+##
+## @seealso{drift}
+## @end deftypefn
+
+function DiffusionRate = diffusion (Alpha, Sigma)
+
+ ## Check number of arguments
+ if (nargin != 2)
+ print_usage();
+ endif
+
+ if (iscolumn (Alpha) && isreal (Alpha))
+ DiffusionRate.Alpha = @(t, X) Alpha;
+ DiffusionRate.IsAlphaConstant = true;
+ elseif (isa (Alpha, "function_handle") && nargin (Alpha) == 1)
+ DiffusionRate.Alpha = @(t, X) Alpha(t);
+ DiffusionRate.IsAlphaConstant = false;
+ elseif (isa (Alpha, "function_handle") && nargin (Alpha) == 2)
+ DiffusionRate.Alpha = Alpha;
+ DiffusionRate.IsAlphaConstant = false;
+ else
+ error ("diffusion: Alpha must either be a real column vector or a function of one or two arguments returning such a vector.");
+ endif
+
+ if (ismatrix (Sigma) && isreal (Sigma) && ((! isreal (Alpha)) || size (Sigma, 1) == size (Alpha, 1)))
+ DiffusionRate.Sigma = @(t, X) Sigma;
+ DiffusionRate.IsSigmaConstant = true;
+ elseif (isa (Sigma, "function_handle") && nargin (Sigma) == 1)
+ DiffusionRate.Sigma = @(t, X) Sigma(t);
+ DiffusionRate.IsSigmaConstant = false;
+ elseif (isa (Sigma, "function_handle") && nargin (Sigma) == 2)
+ DiffusionRate.Sigma = Sigma;
+ DiffusionRate.IsSigmaConstant = false;
+ else
+ error ("diffusion: Sigma must either be a real matrix with number of rows equal to the dimension of Alpha or a function of one or two arguments returning such a matrix.");
+ endif
+
+ DiffusionRate.Rate = @(t, X) bsxfun (@times, DiffusionRate.Sigma (t, X), ...
+ bsxfun (@power, X, DiffusionRate.Alpha (t, X)));
+
+ DiffusionRate = class (DiffusionRate, "diffusion");
+
+endfunction
+
diff --git a/inst/@diffusion/display.m b/inst/@diffusion/display.m
new file mode 100644
index 0000000..9f3ba3d
--- /dev/null
+++ b/inst/@diffusion/display.m
@@ -0,0 +1,38 @@
+## Copyright (C) 2015 Parsiad Azimzadeh <parsiad.azimzadeh@gmail.com>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+function display (DiffusionRate)
+
+ if (DiffusionRate.IsAlphaConstant)
+ AlphaString = mat2str (DiffusionRate.Alpha (0., 0.));
+ else
+ AlphaString = func2str (DiffusionRate.Alpha);
+ endif
+
+ if (DiffusionRate.IsSigmaConstant)
+ SigmaString = mat2str (DiffusionRate.Sigma (0., 0.));
+ else
+ SigmaString = func2str (DiffusionRate.Sigma);
+ endif
+
+ printf ("\n\
+ Class DIFFUSION: Diffusion Rate Specification\n\
+ ---------------------------------------------\n\
+ Rate: %s\n\
+ Alpha: %s\n\
+ Sigma: %s\n\n",
+ func2str (DiffusionRate.Rate), AlphaString, SigmaString);
+
+endfunction
diff --git a/inst/@diffusion/subsasgn.m b/inst/@diffusion/subsasgn.m
new file mode 100644
index 0000000..9343313
--- /dev/null
+++ b/inst/@diffusion/subsasgn.m
@@ -0,0 +1,47 @@
+## Copyright (C) 2015 Parsiad Azimzadeh <parsiad.azimzadeh@gmail.com>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+function DiffusionRate = subsasgn (DiffusionRate, idx, value)
+
+ if (! isa (DiffusionRate, "diffusion"))
+ error ("object must be of the diffusion class but '%s' was used", class (DiffusionRate));
+ elseif (! strcmp (idx(1).type, ".") || numel (idx) > 1)
+ error ("incorrect syntax to reference diffusion object. Use obj.prop to access properties.");
+ endif
+
+ if (DiffusionRate.IsAlphaConstant)
+ Alpha = DiffusionRate.Alpha (0., 0.);
+ else
+ Alpha = DiffusionRate.Alpha;
+ endif
+
+ if (DiffusionRate.IsSigmaConstant)
+ Sigma = DiffusionRate.Sigma (0., 0.);
+ else
+ Sigma = DiffusionRate.Sigma;
+ endif
+
+ switch (idx.subs)
+ case "Alpha"
+ DiffusionRate = diffusion (value, Sigma);
+ case "Sigma"
+ DiffusionRate = diffusion (Alpha, value);
+ case "Rate"
+ error ("diffusion: 'Rate' is private");
+ otherwise
+ error ("diffusion: unknown property '%s'", idx.subs);
+ endswitch
+
+endfunction
diff --git a/inst/@diffusion/subsref.m b/inst/@diffusion/subsref.m
new file mode 100644
index 0000000..52a0951
--- /dev/null
+++ b/inst/@diffusion/subsref.m
@@ -0,0 +1,43 @@
+## Copyright (C) 2015 Parsiad Azimzadeh <parsiad.azimzadeh@gmail.com>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+function v = subsref (DiffusionRate, idx)
+
+ if (! isa (DiffusionRate, "diffusion"))
+ error ("object must be of the diffusion class but '%s' was used", class (DiffusionRate));
+ elseif (! strcmp (idx(1).type, ".") || numel (idx) > 1)
+ error ("incorrect syntax to reference diffusion object. Use obj.prop to access properties.");
+ endif
+
+ switch (idx.subs)
+ case "Alpha"
+ if (DiffusionRate.IsAlphaConstant)
+ v = DiffusionRate.Alpha (0., 0.);
+ else
+ v = DiffusionRate.Alpha;
+ endif
+ case "Sigma"
+ if (DiffusionRate.IsSigmaConstant)
+ v = DiffusionRate.Sigma (0., 0.);
+ else
+ v = DiffusionRate.Sigma;
+ endif
+ case "Rate"
+ v = DiffusionRate.Rate;
+ otherwise
+ error ("diffusion: unknown property '%s'", idx.subs);
+ endswitch
+
+endfunction
diff --git a/inst/@drift/display.m b/inst/@drift/display.m
new file mode 100644
index 0000000..1d57150
--- /dev/null
+++ b/inst/@drift/display.m
@@ -0,0 +1,38 @@
+## Copyright (C) 2015 Parsiad Azimzadeh <parsiad.azimzadeh@gmail.com>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+function display (DriftRate)
+
+ if (DriftRate.IsAConstant)
+ AString = mat2str (DriftRate.A (0., 0.));
+ else
+ AString = func2str (DriftRate.A);
+ endif
+
+ if (DriftRate.IsBConstant)
+ BString = mat2str (DriftRate.B (0., 0.));
+ else
+ BString = func2str (DriftRate.B);
+ endif
+
+ printf ("\n\
+ Class DRIFT: Drift Rate Specification\n\
+ -------------------------------------\n\
+ Rate: %s\n\
+ A: %s\n\
+ B: %s\n\n",
+ func2str (DriftRate.Rate), AString, BString);
+
+endfunction
diff --git a/inst/@drift/drift.m b/inst/@drift/drift.m
new file mode 100644
index 0000000..ca87681
--- /dev/null
+++ b/inst/@drift/drift.m
@@ -0,0 +1,88 @@
+## Copyright (C) 2015 Parsiad Azimzadeh <parsiad.azimzadeh@gmail.com>
+##
+## This program is free software; you can redistribute it and/or modify it under
+## the terms of the GNU Lesser 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 Lesser General Public License
+## for more details.
+##
+## You should have received a copy of the GNU Lesser General Public License
+## along with this program; if not, see <http://www.gnu.org/licenses/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function File} {@var{DriftRate} =} drift (@var{A}, @var{B})
+## Creates an object to represent the drift rate of a stochastic differential
+## equation (SDE).
+##
+## @center @var{DriftRate}(t, X_t) = A(t) + B(t) * X_t
+## @center dX_t = @var{DriftRate}(t, X_t)dt + DiffusionRate(t, X_t)dW_t.
+##
+## @itemize
+## @item (X_t) is an NVARS-dimensional process;
+## @item (W_t) is an NBROWNS-dimensional Wiener process.
+## @end itemize
+##
+## @itemize
+## @item
+## Variable: @var{A} An NVARS-by-1 vector or a function. As a function, @var{A}
+## returns an NVARS-by-1 vector and has either exactly one input (time:
+## @var{A}(t)) or exactly two inputs (time and space: @var{A}(t, X_t)).
+## @item
+## Variable: @var{B} An NVARS-by-NVARS matrix or a function. As a function,
+## @var{B} returns an NVARS-by-NVARS matrix and has either exactly one input
+## (time: @var{B}(t)) or exactly two inputs (time and space: @var{B}(t, X_t)).
+## @end itemize
+##
+## @seealso{diffusion}
+## @end deftypefn
+
+function DriftRate = drift (A, B)
+
+ ## Check number of arguments
+ if (nargin != 2)
+ print_usage();
+ endif
+
+ if (iscolumn (A) && isreal (A))
+ DriftRate.A = @(t, X) A;
+ DriftRate.IsAConstant = true;
+ elseif (isa (A, "function_handle") && nargin (A) == 1)
+ DriftRate.A = @(t, X) A(t);
+ DriftRate.IsAConstant = false;
+ elseif (isa (A, "function_handle") && nargin (A) == 2)
+ DriftRate.A = A;
+ DriftRate.IsAConstant = false;
+ else
+ error ("drift: A must either be a real column vector or a function of one or two arguments returning such a vector.");
+ endif
+
+ if (ismatrix (B) && issquare (B) && isreal (B) && ((! isreal (A)) || size (B, 1) == size (A, 1)) )
+ DriftRate.B = @(t, X) B;
+ DriftRate.IsBConstant = true;
+ elseif (isa (B, "function_handle") && nargin (B) == 1)
+ DriftRate.B = @(t, X) B(t);
+ DriftRate.IsBConstant = false;
+ elseif (isa (B, "function_handle") && nargin (B) == 2)
+ DriftRate.B = B;
+ DriftRate.IsBConstant = false;
+ else
+ error ("drift: B must either be a real square matrix of order equal to the dimension of A or a function of one or two arguments returning such a matrix.");
+ endif
+
+ DriftRate.Rate = @(t, X) reshape ( ...
+ bsxfun ( ...
+ @plus, ...
+ DriftRate.A (t, X), ...
+ DriftRate.B (t, X) * reshape (X, [size(X, 1), size(X, 3)]) ...
+ ), ...
+ [size(X, 1), 1, size(X, 3)] ...
+ );
+
+ DriftRate = class (DriftRate, "drift");
+
+endfunction
+
diff --git a/inst/@drift/subsasgn.m b/inst/@drift/subsasgn.m
new file mode 100644
index 0000000..b9f9de0
--- /dev/null
+++ b/inst/@drift/subsasgn.m
@@ -0,0 +1,47 @@
+## Copyright (C) 2015 Parsiad Azimzadeh <parsiad.azimzadeh@gmail.com>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+function DriftRate = subsasgn (DriftRate, idx, value)
+
+ if (! isa (DriftRate, "drift"))
+ error ("object must be of the drift class but '%s' was used", class (DriftRate));
+ elseif (! strcmp (idx(1).type, ".") || numel (idx) > 1)
+ error ("incorrect syntax to reference drift object. Use obj.prop to access properties.");
+ endif
+
+ if (DriftRate.IsAConstant)
+ A = DriftRate.A (0., 0.);
+ else
+ A = DriftRate.A;
+ endif
+
+ if (DriftRate.IsBConstant)
+ B = DriftRate.B (0., 0.);
+ else
+ B = DriftRate.B;
+ endif
+
+ switch (idx.subs)
+ case "A"
+ DriftRate = drift (value, B);
+ case "B"
+ DriftRate = drift (A, value);
+ case "Rate"
+ error ("drift: 'Rate' is private");
+ otherwise
+ error ("drift: unknown property '%s'", idx.subs);
+ endswitch
+
+endfunction
diff --git a/inst/@drift/subsref.m b/inst/@drift/subsref.m
new file mode 100644
index 0000000..8048a30
--- /dev/null
+++ b/inst/@drift/subsref.m
@@ -0,0 +1,43 @@
+## Copyright (C) 2015 Parsiad Azimzadeh <parsiad.azimzadeh@gmail.com>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+function v = subsref (DriftRate, idx)
+
+ if (! isa (DriftRate, "drift"))
+ error ("object must be of the drift class but '%s' was used", class (DriftRate));
+ elseif (! strcmp (idx(1).type, ".") || numel (idx) > 1)
+ error ("incorrect syntax to reference drift object. Use obj.prop to access properties.");
+ endif
+
+ switch (idx.subs)
+ case "A"
+ if (DriftRate.IsAConstant)
+ v = DriftRate.A (0., 0.);
+ else
+ v = DriftRate.A;
+ endif
+ case "B"
+ if (DriftRate.IsBConstant)
+ v = DriftRate.B (0., 0.);
+ else
+ v = DriftRate.B;
+ endif
+ case "Rate"
+ v = DriftRate.Rate;
+ otherwise
+ error ("drift: unknown property '%s'", idx.subs);
+ endswitch
+
+endfunction
diff --git a/inst/@sde/display.m b/inst/@sde/display.m
new file mode 100644
index 0000000..767cf59
--- /dev/null
+++ b/inst/@sde/display.m
@@ -0,0 +1,43 @@
+## Copyright (C) 2015 Carnë Draug <carandraug+dev@gmail.com>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+function display (SDE)
+
+ NVARS = size (SDE.StartState, 1);
+ NBROWNS = size (SDE.Diffusion (0, ones (NVARS, 1)), 2);
+
+ if (isa (SDE.Correlation, "function_handle"))
+ CorrelationString = func2str (SDE.Correlation);
+ else
+ CorrelationString = mat2str (SDE.Correlation);
+ endif
+
+ printf ("\n\
+ Class SDE: Stochastic Differential Equation\n\
+ -------------------------------------------\n\
+ Dimensions: State = %d, Brownian = %d\n\
+ -------------------------------------------\n\
+ StartTime: %f\n\
+ StartState: %s\n\
+ Correlation: %s\n\
+ Drift: %s\n\
+ Diffusion: %s\n\
+ Simulation: %s\n\n",
+ NVARS, NBROWNS,
+ SDE.StartTime, mat2str (SDE.StartState), CorrelationString,
+ func2str (SDE.Drift), func2str (SDE.Diffusion),
+ func2str (SDE.Simulation));
+
+endfunction
diff --git a/inst/@sde/sde.m b/inst/@sde/sde.m
new file mode 100644
index 0000000..16c2d55
--- /dev/null
+++ b/inst/@sde/sde.m
@@ -0,0 +1,170 @@
+## Copyright (C) 2015 Parsiad Azimzadeh <parsiad.azimzadeh@gmail.com>
+##
+## This program is free software; you can redistribute it and/or modify it under
+## the terms of the GNU Lesser 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 Lesser General Public License
+## for more details.
+##
+## You should have received a copy of the GNU Lesser General Public License
+## along with this program; if not, see <http://www.gnu.org/licenses/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function File} {@var{SDE} =} sde (@var{DriftRate}, @var{DiffusionRate})
+## @deftypefnx {Function File} {@var{SDE} =} sde (@var{DriftRate}, @var{DiffusionRate}, @var{OptionName}, @var{OptionValue}, @dots{})
+## Creates an object to represent a stochastic differential equation (SDE).
+##
+## @center dX_t = @var{DriftRate}(t, X_t)dt + @var{DiffusionRate}(t, X_t)dW_t.
+##
+## @itemize
+## @item (X_t) is an NVARS-dimensional process;
+## @item (W_t) is an NBROWNS-dimensional Wiener process.
+## @end itemize
+##
+## @itemize
+## @item
+## Variable: @var{DriftRate} A drift object or function that returns an
+## NVARS-by-1 vector.
+## @item
+## Variable: @var{DiffusionRate} A diffusion object or function that returns an
+## NVARS-by-NBROWNS matrix.
+## @end itemize
+##
+## A list of options recognized by sde are given below:
+## @itemize
+## @item StartTime - Time of the first observation. If unspecified, the default
+## is 0.
+## @item StartState - Scalar, NVARS-dimensional column vector, or
+## NVARS-by-NTRIALS matrix of initial values of the state
+## variables.
+## If unspecified, X_0 is taken to be a vector of ones.
+## @item Correlation - NBROWNS-by-NBROWNS real symmetric positive definite
+## matrix specifying correlations between Wiener processes.
+## For nonconstant correlation, a function of time returning
+## an NBROWNS-by-NBROWNS matrix can be specified.
+## If unspecified, the identity matrix is used.
+## @item Simulation - Function handle pointing to simulation method.
+## If unspecified, simByEuler is used.
+## @end itemize
+##
+## @seealso{drift, diffusion}
+## @end deftypefn
+
+function SDE = sde (DriftRate, DiffusionRate, varargin)
+
+ ## Check number of arguments
+ if (nargin < 2)
+ print_usage();
+ elseif (mod (nargin, 2) == 1)
+ error ("sde: optional arguments must be specified in key-value pairs");
+ endif
+
+ ## Default parameters
+ SDE.StartTime = 0.;
+ SDE.Simulation = @simByEuler;
+
+ if (isa (DriftRate, "drift"))
+ SDE.Drift = DriftRate.Rate;
+ elseif (isa (DriftRate, "function_handle") && nargin (DriftRate) == 2)
+ SDE.Drift = DriftRate;
+ else
+ error ("sde: DRIFTRATE must be an object of the drift class or a function with two inputs");
+ endif
+
+ if (isa (DiffusionRate, "diffusion"))
+ SDE.Diffusion = DiffusionRate.Rate;
+ elseif (isa (DiffusionRate, "function_handle") && nargin (DiffusionRate) == 2)
+ SDE.Diffusion = DiffusionRate;
+ else
+ error ("sde: DIFFUSIONRATE must be an object of the drift class or a function with two inputs");
+ endif
+
+ ## Parse options
+ UserSpecifiedStartState = false;
+ UserSpecifiedCorrelation = false;
+ for i = 1:length(varargin)/2
+ key = varargin{2*i-1};
+ value = varargin{2*i};
+ if (! (ischar (key) && isvector (key)))
+ error ("sde: key must be a string");
+ endif
+ switch (key)
+ case "StartTime"
+ if (! (isscalar (value) && isreal (value)))
+ error ("sde: StartTime must be a real scalar");
+ endif
+ SDE.StartTime = value;
+ case "StartState"
+ if ((! isreal (value)) || isempty (value))
+ error ("sde: StartState must be a real scalar, vector, or matrix (nonempty)");
+ endif
+ SDE.StartState = value;
+ UserSpecifiedStartState = true;
+ case "Correlation"
+ if (! (isa (value, "function_handle") || (isreal (value) && issymmetric (value) && isdefinite (value))))
+ error ("sde: Correlation must be a real symmetric positive definite matrix or a function of time that returns such a matrix");
+ endif
+ SDE.Correlation = value;
+ UserSpecifiedCorrelation = true;
+ case "Simulation"
+ if (! isa (value, "function_handle"))
+ error ("sde: Simulate must be a function handle");
+ endif
+ SDE.Simulation = value;
+ otherwise
+ error ("sde: unrecognized option %s", key);
+ endswitch
+ endfor
+
+ ## Infer default StartState if unspecified
+ if (! UserSpecifiedStartState)
+ Resolved = false;
+
+ if (isa (DriftRate, "drift"))
+ Resolved = true;
+ if (isnumeric (DriftRate.A))
+ SDE.StartState = ones (rows (DriftRate.A), 1);
+ elseif (isnumeric (DriftRate.B))
+ SDE.StartState = ones (rows (DriftRate.B), 1);
+ else
+ Resolved = false;
+ endif
+ endif
+
+ if ((! Resolved) && isa (DiffusionRate, "diffusion"))
+ Resolved = true;
+ if (isnumeric (DiffusionRate.Alpha))
+ SDE.StartState = ones (rows (DiffusionRate.Alpha), 1);
+ elseif (isnumeric (DiffusionRate.Sigma))
+ SDE.StartState = ones (rows (DiffusionRate.Sigma), 1);
+ else
+ Resolved = false;
+ endif
+ endif
+
+ if (! Resolved)
+ error ("sde: cannot resolve NVARS; you must specify the StartState option explicitly");
+ endif
+ endif
+
+ ## Use the default correlation matrix
+ if (! UserSpecifiedCorrelation)
+ ## Infer the size of NVARS and NBROWNS
+ NVARS = size (SDE.StartState, 1);
+ NBROWNS = size (SDE.Diffusion (0, ones (NVARS, 1)), 2);
+ SDE.Correlation = eye (NBROWNS, NBROWNS);
+ endif
+
+ SDE = class (SDE, "sde");
+
+endfunction
+
+## Test input validation
+%!error sde ()
+%!error sde (1)
+%!error sde (1, 2)
+%!error sde (1, 2, "OptionName")
diff --git a/inst/@sde/simByEuler.m b/inst/@sde/simByEuler.m
new file mode 100644
index 0000000..5c88339
--- /dev/null
+++ b/inst/@sde/simByEuler.m
@@ -0,0 +1,447 @@
+## Copyright (C) 2015 Parsiad Azimzadeh <parsiad.azimzadeh@gmail.com>
+##
+## This program is free software; you can redistribute it and/or modify it under
+## the terms of the GNU Lesser 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 Lesser General Public License
+## for more details.
+##
+## You should have received a copy of the GNU Lesser General Public License
+## along with this program; if not, see <http://www.gnu.org/licenses/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function File} {[@var{Paths}, @var{Times}, @var{Z}] =} simByEuler (@var{SDE}, @var{Periods}, @var{OptionName}, @var{OptionValue}, @dots{})
+## Simulates a stochastic differential equation (SDE) using Euler timestepping.
+##
+## @itemize
+## @item
+## Variable: @var{SDE} An sde object.
+## @item
+## Variable: @var{Periods} Number of simulation periods.
+## @end itemize
+##
+## A list of options recognized by simByEuler are given below:
+## @itemize
+## @item NTRIALS - Number of sample paths to use in simulation.
+## If unspecified, the default is 1.
+## @item DeltaTime - Scalar or NPERIODS-dimensional vector of timesteps.
+## If unspecified, the default is 1.
+## @item NSTEPS - Number of intervals to subdivide each period in.
+## If unspecified, the default is 1.
+## @item Antithetic - Logical flag specifying if antithetic variates, a
+## variance reduction technique, should be used.
+## This value is ignored when Z is specified (see below).
+## If unspecified, the default is false.
+## @item Z - (NPERIODS * NSTEPS)-by-NBROWNS-by-NTRIALS three-dimensional array
+## of random samples to use in the simulation.
+## Alternatively, a function returning an NBROWNS-dimensional column
+## vector can be specified, with inputs:
+## @itemize
+## @item A real-valued observation time t;
+## @item An NVARS-dimensional state vector X_t.
+## @end itemize
+## @item StorePaths - Logical flag specifying whether or not to store sample
+## paths.
+## If false, @var{Paths} is returned as an empty matrix.
+## If unspecified, the default is true.
+## @item Processes - Function or cell-array of functions specifying state
+## adjustments of the form X_t = P(t, X_t-) at the end of
+## each period (X_t- is the limit of X_s as s goes to from the
+## right).
+## If a single function is specified, it is applied to the end
+## of each period.
+## If a cell-array is specified, the functions are all applied
+## at the end of each period in the order that they appear.
+## If unspecified, no adjustments are made at the end of
+## periods.
+## @item Broadcast - Logical flag specifying whether or not to use broadcasting
+## to speed up computation.
+## If false, broadcasting is disabled.
+## If unspecified, the default is true.
+## @end itemize
+##
+## The outputs are described below:
+## @itemize
+## @item
+## Variable: @var{Paths} (NPERIODS + 1)-by-NVARS-by-NTRIALS array consisting of
+## the simulated paths.
+## @item
+## Variable: @var{Times} (NPERIODS + 1)-dimensional column vector of observation
+## corresponding to the paths.
+## @item
+## Variable: @var{Z} (NPERIODS * NSTEPS)-by-NBROWNS-by-NTRIALS array of variates
+## used to generate the process.
+## @end itemize
+##
+## The method will attempt to use a fast broadcasting implementation whenever
+## possible. This is possible when the following requirements are met:
+## @itemize
+## @item The methods Drift(t, X) (resp. Diffusion(t, X)) of the @var{SDE} object
+## return an NVARS-by-1-by-NTRIALS (resp. NVARS-by-NBROWNS-by-NTRIALS)
+## array when X is an NVARS-by-1-by-NTRIALS array.
+## @item If the user specifies Z as a function Z(t, X), it returns an
+## NBROWNS-by-NTRIALS matrix when X is an NVARS-by-1-by-NTRIALS array.
+## @item If the user specifies Processes, each function P(t, X) returns an
+## NVARS-by-1-NTRIALS array when X is an NVARS-by-1-by-NTRIALS array.
+## @end itemize
+## If any of the above conditions are violated, the fast broadcasting
+## implementation is not used.
+##
+## An example is provided in the documentation of @@sde/simulate.
+##
+## @seealso{sde, @@sde/simulate}
+## @end deftypefn
+
+function [Paths, Times, Z] = simByEuler (SDE, Periods, varargin)
+
+ ## Check number of arguments
+ if (nargin < 2)
+ print_usage();
+ elseif (mod (nargin, 2) == 1)
+ error ("simByEuler: optional arguments must be specified in key-value pairs");
+ elseif (! isa (SDE, "sde"))
+ error ("simByEuler: first argument must be an sde object");
+ elseif (! (isscalar (Periods) && Periods > 0 && floor (Periods) == Periods))
+ error ("simByEuler: Periods must be a positive integer");
+ endif
+
+ ## Default values
+ NPERIODS = Periods;
+ NTRIALS = 1;
+ NSTEPS = 1;
+ DeltaTime = ones (NPERIODS, 1);
+ Antithetic = false;
+ StorePaths = true;
+ Processes = @(t, X) X;
+ Broadcast = true;
+
+ ## Parse options
+ ConstantZ = true;
+ UserSpecifiedZ = false;
+ ProcessesIsCell = false;
+ for i = 1:length(varargin)/2
+ key = varargin{2*i-1};
+ value = varargin{2*i};
+ if (! (ischar (key) && isvector (key)))
+ error ("simByEuler: key must be a string");
+ endif
+ switch (key)
+ case "NTRIALS"
+ if (! (isscalar (value) && value > 0 && floor (value) == value))
+ error ("simByEuler: NTRIALS must be a positive integer");
+ endif
+ NTRIALS = value;
+ case "DeltaTime"
+ if (! (isreal (value) && (min (value > 0))))
+ error ("simByEuler: DeltaTime must consist only of positive real numbers");
+ endif
+ if (isscalar (value))
+ DeltaTime = ones (NPERIODS, 1) * value;
+ elseif (isvector (value) && length (value) == NPERIODS)
+ DeltaTime = value;
+ else
+ error ("simByEuler: DeltaTime must be a scalar or column vector of dimension equal to the specified number of periods");
+ endif
+ case "NSTEPS"
+ if (! (isscalar (value) && value > 0 && floor (value) == value))
+ error ("simByEuler: NSTEPS must be a positive integer");
+ endif
+ NSTEPS = value;
+ case "Antithetic"
+ if (! (isscalar (value) && islogical (value)))
+ error ("simByEuler: Antithetic must be a scalar logical true or false");
+ endif
+ Antithetic = value;
+ case "Z"
+ ConstantZ = ! isa (value, "function_handle");
+ if (! (! ConstantZ || (isreal (value) && length (size (value)) == 3)))
+ error ("simByEuler: Z must be a three-dimensional array of real numbers or a function handle");
+ endif
+ Z = value;
+ UserSpecifiedZ = true;
+ case "StorePaths"
+ if (! (isscalar (value) && islogical (value)))
+ error ("simByEuler: StorePaths must be a scalar logical true or false");
+ endif
+ StorePaths = value;
+ case "Processes"
+ ProcessesIsCell = iscell (value);
+ if (ProcessesIsCell)
+ for j = 1:length (value)
+ f = value{j};
+ if (! isa (f, "function_handle"))
+ error ("simByEuler: if specifying Processes as cell-array, each element must be a function handle");
+ endif
+ endfor
+ elseif (! isa (value, "function_handle"))
+ error ("simByEuler: Processes must be a function handle or cell-array of function handles.");
+ endif
+ Processes = value;
+ case "Broadcast"
+ if (! (isscalar (value) && islogical (value)))
+ error ("simByEuler: Broadcast must be a scalar logical true or false");
+ endif
+ Broadcast = value;
+ otherwise
+ error ("simByEuler: unrecognized option %s", key);
+ endswitch
+ endfor
+
+ ## Infer the size of NVARS and NBROWNS
+ NVARS = size (SDE.StartState, 1);
+ NBROWNS = size (SDE.Diffusion (0, ones (NVARS, 1)), 2);
+
+ ## Error checking
+ if (StorePaths)
+ Paths = zeros (NPERIODS + 1, NVARS, NTRIALS);
+ else
+ Paths = zeros (0, 0, 0);
+ endif
+
+ ## Perform Cholesky factorization exactly once if possible
+ ConstantCorrelation = false;
+ if (! isa (SDE.Correlation, "function_handle"))
+ L = chol (SDE.Correlation, "lower");
+ ConstantCorrelation = true;
+ endif
+
+ ## Generate random samples
+ if (UserSpecifiedZ)
+ if (Antithetic)
+ warning("simByEuler: Antithetic specified with Z; ignoring Antithetic");
+ endif
+ else
+ ## Antithetic sampling
+ if (Antithetic)
+ ## Make sure NTRIALS is even
+ NTRIALS += mod (NTRIALS, 2);
+ tmp = randn (NPERIODS * NSTEPS, NBROWNS, NTRIALS / 2);
+ Z(:, :, 1:2:NTRIALS) = tmp;
+ Z(:, :, 2:2:NTRIALS) = -tmp;
+ else
+ Z = randn (NPERIODS * NSTEPS, NBROWNS, NTRIALS);
+ endif
+ endif
+
+ ## Vector of times
+ Times = zeros (NPERIODS + 1, 1);
+ Times(1) = SDE.StartTime;
+ for p = 1:NPERIODS
+ Times(p+1) = Times(p) + DeltaTime(p);
+ endfor
+
+ ## Make StartState NVARS-by-NTRIALS matrix
+ if (isscalar (SDE.StartState))
+ StartState = ones (NVARS, NTRIALS) * SDE.StartState;
+ elseif (iscolumn (SDE.StartState))
+ StartState = zeros (NVARS, NTRIALS);
+ for i = 1:NTRIALS
+ StartState(:, i) = SDE.StartState;
+ endfor
+ else
+ StartState = SDE.StartState;
+ endif
+
+ StateDimensions = [NVARS, 1, NTRIALS];
+ BrownDimensions = [NVARS, NBROWNS, NTRIALS];
+ TrialDimensions = [NBROWNS, NTRIALS];
+
+ ## Check to see if we can use the fast broadcasting implementation
+ X = zeros (StateDimensions);
+
+ BroadcastDrift = true;
+ try
+ BroadcastDrift = isequal (size (SDE.Drift (0., X)), StateDimensions);
+ catch exception
+ BroadcastDrift = false;
+ end_try_catch
+ if (! BroadcastDrift && NTRIALS > 1)
+ warning ("simByEuler: SDE.Drift cannot be used with fast broadcasting implementation");
+ endif
+
+ BroadcastDiffusion = true;
+ try
+ BroadcastDiffusion = isequal (size (SDE.Diffusion (0., X)), BrownDimensions);
+ catch exception
+ BroadcastDiffusion = false;
+ end_try_catch
+ if (! BroadcastDiffusion && NTRIALS > 1)
+ warning ("simByEuler: SDE.Diffusion cannot be used with fast broadcasting implementation");
+ endif
+
+ BroadcastZ = true;
+ try
+ if (! ConstantZ)
+ BroadcastZ = isequal (size (Z (0., X)), TrialDimensions);
+ endif
+ catch exception
+ BroadcastZ = false;
+ end_try_catch
+ if (! BroadcastZ && NTRIALS > 1)
+ warning ("simByEuler: Z cannot be used with fast broadcasting implementation");
+ endif
+
+ BroadcastProcesses = true;
+ try
+ if (ProcessesIsCell)
+ for j = 1:length (Processes)
+ f = Processes{j};
+ if (! isequal (size (f (0., X)), StateDimensions))
+ BroadcastProcesses = false;
+ endif
+ endfor
+ else
+ if (! isequal (size (Processes (0., X)), StateDimensions))
+ BroadcastProcesses = false;
+ endif
+ endif
+ catch exception
+ BroadcastProcesses = false;
+ end_try_catch
+ if (! BroadcastProcesses && NTRIALS > 1)
+ warning ("simByEuler: Processes cannot be used with fast broadcasting implementation");
+ endif
+
+ Broadcast = Broadcast && BroadcastDrift && BroadcastDiffusion && BroadcastZ && BroadcastProcesses;
+
+ if (! Broadcast && NTRIALS > 1)
+ warning ("simByEuler: fast broadcasting disabled; may be slow");
+ endif
+
+ if (Broadcast)
+ NOUTER = 1;
+ else
+ NOUTER = NTRIALS;
+ endif
+
+ if (StorePaths)
+ Paths(1, :, :) = StartState;
+ endif
+
+ for i = 1:NOUTER
+
+ if (Broadcast)
+ X = reshape (StartState, StateDimensions);
+ else
+ X = StartState(:, i);
+ endif
+
+ t = SDE.StartTime;
+
+ for p = 1:NPERIODS
+
+ dt = DeltaTime(p);
+ subdt = dt/NSTEPS;
+ sqrt_subdt = sqrt (subdt);
+
+ if (Broadcast)
+
+ for n = 1:NSTEPS
+
+ tnow = t + subdt * (n-1);
+
+ if (! ConstantCorrelation)
+ L = chol (SDE.Correlation (tnow), "lower");
+ endif
+
+ if (! ConstantZ)
+ phi = Z (tnow, X);
+ else
+ phi = reshape (Z((p-1)*NSTEPS + n, :, :), TrialDimensions);
+ endif
+
+ ## Fast matrix-vector multiply over multiple slices
+ v0 = sum (bsxfun (@times, L * sqrt_subdt, permute (phi, [3, 1, 2])), 2);
+ v1 = reshape (v0, TrialDimensions);
+ v2 = sum (bsxfun (@times, SDE.Diffusion (tnow, X), permute (v1, [3, 1, 2])), 2);
+
+ X += SDE.Drift (tnow, X) * subdt + v2;
+
+ endfor
+
+ else
+
+ for n = 1:NSTEPS
+
+ tnow = t + subdt * (n-1);
+
+ if (! ConstantCorrelation)
+ L = chol (SDE.Correlation (tnow), "lower");
+ endif
+
+ if (! ConstantZ)
+ phi = Z (tnow, X);
+ else
+ phi = reshape (Z((p-1)*NSTEPS + n, :, i), [NBROWNS, 1]);
+ endif
+
+ X += SDE.Drift (tnow, X) * subdt ...
+ + SDE.Diffusion (tnow, X) * (L * phi) * sqrt_subdt;
+
+ endfor
+
+ endif
+
+ t = Times(p+1);
+ if (ProcessesIsCell)
+ for j = 1:length (Processes)
+ f = Processes{j};
+ X = f (t, X);
+ endfor
+ else
+ X = Processes (t, X);
+ endif
+
+ if (StorePaths)
+ if (Broadcast)
+ Paths(p+1, :, :) = X(:, 1, :);
+ else
+ Paths(p+1, :, i) = X;
+ endif
+ endif
+
+ endfor
+
+ endfor
+
+endfunction
+
+## Basket call test
+%!test
+%! Asset1Price = 40.; Asset2Price = 40.; Strike = 40.; RiskFreeRate = 0.05; Volatility1 = 0.5; Volatility2 = 0.5; ExpiryTime = 0.25; Correlation = 0.3;
+%! Simulations = 1e5; Timesteps = 10;
+%! Drift = drift ([0.;0.], [RiskFreeRate 0.;0. RiskFreeRate]);
+%! Diffusion = diffusion ([1.;1.], [Volatility1 0.;0. Volatility2]);
+%! SDE = sde (Drift, Diffusion, "StartState", [Asset1Price;Asset2Price], "Correlation", [1 Correlation;Correlation 1]);
+%! [Paths, ~, ~] = simulate (SDE, 1, "DeltaTime", ExpiryTime, "NTRIALS", Simulations, "NSTEPS", Timesteps, "Antithetic", true);
+%! BasketCallApproximate = exp (-RiskFreeRate * ExpiryTime) * mean (max (max (Paths(end, :, :)) - Strike, 0.));
+%! BasketCall = 6.8477; ## Computed using formula from Stulz (1982)
+%! assert (BasketCallApproximate, BasketCall, 1e-1);
+
+## Confidence interval and options pricing tests
+%!test
+%! AssetPrice = 100.; RiskFreeRate = 0.04; Dividends = 0.01; Volatility = 0.2; ExpiryTime = 1.;
+%! Simulations = 1e6; Timesteps = 10;
+%! Drift = drift (0., RiskFreeRate - Dividends);
+%! Diffusion = diffusion (1., Volatility);
+%! SDE = sde (Drift, Diffusion, "StartState", AssetPrice);
+%! [Paths, ~, ~] = simByEuler (SDE, 1, "DeltaTime", ExpiryTime, "NTRIALS", Simulations, "NSTEPS", Timesteps, "Antithetic", true);
+%! AssetExpiryMean = AssetPrice * exp ((RiskFreeRate - Dividends) * ExpiryTime);
+%! AssetExpiryMeanApproximate = mean (Paths(end, 1, :));
+%! AssetExpiryVariance = AssetPrice * AssetPrice * exp (2 * (RiskFreeRate - Dividends) * ExpiryTime) * (exp (Volatility * Volatility * ExpiryTime) - 1);
+%! ConfidenceInterval = 0.01;
+%! tol = norminv(1 - ConfidenceInterval/2) * sqrt (AssetExpiryVariance / Simulations);
+%! assert (AssetExpiryMeanApproximate, AssetExpiryMean, tol)
+%! Strike = 100.;
+%! CallApproximate = exp (-RiskFreeRate * ExpiryTime) * mean (max (Paths(end, 1, :) - Strike, 0.));
+%! [Call, ~] = blsprice (AssetPrice, Strike, RiskFreeRate, ExpiryTime, Volatility, Dividends);
+%! assert (CallApproximate, Call, 1e-1);
+
+## Test input validation
+%!error simByEuler()
+%!error simByEuler(1)
+%!error simByEuler("invalid type", 1)
diff --git a/inst/@sde/simulate.m b/inst/@sde/simulate.m
new file mode 100644
index 0000000..19f62b9
--- /dev/null
+++ b/inst/@sde/simulate.m
@@ -0,0 +1,83 @@
+## Copyright (C) 2015 Parsiad Azimzadeh <parsiad.azimzadeh@gmail.com>
+##
+## This program is free software; you can redistribute it and/or modify it under
+## the terms of the GNU Lesser 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 Lesser General Public License
+## for more details.
+##
+## You should have received a copy of the GNU Lesser General Public License
+## along with this program; if not, see <http://www.gnu.org/licenses/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function File} {[@var{Paths}, @var{Times}, @var{Z}] =} simulate (@var{SDE}, @dots{})
+## Simulates a stochastic differential equation (SDE).
+##
+## @itemize
+## @item
+## Variable: @var{SDE} An sde object.
+## @end itemize
+##
+## This method passes any additional arguments to the simulation routine
+## specified by the sde object.
+##
+## The outputs are described below:
+## @itemize
+## @item
+## Variable: @var{Paths} (NPERIODS + 1)-by-NVARS-by-NTRIALS array consisting of
+## the simulated paths.
+## @item
+## Variable: @var{Times} (NPERIODS + 1)-dimensional column vector of observation
+## corresponding to the paths.
+## @item
+## Variable: @var{Z} (NPERIODS * NSTEPS)-by-NBROWNS-by-NTRIALS array of variates
+## used to generate the process.
+## @end itemize
+##
+## Below is an example simulating a two-dimensional process driven by two
+## correlated Wiener processes:
+##
+## @example
+## Asset1Price = 100.; Asset2Price = 90. ;
+## Volatility1 = 0.2 ; Volatility2 = 0.3 ;
+## Dividends1 = 0. ; Dividends2 = 0.005;
+## RiskFreeRate = 0.04;
+## Correlation = 0.5;
+## ExpiryTime = 1.;
+##
+## Drift = drift ([0;0], [RiskFreeRate-Dividends1 0;0 RiskFreeRate-Dividends2]);
+## Diffusion = diffusion ([1;1], [Volatility1 0;0 Volatility2]);
+##
+## M = 1000; # Number of simulations
+## N = 10; # Number of timesteps
+##
+## SDE = sde (Drift, Diffusion, "StartState", [Asset1Price;Asset2Price], ...
+## "Correlation", [1 Correlation;Correlation 1]);
+## [Paths, ~, ~] = simulate (SDE, 1, "DeltaTime", ExpiryTime, ...
+## "NTRIALS", M, "NSTEPS", N);
+## @end example
+##
+## @seealso{@@sde/simByEuler}
+## @end deftypefn
+
+function [Paths, Times, Z] = simulate (SDE, varargin)
+
+ if (nargin < 1)
+ print_usage();
+ endif
+
+ if (! isa (SDE, "sde"))
+ error("simulate: first argument must be an sde object");
+ endif
+
+ [Paths, Times, Z] = SDE.Simulation (SDE, varargin{:});
+
+endfunction
+
+## Test input validation
+%!error simulate ()
+%!error simulate (1)
diff --git a/inst/@sde/subsasgn.m b/inst/@sde/subsasgn.m
new file mode 100644
index 0000000..a83eb1a
--- /dev/null
+++ b/inst/@sde/subsasgn.m
@@ -0,0 +1,77 @@
+## Copyright (C) 2015 Parsiad Azimzadeh <parsiad.azimzadeh@gmail.com>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+function SDE = subsasgn (SDE, idx, value)
+
+ if (! isa (SDE, "sde"))
+ error ("object must be of the sde class but '%s' was used", class (SDE));
+ elseif (! strcmp (idx(1).type, ".") || numel (idx) > 1)
+ error ("incorrect syntax to reference sde object. Use obj.prop to access properties.");
+ endif
+
+ switch (idx.subs)
+ case "Drift"
+ SDE = sde (
+ value, SDE.Diffusion,
+ "StartTime", SDE.StartTime,
+ "StartState", SDE.StartState,
+ "Correlation", SDE.Correlation,
+ "Simulation", SDE.Simulation
+ );
+ case "Diffusion"
+ SDE = sde (
+ SDE.Drift, value,
+ "StartTime", SDE.StartTime,
+ "StartState", SDE.StartState,
+ "Correlation", SDE.Correlation,
+ "Simulation", SDE.Simulation
+ );
+ case "StartTime"
+ SDE = sde (
+ SDE.Drift, SDE.Diffusion,
+ "StartTime", value,
+ "StartState", SDE.StartState,
+ "Correlation", SDE.Correlation,
+ "Simulation", SDE.Simulation
+ );
+ case "StartState"
+ SDE = sde (
+ SDE.Drift, SDE.Diffusion,
+ "StartTime", SDE.StartTime,
+ "StartState", value,
+ "Correlation", SDE.Correlation,
+ "Simulation", SDE.Simulation
+ );
+ case "Correlation"
+ SDE = sde (
+ SDE.Drift, SDE.Diffusion,
+ "StartTime", SDE.StartTime,
+ "StartState", SDE.StartState,
+ "Correlation", value,
+ "Simulation", SDE.Simulation
+ );
+ case "Simulation"
+ SDE = sde (
+ SDE.Drift, SDE.Diffusion,
+ "StartTime", SDE.StartTime,
+ "StartState", SDE.StartState,
+ "Correlation", SDE.Correlation,
+ "Simulation", value
+ );
+ otherwise
+ error ("sde: unknown property '%s'", idx.subs);
+ endswitch
+
+endfunction
diff --git a/inst/@sde/subsref.m b/inst/@sde/subsref.m
new file mode 100644
index 0000000..f7ce6c3
--- /dev/null
+++ b/inst/@sde/subsref.m
@@ -0,0 +1,35 @@
+## Copyright (C) 2015 Carnë Draug <carandraug+dev@gmail.com>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+function v = subsref (SDE, idx)
+
+ if (! isa (SDE, "sde"))
+ error ("object must be of the sde class but '%s' was used", class (SDE));
+ elseif (! strcmp (idx(1).type, ".") || numel (idx) > 1)
+ error ("incorrect syntax to reference sde object. Use obj.prop to access properties.");
+ endif
+
+ switch (idx.subs)
+ case "Drift", v = SDE.Drift;
+ case "Diffusion", v = SDE.Diffusion;
+ case "StartTime", v = SDE.StartTime;
+ case "StartState", v = SDE.StartState;
+ case "Correlation", v = SDE.Correlation;
+ case "Simulation", v = SDE.Simulation;
+ otherwise
+ error ("sde: unknown property '%s'", idx.subs);
+ endswitch
+
+endfunction
diff --git a/inst/binprice.m b/inst/binprice.m
new file mode 100644
index 0000000..b475313
--- /dev/null
+++ b/inst/binprice.m
@@ -0,0 +1,150 @@
+## Copyright (C) 2013 Parsiad Azimzadeh <parsiad.azimzadeh@gmail.com>
+##
+## This program is free software; you can redistribute it and/or modify it under
+## the terms of the GNU Lesser 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 Lesser General Public License
+## for more details.
+##
+## You should have received a copy of the GNU Lesser General Public License
+## along with this program; if not, see <http://www.gnu.org/licenses/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function File} {[@var{AssetPrice}, @var{OptionValue}] =} binprice (@var{Price}, @var{Strike}, @var{Rate}, @var{Time}, @var{Increment}, @var{Volatility}, @var{OptType})
+## @deftypefnx {Function File} {[@var{AssetPrice}, @var{OptionValue}] =} binprice (@var{Price}, @var{Strike}, @var{Rate}, @var{Time}, @var{Increment}, @var{Volatility}, @var{OptType}, @var{DividendRate})
+## @deftypefnx {Function File} {[@var{AssetPrice}, @var{OptionValue}] =} binprice (@var{Price}, @var{Strike}, @var{Rate}, @var{Time}, @var{Increment}, @var{Volatility}, @var{OptType}, @var{DividendRate}, @var{Dividend}, @var{ExDiv})
+## Compute American call and put option prices using a binomial tree.
+##
+## @itemize
+## @item
+## Variable: @var{Price} The current price of the underlying asset.
+## @item
+## Variable: @var{Strike} The strike price the option is written on.
+## @item
+## Variable: @var{Rate} The risk-free interest rate.
+## @item
+## Variable: @var{Time} The time-to-expiry.
+## @item
+## Variable: @var{Increment} Time increment. @var{Increment} is rounded to
+## ensure that @var{Time}/@var{Increment} is an integer.
+## @item
+## Variable: @var{Volatility} The volatility of the underlying asset.
+## @item
+## Variable: @var{OptType} Option type. 1 = call option, 0 = put option.
+## @item
+## Variable: @var{DividendRate} (Optional, default = 0) Annualized, continuously
+## compounded rate of dividends of the underlying asset.
+## @item
+## Variable: @var{Dividend} (Optional, default = 0) The dividend payment at an
+## ex-dividend date as specified by @var{ExDiv}.
+## @item
+## Variable: @var{ExDiv} (Optional, default = 0) A vector used to determine the
+## ex-dividend dates. For each j, @var{ExDiv}(j) * @var{Increment} is the
+## corresponding dividend date.
+## @end itemize
+##
+## Computes the American call and put option prices using the
+## Cox-Ross-Rubinstein binomial tree.
+##
+## Discrete dividends (i.e. @var{Dividend} and @var{ExDiv}) have not yet been
+## implemented.
+##
+## Binomial trees are a particular explicit finite difference method for solving
+## the Black-Scholes equation (see
+## @cite{M. Rubinstein. On the relation between binomial and trinomial option
+## pricing models. Journal of Derivatives, 8(2):47-50, 2000}),
+## and exhibit linear convergence along with the usual strict stability
+## requirements of an explicit method.
+## The serious practitioner should consider using a more
+## sophisticated method, and use binomial trees only for explanatory or
+## heuristic purposes.
+##
+## @seealso{blkprice, blsprice}
+## @end deftypefn
+
+function [AssetPrice, OptionValue] = binprice (Price, Strike, Rate, Time, ...
+ Increment, Volatility, ...
+ OptType, DividendRate = 0, ...
+ Dividend = 0, ExDiv = 0 )
+
+ ## Input checking
+ if (nargin < 7 || nargin > 10)
+ print_usage ();
+ elseif (! isbool (OptType) && ! isequal (OptType, 0) && ...
+ ! isequal (OptType, 1))
+ error ("binprice: OPTTYPE must be logical, 0 (call) or 1 (put)");
+ elseif (! isscalar (Price) || ! isscalar (Strike) || ! isscalar (Rate) || ...
+ ! isscalar (Increment) || !isscalar (Volatility) || ...
+ !isscalar (DividendRate))
+ error ("binprice: all inputs except DIVIDEND and EXDIV must be scalars");
+ elseif (! isreal (Price) || Price < 0)
+ error ("binprice: PRICE must be a nonnegative number");
+ elseif (! isreal (Strike) || Strike < 0)
+ error ("binprice: STRIKE must be a nonnegative number");
+ elseif (! isreal (Rate))
+ error ("binprice: RATE must be a number");
+ elseif (! isreal (Time) || Time <= 0)
+ error ("binprice: TIME must be a positive number");
+ elseif (! isreal (Increment) || Increment <= 0)
+ error ("binprice: INCREMENT must be a positive number");
+ elseif (! isreal (Volatility) || Volatility < 0)
+ error ("binprice: VOLATILITY must be a nonnegative number");
+ elseif (! isreal (DividendRate))
+ error ("binprice: DIVIDENDRATE must be a number");
+ elseif (! isequal (Dividend, 0) || ! isequal (ExDiv, 0))
+ error ("binprice: DIVIDEND and EXDIV not yet implemented");
+ endif
+
+ ## Storage
+ N = round ( Time / Increment ) + 1;
+ AssetPrice = OptionValue = zeros (N);
+
+ Increment = Time / (N - 1);
+
+ ## Return from up and down moves
+ u = exp (Volatility * sqrt (Increment));
+ d = 1 / u;
+
+ ## Martingale measure
+ a = exp (Rate * Increment);
+ p = (a * exp (-DividendRate * Increment) - d) / (u - d);
+ q = 1 - p;
+
+ ## Build tree
+ AssetPrice(1, 1) = Price;
+ for n = 2:N
+ AssetPrice(1:(n - 1), n) = u * AssetPrice(1:(n - 1), n - 1);
+ AssetPrice(n, n) = d * AssetPrice(n - 1, n - 1);
+ endfor
+
+ ## Initial condition
+ opt = 2 * OptType - 1;
+ OptionValue(:, N) = max (opt * (AssetPrice(:, N) - Strike), 0);
+
+ ## Time-stepping loop
+ for n = (N - 1):-1:1
+ HoldValue = (q * OptionValue(2:(n + 1), n + 1) + ...
+ p * OptionValue(1:n, n + 1)) / a;
+
+ OptionValue(1:n, n) = max (HoldValue, opt * (AssetPrice(1:n, n) - Strike));
+ endfor
+
+endfunction
+
+## Tests
+%!test
+%! [AssetPrice, OptionValue] = binprice (100, 100, 0.04, 1, 0.25, 0.2, 0, 0.01);
+%! assert (OptionValue(1:2,1:2), [6.4701 2.2159; 0 11.0776], 1e-4)
+
+## Test input validation
+%!error binprice ()
+%!error binprice (1)
+%!error binprice (1, 2)
+%!error binprice (1, 2, 3)
+%!error binprice (1, 2, 3, 4)
+%!error binprice (1, 2, 3, 4, 5)
+%!error binprice (1, 2, 3, 4, 5, 6)
diff --git a/inst/blkimpv.m b/inst/blkimpv.m
new file mode 100644
index 0000000..100e82b
--- /dev/null
+++ b/inst/blkimpv.m
@@ -0,0 +1,73 @@
+## Copyright (C) 2013 Parsiad Azimzadeh <parsiad.azimzadeh@gmail.com>
+##
+## This program is free software; you can redistribute it and/or modify it under
+## the terms of the GNU Lesser 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 Lesser General Public License
+## for more details.
+##
+## You should have received a copy of the GNU Lesser General Public License
+## along with this program; if not, see <http://www.gnu.org/licenses/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function File} {@var{Volatility} =} blkimpv (@var{Price}, @var{Strike}, @var{Rate}, @var{Time}, @var{Value})
+## @deftypefnx {Function File} {@var{Volatility} =} blkimpv (@var{Price}, @var{Strike}, @var{Rate}, @var{Time}, @var{Value}, @var{Limit})
+## @deftypefnx {Function File} {@var{Volatility} =} blkimpv (@var{Price}, @var{Strike}, @var{Rate}, @var{Time}, @var{Value}, @var{Limit}, @var{Tolerance})
+## @deftypefnx {Function File} {@var{Volatility} =} blkimpv (@var{Price}, @var{Strike}, @var{Rate}, @var{Time}, @var{Value}, @var{Limit}, @var{Tolerance}, @var{Class})
+## Compute implied volatility under the Black-Scholes model.
+##
+## @itemize
+## @item
+## Variable: @var{Price} The current price of the underlying asset (a futures
+## contract).
+## @item
+## Variable: @var{Strike} Exercise price of the futures option.
+## @item
+## Variable: @var{Rate} The risk-free interest rate.
+## @item
+## Variable: @var{Time} The time-to-expiry.
+## @item
+## Variable: @var{Value} Price of the European option from which the
+## underlying's volatility is derived.
+## @item
+## Variable: @var{Limit} (Optional, default = 10) Upper bound of the implied
+## volatility.
+## @item
+## Variable: @var{Tolerance} (Optional, default = 1e-6) Tolerance with which the
+## root-finding method terminates.
+## @item
+## Variable: @var{Class} (Optional, default = @{'call'@}) Option class (call or
+## put). To specify a call option, use a value of true or @{'call'@}. To specify
+## put options, use a value of false or @{'put'@}.
+## @end itemize
+##
+## Computes the implied volatility under the Black-Scholes model from a given
+## market option price.
+##
+## @seealso{blsdelta, blsgamma, blslambda, blsprice, blsrho, blstheta}
+## @end deftypefn
+
+function Volatility = blkimpv (Price, Strike, Rate, Time, Value, ...
+ Limit = 10, Tolerance = 1e-6, Option = true)
+ if (nargin < 5 || nargin > 8)
+ print_usage ();
+ endif
+
+ Volatility = blsimpv (Price .* exp (-Rate .* Time), Strike, Rate, Time, ...
+ Value, Limit, 0, Tolerance, Option);
+endfunction
+
+## Tests
+%!assert (blkimpv (90, 100, 0.04, 1, [3.4484 13.0563], 1, 1e-6, [1 0]), [0.2 0.2], 1e-4)
+
+## Test input validation
+%!error blkimpv ()
+%!error blkimpv (1)
+%!error blkimpv (1, 2)
+%!error blkimpv (1, 2, 3)
+%!error blkimpv (1, 2, 3, 4)
+%!error blkimpv (1, 2, 3, 4, 5, 6, 7, 8, 2)
diff --git a/inst/blkprice.m b/inst/blkprice.m
new file mode 100644
index 0000000..443c484
--- /dev/null
+++ b/inst/blkprice.m
@@ -0,0 +1,59 @@
+## Copyright (C) 2013 Parsiad Azimzadeh <parsiad.azimzadeh@gmail.com>
+##
+## This program is free software; you can redistribute it and/or modify it under
+## the terms of the GNU Lesser 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 Lesser General Public License
+## for more details.
+##
+## You should have received a copy of the GNU Lesser General Public License
+## along with this program; if not, see <http://www.gnu.org/licenses/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function File} {[@var{Call}, @var{Put}] =} blkprice (@var{Price}, @var{Strike}, @var{Rate}, @var{Time}, @var{Volatility})
+## Compute European call and put option price using the Black-76 model.
+##
+## @itemize
+## @item
+## Variable: @var{Price} The current price of the underlying asset (a futures
+## contract).
+## @item
+## Variable: @var{Strike} Exercise price of the futures option.
+## @item
+## Variable: @var{Rate} The risk-free interest rate.
+## @item
+## Variable: @var{Time} The time-to-expiry.
+## @item
+## Variable: @var{Volatility} The volatility of the underlying asset.
+## @end itemize
+##
+## @seealso{binprice, blsprice}
+## @end deftypefn
+
+function [Call, Put] = blkprice (Price, Strike, Rate, Time, Volatility)
+
+ if (nargin != 5)
+ print_usage ();
+ endif
+
+ [Call, Put] = blsprice (Price .* exp (-Rate .* Time), Strike, Rate, Time, ...
+ Volatility);
+
+endfunction
+
+## Tests
+%!test
+%! [Call, Put] = blkprice (90:10:110, 100, 0.04, 1, 0.2);
+%! assert (Call, [3.4484 7.6532 13.7316], 1e-4)
+%! assert (Put, [13.0563 7.6532 4.1237], 1e-4)
+
+## Test input validation
+%!error blkprice ()
+%!error blkprice (1)
+%!error blkprice (1, 2)
+%!error blkprice (1, 2, 3)
+%!error blkprice (1, 2, 3, 4)
diff --git a/inst/blsdelta.m b/inst/blsdelta.m
new file mode 100644
index 0000000..5df6be0
--- /dev/null
+++ b/inst/blsdelta.m
@@ -0,0 +1,72 @@
+## Copyright (C) 2013 Parsiad Azimzadeh <parsiad.azimzadeh@gmail.com>
+##
+## This program is free software; you can redistribute it and/or modify it under
+## the terms of the GNU Lesser 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 Lesser General Public License
+## for more details.
+##
+## You should have received a copy of the GNU Lesser General Public License
+## along with this program; if not, see <http://www.gnu.org/licenses/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function File} {[@var{CallDelta}, @var{PutDelta}] =} blsdelta (@var{Price}, @var{Strike}, @var{Rate}, @var{Time}, @var{Volatility})
+## @deftypefnx {Function File} {[@var{CallDelta}, @var{PutDelta}] =} blsdelta (@var{Price}, @var{Strike}, @var{Rate}, @var{Time}, @var{Volatility}, @var{Yield})
+## Computes the Black-Scholes delta, the rate of change of the option value with
+## respect to the value of the underlying asset.
+##
+## @itemize
+## @item
+## Variable: @var{Price} The current price of the underlying asset.
+## @item
+## Variable: @var{Strike} The strike price the option is written on.
+## @item
+## Variable: @var{Rate} The risk-free interest rate.
+## @item
+## Variable: @var{Time} The time-to-expiry.
+## @item
+## Variable: @var{Volatility} The volatility of the underlying asset.
+## @item
+## Variable: @var{Yield} (Optional, default = 0) Annualized, continuously
+## compounded rate of dividends of the underlying asset.
+## @end itemize
+##
+##
+## @seealso{blsgamma, blslambda, blsprice, blsrho, blstheta, blsvega}
+## @end deftypefn
+
+function [CallDelta, PutDelta] = blsdelta (Price, Strike, Rate, Time, ...
+ Volatility, Yield = 0)
+
+ if (nargin < 5 || nargin > 6)
+ print_usage ();
+ endif
+
+ blscheck ("blsdelta", Price, Strike, Rate, Time, Volatility, Yield);
+
+ d1 = 1 ./ (Volatility .* sqrt (Time)) .* (log (Price ./ Strike) + ...
+ (Rate - Yield + Volatility .^2 / 2) .* Time);
+
+ phi = normcdf (d1);
+
+ CallDelta = exp (-Yield .* Time) .* phi;
+ PutDelta = exp (-Yield .* Time) .* (phi - 1);
+
+endfunction
+
+## Tests
+%!test
+%! [CallDelta, PutDelta] = blsdelta (90:10:110, 100, 0.04, 1, 0.2, 0.01);
+%! assert (CallDelta, [0.3871 0.5927 0.7586], 1e-4)
+%! assert (PutDelta, [-0.6030 -0.3973 -0.2314], 1e-4)
+
+## Test input validation
+%!error blsdelta ()
+%!error blsdelta (1)
+%!error blsdelta (1, 2)
+%!error blsdelta (1, 2, 3)
+%!error blsdelta (1, 2, 3, 4)
diff --git a/inst/blsgamma.m b/inst/blsgamma.m
new file mode 100644
index 0000000..7ee733d
--- /dev/null
+++ b/inst/blsgamma.m
@@ -0,0 +1,66 @@
+## Copyright (C) 2013 Parsiad Azimzadeh <parsiad.azimzadeh@gmail.com>
+##
+## This program is free software; you can redistribute it and/or modify it under
+## the terms of the GNU Lesser 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 Lesser General Public License
+## for more details.
+##
+## You should have received a copy of the GNU Lesser General Public License
+## along with this program; if not, see <http://www.gnu.org/licenses/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function File} {@var{Gamma} =} blsgamma (@var{Price}, @var{Strike}, @var{Rate}, @var{Time}, @var{Volatility})
+## @deftypefnx {Function File} {@var{Gamma} =} blsgamma (@var{Price}, @var{Strike}, @var{Rate}, @var{Time}, @var{Volatility}, @var{Yield})
+## Compute Black-Scholes gamma.
+##
+## @itemize
+## @item
+## Variable: @var{Price} The current price of the underlying asset.
+## @item
+## Variable: @var{Strike} The strike price the option is written on.
+## @item
+## Variable: @var{Rate} The risk-free interest rate.
+## @item
+## Variable: @var{Time} The time-to-expiry.
+## @item
+## Variable: @var{Volatility} The volatility of the underlying asset.
+## @item
+## Variable: @var{Yield} (Optional, default = 0) Annualized, continuously
+## compounded rate of dividends of the underlying asset.
+## @end itemize
+##
+## Computes the Black-Scholes gamma, the rate of change of the option delta with
+## respect to the value of the underlying asset.
+##
+## @seealso{blsdelta, blslambda, blsprice, blsrho, blstheta, blsvega}
+## @end deftypefn
+
+function Gamma = blsgamma (Price, Strike, Rate, Time, Volatility, Yield = 0)
+
+ if (nargin < 4 || nargin > 5)
+ print_usage ();
+ endif
+
+ blscheck ("blsgamma", Price, Strike, Rate, Time, Volatility, Yield);
+
+ sigma_sqrtT = Volatility .* sqrt (Time);
+ d1 = 1 ./ sigma_sqrtT .* (log (Price ./ Strike) + (Rate - Yield + ...
+ Volatility .^2 / 2) .* Time);
+ Gamma = exp (-Yield .* Time) .* normpdf (d1) ./ (Price .* sigma_sqrtT);
+
+endfunction
+
+## Tests
+%assert (blsgamma(90:10:110, 100, 0.04, 1, 0.2, 0.01), [0.0211 0.0191 0.0138], 1e-4)
+
+## Test input validation
+%!error blsgamma ()
+%!error blsgamma (1)
+%!error blsgamma (1, 2)
+%!error blsgamma (1, 2, 3)
+%!error blsgamma (1, 2, 3, 4)
diff --git a/inst/blsimpv.m b/inst/blsimpv.m
new file mode 100644
index 0000000..2d6cf13
--- /dev/null
+++ b/inst/blsimpv.m
@@ -0,0 +1,170 @@
+## Copyright (C) 2013 Parsiad Azimzadeh <parsiad.azimzadeh@gmail.com>
+##
+## This program is free software; you can redistribute it and/or modify it under
+## the terms of the GNU Lesser 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 Lesser General Public License
+## for more details.
+##
+## You should have received a copy of the GNU Lesser General Public License
+## along with this program; if not, see <http://www.gnu.org/licenses/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function File} {@var{Volatility} =} blsimpv (@var{Price}, @var{Strike}, @var{Rate}, @var{Time}, @var{Value})
+## @deftypefnx {Function File} {@var{Volatility} =} blsimpv (@var{Price}, @var{Strike}, @var{Rate}, @var{Time}, @var{Value}, @var{Limit})
+## @deftypefnx {Function File} {@var{Volatility} =} blsimpv (@var{Price}, @var{Strike}, @var{Rate}, @var{Time}, @var{Value}, @var{Limit}, @var{Yield})
+## @deftypefnx {Function File} {@var{Volatility} =} blsimpv (@var{Price}, @var{Strike}, @var{Rate}, @var{Time}, @var{Value}, @var{Limit}, @var{Yield}, @var{Tolerance})
+## @deftypefnx {Function File} {@var{Volatility} =} blsimpv (@var{Price}, @var{Strike}, @var{Rate}, @var{Time}, @var{Value}, @var{Limit}, @var{Yield}, @var{Tolerance}, @var{Class})
+## Computes implied volatility under the Black-Scholes model.
+##
+## @itemize
+## @item
+## Variable: @var{Price} The current price of the underlying asset.
+## @item
+## Variable: @var{Strike} The strike price the option is written on.
+## @item
+## Variable: @var{Rate} The risk-free interest rate.
+## @item
+## Variable: @var{Time} The time-to-expiry.
+## @item
+## Variable: @var{Value} Price of the European option from which the
+## underlying's volatility is derived.
+## @item
+## Variable: @var{Limit} (Optional, default = 10) Upper bound of the implied
+## volatility.
+## @item
+## Variable: @var{Yield} (Optional, default = 0) Annualized, continuously
+## compounded rate of dividends of the underlying asset.
+## @item
+## Variable: @var{Tolerance} (Optional, default = 1e-6) Tolerance with which the
+## root-finding method terminates.
+## @item
+## Variable: @var{Class} (Optional, default = @{'call'@}) Option class (call or
+## put). To specify a call option, use a value of true or @{'call'@}. To specify
+## put options, use a value of false or @{'put'@}.
+## @end itemize
+##
+## Computes the implied volatility under the Black-Scholes model from a given
+## market option price.
+##
+## @seealso{blsdelta, blsgamma, blslambda, blsprice, blsrho, blstheta}
+## @end deftypefn
+
+function Volatility = blsimpv (Price, Strike, Rate, Time, Value, ...
+ Limit = 10, Yield = 0, Tolerance = 1e-6, ...
+ Class = true)
+
+ if (nargin < 5 || nargin > 9)
+ print_usage ();
+ endif
+
+ ## Get maximum sizes of matrices
+ res_size_row = max ([rows(Price) rows(Strike) rows(Rate) rows(Time) ...
+ rows(Value) rows(Limit) rows(Yield) rows(Tolerance) ...
+ rows(Class)]);
+ res_size_col = max ([columns(Price) columns(Strike) columns(Rate) ...
+ columns(Time) columns(Value) columns(Limit) ...
+ columns(Yield) columns(Tolerance) columns(Class)]);
+ res_size = [res_size_row res_size_col];
+
+ ## Resize scalars
+ Price = resize_scalar (res_size, Price, "PRICE");
+ Strike = resize_scalar (res_size, Strike, "STRIKE");
+ Rate = resize_scalar (res_size, Rate, "RATE");
+ Time = resize_scalar (res_size, Time, "TIME");
+ Value = resize_scalar (res_size, Value, "VALUE");
+ Limit = resize_scalar (res_size, Limit, "LIMIT");
+ Yield = resize_scalar (res_size, Yield, "YIELD");
+ Tolerance = resize_scalar (res_size, Tolerance, "TOLERANCE");
+
+ if (isscalar (Class))
+ Class = repmat ({Class}, res_size);
+ elseif (! isequal (size (Class), res_size))
+ error ("blsimpv: CLASS must be a scalar or cell array of conforming size with other inputs",
+ arg_name);
+ endif
+
+ ## Check that all values in the cell array option are either boolean
+ ## or the string call, and put. Replace the strings call and put by their
+ ## respective boolean and then convert it into a boolean matrix.
+ if (iscell (Class))
+ bool_idx = cellfun ("islogical", Class);
+ call_idx = strcmpi (Class, "call");
+ put_idx = strcmpi (Class, "put");
+ if (! all (bool_idx | put_idx | call_idx))
+ error ("blsimpv: all values in OPTION must be logical, \"call\", or \"put\"");
+ endif
+ Class(call_idx) = true;
+ Class(put_idx) = false;
+ Class = cell2mat (Class);
+ endif
+
+ Volatility = zeros (res_size); # output matrix
+
+ for j = 1:res_size_row
+ for k = 1:res_size_col
+
+ ## Make option set
+ ## At the time of writing, fzero did not recognize the
+ ## GradObj option.
+ opts = optimset ("fzero");
+ opts = optimset (opts, "TolX", Tolerance(j, k), "GradObj", "on");
+
+ ## Construct function
+ if (Class(j, k)) # call
+ fun = @(x) blscall (Price(j, k), Strike(j, k), Rate(j, k), Time(j, k), x,
+ Yield(j, k)) - Value(j, k);
+ else # put
+ fun = @(x) blsput (Price(j, k), Strike(j, k), Rate(j, k), Time(j, k), x,
+ Yield(j, k)) - Value(j, k);
+ endif
+
+ ## Solve
+ try
+ [x, fval, exitflag, output] = fzero (fun, [Tolerance(j, k) Limit(j, k)], opts);
+ if (exitflag != 1)
+ x = NaN;
+ endif
+ catch
+ x = NaN;
+ end_try_catch
+ Volatility(j, k) = x;
+
+ endfor
+ endfor
+
+endfunction
+
+function sc = resize_scalar (res_size, sc, arg_name);
+ if (isscalar (sc))
+ sc = repmat (sc, res_size);
+ elseif (! isequal (size(sc), res_size))
+ error ("blsimpv: %s must be a scalar or matrix of conforming size with other inputs",
+ arg_name);
+ endif
+endfunction
+
+function [C, v] = blscall (Price, Strike, Rate, Time, x, Yield)
+ C = blsprice (Price, Strike, Rate, Time, x, Yield);
+ v = blsvega (Price, Strike, Rate, Time, x, Yield);
+endfunction
+
+function [P, v] = blsput (Price, Strike, Rate, Time, x, Yield)
+ [~, P] = blsprice (Price, Strike, Rate, Time, x, Yield);
+ v = blsvega (Price, Strike, Rate, Time, x, Yield);
+endfunction
+
+## Tests
+%!assert (blsimpv (100, 100, 0.04, 1, [9.9251 6.0040], 1, 0, 1e-6, [1 0]), [0.2 0.2], 1e-4)
+
+## Test input validation
+%!error blsimpv ()
+%!error blsimpv (1)
+%!error blsimpv (1, 2)
+%!error blsimpv (1, 2, 3)
+%!error blsimpv (1, 2, 3, 4)
+%!error blsimpv (1, 2, 3, 4, 5, 6, 7, 8, 2)
diff --git a/inst/blslambda.m b/inst/blslambda.m
new file mode 100644
index 0000000..65cb500
--- /dev/null
+++ b/inst/blslambda.m
@@ -0,0 +1,85 @@
+## Copyright (C) 2013 Parsiad Azimzadeh <parsiad.azimzadeh@gmail.com>
+##
+## This program is free software; you can redistribute it and/or modify it under
+## the terms of the GNU Lesser 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 Lesser General Public License
+## for more details.
+##
+## You should have received a copy of the GNU Lesser General Public License
+## along with this program; if not, see <http://www.gnu.org/licenses/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function File} {[@var{CallEl}, @var{PutEl}] =} blslambda (@var{Price}, @var{Strike}, @var{Rate}, @var{Time}, @var{Volatility})
+## @deftypefnx {Function File} {[@var{CallEl}, @var{PutEl}] =} blslambda (@var{Price}, @var{Strike}, @var{Rate}, @var{Time}, @var{Volatility}, @var{Yield})
+## Computes elasticity of option under the Black-Scholes model.
+##
+## @itemize
+## @item
+## Variable: @var{Price} The current price of the underlying asset.
+## @item
+## Variable: @var{Strike} The strike price the option is written on.
+## @item
+## Variable: @var{Rate} The risk-free interest rate.
+## @item
+## Variable: @var{Time} The time-to-expiry.
+## @item
+## Variable: @var{Volatility} The volatility of the underlying asset.
+## @item
+## Variable: @var{Yield} (Optional, default = 0) Annualized, continuously
+## compounded rate of dividends of the underlying asset.
+## @end itemize
+##
+## Computes the elasticity of an option under the Black-Scholes model.
+## Elasticity measures the percent change in the option price per percent change
+## in the underlying asset price.
+##
+## Update: the following bug has been fixed in MATLAB R2014a(5.3):
+## There is a bug in the MATLAB version of blslambda in which the deltas of the
+## option are not discounted by @var{Yield} in the nonzero dividend case. That
+## is, they compute normcdf(d1) * S / V when they should compute
+## exp(-Yield*T) * normcdf(d1) * S / V. At the time of writing, this bug is
+## present in the financial toolbox shipped with R2013a. Both this version of
+## blslambda and that shipped with R2013a agree when there are no dividends.
+##
+## @seealso{blsdelta, blsgamma, blsprice, blsrho, blstheta, blsvega}
+## @end deftypefn
+
+function [CallEl, PutEl] = blslambda (Price, Strike, Rate, Time, ...
+ Volatility, Yield = 0)
+
+ if (nargin < 5 || nargin > 6)
+ print_usage ();
+ endif
+
+ blscheck ("blslambda", Price, Strike, Rate, Time, Volatility, Yield);
+
+ [Call, Put] = blsprice (Price, Strike, Rate, Time, Volatility, Yield);
+ [CallDelta, PutDelta] = blsdelta (Price, Strike, Rate, Time, Volatility, ...
+ Yield);
+
+ CallEl = CallDelta .* Price ./ Call;
+ PutEl = PutDelta .* Price ./ Put;
+
+endfunction
+
+## Tests
+%!test
+%! [CallEl, PutEl] = blslambda (90:10:110, 100, 0.04, 1, 0.2);
+%! assert (CallEl, [7.7536 6.2258 5.0647], 1e-4)
+%! assert (PutEl, [-4.8955 -6.3639 -7.8941], 1e-4)
+%!test
+%! [CallEl, PutEl] = blslambda (90:10:110, 100, 0.04, 1, 0.2, 0.01);
+%! assert (CallEl, [7.9108 6.3601 5.1762], 1e-4)
+%! assert (PutEl, [-4.7695 -6.2139 -7.7255], 1e-4)
+
+## Test input validation
+%!error blslambda ()
+%!error blslambda (1)
+%!error blslambda (1, 2)
+%!error blslambda (1, 2, 3)
+%!error blslambda (1, 2, 3, 4)
diff --git a/inst/blsprice.m b/inst/blsprice.m
new file mode 100644
index 0000000..195d442
--- /dev/null
+++ b/inst/blsprice.m
@@ -0,0 +1,81 @@
+## Copyright (C) 2013 Parsiad Azimzadeh <parsiad.azimzadeh@gmail.com>
+##
+## This program is free software; you can redistribute it and/or modify it under
+## the terms of the GNU Lesser 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 Lesser General Public License
+## for more details.
+##
+## You should have received a copy of the GNU Lesser General Public License
+## along with this program; if not, see <http://www.gnu.org/licenses/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function File} {[@var{Call}, @var{Put}] =} blsprice (@var{Price}, @var{Strike}, @var{Rate}, @var{Time}, @var{Volatility})
+## @deftypefnx {Function File} {[@var{Call}, @var{Put}] =} blsprice (@var{Price}, @var{Strike}, @var{Rate}, @var{Time}, @var{Volatility}, @var{Yield})
+## Compute European call and put option prices.
+##
+## @itemize
+## @item
+## Variable: @var{Price} The current price of the underlying asset.
+## @item
+## Variable: @var{Strike} The strike price the option is written on.
+## @item
+## Variable: @var{Rate} The risk-free interest rate.
+## @item
+## Variable: @var{Time} The time-to-expiry.
+## @item
+## Variable: @var{Volatility} The volatility of the underlying asset.
+## @item
+## Variable: @var{Yield} (Optional, default = 0) Annualized, continuously
+## compounded rate of dividends of the underlying asset.
+## @end itemize
+##
+## Computes the European call and put option prices using the Black-Scholes
+## model.
+##
+## @seealso{blskprice, blsdelta, blsgamma, blsimpv, blslambda, blsrho, blstheta, blsvega}
+## @end deftypefn
+
+function [Call, Put] = blsprice (Price, Strike, Rate, Time, Volatility, ...
+ Yield = 0)
+
+ if (nargin < 5 || nargin > 6)
+ print_usage ();
+ endif
+
+ blscheck ("blsprice", Price, Strike, Rate, Time, Volatility, Yield);
+
+ sigma_sqrtT = Volatility .* sqrt (Time);
+
+ d1 = 1 ./ sigma_sqrtT .* (log (Price ./ Strike) + (Rate - Yield + ...
+ Volatility.^2 / 2) .* Time);
+ d2 = d1 - sigma_sqrtT;
+
+ phi1 = normcdf (d1);
+ phi2 = normcdf (d2);
+ disc = exp (-Rate .* Time);
+ F = Price .* exp ((Rate - Yield) .* Time);
+
+ Call = disc .* (F .* phi1 - Strike .* phi2 );
+ Put = disc .* (Strike .* (1 - phi2) + F .* (phi1 - 1));
+
+endfunction
+
+## Tests
+%!test
+%! [Call, Put] = blsprice (90:10:110, 100, 0.04, 1, 0.2, 0.01);
+%! assert (Call, [4.4037 9.3197 16.1217], 1e-4)
+%! assert (Put, [11.3781 6.3937 3.2952], 1e-4)
+
+## Test input validation
+%!error blsprice ()
+%!error blsprice (1)
+%!error blsprice (1, 2)
+%!error blsprice (1, 2, 3)
+%!error blsprice (1, 2, 3, 4)
+%!error blsprice ("invalid", "type", "argument", 4, 5)
+%!error blsprice ({1, 2, 3}, [2 7 8], [8 3 1], 4, 10)
diff --git a/inst/blsrho.m b/inst/blsrho.m
new file mode 100644
index 0000000..339b15e
--- /dev/null
+++ b/inst/blsrho.m
@@ -0,0 +1,74 @@
+## Copyright (C) 2013 Parsiad Azimzadeh <parsiad.azimzadeh@gmail.com>
+##
+## This program is free software; you can redistribute it and/or modify it under
+## the terms of the GNU Lesser 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 Lesser General Public License
+## for more details.
+##
+## You should have received a copy of the GNU Lesser General Public License
+## along with this program; if not, see <http://www.gnu.org/licenses/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function File} {[@var{CallRho}, @var{PutRho}] =} blsrho (@var{Price}, @var{Strike}, @var{Rate}, @var{Time}, @var{Volatility})
+## @deftypefnx {Function File} {[@var{CallRho}, @var{PutRho}] =} blsrho (@var{Price}, @var{Strike}, @var{Rate}, @var{Time}, @var{Volatility}, @var{Yield})
+## Compute the Black-Scholes rho.
+##
+## @itemize
+## @item
+## Variable: @var{Price} The current price of the underlying asset.
+## @item
+## Variable: @var{Strike} The strike price the option is written on.
+## @item
+## Variable: @var{Rate} The risk-free interest rate.
+## @item
+## Variable: @var{Time} The time-to-expiry.
+## @item
+## Variable: @var{Volatility} The volatility of the underlying asset.
+## @item
+## Variable: @var{Yield} (Optional, default = 0) Annualized, continuously
+## compounded rate of dividends of the underlying asset.
+## @end itemize
+##
+## Computes the Black-Scholes rho, the rate of change of the option value with
+## respect to the risk-free interest rate.
+##
+## @seealso{blsdelta, blsgamma, blslambda, blsprice, blstheta, blsvega}
+## @end deftypefn
+
+function [CallRho, PutRho] = blsrho (Price, Strike, Rate, Time, Volatility, ...
+ Yield = 0)
+
+ if (nargin < 5 || nargin > 6)
+ print_usage ();
+ endif
+
+ blscheck ("blsrho", Price, Strike, Rate, Time, Volatility, Yield);
+
+ d2 = 1 ./ (Volatility .* sqrt (Time)) .* (log (Price ./ Strike) + ...
+ (Rate - Yield - Volatility .^2 / 2) .* Time);
+
+ phi = normcdf(d2);
+ common = Strike .* Time .* exp (-Rate .* Time);
+
+ CallRho = common .* phi;
+ PutRho = common .* (phi - 1);
+
+endfunction
+
+## Tests
+%!test
+%! [CallRho, PutRho] = blsrho (90:10:110, 100, 0.04, 1, 0.2, 0.01);
+%! assert (CallRho, [30.4331 49.9552 67.3271], 1e-4)
+%! assert (PutRho, [-65.6458 -46.1238 -28.7519], 1e-4)
+
+## Test input validation
+%!error blsrho ()
+%!error blsrho (1)
+%!error blsrho (1, 2)
+%!error blsrho (1, 2, 3)
+%!error blsrho (1, 2, 3, 4)
diff --git a/inst/blstheta.m b/inst/blstheta.m
new file mode 100644
index 0000000..469e3fb
--- /dev/null
+++ b/inst/blstheta.m
@@ -0,0 +1,82 @@
+## Copyright (C) 2013 Parsiad Azimzadeh <parsiad.azimzadeh@gmail.com>
+##
+## This program is free software; you can redistribute it and/or modify it under
+## the terms of the GNU Lesser 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 Lesser General Public License
+## for more details.
+##
+## You should have received a copy of the GNU Lesser General Public License
+## along with this program; if not, see <http://www.gnu.org/licenses/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function File} {[@var{CallTheta}, @var{PutTheta}] =} blstheta (@var{Price}, @var{Strike}, @var{Rate}, @var{Time}, @var{Volatility})
+## @deftypefnx {Function File} {[@var{CallTheta}, @var{PutTheta}] =} blstheta (@var{Price}, @var{Strike}, @var{Rate}, @var{Time}, @var{Volatility}, @var{Yield})
+## Compute the Black-Scholes theta.
+##
+## @itemize
+## @item
+## Variable: @var{Price} The current price of the underlying asset.
+## @item
+## Variable: @var{Strike} The strike price the option is written on.
+## @item
+## Variable: @var{Rate} The risk-free interest rate.
+## @item
+## Variable: @var{Time} The time-to-expiry.
+## @item
+## Variable: @var{Volatility} The volatility of the underlying asset.
+## @item
+## Variable: @var{Yield} (Optional, default = 0) Annualized, continuously
+## compounded rate of dividends of the underlying asset.
+## @end itemize
+##
+## Computes the Black-Scholes theta, the rate of change of the option value with
+## respect to the time-to-expiry.
+##
+## @seealso{blsdelta, blsgamma, blslambda, blsprice, blsrho, blsvega}
+## @end deftypefn
+
+function [CallTheta, PutTheta] = blstheta (Price, Strike, Rate, Time, ...
+ Volatility, Yield = 0)
+
+ if (nargin < 5 || nargin > 6)
+ print_usage ();
+ endif
+
+ blscheck ("blstheta", Price, Strike, Rate, Time, Volatility, Yield);
+
+ sqrtT = sqrt (Time);
+ sigma_sqrtT = Volatility .* sqrtT;
+
+ d1 = 1 ./ sigma_sqrtT .* (log (Price ./ Strike) + (Rate - Yield + Volatility.^2 / 2) .* Time);
+ d2 = d1 - sigma_sqrtT;
+
+ phi1 = normcdf (d1);
+ phi2 = normcdf (d2);
+
+ disc = exp (-Yield .* Time);
+ shift = -disc .* Price .* normpdf (d1) .* Volatility / 2 ./ sqrtT;
+ t1 = Rate .* Strike .* exp (-Rate .* Time);
+ t2 = Yield .* Price .* disc;
+
+ CallTheta = shift - t1 .* phi2 + t2 .* phi1 ;
+ PutTheta = shift + t1 .* (1 - phi2) + t2 .* (phi1 - 1);
+
+endfunction
+
+## Tests
+%!test
+%! [CallTheta, PutTheta] = blstheta (90:10:110, 100, 0.04, 1, 0.2, 0.01);
+%! assert (CallTheta, [-4.2901 -5.2337 -5.1954], 1e-4)
+%! assert (PutTheta, [-1.3380 -2.3806 -2.4413], 1e-4)
+
+## Test input validation
+%!error blstheta ()
+%!error blstheta (1)
+%!error blstheta (1, 2)
+%!error blstheta (1, 2, 3)
+%!error blstheta (1, 2, 3, 4)
diff --git a/inst/blsvega.m b/inst/blsvega.m
new file mode 100644
index 0000000..2533b82
--- /dev/null
+++ b/inst/blsvega.m
@@ -0,0 +1,66 @@
+## Copyright (C) 2013 Parsiad Azimzadeh <parsiad.azimzadeh@gmail.com>
+##
+## This program is free software; you can redistribute it and/or modify it under
+## the terms of the GNU Lesser 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 Lesser General Public License
+## for more details.
+##
+## You should have received a copy of the GNU Lesser General Public License
+## along with this program; if not, see <http://www.gnu.org/licenses/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function File} {@var{Vega} =} blsvega (@var{Price}, @var{Strike}, @var{Rate}, @var{Time}, @var{Volatility})
+## @deftypefnx {Function File} {@var{Vega} =} blsvega (@var{Price}, @var{Strike}, @var{Rate}, @var{Time}, @var{Volatility}, @var{Yield})
+## Computes the Black-Scholes vega.
+##
+## @itemize
+## @item
+## Variable: @var{Price} The current price of the underlying asset.
+## @item
+## Variable: @var{Strike} The strike price the option is written on.
+## @item
+## Variable: @var{Rate} The risk-free interest rate.
+## @item
+## Variable: @var{Time} The time-to-expiry.
+## @item
+## Variable: @var{Volatility} The volatility of the underlying asset.
+## @item
+## Variable: @var{Yield} (Optional, default = 0) Annualized, continuously compounded rate of dividends of the underlying asset.
+## @end itemize
+##
+## Computes the Black-Scholes vega, the rate of change of the option value with
+## respect to the volatility of the underlying asset.
+##
+## @seealso{blsdelta, blsgamma, blslambda, blsprice, blsrho, blstheta}
+## @end deftypefn
+
+function Vega = blsvega (Price, Strike, Rate, Time, Volatility, Yield = 0)
+
+ if (nargin < 5 || nargin > 6)
+ print_usage ();
+ endif
+
+ blscheck ("blsvega", Price, Strike, Rate, Time, Volatility, Yield);
+
+ sqrtT = sqrt (Time);
+ d1 = 1 ./ (Volatility .* sqrtT) .* (log (Price ./ Strike) + ...
+ (Rate - Yield + Volatility.^2 / 2) .* Time);
+ Vega = Price .* exp (-Yield .* Time) .* normpdf (d1) .* sqrtT;
+
+endfunction
+
+## Tests
+%!test
+%assert (blsvega(90:10:110, 100, 0.04, 1, 0.2, 0.01), [34.2115 38.2821 33.3682], 1e-4)
+
+## Test input validation
+%!error blsvega ()
+%!error blsvega (1)
+%!error blsvega (1, 2)
+%!error blsvega (1, 2, 3)
+%!error blsvega (1, 2, 3, 4)
diff --git a/inst/bm.m b/inst/bm.m
new file mode 100644
index 0000000..0c8601f
--- /dev/null
+++ b/inst/bm.m
@@ -0,0 +1,47 @@
+## Copyright (C) 2016 Parsiad Azimzadeh <parsiad.azimzadeh@gmail.com>
+##
+## This program is free software; you can redistribute it and/or modify it under
+## the terms of the GNU Lesser 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 Lesser General Public License
+## for more details.
+##
+## You should have received a copy of the GNU Lesser General Public License
+## along with this program; if not, see <http://www.gnu.org/licenses/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function File} {@var{BM} =} bm (@var{Mu}, @var{Sigma})
+## @deftypefnx {Function File} {@var{BM} =} bm (@var{Mu}, @var{Sigma}, @var{OptionName}, @var{OptionValue}, @dots{})
+## Creates an object to represent an arithmetic Brownian motion.
+##
+## @center dX_t = @var{Mu}(t)dt + @var{Sigma}(t)dW_t.
+##
+## See the @@sde documentation for a list of optional arguments.
+##
+## @seealso{sde}
+## @end deftypefn
+
+function BM = bm (Mu, Sigma, varargin)
+
+ if (nargin < 2)
+ print_usage ();
+ endif
+
+ ## Infer NVARS
+ NVARS = 0;
+ if (isnumeric (Mu))
+ NVARS = rows (Mu);
+ elseif (isnumeric (Sigma))
+ NVARS = rows (Sigma);
+ else
+ NVARS = sdenvars (varargin{:});
+ endif
+
+ BM = sdeld (Mu, zeros (NVARS, NVARS), zeros (NVARS, 1), Sigma, varargin{:});
+
+endfunction
+
diff --git a/inst/bolling.m b/inst/bolling.m
new file mode 100644
index 0000000..4e6d9e8
--- /dev/null
+++ b/inst/bolling.m
@@ -0,0 +1,81 @@
+## Copyright (C) 2008 Bill Denney <bill@denney.ws>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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) = width * std (asset(1:samples));
+ for i = samples+1:length (asset)
+ s(i) = width * std (asset(i - samples + 1:i));
+ endfor
+
+ if nargout > 0
+ varargout{1} = avg;
+ else
+ x = 1:length (avg);
+ h = plot (x, asset, x, avg, x, avg .+ [-s, s], "-r");
+ cls = get (gca, "colororder");
+ set (h(4), "color", cls(3,:));
+ endif
+ if nargout > 1
+ varargout{2} = avg + s;
+ endif
+ if nargout > 2
+ varargout{3} = avg - s;
+ endif
+
+endfunction
+
+## Test input validation
+%!error bolling ()
+%!error bolling (1)
+%!error bolling (1, 2)
+%!error bolling ("invalid", "type")
diff --git a/inst/busdate.m b/inst/busdate.m
new file mode 100644
index 0000000..0c43102
--- /dev/null
+++ b/inst/busdate.m
@@ -0,0 +1,97 @@
+## Copyright (C) 2008 Bill Denney <bill@denney.ws>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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,3)])
+%!assert(busdate([datenum(2008,1,2) datenum(2007,1,1)], [1 1]), [datenum(2008,1,3) datenum(2007,1,3)])
+%!assert(busdate([datenum(2008,1,2) datenum(2007,1,1)], 1), [datenum(2008,1,3) datenum(2007,1,3)])
+%!assert(busdate([datenum(2008,1,2);datenum(2007,1,1)], [1;1]), [datenum(2008,1,3);datenum(2007,1,3)])
+## 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))
diff --git a/inst/busdays.m b/inst/busdays.m
new file mode 100644
index 0000000..4314a81
--- /dev/null
+++ b/inst/busdays.m
@@ -0,0 +1,127 @@
+## Copyright (C) 2008 Bill Denney <bill@denney.ws>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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;31;30]))
diff --git a/inst/candle.m b/inst/candle.m
new file mode 100644
index 0000000..ab1e90b
--- /dev/null
+++ b/inst/candle.m
@@ -0,0 +1,319 @@
+## Copyright (C) 2017 dekalog (https://dekalogblog.blogspot.com)
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function File} candle (@var{HighPrices}, @var{LowPrices}, @var{ClosePrices}, @var{OpenPrices})
+## @deftypefnx {Function File} candle (@var{HighPrices}, @var{LowPrices}, @var{ClosePrices}, @var{OpenPrices}, @var{color})
+## @deftypefnx {Function File} candle (@var{HighPrices}, @var{LowPrices}, @var{ClosePrices}, @var{OpenPrices}, @var{color}, @var{dates})
+## @deftypefnx {Function File} candle (@var{HighPrices}, @var{LowPrices}, @var{ClosePrices}, @var{OpenPrices}, @var{color}, @var{dates}, @var{dateform})
+## Plot the @var{HighPrices}, @var{LowPrices}, @var{ClosePrices} and @var{OpenPrices} of a security as a candlestick chart.
+##
+## @itemize
+## @item
+## Variable: @var{HighPrices} Column vector of high prices for a security.
+## @item
+## Variable: @var{LowPrices} Column vector of low prices for a security.
+## @item
+## Variable: @var{ClosePrices} Column vector of close prices for a security.
+## @item
+## Variable: @var{OpenPrices} Column vector of open prices for a security.
+## @item
+## Variable: @var{Color} (Optional, default = "brwk") Candlestick color is
+## specified as a case insensitive four character row vector, e.g. "brwk". The
+## characters that are accepted are k, b, c, r, m, w, g and y for black, blue,
+## cyan, red, magenta, white, green and yellow respectively. Default colors are
+## "brwk" applied in order to bars where the closing price is greater than the
+## opening price, bars where the closing price is less than the opening price,
+## the chart background color and the candlestick wicks. If fewer than four
+## colors are specified, they are applied in turn in the above order with
+## default colors for unspecified colors. For example, user supplied colors
+## "gm" will plot green upbars and magenta downbars with a default white
+## background and black wicks. If the user specified color for background is
+## black, without specifying the wick color, e.g. "gmk", the default wick color
+## is white. All other choices for background color will default to black for
+## wicks. If all four colors are user specified, those colors will be used. Doji
+## bars and single price bars, e.g. open = high = low = close, are plotted with
+## the color for wicks, with single price bars being plotted as points/dots.
+## @item
+## Variable: @var{Dates} (Optional) Dates for user specified x-axis tick labels.
+## Dates can be a serial date number column (see datenum), a datevec matrix (See
+## datevec) or a character vector of dates. If specified as either a datenum or
+## a datevec, the @var{Dateform} argument is required.
+## @item
+## Variable: @var{Dateform} (Optional) Either a date character string or a
+## single integer code number used to format the x-axis tick labels (See
+## datestr). Only required if @var{Dates} is specified as a serial date number
+## column (See datenum) or a datevec matrix (See datevec).
+## @end itemize
+##
+## @seealso{datenum, datestr, datevec, highlow, bolling, dateaxis, movavg,
+## pointfig}
+## @end deftypefn
+
+function candle (varargin)
+
+ ## Input checking
+ if (nargin < 4 || nargin > 7)
+ print_usage ();
+ endif
+ HighPrices = varargin{1};
+ LowPrices = varargin{2};
+ ClosePrices = varargin{3};
+ OpenPrices = varargin{4};
+ if (nargin == 4)
+ color = "brwk";
+ endif
+ if (nargin >= 5)
+ color = varargin{5};
+ endif
+ if (nargin >= 6)
+ dates = varargin{6};
+ endif
+ if (nargin >= 7)
+ dateform = varargin{7};
+ endif
+ function retval = is_price_vector (prices)
+ retval = isnumeric (prices) && isvector (prices) && iscolumn (prices);
+ endfunction
+ if ( ! (is_price_vector (HighPrices) && is_price_vector (LowPrices) && ...
+ is_price_vector (ClosePrices) && is_price_vector (OpenPrices) ) )
+ error ("candle: prices must be numeric column vector");
+ endif
+ num_points = length (HighPrices);
+ if ( ! (num_points == length (LowPrices) && ...
+ num_points == length (ClosePrices) && ...
+ num_points == length (OpenPrices) ) )
+ error ("candle: price vectors must be of the same size");
+ endif
+
+ ## Make figure
+ fig = figure;
+ washold = ishold;
+ hold on;
+
+ ## Is color a character vector?
+ if (ischar (color) && size (color, 1) == 1)
+ if (size (color, 2) == 1) # only one color has been user specified
+ color = [tolower(color) "rwk"]; # so add default colors for down bars, background and wicks
+ elseif (size (color, 2) == 2) # two colors have been user specified
+ color = [tolower(color) "wk"]; # so add default colors for background and wicks
+ elseif (size (color, 2) == 3) # three colors have been user specified
+ if (color(3) == "k" || color(3) == "K") # if user selected background is black
+ color = [tolower(color) "w"]; # set wicks to default white
+ else
+ color = [tolower(color) "k"]; # else default black wicks
+ endif
+ elseif (size (color, 2) >= 4) # all four colors have been user specified, extra character inputs ignored
+ color = tolower (color); # correct in case user input contains upper case e.g. "BRWK"
+ endif
+ else
+ warning ("candle: COLOR should be a character row vector; ignoring user input");
+ color = "brwk";
+ endif # end of nargin >= 5 && ischar (color) && size (color, 1) == 1 if statement
+
+ x = 1 : num_points;
+ wicks = HighPrices .- LowPrices;
+ body = ClosePrices .- OpenPrices;
+ up_down = sign (body);
+ scaling = 10 / num_points;
+ body_width = max(20 * scaling, 1);
+ wick_width = 1;
+ doji_size = 10 * max(scaling, 1);
+ one_price_size = 2 * max(scaling, 1);
+
+ ## Background color
+ plot (HighPrices, color(3), LowPrices, color(3));
+ fill ( [ min(xlim) max(xlim) max(xlim) min(xlim) ], ...
+ [ min(ylim) min(ylim) max(ylim) max(ylim) ], color(3) );
+
+ function [X, Y] = helper(idx, hi, lo)
+ high_nan = low_nan = nan (num_points, 1);
+ high_nan(idx) = hi(idx);
+ low_nan(idx) = lo(idx);
+ X = reshape ([ x ; x ; nan(1, num_points) ], [], 1);
+ Y = reshape ([ high_nan(:)'; low_nan(:)'; nan(1, num_points) ], [], 1);
+ endfunction
+
+ ## Plot the wicks
+ [X, Y] = helper(1 : num_points, HighPrices, LowPrices);
+ plot (X, Y, color(4), "linewidth", wick_width);
+
+ ## FIXME: Use rectangle bar bodies
+
+ ## Plot the up bar bodies
+ [X, Y] = helper (find (up_down == 1), ClosePrices, OpenPrices);
+ plot (X, Y, color(1), "linewidth", body_width);
+
+ ## Plot the down bar bodies
+ [X, Y] = helper (find (up_down == -1), OpenPrices, ClosePrices);
+ plot (X, Y, color( 2 ), "linewidth", body_width);
+
+ ## Doji bars
+ doji_ix = find ((HighPrices > LowPrices) .* (ClosePrices == OpenPrices));
+ if (length (doji_ix) >= 1)
+ plot (x(doji_ix), ClosePrices(doji_ix), ["+" char(color(4))], "markersize", doji_size);
+ endif
+
+ ## Prices all the same
+ one_price_ix = find ((HighPrices == LowPrices) .* (HighPrices == OpenPrices) .* (HighPrices == ClosePrices));
+ if (length (one_price_ix) >= 1)
+ plot (x(one_price_ix), ClosePrices(one_price_ix), ["." char(color(4))], "markersize", one_price_size);
+ endif
+
+ ## Revert to previous value of hold
+ if (! washold)
+ hold off
+ endif
+
+ ## No date argument
+ if (nargin < 6)
+ return
+ endif
+ if (! ismatrix (dates))
+ warning ("candle: DATES must be a matrix; ignoring DATES");
+ return
+ endif
+ if (! (isnumeric (dates) || ischar (dates)))
+ warning ("candle: DATES must be of numeric or character type");
+ return
+ endif
+ if (size (dates, 1) != num_points)
+ warning ("candle: DATES and price vectors must be of the same length; ignoring DATES");
+ return
+ endif
+ if (nargin < 7 && isnumeric (dates))
+ warning ("candle: if DATES is a serial date number (see datenum) or a datevec matrix (see datevec), DATEFORM is required; ignoring DATES");
+ return
+ endif
+ if (nargin >= 7)
+ if (ischar (dates))
+ warning ("candle: DATES is of character type but DATEFORM is also specified; ignoring DATES");
+ return
+ endif
+ if (isnumeric (dateform) && (dateform < 0 || dateform > 31))
+ warning ("candle: DATEFORM integer code number is out of bounds (See datestr); ignoring DATES");
+ return
+ elseif (isnumeric (dateform) && rem (dateform, 1) > 0)
+ warning ("candle: DATEFORM code number should be an integer 0 - 31 (See datestr); ignoring DATES");
+ return
+ endif
+ if (size (dates, 2) == 1)
+ is_monotonically_increasing = sum (dates == cummax (dates)) / size (dates, 1);
+ if (is_monotonically_increasing != 1)
+ warning ("candle: DATES does not appear to be a serial date number column as it is not monotonically increasing; ignoring DATES");
+ return
+ endif
+ endif
+ endif
+
+ if (nargin == 6)
+ ticks = cellstr (dates);
+ else
+ ticks = datestr (dates, dateform);
+ ticks = mat2cell (ticks, ones (size (ticks, 1), 1), size (ticks, 2));
+ endif
+
+ ## FIXME: choose the number of ticks in a smarter way
+ num_ticks = 5;
+ xx = 1 : floor(num_points / num_ticks) : num_points;
+
+ h = gca ();
+ set (h, "xtick", xx);
+ set (h, ["x" "ticklabel"], ticks(xx));
+
+endfunction
+
+%!demo 1
+%! close();
+%! OpenPrices = [ 1292.4; 1291.7; 1291.8; 1292.2; 1291.5; 1291.0; 1291.0; 1291.5; 1291.7; 1291.5; 1290.7 ];
+%! HighPrices = [ 1292.6; 1292.1; 1292.5; 1292.3; 1292.2; 1292.2; 1292.7; 1292.4; 1292.3; 1292.1; 1292.9 ];
+%! LowPrices = [ 1291.3; 1291.3; 1291.7; 1291.1; 1290.7; 1290.2; 1290.3; 1291.1; 1291.2; 1290.5; 1290.4 ];
+%! ClosePrices = [ 1291.8; 1291.7; 1292.2; 1291.5; 1291.0; 1291.1; 1291.5; 1291.7; 1291.6; 1290.8; 1292.8 ];
+%! candle( HighPrices, LowPrices, ClosePrices, OpenPrices );
+%! title("default plot.");
+
+%!demo 2
+%! close();
+%! OpenPrices = [ 1292.4; 1291.7; 1291.8; 1292.2; 1291.5; 1291.0; 1291.0; 1291.5; 1291.7; 1291.5; 1290.7 ];
+%! HighPrices = [ 1292.6; 1292.1; 1292.5; 1292.3; 1292.2; 1292.2; 1292.7; 1292.4; 1292.3; 1292.1; 1292.9 ];
+%! LowPrices = [ 1291.3; 1291.3; 1291.7; 1291.1; 1290.7; 1290.2; 1290.3; 1291.1; 1291.2; 1290.5; 1290.4 ];
+%! ClosePrices = [ 1291.8; 1291.7; 1292.2; 1291.5; 1291.0; 1291.1; 1291.5; 1291.7; 1291.6; 1290.8; 1292.8 ];
+%! candle( HighPrices, LowPrices, ClosePrices, OpenPrices, 'brk' );
+%! title("default plot with user selected black background");
+
+%!demo 3
+%! close();
+%! OpenPrices = [ 1292.4; 1291.7; 1291.8; 1292.2; 1291.5; 1291.0; 1291.0; 1291.5; 1291.7; 1291.5; 1290.7 ];
+%! HighPrices = [ 1292.6; 1292.1; 1292.5; 1292.3; 1292.2; 1292.2; 1292.7; 1292.4; 1292.3; 1292.1; 1292.9 ];
+%! LowPrices = [ 1291.3; 1291.3; 1291.7; 1291.1; 1290.7; 1290.2; 1290.3; 1291.1; 1291.2; 1290.5; 1290.4 ];
+%! ClosePrices = [ 1291.8; 1291.7; 1292.2; 1291.5; 1291.0; 1291.1; 1291.5; 1291.7; 1291.6; 1290.8; 1292.8 ];
+%! candle( HighPrices, LowPrices, ClosePrices, OpenPrices, 'brkg' );
+%! title("default color candlestick bodies and user selected background and wick colors");
+
+%!demo 4
+%! close();
+%! OpenPrices = [ 1292.4; 1291.7; 1291.8; 1292.2; 1291.5; 1291.0; 1291.0; 1291.5; 1291.7; 1291.5; 1290.7 ];
+%! HighPrices = [ 1292.6; 1292.1; 1292.5; 1292.3; 1292.2; 1292.2; 1292.7; 1292.4; 1292.3; 1292.1; 1292.9 ];
+%! LowPrices = [ 1291.3; 1291.3; 1291.7; 1291.1; 1290.7; 1290.2; 1290.3; 1291.1; 1291.2; 1290.5; 1290.4 ];
+%! ClosePrices = [ 1291.8; 1291.7; 1292.2; 1291.5; 1291.0; 1291.1; 1291.5; 1291.7; 1291.6; 1290.8; 1292.8 ];
+%! candle( HighPrices, LowPrices, ClosePrices, OpenPrices, 'gmby' );
+%! title("all four colors being user selected");
+
+%!demo 5
+%! close();
+%! OpenPrices = [ 1292.4; 1291.7; 1291.8; 1292.2; 1291.5; 1291.0; 1291.0; 1291.5; 1291.7; 1291.5; 1290.7 ];
+%! HighPrices = [ 1292.6; 1292.1; 1292.5; 1292.3; 1292.2; 1292.2; 1292.7; 1292.4; 1292.3; 1292.1; 1292.9 ];
+%! LowPrices = [ 1291.3; 1291.3; 1291.7; 1291.1; 1290.7; 1290.2; 1290.3; 1291.1; 1291.2; 1290.5; 1290.4 ];
+%! ClosePrices = [ 1291.8; 1291.7; 1292.2; 1291.5; 1291.0; 1291.1; 1291.5; 1291.7; 1291.6; 1290.8; 1292.8 ];
+%! datenum_vec = [ 7.3702e+05; 7.3702e+05 ;7.3702e+05; 7.3702e+05; 7.3702e+05; 7.3702e+05; 7.3702e+05; ...
+%! 7.3702e+05; 7.3702e+05; 7.3702e+05; 7.3702e+05 ];
+%! candle( HighPrices, LowPrices, ClosePrices, OpenPrices, 'brwk', datenum_vec, "yyyy-mm-dd" );
+%! title("default plot with datenum dates and character dateform arguments");
+
+%!demo 6
+%! close();
+%! OpenPrices = [ 1292.4; 1291.7; 1291.8; 1292.2; 1291.5; 1291.0; 1291.0; 1291.5; 1291.7; 1291.5; 1290.7 ];
+%! HighPrices = [ 1292.6; 1292.1; 1292.5; 1292.3; 1292.2; 1292.2; 1292.7; 1292.4; 1292.3; 1292.1; 1292.9 ];
+%! LowPrices = [ 1291.3; 1291.3; 1291.7; 1291.1; 1290.7; 1290.2; 1290.3; 1291.1; 1291.2; 1290.5; 1290.4 ];
+%! ClosePrices = [ 1291.8; 1291.7; 1292.2; 1291.5; 1291.0; 1291.1; 1291.5; 1291.7; 1291.6; 1290.8; 1292.8 ];
+%! datenum_vec = [ 7.3702e+05; 7.3702e+05 ;7.3702e+05; 7.3702e+05; 7.3702e+05; 7.3702e+05; 7.3702e+05; ...
+%! 7.3702e+05; 7.3702e+05; 7.3702e+05; 7.3702e+05 ];
+%! candle( HighPrices, LowPrices, ClosePrices, OpenPrices, 'brk', datenum_vec, 29 );
+%! title("default plot with user selected black background with datenum dates and integer dateform arguments");
+
+%!demo 7
+%! close();
+%! OpenPrices = [ 1292.4; 1291.7; 1291.8; 1292.2; 1291.5; 1291.0; 1291.0; 1291.5; 1291.7; 1291.5; 1290.7 ];
+%! HighPrices = [ 1292.6; 1292.1; 1292.5; 1292.3; 1292.2; 1292.2; 1292.7; 1292.4; 1292.3; 1292.1; 1292.9 ];
+%! LowPrices = [ 1291.3; 1291.3; 1291.7; 1291.1; 1290.7; 1290.2; 1290.3; 1291.1; 1291.2; 1290.5; 1290.4 ];
+%! ClosePrices = [ 1291.8; 1291.7; 1292.2; 1291.5; 1291.0; 1291.1; 1291.5; 1291.7; 1291.6; 1290.8; 1292.8 ];
+%! datenum_vec = [ 7.3702e+05; 7.3702e+05 ;7.3702e+05; 7.3702e+05; 7.3702e+05; 7.3702e+05; 7.3702e+05; ...
+%! 7.3702e+05; 7.3702e+05; 7.3702e+05; 7.3702e+05 ];
+%! datevec_vec = datevec( datenum_vec );
+%! candle( HighPrices, LowPrices, ClosePrices, OpenPrices, 'brwk', datevec_vec, 23 );
+%! title("default plot with datevec dates and integer dateform arguments");
+
+%!demo 8
+%! close();
+%! OpenPrices = [ 1292.4; 1291.7; 1291.8; 1292.2; 1291.5; 1291.0; 1291.0; 1291.5; 1291.7; 1291.5; 1290.7 ];
+%! HighPrices = [ 1292.6; 1292.1; 1292.5; 1292.3; 1292.2; 1292.2; 1292.7; 1292.4; 1292.3; 1292.1; 1292.9 ];
+%! LowPrices = [ 1291.3; 1291.3; 1291.7; 1291.1; 1290.7; 1290.2; 1290.3; 1291.1; 1291.2; 1290.5; 1290.4 ];
+%! ClosePrices = [ 1291.8; 1291.7; 1292.2; 1291.5; 1291.0; 1291.1; 1291.5; 1291.7; 1291.6; 1290.8; 1292.8 ];
+%! character_dates = char ( [] );
+%! for i = 1 : 11
+%! character_dates = [ character_dates ; "a date" ] ;
+%! endfor
+%! candle( HighPrices, LowPrices, ClosePrices, OpenPrices, 'brk', character_dates );
+%! title("default plot with user selected black background with character dates argument");
diff --git a/inst/cev.m b/inst/cev.m
new file mode 100644
index 0000000..cfff831
--- /dev/null
+++ b/inst/cev.m
@@ -0,0 +1,49 @@
+## Copyright (C) 2016 Parsiad Azimzadeh <parsiad.azimzadeh@gmail.com>
+##
+## This program is free software; you can redistribute it and/or modify it under
+## the terms of the GNU Lesser 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 Lesser General Public License
+## for more details.
+##
+## You should have received a copy of the GNU Lesser General Public License
+## along with this program; if not, see <http://www.gnu.org/licenses/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function File} {@var{CEV} =} cev (@var{Return}, @var{Alpha}, @var{Sigma})
+## @deftypefnx {Function File} {@var{CEV} =} cev (@var{Return}, @var{Alpha}, @var{Sigma}, @var{OptionName}, @var{OptionValue}, @dots{})
+## Creates an object to represent a constant elasticity of variance (CEV)
+## stochastic differential equation (SDE).
+##
+## @center dX_t = (@var{Return}(t) * X_t)dt + (diag(X_t.^@var{Alpha}(t)) * @var{Sigma}(t))dW_t
+##
+## See the @@sde documentation for a list of optional arguments.
+##
+## @seealso{sde}
+## @end deftypefn
+
+function CEV = cev (Return, Alpha, Sigma, varargin)
+
+ if (nargin < 3)
+ print_usage ();
+ endif
+
+ ## Infer NVARS
+ NVARS = 0;
+ if (isnumeric (Return))
+ NVARS = rows (Return);
+ elseif (isnumeric (Alpha))
+ NVARS = rows (Alpha);
+ elseif (isnumeric (Sigma))
+ NVARS = rows (Sigma);
+ else
+ NVARS = sdenvars (varargin{:});
+ endif
+
+ CEV = sdeld (zeros (NVARS, 1), Return, Alpha, Sigma, varargin{:});
+
+endfunction
diff --git a/inst/cfconv.m b/inst/cfconv.m
new file mode 100644
index 0000000..85a987f
--- /dev/null
+++ b/inst/cfconv.m
@@ -0,0 +1,60 @@
+## Copyright (C) 2011 Hong Yu <hyu0401@hotmail.com>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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)
diff --git a/inst/cfdur.m b/inst/cfdur.m
new file mode 100644
index 0000000..02582be
--- /dev/null
+++ b/inst/cfdur.m
@@ -0,0 +1,62 @@
+## Copyright (C) 2011 Hong Yu <hyu0401@hotmail.com>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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 )
diff --git a/inst/cir.m b/inst/cir.m
new file mode 100644
index 0000000..cfa48f7
--- /dev/null
+++ b/inst/cir.m
@@ -0,0 +1,64 @@
+## Copyright (C) 2016 Parsiad Azimzadeh <parsiad.azimzadeh@gmail.com>
+##
+## This program is free software; you can redistribute it and/or modify it under
+## the terms of the GNU Lesser 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 Lesser General Public License
+## for more details.
+##
+## You should have received a copy of the GNU Lesser General Public License
+## along with this program; if not, see <http://www.gnu.org/licenses/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function File} {@var{CIR} =} cir (@var{Speed}, @var{Level}, @var{Sigma})
+## @deftypefnx {Function File} {@var{CIR} =} cir (@var{Speed}, @var{Level}, @var{Sigma}, @var{OptionName}, @var{OptionValue}, @dots{})
+## Creates an object to represent a Cox-Ingersoll-Ross (CIR) mean-reverting
+## square root diffusion.
+##
+## @center dX_t = (@var{Speed}(t) * (@var{Level}(t) - X_t))dt + (diag(X_t.^1/2) * @var{Sigma}(t))dW_t.
+##
+## See the @@sde documentation for a list of optional arguments.
+##
+## @seealso{sde}
+## @end deftypefn
+
+function CIR = cir (Speed, Level, Sigma, varargin)
+
+ if (nargin < 3)
+ print_usage ();
+ endif
+
+ ## Infer NVARS
+ NVARS = 0;
+ if (isnumeric (Speed))
+ NVARS = rows (Speed);
+ elseif (isnumeric (Level))
+ NVARS = rows (Level);
+ elseif (isnumeric (Sigma))
+ NVARS = rows (Sigma);
+ else
+ NVARS = sdenvars (varargin{:});
+ endif
+
+ CIR = sdemrd (Speed, Level, ones (NVARS, 1) * .5, Sigma, varargin{:});
+
+endfunction
+
+## Bond pricing test
+%!test
+%! InitialInterestRate = 0.03; Speed = 1.; MeanInterestRate = 0.04; Volatility = 0.3; ExpiryTime = 1.;
+%! Simulations = 1e4; Timesteps = 100;
+%! SDE = cir (Speed, MeanInterestRate, Volatility, "StartState", InitialInterestRate);
+%! [Paths, ~, ~] = simByEuler (SDE, Timesteps, "DeltaTime", ExpiryTime / Timesteps, "NTRIALS", Simulations, "NSTEPS", 1, "Antithetic", true, "Processes", @(t, X) max(X, 0));
+%! BondApproximate = mean (exp (-(sum (Paths) - InitialInterestRate) * ExpiryTime / Timesteps));
+%! h = sqrt (Speed * Speed + 2 * Volatility * Volatility);
+%! d = (2 * h + (Speed + h) * (exp (ExpiryTime * h) - 1));
+%! A = ( (2 * h * exp ((Speed + h) * ExpiryTime / 2)) / d )^((2 * Speed * MeanInterestRate) / (Volatility * Volatility));
+%! B = 2 * (exp (ExpiryTime * h) - 1) / d;
+%! Bond = A * exp (-B * InitialInterestRate);
+%! assert (BondApproximate, Bond, 1e-3);
+
diff --git a/inst/corr2cov.m b/inst/corr2cov.m
new file mode 100644
index 0000000..caa657c
--- /dev/null
+++ b/inst/corr2cov.m
@@ -0,0 +1,55 @@
+## Copyright (C) 2011 Hong Yu <hyu0401@hotmail.com>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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 ] )
diff --git a/inst/cov2corr.m b/inst/cov2corr.m
new file mode 100644
index 0000000..23de4ef
--- /dev/null
+++ b/inst/cov2corr.m
@@ -0,0 +1,53 @@
+## Copyright (C) 2011 Hong Yu <hyu0401@hotmail.com>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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] );
diff --git a/inst/dateaxis.m b/inst/dateaxis.m
new file mode 100644
index 0000000..5711ca9
--- /dev/null
+++ b/inst/dateaxis.m
@@ -0,0 +1,101 @@
+## Copyright (C) 2008 Bill Denney <bill@denney.ws>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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
diff --git a/inst/datefind.m b/inst/datefind.m
new file mode 100644
index 0000000..30a97a2
--- /dev/null
+++ b/inst/datefind.m
@@ -0,0 +1,44 @@
+## Copyright (C) 2008 Bill Denney <bill@denney.ws>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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])
diff --git a/inst/day.m b/inst/day.m
new file mode 100644
index 0000000..1a031a3
--- /dev/null
+++ b/inst/day.m
@@ -0,0 +1,41 @@
+## Copyright (C) 2008 Bill Denney <bill@denney.ws>
+## Copyright (C) 2013 Carnë Draug <carandraug@octave.org>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function File} {} day (@var{date})
+## @deftypefnx {Function File} {} day (@var{date}, @var{f})
+## Return hours of a date.
+##
+## For a given @var{date} in a serial date number or date string format,
+## returns its day. The optional variable @var{f}, specifies the
+## format string used to interpret date strings.
+##
+## @seealso{date, datevec, now, month, year}
+## @end deftypefn
+
+function t = day (varargin)
+
+ if (nargin < 1 || nargin > 2)
+ print_usage ();
+ elseif (nargin >= 2 && ! ischar (varargin{2}))
+ error ("day: F must be a string");
+ endif
+
+ t = datevec (varargin{:})(:,3);
+endfunction
+
+%!assert (day (523383), 21);
+%!assert (day ("12-02-34", "mm-dd-yy"), 2);
diff --git a/inst/daysact.m b/inst/daysact.m
new file mode 100644
index 0000000..7238101
--- /dev/null
+++ b/inst/daysact.m
@@ -0,0 +1,53 @@
+## Copyright (C) 2007 David Bateman
+## Copyright (C) 2016 Stefan Schlögl
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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)
+ days = datenum (d1);
+ elseif (nargin == 2)
+ nr1 = size (d1, 1);
+ nr2 = size (d2, 1);
+ if (nr1 != nr2 && nr1 != 1 && nr2 != 1)
+ error ("daysact: size mismatch");
+ endif
+ days = datenum (d2) - datenum (d1);
+ else
+ print_usage ();
+ endif
+endfunction
+
+%!assert (daysact ("01-Jan-2007", ["10-Jan-2007"; "23-Feb-2007"; "23-Jul-2007"]), [9;53;203])
+%!assert (daysact ("7-sep-2002", "25-dec-2002"), 109)
diff --git a/inst/easter.m b/inst/easter.m
new file mode 100644
index 0000000..deffef2
--- /dev/null
+++ b/inst/easter.m
@@ -0,0 +1,69 @@
+## Copyright (C) 2008 Bill Denney <bill@denney.ws>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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)])
diff --git a/inst/effrr.m b/inst/effrr.m
new file mode 100644
index 0000000..3e0ba89
--- /dev/null
+++ b/inst/effrr.m
@@ -0,0 +1,34 @@
+## Copyright (C) 2008 Bill Denney <bill@denney.ws>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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)
diff --git a/inst/eomdate.m b/inst/eomdate.m
new file mode 100644
index 0000000..cd066b8
--- /dev/null
+++ b/inst/eomdate.m
@@ -0,0 +1,40 @@
+## Copyright (C) 2008 Bill Denney <bill@denney.ws>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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)])
diff --git a/inst/fbusdate.m b/inst/fbusdate.m
new file mode 100644
index 0000000..9d0390f
--- /dev/null
+++ b/inst/fbusdate.m
@@ -0,0 +1,58 @@
+## Copyright (C) 2008 Bill Denney <bill@denney.ws>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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))
diff --git a/inst/fv.m b/inst/fv.m
new file mode 100644
index 0000000..1ce5ce6
--- /dev/null
+++ b/inst/fv.m
@@ -0,0 +1,74 @@
+## Copyright (C) 1995-1998, 2000, 2002, 2005-2007 Kurt Hornik <Kurt.Hornik@wu-wien.ac.at>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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
diff --git a/inst/fvl.m b/inst/fvl.m
new file mode 100644
index 0000000..115aa48
--- /dev/null
+++ b/inst/fvl.m
@@ -0,0 +1,42 @@
+## Copyright (C) 1995-1998, 2000, 2002, 2005-2007 Kurt Hornik <Kurt.Hornik@wu-wien.ac.at>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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
diff --git a/inst/gbm.m b/inst/gbm.m
new file mode 100644
index 0000000..9e9b8e3
--- /dev/null
+++ b/inst/gbm.m
@@ -0,0 +1,58 @@
+## Copyright (C) 2016 Parsiad Azimzadeh <parsiad.azimzadeh@gmail.com>
+##
+## This program is free software; you can redistribute it and/or modify it under
+## the terms of the GNU Lesser 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 Lesser General Public License
+## for more details.
+##
+## You should have received a copy of the GNU Lesser General Public License
+## along with this program; if not, see <http://www.gnu.org/licenses/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function File} {@var{GBM} =} gbm (@var{Return}, @var{Sigma})
+## @deftypefnx {Function File} {@var{GBM} =} gbm (@var{Return}, @var{Sigma}, @var{OptionName}, @var{OptionValue}, @dots{})
+## Creates an object to represent a geometric Brownian motion (GBM).
+##
+## @center dX_t = (@var{Return}(t) * X_t)dt + (diag(X_t) * @var{Sigma}(t))dW_t
+##
+## See the @@sde documentation for a list of optional arguments.
+##
+## @seealso{sde}
+## @end deftypefn
+
+function GBM = gbm (Return, Sigma, varargin)
+
+ if (nargin < 2)
+ print_usage ();
+ endif
+
+ ## Infer NVARS
+ NVARS = 0;
+ if (isnumeric (Return))
+ NVARS = rows (Return);
+ elseif (isnumeric (Sigma))
+ NVARS = rows (Sigma);
+ else
+ NVARS = sdenvars (varargin{:});
+ endif
+
+ GBM = cev (Return, ones (NVARS, 1), Sigma, varargin{:});
+
+endfunction
+
+## Options pricing tests
+%!test
+%! AssetPrice = 100.; RiskFreeRate = 0.04; Dividends = 0.01; Volatility = 0.2; ExpiryTime = 1.;
+%! Simulations = 1e6; Timesteps = 10;
+%! SDE = gbm (RiskFreeRate - Dividends, Volatility, "StartState", AssetPrice);
+%! [Paths, ~, ~] = simByEuler (SDE, 1, "DeltaTime", ExpiryTime, "NTRIALS", Simulations, "NSTEPS", Timesteps, "Antithetic", true);
+%! Strike = 100.;
+%! CallApproximate = exp (-RiskFreeRate * ExpiryTime) * mean (max (Paths(end, 1, :) - Strike, 0.));
+%! [Call, ~] = blsprice (AssetPrice, Strike, RiskFreeRate, ExpiryTime, Volatility, Dividends);
+%! assert (CallApproximate, Call, 1e-1);
+
diff --git a/inst/heston.m b/inst/heston.m
new file mode 100644
index 0000000..2582a55
--- /dev/null
+++ b/inst/heston.m
@@ -0,0 +1,81 @@
+## Copyright (C) 2016 Parsiad Azimzadeh <parsiad.azimzadeh@gmail.com>
+##
+## This program is free software; you can redistribute it and/or modify it under
+## the terms of the GNU Lesser 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 Lesser General Public License
+## for more details.
+##
+## You should have received a copy of the GNU Lesser General Public License
+## along with this program; if not, see <http://www.gnu.org/licenses/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function File} {@var{heston} =} heston (@var{Return}, @var{Speed}, @var{Level}, @var{Volatility})
+## @deftypefnx {Function File} {@var{heston} =} heston (@var{Return}, @var{Speed}, @var{Level}, @var{Volatility}, @var{OptionName}, @var{OptionValue}, @dots{})
+## Creates an object to represent a Heston stochastic volatility model.
+##
+## @center dX_1 = (@var{Return}(t) * X_1)dt + (sqrt (X_2) * X_1)dW_1;
+## @center dX_2 = (@var{Speed}(t) * (@var{Level}(t) - X_2))dt + (sqrt (X_2) * @var{Volatility}(t))dW_2.
+##
+## See the @@sde documentation for a list of optional arguments.
+##
+## @seealso{sde}
+## @end deftypefn
+
+function heston = heston (Return, Speed, Level, Volatility, varargin)
+
+ if (nargin < 4)
+ print_usage ();
+ endif
+
+ if (isscalar (Return) && isreal (Return))
+ ReturnFunction = @(t, X) Return;
+ elseif (isa (Return, "function_handle") && nargin (Return) == 1)
+ ReturnFunction = @(t, X) Return (t);
+ elseif (isa (Return, "function_handle") && nargin (Return) == 2)
+ ReturnFunction = Return;
+ else
+ error ("heston: RETURN must either be a real scalar or a function of one or two arguments returning such a scalar");
+ endif
+
+ if (isscalar (Speed) && isreal (Speed))
+ SpeedFunction = @(t, X) Speed;
+ elseif (isa (Speed, "function_handle") && nargin (Speed) == 1)
+ SpeedFunction = @(t, X) Speed (t);
+ elseif (isa (Speed, "function_handle") && nargin (Speed) == 2)
+ SpeedFunction = Speed;
+ else
+ error ("heston: SPEED must either be a real scalar or a function of one or two arguments returning such a scalar");
+ endif
+
+ if (isscalar (Level) && isreal (Level))
+ LevelFunction = @(t, X) Level;
+ elseif (isa (Level, "function_handle") && nargin (Level) == 1)
+ LevelFunction = @(t, X) Level (t);
+ elseif (isa (Level, "function_handle") && nargin (Level) == 2)
+ LevelFunction = Level;
+ else
+ error ("heston: LEVEL must either be a real scalar or a function of one or two arguments returning such a scalar");
+ endif
+
+ if (isscalar (Volatility) && isreal (Volatility))
+ VolatilityFunction = @(t, X) Volatility;
+ elseif (isa (Volatility, "function_handle") && nargin (Volatility) == 1)
+ VolatilityFunction = @(t, X) Volatility (t);
+ elseif (isa (Volatility, "function_handle") && nargin (Volatility) == 2)
+ VolatilityFunction = Volatility;
+ else
+ error ("heston: VOLATILITY must either be a real scalar or a function of one or two arguments returning such a scalar");
+ endif
+
+ ## TODO: Optimize
+ Drift = @(t, X) [ReturnFunction(t, X) * X(1); SpeedFunction(t, X) * (LevelFunction(t, X) - X(2))];
+ Diffusion = @(t, X) [sqrt(X(2)) * X(1) 0.;0. VolatilityFunction(t, X) * sqrt(X(2))];
+
+ heston = sde (Drift, Diffusion, varargin{:});
+
+endfunction
diff --git a/inst/hhigh.m b/inst/hhigh.m
new file mode 100644
index 0000000..d48eba2
--- /dev/null
+++ b/inst/hhigh.m
@@ -0,0 +1,54 @@
+## Copyright (C) 2008 Bill Denney <bill@denney.ws>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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')
diff --git a/inst/highlow.m b/inst/highlow.m
new file mode 100644
index 0000000..b1cf068
--- /dev/null
+++ b/inst/highlow.m
@@ -0,0 +1,71 @@
+## Copyright (C) 2008 Bill Denney <bill@denney.ws>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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
diff --git a/inst/holidays.m b/inst/holidays.m
new file mode 100644
index 0000000..fb60735
--- /dev/null
+++ b/inst/holidays.m
@@ -0,0 +1,176 @@
+## Copyright (C) 2008 Bill Denney <bill@denney.ws>
+## Copyright (C) 2012 Carnë Draug <carandraug+dev@gmail.com>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function File} {@var{h} =} holidays
+## @deftypefnx {Function File} {@var{h} =} holidays (@var{startdate}, @var{enddate})
+## List holidays and non-trading days.
+##
+## Returns vector @var{h} of all holidays and non-trading days between
+## @var{startdate} and @var{enddate}, inclusive. Output dates are in the serial
+## day number format. Any date format accepted by @code{datevec} can be used.
+## If called with no input arguments, returns all holidays between the 1st of
+## January of 1885 and 31st of December of 2050.
+##
+## For example, to get all holidays for 2007 (02-Jan-2007 was mourning day of
+## Gerald Ford. See below for comments on such special occasions):
+## @group
+## @example
+## holidays ("jan 01 2007", "dec 31 2007")
+## @result{} 733043
+## 733044
+## 733057
+## 733092
+## 733138
+## 733190
+## 733227
+## 733288
+## 733368
+## 733401
+## @end example
+## @end group
+##
+## For ease of read, the output of @code{holidays} can be passed to
+## @code{datestr}. Also, the function @code{now} can be used to list all dates
+## until current date.
+## @group
+## @example
+## datestr (holidays ("may 01 2012", now))
+## @result{} 28-May-2012
+## 04-Jul-2012
+## 03-Sep-2012
+## @end example
+## @end group
+##
+## These holidays are trading holidays observed by the NYSE according to its
+## rule 51.10. It also tries to take into account the exceptions due to "unusual
+## business conditions" or for additional days that have been called as holidays
+## for one-time purposes. However, as these are unpredictable by nature only the
+## ones until 2011/02/01 have been listed.
+##
+## 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
+
+## XXX when editiong this function, keep the list of unusual holidays up to date.
+## For example, the following dates should be listed but cannot be guessed:
+## * Tue, 02 Jan 2007: DayOfMourning-GeraldFord
+## * Tue, 11 Sep 2001: WorldTradeCenterEvent
+## * Wed, 12 Sep 2001: WorldTradeCenterEvent
+## * Thu, 13 Sep 2001: WorldTradeCenterEvent
+## * Fri, 14 Sep 2001: WorldTradeCenterEvent
+##
+## The following makes it easier to check dates:
+## datestr (holidays ("jan 01 2011", now))
+##
+## Just google for the closing dates of NYSE and see if it's up to date. This
+## link may, or may not, be up to date http://www.nyse.com/pdfs/closings.pdf
+## Please update help text when rechecking this.
+
+function hol = holidays (sd, ed)
+
+ if (nargin != 0 && nargin != 2)
+ print_usage;
+ endif
+ ## list of all holidays between jan 1 1885 and dec 31 2050
+ ## 688484 = datenum (1885, 1, 1); 749113 = datenum (2050, 12, 31);
+ sd_hol = 688484; ed_hol = 749113;
+ hol = [688484; 688537; 688576; 688790; 688813; 688842; 688849; 688901; 688961; 688999; 689034; 689154; 689177; 689266; 689311; 689363; 689398; 689461; 689525; 689541; 689573; 689580; 689631; 689650; 689651; 689668; 689729; 689764; 689825; 689889; 689912; 689913; 689938; 689945; 689997; 690053; 690063; 690064; 690065; 690094; 690129; 690189; 690253; 690276; 690303; 690310; 690403; 690459; 690494; 690553; 690617; 690640; 690668; 690675; 690728; 690760; 690924; 690981; 691004; 691033; 691040; 691092; 691145; 691190; 691225; 691288; 691325; 691334; 691352; 691368; 691400; 691407; 691458; 691502; 691522; 691555; 691590; 691652; 691716; 691739; 691764; 691771; 691823; 691852; 691920; 691955; 692016; 692080; 692103; 692129; 692136; 692188; 692237; 692285; 692320; 692380; 692444; 692467; 692494; 692501; 692543; 692594; 692751; 692808; 692831; 692860; 692867; 692909; 692919; 692972; 692983; 693017; 693052; 693115; 693172; 693195; 693284; 693355; 693381; 693416; 693479; 693543; 693559; 693591; 693598; 693640; 693649; 693686; 693745; 693746; 693780; 693781; 693843; 693868; 693907; 693930; 693955; 693962; 694004; 694014; 694064; 694111; 694146; 694207; 694271; 694294; 694319; 694320; 694327; 694369; 694379; 694421; 694476; 694511; 694512; 694571; 694588; 694635; 694658; 694685; 694692; 694734; 694778; 694841; 694876; 694935; 694999; 695022; 695050; 695057; 695099; 695110; 695156; 695168; 695306; 695363; 695386; 695415; 695422; 695464; 695474; 695513; 695572; 695607; 695670; 695734; 695750; 695782; 695789; 695831; 695840; 695898; 695937; 695972; 696034; 696098; 696121; 696146; 696153; 696195; 696205; 696302; 696337; 696398; 696462; 696485; 696511; 696518; 696560; 696570; 696667; 696702; 696762; 696826; 696849; 696876; 696883; 696925; 696990; 697133; 697190; 697213; 697242; 697249; 697291; 697301; 697347; 697399; 697434; 697497; 697533; 697554; 697577; 697666; 697697; 697763; 697798; 697861; 697898; 697925; 697941; 697973; 697980; 698022; 698031; 698082; 698128; 698163; 698225; 698263; 698289; 698312; 698337; 698344; 698386; 698396; 698439; 698494; 698529; 698589; 698653; 698676; 698703; 698710; 698752; 698789; 698859; 698894; 698953; 698995; 699017; 699040; 699068; 699075; 699117; 699128; 699174; 699286; 699289; 699290; 699291; 699292; 699293; 699296; 699297; 699298; 699299; 699300; 699303; 699304; 699305; 699306; 699307; 699310; 699311; 699312; 699313; 699314; 699317; 699318; 699319; 699320; 699321; 699324; 699325; 699326; 699327; 699328; 699331; 699332; 699333; 699334; 699335; 699338; 699339; 699340; 699341; 699342; 699345; 699346; 699347; 699348; 699349; 699352; 699353; 699354; 699355; 699356; 699359; 699360; 699361; 699362; 699363; 699366; 699367; 699368; 699369; 699370; 699373; 699374; 699375; 699376; 699377; 699380; 699381; 699382; 699383; 699384; 699387; 699388; 699389; 699390; 699391; 699394; 699395; 699396; 699397; 699398; 699401; 699402; 699403; 699404; 699405; 699408; 699409; 699410; 699411; 699412; 699415; 699416; 699417; 699418; 699419; 699433; 699440; 699482; 699492; 699531; 699590; 699625; 699688; 699724; 699745; 699768; 699857; 699916; 699955; 699990; 700052; 700090; 700116; 700139; 700164; 700171; 700213; 700223; 700266; 700320; 700326; 700355; 700416; 700455; 700480; 700503; 700529; 700536; 700563; 700570; 700577; 700578; 700588; 700623; 700685; 700720; 700780; 700790; 700844; 700850; 700867; 700894; 700901; 700943; 700984; 701008; 701026; 701050; 701085; 701144; 701153; 701186; 701208; 701231; 701259; 701266; 701308; 701319; 701358; 701417; 701452; 701515; 701551; 701572; 701595; 701684; 701715; 701781; 701816; 701879; 701916; 701943; 701946; 701959; 701991; 701998; 702040; 702049; 702100; 702146; 702181; 702243; 702281; 702307; 702330; 702355; 702362; 702404; 702414; 702450; 702511; 702546; 702576; 702583; 702607; 702646; 702671; 702694; 702720; 702727; 702769; 702779; 702835; 702877; 702912; 702971; 703013; 703035; 703058; 703086; 703093; 703135; 703146; 703192; 703342; 703377; 703399; 703422; 703451; 703458; 703500; 703510; 703549; 703608; 703643; 703706; 703742; 703763; 703786; 703875; 703927; 703972; 703986; 704007; 704070; 704107; 704134; 704150; 704182; 704189; 704231; 704240; 704284; 704338; 704373; 704434; 704473; 704498; 704521; 704547; 704554; 704596; 704606; 704641; 704703; 704738; 704798; 704858; 704862; 704885; 704886; 704912; 704919; 704961; 705026; 705068; 705103; 705162; 705204; 705226; 705249; 705277; 705284; 705326; 705337; 705376; 705533; 705568; 705590; 705613; 705642; 705649; 705691; 705701; 705733; 705799; 705834; 705897; 705934; 705961; 705977; 706009; 706016; 706058; 706067; 706079; 706080; 706081; 706082; 706083; 706086; 706087; 706118; 706164; 706199; 706261; 706299; 706325; 706348; 706373; 706380; 706422; 706432; 706468; 706529; 706564; 706625; 706664; 706689; 706695; 706712; 706738; 706745; 706787; 706797; 706853; 706894; 706929; 706989; 707053; 707059; 707076; 707103; 707110; 707152; 707210; 707360; 707395; 707417; 707425; 707440; 707469; 707476; 707518; 707528; 707560; 707626; 707661; 707724; 707760; 707781; 707790; 707804; 707893; 707945; 707990; 708025; 708088; 708125; 708152; 708155; 708168; 708200; 708207; 708249; 708258; 708302; 708355; 708390; 708452; 708490; 708516; 708532; 708564; 708571; 708613; 708623; 708652; 708721; 708756; 708816; 708880; 708886; 708896; 708930; 708937; 708979; 709037; 709086; 709121; 709180; 709222; 709244; 709251; 709260; 709295; 709302; 709344; 709355; 709394; 709551; 709586; 709608; 709616; 709631; 709660; 709667; 709709; 709719; 709779; 709817; 709852; 709915; 709951; 709972; 709981; 709995; 710084; 710129; 710182; 710217; 710279; 710317; 710343; 710359; 710391; 710398; 710440; 710450; 710486; 710547; 710582; 710624; 710625; 710643; 710682; 710707; 710713; 710723; 710755; 710756; 710763; 710805; 710815; 710871; 710912; 710947; 711007; 711071; 711077; 711094; 711121; 711128; 711170; 711221; 711277; 711312; 711371; 711413; 711435; 711442; 711458; 711486; 711493; 711535; 711546; 711578; 711644; 711679; 711742; 711778; 711799; 711808; 711822; 711911; 711963; 712008; 712043; 712106; 712143; 712170; 712173; 712186; 712218; 712225; 712267; 712276; 712320; 712373; 712408; 712470; 712508; 712534; 712550; 712582; 712589; 712631; 712641; 712670; 712738; 712773; 712834; 712873; 712898; 712904; 712914; 712947; 712954; 712996; 713006; 713055; 713104; 713139; 713198; 713240; 713262; 713269; 713285; 713313; 713320; 713362; 713373; 713412; 713569; 713604; 713626; 713634; 713649; 713678; 713685; 713737; 713790; 713835; 713870; 713933; 713990; 714013; 714042; 714102; 714147; 714199; 714234; 714297; 714361; 714377; 714409; 714416; 714467; 714504; 714565; 714600; 714661; 714725; 714741; 714773; 714774; 714781; 714833; 714889; 714930; 714965; 715025; 715089; 715112; 715139; 715146; 715239; 715295; 715330; 715389; 715453; 715476; 715504; 715505; 715511; 715564; 715596; 715694; 715760; 715817; 715840; 715869; 715876; 715928; 715981; 716026; 716061; 716124; 716188; 716204; 716236; 716243; 716294; 716331; 716390; 716391; 716426; 716488; 716552; 716568; 716600; 716607; 716659; 716716; 716756; 716791; 716852; 716916; 716932; 716965; 716972; 717024; 717073; 717121; 717156; 717216; 717280; 717300; 717303; 717330; 717337; 717388; 717423; 717486; 717521; 717587; 717644; 717667; 717696; 717703; 717755; 717808; 717853; 717888; 717951; 718008; 718031; 718060; 718120; 718165; 718217; 718252; 718315; 718379; 718395; 718427; 718434; 718485; 718515; 718582; 718617; 718679; 718743; 718759; 718791; 718798; 718840; 718850; 718897; 718900; 718948; 718961; 718968; 718975; 718983; 718984; 718989; 718996; 719003; 719010; 719017; 719024; 719031; 719038; 719043; 719052; 719059; 719066; 719073; 719080; 719087; 719094; 719101; 719107; 719113; 719122; 719130; 719136; 719143; 719150; 719157; 719164; 719204; 719215; 719253; 719257; 719313; 719348; 719365; 719407; 719494; 719522; 719529; 719582; 719614; 719712; 719778; 719858; 719887; 719894; 719939; 719992; 720044; 720079; 720142; 720222; 720251; 720310; 720349; 720408; 720444; 720506; 720570; 720586; 720618; 720621; 720625; 720649; 720674; 720734; 720772; 720809; 720870; 720950; 720983; 720990; 721038; 721091; 721136; 721174; 721234; 721321; 721348; 721355; 721402; 721441; 721500; 721539; 721598; 721685; 721713; 721720; 721766; 721826; 721871; 721906; 721969; 722026; 722049; 722078; 722137; 722183; 722235; 722270; 722280; 722333; 722413; 722445; 722452; 722501; 722533; 722599; 722635; 722697; 722777; 722809; 722816; 722865; 722918; 722963; 723000; 723061; 723141; 723174; 723181; 723229; 723275; 723327; 723366; 723425; 723489; 723512; 723540; 723547; 723593; 723653; 723691; 723730; 723796; 723876; 723905; 723912; 723957; 724010; 724062; 724097; 724160; 724240; 724269; 724328; 724367; 724426; 724461; 724524; 724604; 724636; 724643; 724692; 724752; 724790; 724827; 724888; 724968; 725001; 725008; 725056; 725102; 725154; 725192; 725252; 725277; 725339; 725366; 725373; 725420; 725459; 725518; 725557; 725616; 725703; 725731; 725738; 725784; 725844; 725882; 725921; 725987; 726067; 726096; 726103; 726148; 726194; 726253; 726288; 726351; 726431; 726463; 726470; 726519; 726551; 726617; 726653; 726715; 726795; 726827; 726834; 726883; 726936; 726981; 727018; 727079; 727159; 727192; 727199; 727247; 727286; 727345; 727383; 727443; 727530; 727557; 727564; 727611; 727671; 727709; 727748; 727814; 727894; 727923; 727930; 727975; 728028; 728080; 728115; 728178; 728258; 728287; 728346; 728385; 728411; 728444; 728479; 728542; 728622; 728654; 728661; 728710; 728763; 728808; 728844; 728906; 728986; 729018; 729025; 729074; 729120; 729172; 729210; 729270; 729357; 729384; 729391; 729438; 729477; 729536; 729575; 729634; 729721; 729749; 729756; 729774; 729802; 729855; 729900; 729939; 730005; 730085; 730114; 730121; 730138; 730166; 730212; 730271; 730306; 730369; 730449; 730478; 730502; 730537; 730597; 730635; 730671; 730733; 730813; 730845; 730852; 730866; 730901; 730954; 730999; 731036; 731097; 731105; 731106; 731107; 731108; 731177; 731210; 731217; 731237; 731265; 731304; 731363; 731401; 731461; 731548; 731575; 731582; 731601; 731629; 731689; 731727; 731766; 731825; 731912; 731940; 731947; 731965; 731993; 732046; 732098; 732109; 732133; 732196; 732276; 732305; 732329; 732364; 732396; 732462; 732497; 732560; 732640; 732672; 732679; 732693; 732728; 732781; 732826; 732862; 732924; 733004; 733036; 733043; 733044; 733057; 733092; 733138; 733190; 733227; 733288; 733368; 733401; 733408; 733428; 733456; 733488; 733554; 733593; 733652; 733739; 733767; 733774; 733792; 733820; 733873; 733918; 733957; 734023; 734103; 734132; 734139; 734156; 734184; 734230; 734289; 734324; 734387; 734467; 734496; 734520; 734555; 734615; 734653; 734688; 734751; 734831; 734863; 734870; 734884; 734919; 734965; 735017; 735054; 735115; 735195; 735228; 735235; 735255; 735283; 735322; 735381; 735419; 735479; 735566; 735593; 735600; 735619; 735647; 735707; 735745; 735784; 735843; 735930; 735958; 735965; 735983; 736011; 736057; 736109; 736148; 736214; 736294; 736323; 736330; 736347; 736375; 736414; 736480; 736515; 736578; 736658; 736690; 736697; 736711; 736746; 736799; 736844; 736880; 736942; 737022; 737054; 737061; 737075; 737110; 737149; 737208; 737245; 737306; 737386; 737419; 737426; 737446; 737474; 737534; 737572; 737610; 737670; 737757; 737784; 737791; 737810; 737838; 737891; 737936; 737975; 738041; 738121; 738150; 738157; 738174; 738202; 738248; 738307; 738342; 738405; 738485; 738514; 738538; 738573; 738626; 738671; 738706; 738769; 738849; 738881; 738888; 738902; 738937; 738983; 739035; 739071; 739133; 739213; 739245; 739252; 739266; 739301; 739340; 739399; 739437; 739497; 739584; 739611; 739618; 739637; 739665; 739725; 739763; 739802; 739861; 739948; 739976; 739983; 740001; 740029; 740075; 740127; 740166; 740232; 740312; 740341; 740348; 740365; 740393; 740432; 740498; 740533; 740596; 740676; 740705; 740729; 740764; 740817; 740862; 740898; 740960; 741040; 741072; 741079; 741093; 741128; 741167; 741226; 741263; 741324; 741404; 741437; 741444; 741464; 741492; 741552; 741590; 741628; 741688; 741775; 741802; 741809; 741828; 741856; 741909; 741954; 741993; 742052; 742139; 742167; 742174; 742192; 742220; 742259; 742325; 742360; 742423; 742503; 742532; 742556; 742591; 742644; 742689; 742724; 742787; 742867; 742899; 742906; 742920; 742955; 743001; 743053; 743089; 743151; 743231; 743263; 743270; 743284; 743319; 743351; 743417; 743454; 743515; 743595; 743628; 743635; 743655; 743683; 743736; 743781; 743820; 743879; 743966; 743994; 744001; 744019; 744047; 744093; 744145; 744184; 744250; 744330; 744359; 744366; 744383; 744411; 744478; 744516; 744551; 744614; 744694; 744723; 744747; 744782; 744828; 744880; 744915; 744978; 745058; 745090; 745097; 745111; 745146; 745185; 745244; 745281; 745342; 745422; 745455; 745462; 745482; 745510; 745570; 745608; 745646; 745706; 745793; 745820; 745827; 745846; 745874; 745920; 745972; 746011; 746070; 746157; 746185; 746192; 746210; 746238; 746277; 746336; 746375; 746441; 746521; 746550; 746557; 746574; 746602; 746662; 746707; 746742; 746805; 746885; 746917; 746924; 746938; 746973; 747019; 747071; 747107; 747169; 747249; 747281; 747288; 747302; 747337; 747369; 747435; 747472; 747533; 747613; 747646; 747653; 747673; 747701; 747754; 747799; 747837; 747897; 747984; 748011; 748018; 748037; 748065; 748111; 748163; 748202; 748268; 748348; 748377; 748384; 748401; 748429; 748489; 748534; 748569; 748632; 748712; 748741; 748765; 748800; 748846; 748898; 748933; 748996; 749076; 749108 ];
+ if (nargin == 0)
+ return
+ endif
+
+ sd = datenum (datevec (sd));
+ ed = datenum (datevec (ed));
+
+ if (sd > ed)
+ hol = zeros (0,1); # matlab compatibility 0x1
+ else
+ hol = hol(hol >= sd & hol <= ed);
+ if (sd < sd_hol); hol = [calculate_holidays(sd, sd_hol -1); hol]; endif
+ if (ed > ed_hol); hol = [hol; calculate_holidays(ed_hol +1, ed)]; endif
+ endif
+
+endfunction
+
+function hol = calculate_holidays (sd, ed)
+ ## for dates outside the list, we can try to calculate them
+
+ ## calculate all holidays on the request years. We will trim them at the end
+ yrs = year (sd) : year (ed);
+
+ hol = [];
+ ## New Year's Day
+ ## when it falls on a Saturday it will not move to Friday so the adjustment
+ ## later on will not work for those cases. As such, we prune them now
+ hol = [hol; (weekday (datenum(yrs, 1, 1)) != 7)(:)];
+ ## Martin Luther King Day, the third Monday in January
+ hol = [hol; nweekdate(3, 2, yrs, 1)(:)];
+ ## Washington's Birthday, the third Monday in February
+ hol = [hol; nweekdate(3, 2, yrs, 2)(:)];
+ ## Good Friday (Friday of Easter)
+ hol = [hol; (easter (yrs) - 2)(:)];
+ ## Memorial Day, the last Monday in May
+ hol = [hol; lweekdate(2, yrs, 5)(:)];
+ ## Independence Day, July 4
+ hol = [hol; datenum(yrs, 7, 4)(:)];
+ ## Labor Day, the first Monday in September
+ hol = [hol; nweekdate(1, 2, yrs, 9)(:)];
+ ## Thanksgiving Day, the fourth Thursday in November
+ hol = [hol; nweekdate(4, 5, yrs, 11)(:)];
+ ## Christmas Day
+ hol = [hol; datenum(yrs, 12, 25)(:)];
+
+ ## Adjust for Saturdays and Sundays
+ ## From NYSE rules at http://nyserules.nyse.com/nysetools/PlatformViewer.asp?SelectedNode=chp_1_3&manual=/nyse/rules/nyse-rules/
+ ##
+ ## The Exchange Board has also determined that, when any holiday observed by
+ ## the Exchange falls on a Saturday, the Exchange will not be open for business
+ ## on the preceding Friday and when any holiday observed by the Exchange falls
+ ## on a Sunday, the Exchange will not be open for business on the succeeding
+ ## Monday, unless unusual business conditions exist, such as the ending of a
+ ## monthly or the yearly accounting period.
+ ##
+ ## Basically, Saturday holidays should be shifted to the previous Friday, and
+ ## Sunday holidays to the next Monday, except when it crosses a calendar year.
+ wd = weekday (hol);
+ hol(wd == 1) = hol(wd == 1) + 1; # Sunday holidays move to Monday
+ hol(wd == 7) = hol(wd == 7) - 1; # Saturday holidays move to Friday
+
+ ## Trim out the days that are not in the date range
+ hol(hol > ed | hol < sd) = [];
+ hol = sort (hol);
+
+endfunction
+
+%!assert(holidays("jan 1 1999", "jan 1 1998"), zeros(0,1)); # return empty when startdate is after enddate
+%!assert(holidays("mar 5 2008", "mar 8 2008"), 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));
+
+## accept input dates in multiple formats
+%!assert (holidays ("jan 1 2010", "mar 1 2010"), [734139; 734156; 734184]);
+%!assert (holidays (datenum (2010, 1, 1), datenum (2010, 3, 1)), [734139; 734156; 734184]);
+
+## do NOT move new year's day to Friday when it falls on a Saturday (Jan 2005)
+%!assert (holidays ("dec 29 2004", "jan 2 2005"), zeros (0, 1));
+## but do move new year's day to Monday when it falls on a Sunday (Jan 2006)
+%!assert (holidays ("dec 29 2005", "jan 2 2006"), datenum (2006 ,1 ,2));
+
+## check for special dates such as 11-jun-2004 (PresidentialFuneral-RonaldReagan) which can't be guessed, are just on the list
+%!assert(holidays(datenum(2004,1,1), datenum(2004,12,31)), datenum(2004*ones(10,1), [1;1;2;4;5;6;7;9;11;12], [1;19;16;9;31;11;5;6;25;24]));
diff --git a/inst/hour.m b/inst/hour.m
new file mode 100644
index 0000000..56385b0
--- /dev/null
+++ b/inst/hour.m
@@ -0,0 +1,41 @@
+## Copyright (C) 2008 Bill Denney <bill@denney.ws>
+## Copyright (C) 2013 Carnë Draug <carandraug@octave.org>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function File} {} hour (@var{date})
+## @deftypefnx {Function File} {} hour (@var{date}, @var{f})
+## Return hours of a date.
+##
+## For a given @var{date} in a serial date number or date string format,
+## returns its hours. The optional variable @var{f}, specifies the
+## format string used to interpret date strings.
+##
+## @seealso{date, datevec, now, minute, second}
+## @end deftypefn
+
+function t = hour (varargin)
+
+ if (nargin < 1 || nargin > 2)
+ print_usage ();
+ elseif (nargin >= 2 && ! ischar (varargin{2}))
+ error ("hour: F must be a string");
+ endif
+
+ t = datevec (varargin{:})(:,4);
+endfunction
+
+%!assert (hour (451482.906781456), 21)
+%!assert (hour ("1967-09-21 11:56:34", "yyyy-mm-dd HH:MM:SS"), 11)
diff --git a/inst/hwv.m b/inst/hwv.m
new file mode 100644
index 0000000..2907409
--- /dev/null
+++ b/inst/hwv.m
@@ -0,0 +1,49 @@
+## Copyright (C) 2016 Parsiad Azimzadeh <parsiad.azimzadeh@gmail.com>
+##
+## This program is free software; you can redistribute it and/or modify it under
+## the terms of the GNU Lesser 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 Lesser General Public License
+## for more details.
+##
+## You should have received a copy of the GNU Lesser General Public License
+## along with this program; if not, see <http://www.gnu.org/licenses/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function File} {@var{HWV} =} hwv (@var{Speed}, @var{Level}, @var{Sigma})
+## @deftypefnx {Function File} {@var{HWV} =} hwv (@var{Speed}, @var{Level}, @var{Sigma}, @var{OptionName}, @var{OptionValue}, @dots{})
+## Creates an object to represent a Hull-White/Vasicek (HWV) diffusion.
+##
+## @center dX_t = (@var{Speed}(t) * (@var{Level}(t) - X_t))dt + @var{Sigma}(t)dW_t.
+##
+## See the @@sde documentation for a list of optional arguments.
+##
+## @seealso{sde}
+## @end deftypefn
+
+function HWV = hwv (Speed, Level, Sigma, varargin)
+
+ if (nargin < 3)
+ print_usage ();
+ endif
+
+ ## Infer NVARS
+ NVARS = 0;
+ if (isnumeric (Speed))
+ NVARS = rows (Speed);
+ elseif (isnumeric (Level))
+ NVARS = rows (Level);
+ elseif (isnumeric (Sigma))
+ NVARS = rows (Sigma);
+ else
+ NVARS = sdenvars (varargin{:});
+ endif
+
+ HWV = sdemrd (Speed, Level, zeros (NVARS, 1), Sigma, varargin{:});
+
+endfunction
+
diff --git a/inst/irr.m b/inst/irr.m
new file mode 100644
index 0000000..3155c24
--- /dev/null
+++ b/inst/irr.m
@@ -0,0 +1,39 @@
+## Copyright (C) 1995-1998, 2000, 2002, 2004-2007 Kurt Hornik <Kurt.Hornik@wu-wien.ac.at>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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
diff --git a/inst/isbusday.m b/inst/isbusday.m
new file mode 100644
index 0000000..442602a
--- /dev/null
+++ b/inst/isbusday.m
@@ -0,0 +1,72 @@
+## Copyright (C) 2008 Bill Denney <bill@denney.ws>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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 (floor (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()])
diff --git a/inst/lbusdate.m b/inst/lbusdate.m
new file mode 100644
index 0000000..fc7e8b1
--- /dev/null
+++ b/inst/lbusdate.m
@@ -0,0 +1,56 @@
+## Copyright (C) 2008 Bill Denney <bill@denney.ws>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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))
diff --git a/inst/llow.m b/inst/llow.m
new file mode 100644
index 0000000..8133121
--- /dev/null
+++ b/inst/llow.m
@@ -0,0 +1,52 @@
+## Copyright (C) 2008 Bill Denney <bill@denney.ws>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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')
diff --git a/inst/lweekdate.m b/inst/lweekdate.m
new file mode 100644
index 0000000..d372314
--- /dev/null
+++ b/inst/lweekdate.m
@@ -0,0 +1,37 @@
+## Copyright (C) 2008 Bill Denney <bill@denney.ws>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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
diff --git a/inst/m2xdate.m b/inst/m2xdate.m
new file mode 100644
index 0000000..a340e0c
--- /dev/null
+++ b/inst/m2xdate.m
@@ -0,0 +1,74 @@
+## Copyright (C) 2008 Bill Denney <bill@denney.ws>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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)
+
diff --git a/inst/macd.m b/inst/macd.m
new file mode 100644
index 0000000..0f362e1
--- /dev/null
+++ b/inst/macd.m
@@ -0,0 +1,87 @@
+## Copyright (C) 2015 Adam Thompson <adammilesthompson [at] gmail [dot] com>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function File} {[@var{macdvec, nineperma}] =} macd (@var{data})
+## @deftypefnx {Function File} {[@var{macdvec, nineperma}] =} macd (@var{data}, @var{dim})
+##
+## Calculate the Moving Average Convergence/Divergence (MACD)
+## line of an asset from the vector of prices (@var{data}).
+## Also calculate the nine-period exponential moving average
+## from the MACD line. If given, @var{dim} indicates whether
+## each row is a set of observations (dim = 2) or each
+## column is a set of observations (dim = 1, the default).
+##
+## The MACD line is calculated as the twelve-period
+## exponential moving average (EMA) minus the 26-period EMA.
+## Closing prices are typically used for the moving
+## averages. The nine-period EMA of the MACD line is used as
+## the signal line.
+## @end deftypefn
+function [macdvec, nineperma] = macd (data, dim = 1)
+
+ ## Constants:
+ S_PER = 12;
+ L_PER = 26;
+ SL_PER = 9;
+ ## End constants
+
+ ## Check input and set the defaults
+ if nargin < 1 || nargin > 2
+ print_usage ();
+ elseif nargin < 2
+ dim = 1;
+ endif
+
+ if dim == 2
+ data = data';
+ end
+
+ ## MACD line:
+ ## 12-day EMA:
+ alpha = 2 / (S_PER + 1);
+ sma = mean(data(1:12));
+ s_ema = filter (alpha, [1 (alpha - 1)], data(12:end), sma * (1 - alpha));
+ # Formula for calculating EMA provided by James Sherman, Jr.
+ # http://octave.1599824.n4.nabble.com/vectorized-moving-average-td2132090.html
+ ## 26-day EMA:
+ alpha = 2 / (L_PER + 1);
+ sma = mean(data(1:26));
+ l_ema = filter (alpha, [1 (alpha - 1)], data(26:end), sma * (1 - alpha));
+ ## MACD:
+ s_ema = [nan(1,11) s_ema];
+ l_ema = [nan(1,25) l_ema];
+
+ macdvec = s_ema - l_ema;
+ sma = mean(macdvec(26:34));
+ ## Signal line:
+ alpha = 2 / (SL_PER + 1);
+ nineperma = filter (alpha, [1 (alpha - 1)], macdvec(34:end), sma * (1 - alpha));
+ nineperma = [nan(1,33) nineperma];
+
+endfunction
+
+## Tests
+%!shared d, m, n, a, b
+%! d = [46.84 47.07 45.92 47.24 47.64 47.3 48.22 46.98 46.41 44.78 46.29 47.99 47.47 49.19 48.85 48.13 49.13 50.91 51.01 50.48 50.88 51.2 50.85 50.16 48.44 49.1 47.67 45.43 46.47 48.76 50.08 50.74 51.91 51.11 49.36 48.96 49.28 49.02 48.24 49.71];
+%! m = [NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 1.10928 0.87603 0.50460 0.29081 0.30268 0.41383 0.54884 0.74170 0.82053 0.73334 0.62476 0.55810 0.47877 0.34894 0.36051];
+%! n = [NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 0.66262 0.67677 0.66636 0.64471 0.61152 0.55901 0.51931];
+%! [a, b] = macd (d);
+%!assert([a, b], [m, n], 0.0001)
+%! [a, b] = macd (d, 1);
+%!assert([a, b], [m, n], 0.0001)
+%! [a, b] = macd (d', 2);
+%!assert([a, b], [m, n], 0.0001)
+
diff --git a/inst/minute.m b/inst/minute.m
new file mode 100644
index 0000000..d482735
--- /dev/null
+++ b/inst/minute.m
@@ -0,0 +1,41 @@
+## Copyright (C) 2008 Bill Denney <bill@denney.ws>
+## Copyright (C) 2013 Carnë Draug <carandraug@octave.org>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function File} {} minute (@var{date})
+## @deftypefnx {Function File} {} minute (@var{date}, @var{f})
+## Return minutes of a date.
+##
+## For a given @var{date} in a serial date number or date string format,
+## returns its minutes. The optional variable @var{f}, specifies the
+## format string used to interpret date strings.
+##
+## @seealso{date, datevec, now, hour, second}
+## @end deftypefn
+
+function t = minute (varargin)
+
+ if (nargin < 1 || nargin > 2)
+ print_usage ();
+ elseif (nargin >= 2 && ! ischar (varargin{2}))
+ error ("minute: F must be a string");
+ endif
+
+ t = datevec (varargin{:})(:,5);
+endfunction
+
+%!assert (minute (451482.906781456), 45)
+%!assert (minute ("1967-09-21 11:56:34", "yyyy-mm-dd HH:MM:SS"), 56)
diff --git a/inst/mirr.m b/inst/mirr.m
new file mode 100644
index 0000000..18f461d
--- /dev/null
+++ b/inst/mirr.m
@@ -0,0 +1,48 @@
+## Copyright (C) 2008 Bill Denney <bill@denney.ws>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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)
diff --git a/inst/month.m b/inst/month.m
new file mode 100644
index 0000000..8f0e31c
--- /dev/null
+++ b/inst/month.m
@@ -0,0 +1,46 @@
+## Copyright (C) 2008 Bill Denney <bill@denney.ws>
+## Copyright (C) 2013 Carnë Draug <carandraug@octave.org>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function File} {[@var{num}, @var{str}] =} month (@var{date})
+## @deftypefnx {Function File} {[@dots{}] =} month (@var{date}, @var{f})
+## Return month of a date.
+##
+## For a given @var{date} in a serial date number or date string format,
+## returns its month number (@var{num}) or 3 letter name (@var{str}).
+##
+## The optional variable @var{f}, specifies the format string used to
+## interpret date strings.
+##
+## @seealso{date, datevec, now, day, year}
+## @end deftypefn
+
+function [num, str] = month (varargin)
+
+ if (nargin < 1 || nargin > 2)
+ print_usage ();
+ elseif (nargin >= 2 && ! ischar (varargin{2}))
+ error ("month: F must be a string");
+ endif
+
+ num = datevec (varargin{:})(:,2);
+ str = datestr ([0 num 0 0 0 0], "mmm");
+
+endfunction
+
+%!assert (nthargout (1:2, @month, 523383), {12 "Dec"});
+%!assert (nthargout (1:2, @month, "12-02-34", "mm-dd-yy"), {12 "Dec"});
+
diff --git a/inst/months.m b/inst/months.m
new file mode 100644
index 0000000..ac27c98
--- /dev/null
+++ b/inst/months.m
@@ -0,0 +1,58 @@
+## Copyright (C) 2008 Bill Denney <bill@denney.ws>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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)
diff --git a/inst/movavg.m b/inst/movavg.m
new file mode 100644
index 0000000..a1cb192
--- /dev/null
+++ b/inst/movavg.m
@@ -0,0 +1,105 @@
+## Copyright (C) 2008 Bill Denney <bill@denney.ws>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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)
diff --git a/inst/negvolidx.m b/inst/negvolidx.m
new file mode 100644
index 0000000..cff16e1
--- /dev/null
+++ b/inst/negvolidx.m
@@ -0,0 +1,82 @@
+## Copyright (C) 2008 Bill Denney <bill@denney.ws>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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)
diff --git a/inst/nomrr.m b/inst/nomrr.m
new file mode 100644
index 0000000..84c50bc
--- /dev/null
+++ b/inst/nomrr.m
@@ -0,0 +1,34 @@
+## Copyright (C) 2008 Bill Denney <bill@denney.ws>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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)
diff --git a/inst/nper.m b/inst/nper.m
new file mode 100644
index 0000000..891188d
--- /dev/null
+++ b/inst/nper.m
@@ -0,0 +1,75 @@
+## Copyright (C) 1995-1998, 2000, 2002, 2004-2007 Kurt Hornik <Kurt.Hornik@wu-wien.ac.at>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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
diff --git a/inst/npv.m b/inst/npv.m
new file mode 100644
index 0000000..516a0d7
--- /dev/null
+++ b/inst/npv.m
@@ -0,0 +1,69 @@
+## Copyright (C) 1995-2000, 2002, 2004-2007 Kurt Hornik <Kurt.Hornik@wu-wien.ac.at>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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
diff --git a/inst/nweekdate.m b/inst/nweekdate.m
new file mode 100644
index 0000000..28b86ed
--- /dev/null
+++ b/inst/nweekdate.m
@@ -0,0 +1,152 @@
+## Copyright (C) 2008 Bill Denney <bill@denney.ws>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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))
+
diff --git a/inst/onbalvol.m b/inst/onbalvol.m
new file mode 100644
index 0000000..4040b6a
--- /dev/null
+++ b/inst/onbalvol.m
@@ -0,0 +1,59 @@
+## Copyright (C) 2008 Bill Denney <bill@denney.ws>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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)
diff --git a/inst/opprofit.m b/inst/opprofit.m
new file mode 100644
index 0000000..6ad760b
--- /dev/null
+++ b/inst/opprofit.m
@@ -0,0 +1,65 @@
+## Copyright (C) 2013 Parsiad Azimzadeh <parsiad.azimzadeh@gmail.com>
+##
+## This program is free software; you can redistribute it and/or modify it under
+## the terms of the GNU Lesser 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 Lesser General Public License
+## for more details.
+##
+## You should have received a copy of the GNU Lesser General Public License
+## along with this program; if not, see <http://www.gnu.org/licenses/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function File} {@var{Profit} =} opprofit (@var{AssetPrice}, @var{Strike}, @var{Cost}, @var{PosFlag}, @var{OptType})
+## Compute profit of an option.
+##
+## @itemize
+## @item
+## Variable: @var{AssetPrice} The price of the underlying asset at the expiry time.
+## @item
+## Variable: @var{Strike} The strike price the option is written on.
+## @item
+## Variable: @var{Cost} The premium paid/charged for the option.
+## @item
+## Variable: @var{PosFlag} Option position. 0 = long, 1 = short.
+## @item
+## Variable: @var{OptType} Option type. 0 = call option, 1 = put option.
+## @end itemize
+##
+## @seealso{binprice, blsprice}
+## @end deftypefn
+
+function Profit = opprofit (AssetPrice, Strike, Cost, PosFlag, OptType)
+
+ if (nargin != 5)
+ print_usage ();
+ elseif (! isbool (PosFlag) && any (PosFlag(:) != 0 & PosFlag(:) != 1))
+ error ("opprofit: POSFLAG must be logical, 0 (long) or 1 (short)");
+ elseif (! isbool (OptType) && any (OptType(:) != 0 & OptType(:) != 1))
+ error ("opprofit: OPTTYPE must be logical, 0 (call) or 1 (put)");
+ end
+
+ pos = -2 * PosFlag + 1;
+ opt = -2 * OptType + 1;
+ Profit = pos .* (max (opt .* (AssetPrice - Strike), 0) - Cost);
+
+endfunction
+
+## Tests
+%!assert (opprofit (100, 90, 4, 0, 0), 6)
+%!assert (opprofit (80:20:120, 90, 4, 0, 0), [-4 6 26])
+%!assert (opprofit (80:20:120, 80:20:120, 0, 0, 0), [0 0 0])
+%!assert (opprofit (100, 90, 4, [0 0 1 1], [0 1 0 1]), [6 -4 -6 4])
+
+## Test input validation
+%!error opprofit ()
+%!error opprofit (1)
+%!error opprofit (1, 2)
+%!error opprofit (1, 2, 3)
+%!error opprofit (1, 2, 3, 4)
+%!error opprofit (1, 2, 3, 4, 0)
+%!error opprofit (1, 2, 3, 0, 5)
diff --git a/inst/pmt.m b/inst/pmt.m
new file mode 100644
index 0000000..9b662c1
--- /dev/null
+++ b/inst/pmt.m
@@ -0,0 +1,66 @@
+## Copyright (C) 1995-1998, 2000-2002, 2004-2007 Kurt Hornik <Kurt.Hornik@wu-wien.ac.at>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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
diff --git a/inst/pointfig.m b/inst/pointfig.m
new file mode 100644
index 0000000..75a5311
--- /dev/null
+++ b/inst/pointfig.m
@@ -0,0 +1,88 @@
+## Copyright (C) 2008 Bill Denney <bill@denney.ws>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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)
diff --git a/inst/posvolidx.m b/inst/posvolidx.m
new file mode 100644
index 0000000..fefc77b
--- /dev/null
+++ b/inst/posvolidx.m
@@ -0,0 +1,82 @@
+## Copyright (C) 2008 Bill Denney <bill@denney.ws>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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)
diff --git a/inst/private/blscheck.m b/inst/private/blscheck.m
new file mode 100644
index 0000000..019111e
--- /dev/null
+++ b/inst/private/blscheck.m
@@ -0,0 +1,64 @@
+## Copyright (C) 2015 CarnĂŤ Draug <carandraug@octave.org>
+## Copyright (C) 2015 Parsiad Azimzadeh <parsiad.azimzadeh@gmail.com>
+##
+## This program is free software; you can redistribute it and/or modify it under
+## the terms of the GNU Lesser 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 Lesser General Public License
+## for more details.
+##
+## You should have received a copy of the GNU Lesser General Public License
+## along with this program; if not, see <http://www.gnu.org/licenses/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function File} {[@var{Call}, @var{Put}] =} blscheck (@var{Price}, @var{Strike}, @var{Rate}, @var{Time}, @var{Volatility})
+## @deftypefnx {Function File} {[@var{Call}, @var{Put}] =} blscheck (@var{Price}, @var{Strike}, @var{Rate}, @var{Time}, @var{Volatility}, @var{Yield})
+## Performs input checking for the bls* functions.
+##
+## @itemize
+## @item
+## Variable: @var{Parent} The calling function.
+## @item
+## Variable: @var{Price} The current price of the underlying asset.
+## @item
+## Variable: @var{Strike} The strike price the option is written on.
+## @item
+## Variable: @var{Rate} The risk-free interest rate.
+## @item
+## Variable: @var{Time} The time-to-expiry.
+## @item
+## Variable: @var{Volatility} The volatility of the underlying asset.
+## @item
+## Variable: @var{Yield} (Optional, default = 0) Annualized, continuously
+## compounded rate of dividends of the underlying asset.
+## @end itemize
+##
+## Performs input checking for the bls* functions. All variables must be the
+## same size matrix. @var{Price}, @var{Strike}, @var{Time}, @var{Volatility}
+## must be positive.
+##
+## @seealso{blsprice}
+## @end deftypefn
+
+function blscheck (Parent, Price, Strike, Rate, Time, Volatility, Yield = 0)
+
+ ## FIXME: Error on negative Price, Strike, Time, Volatility, Yield
+ persistent names = {"PRICE", "STRIKE", "RATE", "TIME", "VOLATILITY", "YIELD"};
+ inputs = {Price, Strike, Rate, Time, Volatility, Yield};
+ numerics = cellfun (@isnumeric, inputs);
+ if (! all (numerics))
+ error ("%s: inputs must be numeric", Parent);
+ endif
+ scalars = cellfun (@isscalar, inputs);
+ if (! all (scalars))
+ sizes = cellfun (@size, inputs(! scalars), "UniformOutput", false);
+ if (! all (cellfun (@(x) isequal (sizes{1}, x), sizes)))
+ error ("%s: matrix arguments must all have the same size", Parent);
+ endif
+ endif
+
+end
diff --git a/inst/private/fetch.m b/inst/private/fetch.m
new file mode 100644
index 0000000..63a1d9b
--- /dev/null
+++ b/inst/private/fetch.m
@@ -0,0 +1,157 @@
+## Copyright (C) 2008 Bill Denney <bill@denney.ws>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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
+## @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
+## @item 'd': daily
+## @item 'w': weekly (Yahoo only)
+## @item 'm': monthly (Yahoo only)
+## @item 'v': dividends (Yahoo only)
+## @end itemize
+##
+## @example
+## fetch(google(), "SNE", "01-Jan-2016", "31-Dec-2016", "d");
+## @end example
+##
+## @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, wgood
+%! fgood = {"Date", "Open", "High", "Low", "Close", "Volume"};
+%! dgood = [732501,34.77,34.87,34.25,34.62,15520553;
+%! 732500,33.87,34.77,33.72,34.63,16360297;
+%! 732499,34.64,34.97,34.03,34.12,13694806;
+%! 732498,34.25,35.08,34.20,34.60,16103029;
+%! 732494,34.76,34.85,34.22,34.44,9875220];
+%! 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(), "yhoo", 732494, 732501, "d");
+%! assert(d, dgood, eps);
+%! assert(f, fgood, eps);
+## test that the automatic period works
+%!test
+%! [d f] = fetch (google(), "yhoo", 732494, 732501);
+%! assert(d, dgood, eps);
+%! assert(f, fgood, eps);
+## Test that weekly fails
+%!test
+%! fail ('fetch (google(), "yhoo", 732494, 732501, "w")', ".*weekly.*")
diff --git a/inst/private/fetch_google.m b/inst/private/fetch_google.m
new file mode 100644
index 0000000..9cedbcc
--- /dev/null
+++ b/inst/private/fetch_google.m
@@ -0,0 +1,87 @@
+## Copyright (C) 2008 Bill Denney <bill@denney.ws>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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
+## @item 'd': daily
+## @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")
+
+ error ("Google Finance no longer supports downloading stock data");
+
+ pkg load io;
+
+ if strcmpi(period, "w")
+ error("Google Financial no longer supports weekly stock data");
+ endif
+ periods = struct("d", "daily");
+ 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
+ dates = datenum (datevec (d(:,1), "dd-mmm-yy"));
+ ternary = @(c, varargin) varargin{2-logical(c)};
+ filtered = cellfun (@(x) ternary(x == "-", NaN, x), d(:, 2:end));
+ data = [dates, filtered];
+ ## 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
+
diff --git a/inst/private/fetch_yahoo.m b/inst/private/fetch_yahoo.m
new file mode 100644
index 0000000..1a437de
--- /dev/null
+++ b/inst/private/fetch_yahoo.m
@@ -0,0 +1,81 @@
+## Copyright (C) 2008 Bill Denney <bill@denney.ws>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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
+## @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")
+
+ error ("Yahoo! Finance no longer supports downloading stock data");
+
+ pkg load io;
+
+ 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));
+ disp(geturl);
+ ## 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
+
diff --git a/inst/private/google.m b/inst/private/google.m
new file mode 100644
index 0000000..3397c4a
--- /dev/null
+++ b/inst/private/google.m
@@ -0,0 +1,44 @@
+## Copyright (C) 2008 Bill Denney <bill@denney.ws>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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
diff --git a/inst/private/sdenvars.m b/inst/private/sdenvars.m
new file mode 100644
index 0000000..7cdc24b
--- /dev/null
+++ b/inst/private/sdenvars.m
@@ -0,0 +1,49 @@
+## Copyright (C) 2016 Parsiad Azimzadeh <parsiad.azimzadeh@gmail.com>
+##
+## This program is free software; you can redistribute it and/or modify it under
+## the terms of the GNU Lesser 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 Lesser General Public License
+## for more details.
+##
+## You should have received a copy of the GNU Lesser General Public License
+## along with this program; if not, see <http://www.gnu.org/licenses/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function File} {[@var{NVARS}] =} (@dots{})
+## Attempts to infer and return the number of state variables from optional SDE
+## arguments.
+##
+## @end deftypefn
+
+function NVARS = sdenvars (varargin)
+
+ if (mod (nargin, 2) == 1)
+ error ("sde: optional arguments must be specified in key-value pairs");
+ endif
+
+ NVARS = 0;
+ for i = 1:length(varargin)/2
+ key = varargin{2*i-1};
+ value = varargin{2*i};
+ if (! (ischar (key) && isvector (key)))
+ continue;
+ endif
+ switch (key)
+ case "StartState"
+ if (isreal (value))
+ NVARS = size (value, 1);
+ endif
+ endswitch
+ endfor
+
+ if (NVARS <= 0)
+ error ("sde: unable to infer NVARS; you must specify the StartState option as a nonempty vector or matrix");
+ endif
+
+endfunction
+
diff --git a/inst/private/yahoo.m b/inst/private/yahoo.m
new file mode 100644
index 0000000..1088d5b
--- /dev/null
+++ b/inst/private/yahoo.m
@@ -0,0 +1,44 @@
+## Copyright (C) 2008 Bill Denney <bill@denney.ws>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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
diff --git a/inst/pv.m b/inst/pv.m
new file mode 100644
index 0000000..8585a20
--- /dev/null
+++ b/inst/pv.m
@@ -0,0 +1,74 @@
+## Copyright (C) 1995-1996, 1998, 2000, 2002, 2004-2007 Kurt Hornik <Kurt.Hornik@wu-wien.ac.at>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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
diff --git a/inst/pvl.m b/inst/pvl.m
new file mode 100644
index 0000000..d6dbcb0
--- /dev/null
+++ b/inst/pvl.m
@@ -0,0 +1,42 @@
+## Copyright (C) 1995-1998, 2000, 2002, 2005-2007 Kurt Hornik <Kurt.Hornik@wu-wien.ac.at>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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
diff --git a/inst/rate.m b/inst/rate.m
new file mode 100644
index 0000000..1d5a725
--- /dev/null
+++ b/inst/rate.m
@@ -0,0 +1,67 @@
+## Copyright (C) 1995-1998, 2000, 2002, 2004-2007 Kurt Hornik <Kurt.Hornik@wu-wien.ac.at>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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 (m, {"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
diff --git a/inst/renko.m b/inst/renko.m
new file mode 100644
index 0000000..0c78b75
--- /dev/null
+++ b/inst/renko.m
@@ -0,0 +1,124 @@
+## Copyright (C) 2015 Parsiad Azimzadeh <parsiad.azimzadeh@gmail.com>
+##
+## This program is free software; you can redistribute it and/or modify it under
+## the terms of the GNU Lesser 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 Lesser General Public License
+## for more details.
+##
+## You should have received a copy of the GNU Lesser General Public License
+## along with this program; if not, see <http://www.gnu.org/licenses/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function File} renko (@var{X})
+## @deftypefnx {Function File} renko (@var{X}, @var{threshold})
+## Plots price changes using a Renko chart.
+##
+## @itemize
+## @item
+## Variable: @var{X} An M-by-2 matrix in which the first column contains datenum
+## bers and the second contains prices.
+## @item
+## Variable: @var{threshold} (Optional, default = 1.) A new box is added only
+## when subsequent prices change by more than the threshold.
+## @end itemize
+##
+## @example
+## X = [...
+## 730299.00 23.45; ...
+## 730300.00 23.30; ...
+## 730305.00 24.00; ...
+## 730310.00 23.50; ...
+## 730315.00 23.55; ...
+## 730320.00 24.11; ...
+## 730325.00 26.00; ...
+## 730330.00 26.59; ...
+## 730335.00 26.50; ...
+## 730340.00 26.40; ...
+## 730345.00 25.00];
+## renko(X, .1);
+## @end example
+##
+## @seealso{bolling, candle, highlow, kagi, linebreak, movavg, pointfig, priceandvol, volarea}
+## @end deftypefn
+
+function renko (X, threshold = 1.)
+
+ ## Input checking
+ if (nargin < 1 || nargin > 2)
+ print_usage ();
+ elseif (! (ismatrix (X) && isreal (X) && size (X, 2) == 2))
+ error ("renko: X must be a real matrix with exactly two columns");
+ elseif (size (X, 1) < 2)
+ error ("renko: X must have at least two data points");
+ elseif (! (isscalar (threshold) && isreal (threshold) && threshold >= 0.))
+ error ("renko: THRESHOLD must be a nonnegative real scalar");
+ elseif (! (all (diff (X(:, 1)) > 0)))
+ error ("renko: the first column of X should be increasing");
+ endif
+
+ fig = figure;
+ washold = ishold; hold on; grid on;
+ ax = gca;
+
+ total = [];
+
+ m = size (X, 1);
+ while (m >= 2)
+
+ found_n = false;
+ n = m - 1;
+ for n = (m-1):-1:1
+ if (abs(X(n, 2) - X(m, 2)) >= threshold)
+ found_n = true;
+ while (n > 1 && abs(X(n-1, 2) - X(n, 2)) < threshold)
+ n = n - 1;
+ endwhile
+ break;
+ endif
+ endfor
+
+ if (! found_n)
+ break;
+ endif
+
+ if (X(m, 2) > X(n, 2))
+ direction = -1;
+ else
+ direction = +1;
+ endif
+
+ X2 = fliplr (X(m, 2):(direction*threshold):X(n, 2));
+ tmp = (1 - (X(m, 2) - X2(1)) / (X(m, 2) - X(n, 2))) * (X(m, 1) - X(n, 1)) + X(n, 1);
+ X1 = linspace (tmp, X(m, 1), length (X2));
+
+ l = plot (X1, X2, "s");
+ if (direction == -1)
+ set (l, "MarkerFaceColor", "w");
+ else
+ set (l, "MarkerFaceColor", "k");
+ endif
+ set (l, "MarkerEdgeColor", "k");
+
+ m = n;
+
+ minX = X(1);
+
+ endwhile
+
+ axis([minX X(end, 1) -Inf Inf]);
+ ticks = get (ax, "XTick");
+ dates = datestr (ticks, 1);
+
+ set (ax, "XTickLabel", dates)
+
+ if (! washold)
+ hold off
+ endif
+
+endfunction
+
diff --git a/inst/rsindex.m b/inst/rsindex.m
new file mode 100644
index 0000000..670488c
--- /dev/null
+++ b/inst/rsindex.m
@@ -0,0 +1,66 @@
+## Copyright (C) 2008 Bill Denney <bill@denney.ws>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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)
diff --git a/inst/sdeddo.m b/inst/sdeddo.m
new file mode 100644
index 0000000..4960f86
--- /dev/null
+++ b/inst/sdeddo.m
@@ -0,0 +1,57 @@
+## Copyright (C) 2016 Parsiad Azimzadeh <parsiad.azimzadeh@gmail.com>
+##
+## This program is free software; you can redistribute it and/or modify it under
+## the terms of the GNU Lesser 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 Lesser General Public License
+## for more details.
+##
+## You should have received a copy of the GNU Lesser General Public License
+## along with this program; if not, see <http://www.gnu.org/licenses/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function File} {@var{SDE} =} sdeddo (@var{DriftRate}, @var{DiffusionRate})
+## @deftypefnx {Function File} {@var{SDE} =} sdeddo (@var{DriftRate}, @var{DiffusionRate}, @var{OptionName}, @var{OptionValue}, @dots{})
+## Creates an object to represent a stochastic differential equation (SDE) using
+## drift and diffusion objects.
+##
+## @center dX_t = @var{DriftRate}(t, X_t)dt + @var{DiffusionRate}(t, X_t)dW_t.
+##
+## @itemize
+## @item (X_t) is an NVARS-dimensional process;
+## @item (W_t) is an NBROWNS-dimensional Wiener process.
+## @end itemize
+##
+## @itemize
+## @item
+## Variable: @var{DriftRate} A drift object.
+## @item
+## Variable: @var{DiffusionRate} A diffusion object.
+## @end itemize
+##
+## See the @@sde documentation for a list of optional arguments.
+##
+## @seealso{drift, diffusion, sde}
+## @end deftypefn
+
+function SDE = sdeddo (DriftRate, DiffusionRate, varargin)
+
+ if (nargin < 2)
+ print_usage ();
+ endif
+
+ if (! isa (DriftRate, "drift"))
+ error ("sdeddo: DRIFTRATE must be a drift object");
+ endif
+
+ if (! isa (DiffusionRate, "diffusion"))
+ error ("sdeddo: DIFFUSIONRATE must be a diffusion object");
+ endif
+
+ SDE = sde (DriftRate, DiffusionRate, varargin{:});
+
+endfunction
diff --git a/inst/sdeld.m b/inst/sdeld.m
new file mode 100644
index 0000000..c450be3
--- /dev/null
+++ b/inst/sdeld.m
@@ -0,0 +1,49 @@
+## Copyright (C) 2016 Parsiad Azimzadeh <parsiad.azimzadeh@gmail.com>
+##
+## This program is free software; you can redistribute it and/or modify it under
+## the terms of the GNU Lesser 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 Lesser General Public License
+## for more details.
+##
+## You should have received a copy of the GNU Lesser General Public License
+## along with this program; if not, see <http://www.gnu.org/licenses/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function File} {@var{SDE} =} sdeld (@var{A}, @var{B}, @var{Alpha}, @var{Sigma})
+## @deftypefnx {Function File} {@var{SDE} =} sdeld (@var{A}, @var{B}, @var{Alpha}, @var{Sigma}, @var{OptionName}, @var{OptionValue}, @dots{})
+## Creates an object to represent a stochastic differential equation (SDE) in
+## linear drift-rate form.
+##
+## @center dX_t = (@var{A}(t) + @var{B}(t) * X_t)dt + (diag(X_t.^@var{Alpha}(t)) * @var{Sigma}(t))dW_t
+##
+## @itemize
+## @item (X_t) is an NVARS-dimensional process;
+## @item (W_t) is an NBROWNS-dimensional Wiener process.
+## @end itemize
+##
+## The parameters @var{A} and @var{B} appear in the @@sde/drift documentation.
+##
+## The parameters @var{Alpha} and @var{Sigma} appear in the @@sde/diffusion
+## documentation.
+##
+## See the @@sde documentation for a list of optional arguments.
+##
+## @seealso{drift, diffusion, sde}
+## @end deftypefn
+
+function SDE = sdeld (A, B, Alpha, Sigma, varargin)
+
+ if (nargin < 4)
+ print_usage ();
+ endif
+
+ Drift = drift (A, B);
+ Diffusion = diffusion (Alpha, Sigma);
+ SDE = sde (Drift, Diffusion, varargin{:});
+
+endfunction
diff --git a/inst/sdemrd.m b/inst/sdemrd.m
new file mode 100644
index 0000000..6751b28
--- /dev/null
+++ b/inst/sdemrd.m
@@ -0,0 +1,85 @@
+## Copyright (C) 2016 Parsiad Azimzadeh <parsiad.azimzadeh@gmail.com>
+##
+## This program is free software; you can redistribute it and/or modify it under
+## the terms of the GNU Lesser 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 Lesser General Public License
+## for more details.
+##
+## You should have received a copy of the GNU Lesser General Public License
+## along with this program; if not, see <http://www.gnu.org/licenses/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function File} {@var{SDE} =} sdemrd (@var{Speed}, @var{Level}, @var{Alpha}, @var{Sigma})
+## @deftypefnx {Function File} {@var{SDE} =} sdemrd (@var{Speed}, @var{Level}, @var{Alpha}, @var{Sigma}, @var{OptionName}, @var{OptionValue}, @dots{})
+## Creates an object to represent a stochastic differential equation (SDE) in
+## in mean-reverting drift-rate form.
+##
+## @center dX_t = (@var{Speed}(t) * (@var{Level}(t) - X_t))dt + (diag(X_t.^@var{Alpha}(t)) * @var{Sigma}(t))dW_t.
+##
+## @itemize
+## @item (X_t) is an NVARS-dimensional process;
+## @item (W_t) is an NBROWNS-dimensional Wiener process.
+## @end itemize
+##
+## @itemize
+## @item
+## Variable: @var{Speed} An NVARS-by-NVARS matrix or a function. As a function,
+## @var{Speed} returns an NVARS-by-NVARS matrix and has either exactly one input
+## (time: @var{Speed}(t)) or exactly two inputs (time and space:
+## @var{Speed}(t, X_t)).
+## @item
+## Variable: @var{Level} An NVARS-by-1 vector or a function. As a function,
+## @var{Level} returns an NVARS-by-1 vector and has either exactly one input
+## (time: @var{Level}(t)) or exactly two inputs (time and space:
+## @var{Level}(t, X_t)).
+## @end itemize
+##
+## The parameters @var{Alpha} and @var{Sigma} appear in the @@sde/diffusion
+## documentation.
+##
+## See the @@sde documentation for a list of optional arguments.
+##
+## @seealso{drift, diffusion, sde}
+## @end deftypefn
+
+function SDE = sdemrd (Speed, Level, Alpha, Sigma, varargin)
+
+ if (nargin < 4)
+ print_usage ();
+ endif
+
+ if (ismatrix (Speed) && isreal (Speed))
+ SpeedFunction = @(t, X) Speed;
+ NegativeSpeed = @(t, X) -Speed;
+ elseif (isa (Speed, "function_handle") && nargin (Speed) == 1)
+ SpeedFunction = @(t, X) Speed (t);
+ NegativeSpeed = @(t, X) -Speed (t);
+ elseif (isa (Speed, "function_handle") && nargin (Speed) == 2)
+ SpeedFunction = Speed;
+ NegativeSpeed = -Speed;
+ else
+ error ("sdemrd: SPEED must either be a real matrix or a function of one or two arguments returning such a matrix.");
+ endif
+
+ if (iscolumn (Level) && isreal (Level))
+ LevelFunction = @(t, X) Level;
+ elseif (isa (Level, "function_handle") && nargin (Level) == 1)
+ LevelFunction = @(t, X) Level (t);
+ elseif (isa (Level, "function_handle") && nargin (Level) == 2)
+ LevelFunction = Level;
+ else
+ error ("sdemrd: LEVEL must either be a real column vector or a function of one or two arguments returning such a vector.");
+ endif
+
+ SpeedLevel = @(t, X) SpeedFunction (t, X) * LevelFunction (t, X);
+
+ Drift = drift (SpeedLevel, NegativeSpeed);
+ Diffusion = diffusion (Alpha, Sigma);
+ SDE = sde (Drift, Diffusion, varargin{:});
+
+endfunction
diff --git a/inst/second.m b/inst/second.m
new file mode 100644
index 0000000..c4acb88
--- /dev/null
+++ b/inst/second.m
@@ -0,0 +1,41 @@
+## Copyright (C) 2008 Bill Denney <bill@denney.ws>
+## Copyright (C) 2013 Carnë Draug <carandraug@octave.org>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function File} {} second (@var{date})
+## @deftypefnx {Function File} {} second (@var{date}, @var{f})
+## Return seconds of a date.
+##
+## For a given @var{date} in a serial date number or date string format,
+## returns its seconds. The optional variable @var{f}, specifies the
+## format string used to interpret date strings.
+##
+## @seealso{date, datevec, now, hour, minute}
+## @end deftypefn
+
+function t = second (varargin)
+
+ if (nargin < 1 || nargin > 2)
+ print_usage ();
+ elseif (nargin >= 2 && ! ischar (varargin{2}))
+ error ("second: F must be a string");
+ endif
+
+ t = datevec (varargin{:})(:,6);
+endfunction
+
+%!assert (second (451482.906781456), 45.918, 0.01)
+%!assert (second ("1967-09-21 11:56:34", "yyyy-mm-dd HH:MM:SS"), 34)
diff --git a/inst/taxedrr.m b/inst/taxedrr.m
new file mode 100644
index 0000000..2501ac7
--- /dev/null
+++ b/inst/taxedrr.m
@@ -0,0 +1,38 @@
+## Copyright (C) 2008 Bill Denney <bill@denney.ws>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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)
diff --git a/inst/thirdwednesday.m b/inst/thirdwednesday.m
new file mode 100644
index 0000000..18ce73d
--- /dev/null
+++ b/inst/thirdwednesday.m
@@ -0,0 +1,68 @@
+## Copyright (C) 2008 Bill Denney <bill@denney.ws>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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')
diff --git a/inst/today.m b/inst/today.m
new file mode 100644
index 0000000..6ca1c99
--- /dev/null
+++ b/inst/today.m
@@ -0,0 +1,32 @@
+## Copyright (C) 2008 Bill Denney <bill@denney.ws>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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
diff --git a/inst/vol.m b/inst/vol.m
new file mode 100644
index 0000000..0444ed5
--- /dev/null
+++ b/inst/vol.m
@@ -0,0 +1,70 @@
+## Copyright (C) 1995-1998, 2000, 2002, 2005-2007 Friedrich Leisch <Friedrich.Leisch@ci.tuwien.ac.at>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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
diff --git a/inst/weeknum.m b/inst/weeknum.m
new file mode 100644
index 0000000..0438376
--- /dev/null
+++ b/inst/weeknum.m
@@ -0,0 +1,126 @@
+## Copyright (C) 2015 Ronald van der Meer
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function File} {[@var{n}, @var{y}] =} weeknum (@var{d})
+## @deftypefnx {Function File} {[@var{n}, @var{y}] =} weeknum (@var{d}, @var{w})
+## @deftypefnx {Function File} {[@var{n}, @var{y}] =} weeknum (@var{d}, @var{w}, @var{e})
+## Return the week number of the year of a date
+##
+## @var{d} is a serial date number or datestring.
+##
+## @var{w} is (optionally) the day that defines the first day of the week
+## (1 is Sunday, 2 is Monday etc.). Default is 1 (Sunday).
+##
+## @var{e} is a boolean to toggle the "European" definition that the first
+## week should contain at least 4 days of the new year. (And hence always
+## contains 4th of January). Default is 0, in which case the first week of
+## the year is the week that contains the first day of the year.
+##
+## Please note that when @var{e} is zero, days in a week that overlap two
+## years do not all return the same weeknumber.
+##
+## @var{y} will be the year in which the week falls.
+## When e=0 (default) @var{y} will always be the year of the input date.
+## When e=1, the week may be in the next or previous year.
+##
+## @emph{Note}: In ISO8601 weeks start with Monday. The first week of a year
+## is the week that contains at least 4 days (and hence contains the first
+## Thursday of the year and also always contains the 4th of January).
+## So for an ISO8601 weeknumber use: @code{@var{n} = weeknum (@var{d}, 2, 1)}.
+##
+## @seealso{datenum, datestr}
+## @end deftypefn
+
+function [n, y] = weeknum (d, w = 1, e = false)
+
+ if (nargin < 1 || nargin > 3)
+ print_usage ();
+ elseif (! isscalar (w) || w < 1 || w > 7)
+ error ("weeknum: W must be a scalar between 1 and 7");
+ endif
+
+ if (isa (d, "char"))
+ d = datenum (d);
+ endif
+
+ d = floor (d); # reduce resolution to days
+
+ ## first day of the week considering the week start day in w
+ firstdayofweek = d - mod (weekday (d) - w, 7);
+ y = year (d);
+
+ if (e)
+ firstdayofnextyear = datenum (y + 1, 1, 1);
+ ## when week has 3 or less days in this year, so it falls in next year
+ inextyear = find ((firstdayofnextyear - firstdayofweek) < 4);
+ y(inextyear) = y(inextyear) + 1;
+
+ ## when week has 4 or more days in previous year, so it falls in the
+ ## previous year
+ iprevyear = find (datenum (y, 1, 1) - firstdayofweek > 3);
+ y(iprevyear) = y(iprevyear) - 1;
+
+ ## by "european" definition first week contains the 4th of januari
+ dayinfirstweek = datenum (y, 1, 4);
+ else
+ ## otherwise the first week is defined by the week that contains the
+ ## first day of the year
+ dayinfirstweek=datenum(y,1,1);
+ endif
+ firstdayoffirstweek = dayinfirstweek - mod (weekday (dayinfirstweek) - w, 7);
+
+ n = (firstdayofweek - firstdayoffirstweek) / 7 + 1;
+endfunction
+
+%!assert (weeknum (728647), 52)
+## Test vector inputs for both directions
+%!assert (weeknum ([728647 728848]), [52 27])
+%!assert (weeknum ([728647 ;728648]), [52 ;52])
+%!assert (weeknum ([736413 736813 ; 737213 737613]), [13 17 ; 22 28])
+
+## Tests ISO examples from http://en.wikipedia.org/wiki/ISO_week_date
+%!assert (weeknum (datenum (2005, 01, 01), 2, 1), 53)
+%!assert (weeknum (datenum (2005, 01, 02), 2, 1), 53)
+%!assert (weeknum (datenum (2005, 12, 31), 2, 1), 52)
+%!assert (weeknum (datenum (2007, 01, 01), 2, 1), 1)
+%!assert (weeknum (datenum (2007, 12, 30), 2, 1), 52)
+%!assert (weeknum (datenum (2007, 12, 31), 2, 1), 1)
+%!assert (weeknum (datenum (2008, 01, 01), 2, 1), 1)
+%!assert (weeknum (datenum (2008, 12, 28), 2, 1), 52)
+%!assert (weeknum (datenum (2008, 12, 29), 2, 1), 1)
+%!assert (weeknum (datenum (2008, 12, 30), 2, 1), 1)
+%!assert (weeknum (datenum (2008, 12, 31), 2, 1), 1)
+%!assert (weeknum (datenum (2009, 01, 01), 2, 1), 1)
+%!assert (weeknum (datenum (2009, 12, 31), 2, 1), 53)
+%!assert (weeknum (datenum (2010, 01, 01), 2, 1), 53)
+%!assert (weeknum (datenum (2010, 01, 02), 2, 1), 53)
+%!assert (weeknum (datenum (2010, 01, 03), 2, 1), 53)
+
+##A vector which combines next- and previous year exceptions
+%!assert (weeknum ([datenum(2005, 1, 1) datenum(2008, 12, 29)], 2, 1), [53 1])
+
+%!test
+%! [n, y] = weeknum (datenum (2010, 1, 3), 2, 1);
+%! assert ([n y],[53 2009])
+##http://www.mathworks.com/help/finance/weeknum.html says weeknum('08-jan-2004',1,1)
+##should be 2 but this is not correct occording to their own definition
+
+%!demo
+%! d = datenum (2014, 12, 29);
+%! [w, y] = weeknum (datenum (2014, 12, 29), 2, 1);
+%! disp(['In ISO8601 ' datestr(d) ' is week ' num2str(w) ' of year ' num2str(y)])
+%! disp(['Octave default weeknumber for ' datestr(d) ' is ' num2str(weeknum (d))])
+
diff --git a/inst/x2mdate.m b/inst/x2mdate.m
new file mode 100644
index 0000000..7db9743
--- /dev/null
+++ b/inst/x2mdate.m
@@ -0,0 +1,75 @@
+## Copyright (C) 2008 Bill Denney <bill@denney.ws>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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))
+
diff --git a/inst/year.m b/inst/year.m
new file mode 100644
index 0000000..7a694d8
--- /dev/null
+++ b/inst/year.m
@@ -0,0 +1,55 @@
+## Copyright (C) 2008 Bill Denney <bill@denney.ws>
+## Copyright (C) 2013, 2015 Carnë Draug <carandraug@octave.org>
+## Copyright (C) 2015 Ronald van der Meer <revdmeer@gmail.com>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function File} {} year (@var{date})
+## @deftypefnx {Function File} {} year (@var{date}, @var{f})
+## Return year of a date.
+##
+## For a given @var{date} in a serial date number or date string format,
+## returns its year. The optional variable @var{f}, specifies the
+## format string used to interpret date strings.
+##
+## @seealso{date, datevec, now, day, month}
+## @end deftypefn
+
+function t = year (varargin)
+
+ if (nargin < 1 || nargin > 2)
+ print_usage ();
+ elseif (nargin >= 2 && ! ischar (varargin{2}))
+ error ("year: F must be a string");
+ endif
+
+ t = datevec (varargin{:})(:,1);
+
+ if (! isa (varargin{1}, "char"))
+ t = reshape (t, size (varargin{1}));
+ endif
+endfunction
+
+%!assert (year (523383), 1432);
+%!assert (year ("12-02-34", "mm-dd-yy"), 2034);
+
+## Test that we keep the same as the input
+%!assert (year ([728647 728848]), [1994 1995]);
+%!assert (year ([728647; 728848]), [1994; 1995]);
+
+## test cell array of strings with different sizes
+%!assert (year ({"12-02-34", "12-02-85"}, "mm-dd-yy"), [2034 1985]);
+%!assert (year ({"12-02-34"; "12-02-85"}, "mm-dd-yy"), [2034; 1985]);
+
diff --git a/inst/yeardays.m b/inst/yeardays.m
new file mode 100644
index 0000000..cc471ac
--- /dev/null
+++ b/inst/yeardays.m
@@ -0,0 +1,111 @@
+## Copyright (C) 2008 Bill Denney <bill@denney.ws>
+##
+## 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 <http://www.gnu.org/licenses/>.
+
+## -*- 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
+## @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)
+