"""Some simple financial calculations
patterned after spreadsheet computations.
There is some complexity in each function
so that the functions behave like ufuncs with
broadcasting and being able to be called with scalars
or arrays (or other sequences).
Functions support the :class:`decimal.Decimal` type unless
otherwise stated.
"""
import warnings
from decimal import Decimal
import functools
import numpy as np
from numpy.core import overrides
_depmsg = ("numpy.{name} is deprecated and will be removed from NumPy 1.20. "
"Use numpy_financial.{name} instead "
"(https://pypi.org/project/numpy-financial/).")
array_function_dispatch = functools.partial(
overrides.array_function_dispatch, module='numpy')
__all__ = ['fv', 'pmt', 'nper', 'ipmt', 'ppmt', 'pv', 'rate',
'irr', 'npv', 'mirr']
_when_to_num = {'end':0, 'begin':1,
'e':0, 'b':1,
0:0, 1:1,
'beginning':1,
'start':1,
'finish':0}
def _convert_when(when):
#Test to see if when has already been converted to ndarray
#This will happen if one function calls another, for example ppmt
if isinstance(when, np.ndarray):
return when
try:
return _when_to_num[when]
except (KeyError, TypeError):
return [_when_to_num[x] for x in when]
def _fv_dispatcher(rate, nper, pmt, pv, when=None):
warnings.warn(_depmsg.format(name='fv'),
DeprecationWarning, stacklevel=3)
return (rate, nper, pmt, pv)
@array_function_dispatch(_fv_dispatcher)
def fv(rate, nper, pmt, pv, when='end'):
"""
Compute the future value.
.. deprecated:: 1.18
`fv` is deprecated; for details, see NEP 32 [1]_.
Use the corresponding function in the numpy-financial library,
https://pypi.org/project/numpy-financial.
Given:
* a present value, `pv`
* an interest `rate` compounded once per period, of which
there are
* `nper` total
* a (fixed) payment, `pmt`, paid either
* at the beginning (`when` = {'begin', 1}) or the end
(`when` = {'end', 0}) of each period
Return:
the value at the end of the `nper` periods
Parameters
----------
rate : scalar or array_like of shape(M, )
Rate of interest as decimal (not per cent) per period
nper : scalar or array_like of shape(M, )
Number of compounding periods
pmt : scalar or array_like of shape(M, )
Payment
pv : scalar or array_like of shape(M, )
Present value
when : {{'begin', 1}, {'end', 0}}, {string, int}, optional
When payments are due ('begin' (1) or 'end' (0)).
Defaults to {'end', 0}.
Returns
-------
out : ndarray
Future values. If all input is scalar, returns a scalar float. If
any input is array_like, returns future values for each input element.
If multiple inputs are array_like, they all must have the same shape.
Notes
-----
The future value is computed by solving the equation::
fv +
pv*(1+rate)**nper +
pmt*(1 + rate*when)/rate*((1 + rate)**nper - 1) == 0
or, when ``rate == 0``::
fv + pv + pmt * nper == 0
References
----------
.. [1] NumPy Enhancement Proposal (NEP) 32,
https://numpy.org/neps/nep-0032-remove-financial-functions.html
.. [2] Wheeler, D. A., E. Rathke, and R. Weir (Eds.) (2009, May).
Open Document Format for Office Applications (OpenDocument)v1.2,
Part 2: Recalculated Formula (OpenFormula) Format - Annotated Version,
Pre-Draft 12. Organization for the Advancement of Structured Information
Standards (OASIS). Billerica, MA, USA. [ODT Document].
Available:
http://www.oasis-open.org/committees/documents.php?wg_abbrev=office-formula
OpenDocument-formula-20090508.odt
Examples
--------
What is the future value after 10 years of saving $100 now, with
an additional monthly savings of $100. Assume the interest rate is
5% (annually) compounded monthly?
>>> np.fv(0.05/12, 10*12, -100, -100)
15692.928894335748
By convention, the negative sign represents cash flow out (i.e. money not
available today). Thus, saving $100 a month at 5% annual interest leads
to $15,692.93 available to spend in 10 years.
If any input is array_like, returns an array of equal shape. Let's
compare different interest rates from the example above.
>>> a = np.array((0.05, 0.06, 0.07))/12
>>> np.fv(a, 10*12, -100, -100)
array([ 15692.92889434, 16569.87435405, 17509.44688102]) # may vary
"""
when = _convert_when(when)
(rate, nper, pmt, pv, when) = map(np.asarray, [rate, nper, pmt, pv, when])
temp = (1+rate)**nper
fact = np.where(rate == 0, nper,
(1 + rate*when)*(temp - 1)/rate)
return -(pv*temp + pmt*fact)
def _pmt_dispatcher(rate, nper, pv, fv=None, when=None):
warnings.warn(_depmsg.format(name='pmt'),
DeprecationWarning, stacklevel=3)
return (rate, nper, pv, fv)
@array_function_dispatch(_pmt_dispatcher)
def pmt(rate, nper, pv, fv=0, when='end'):
"""
Compute the payment against loan principal plus interest.
.. deprecated:: 1.18
`pmt` is deprecated; for details, see NEP 32 [1]_.
Use the corresponding function in the numpy-financial library,
https://pypi.org/project/numpy-financial.
Given:
* a present value, `pv` (e.g., an amount borrowed)
* a future value, `fv` (e.g., 0)
* an interest `rate` compounded once per period, of which
there are
* `nper` total
* and (optional) specification of whether payment is made
at the beginning (`when` = {'begin', 1}) or the end
(`when` = {'end', 0}) of each period
Return:
the (fixed) periodic payment.
Parameters
----------
rate : array_like
Rate of interest (per period)
nper : array_like
Number of compounding periods
pv : array_like
Present value
fv : array_like, optional
Future value (default = 0)
when : {{'begin', 1}, {'end', 0}}, {string, int}
When payments are due ('begin' (1) or 'end' (0))
Returns
-------
out : ndarray
Payment against loan plus interest. If all input is scalar, returns a
scalar float. If any input is array_like, returns payment for each
input element. If multiple inputs are array_like, they all must have
the same shape.
Notes
-----
The payment is computed by solving the equation::
fv +
pv*(1 + rate)**nper +
pmt*(1 + rate*when)/rate*((1 + rate)**nper - 1) == 0
or, when ``rate == 0``::
fv + pv + pmt * nper == 0
for ``pmt``.
Note that computing a monthly mortgage payment is only
one use for this function. For example, pmt returns the
periodic deposit one must make to achieve a specified
future balance given an initial deposit, a fixed,
periodically compounded interest rate, and the total
number of periods.
References
----------
.. [1] NumPy Enhancement Proposal (NEP) 32,
https://numpy.org/neps/nep-0032-remove-financial-functions.html
.. [2] Wheeler, D. A., E. Rathke, and R. Weir (Eds.) (2009, May).
Open Document Format for Office Applications (OpenDocument)v1.2,
Part 2: Recalculated Formula (OpenFormula) Format - Annotated Version,
Pre-Draft 12. Organization for the Advancement of Structured Information
Standards (OASIS). Billerica, MA, USA. [ODT Document].
Available:
http://www.oasis-open.org/committees/documents.php
?wg_abbrev=office-formulaOpenDocument-formula-20090508.odt
Examples
--------
What is the monthly payment needed to pay off a $200,000 loan in 15
years at an annual interest rate of 7.5%?
>>> np.pmt(0.075/12, 12*15, 200000)
-1854.0247200054619
In order to pay-off (i.e., have a future-value of 0) the $200,000 obtained
today, a monthly payment of $1,854.02 would be required. Note that this
example illustrates usage of `fv` having a default value of 0.
"""
when = _convert_when(when)
(rate, nper, pv, fv, when) = map(np.array, [rate, nper, pv, fv, when])
temp = (1 + rate)**nper
mask = (rate == 0)
masked_rate = np.where(mask, 1, rate)
fact = np.where(mask != 0, nper,
(1 + masked_rate*when)*(temp - 1)/masked_rate)
return -(fv + pv*temp) / fact
def _nper_dispatcher(rate, pmt, pv, fv=None, when=None):
warnings.warn(_depmsg.format(name='nper'),
DeprecationWarning, stacklevel=3)
return (rate, pmt, pv, fv)
@array_function_dispatch(_nper_dispatcher)
def nper(rate, pmt, pv, fv=0, when='end'):
"""
Compute the number of periodic payments.
.. deprecated:: 1.18
`nper` is deprecated; for details, see NEP 32 [1]_.
Use the corresponding function in the numpy-financial library,
https://pypi.org/project/numpy-financial.
:class:`decimal.Decimal` type is not supported.
Parameters
----------
rate : array_like
Rate of interest (per period)
pmt : array_like
Payment
pv : array_like
Present value
fv : array_like, optional
Future value
when : {{'begin', 1}, {'end', 0}}, {string, int}, optional
When payments are due ('begin' (1) or 'end' (0))
Notes
-----
The number of periods ``nper`` is computed by solving the equation::
fv + pv*(1+rate)**nper + pmt*(1+rate*when)/rate*((1+rate)**nper-1) = 0
but if ``rate = 0`` then::
fv + pv + pmt*nper = 0
References
----------
.. [1] NumPy Enhancement Proposal (NEP) 32,
https://numpy.org/neps/nep-0032-remove-financial-functions.html
Examples
--------
If you only had $150/month to pay towards the loan, how long would it take
to pay-off a loan of $8,000 at 7% annual interest?
>>> print(np.round(np.nper(0.07/12, -150, 8000), 5))
64.07335
So, over 64 months would be required to pay off the loan.
The same analysis could be done with several different interest rates
and/or payments and/or total amounts to produce an entire table.
>>> np.nper(*(np.ogrid[0.07/12: 0.08/12: 0.01/12,
... -150 : -99 : 50 ,
... 8000 : 9001 : 1000]))
array([[[ 64.07334877, 74.06368256],
[108.07548412, 127.99022654]],
[[ 66.12443902, 76.87897353],
[114.70165583, 137.90124779]]])
"""
when = _convert_when(when)
(rate, pmt, pv, fv, when) = map(np.asarray, [rate, pmt, pv, fv, when])
use_zero_rate = False
with np.errstate(divide="raise"):
try:
z = pmt*(1+rate*when)/rate
except FloatingPointError:
use_zero_rate = True
if use_zero_rate:
return (-fv + pv) / pmt
else:
A = -(fv + pv)/(pmt+0)
Loading ...