├── docs ├── requirements.txt ├── index.md └── conf.py ├── setup.py ├── bond_pricing ├── __init__.py ├── utils.py ├── no_scipy_workarounds.py ├── key_rates.py ├── simple_bonds.py ├── zero_curve_bond_price.py └── present_value.py ├── pyproject.toml ├── .readthedocs.yaml ├── README.md └── LICENSE /docs/requirements.txt: -------------------------------------------------------------------------------- 1 | myst-parser 2 | numpy 3 | scipy 4 | pandas 5 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from setuptools import setup 3 | from os import environ 4 | 5 | dependencies = ['numpy', 'pandas'] 6 | if 'no_scipy' not in environ: 7 | dependencies += ['scipy'] 8 | 9 | setup(install_requires=dependencies) 10 | -------------------------------------------------------------------------------- /bond_pricing/__init__.py: -------------------------------------------------------------------------------- 1 | from bond_pricing.simple_bonds import ( # noqa E401 2 | bond_price_breakup, bond_price, bond_duration, 3 | bond_yield) 4 | from bond_pricing.present_value import ( # noqa E401 5 | pvaf, fvaf, npv, irr, equiv_rate, duration, annuity_fv, annuity_pv, 6 | annuity_instalment, annuity_instalment_breakup, annuity_periods, 7 | annuity_rate) 8 | from bond_pricing.utils import (newton_wrapper, edate) # noqa E401 9 | from bond_pricing.zero_curve_bond_price import ( # noqa E401 10 | par_yld_to_zero, zero_to_par, nelson_siegel_zero_rate, 11 | make_zero_price_fun, zero_curve_bond_price_breakup, 12 | zero_curve_bond_price, zero_curve_bond_duration, 13 | static_zero_spread) 14 | from bond_pricing.key_rates import ( # noqa E401 15 | key_rate_shift, make_KRS, 16 | standard_krs_points, key_rate_shifted_zero_curve) 17 | from bond_pricing.no_scipy_workarounds import ( # noqa E401 18 | my_irr, no_scipy) 19 | -------------------------------------------------------------------------------- /docs/index.md: -------------------------------------------------------------------------------- 1 | ```{contents} Table of Contents 2 | :depth: 2 3 | ``` 4 | 5 | ```{include} ../README.md 6 | ``` 7 | 8 | ```{eval-rst} 9 | 10 | Bond Valuation using YTM 11 | ======================== 12 | 13 | .. automodule:: bond_pricing.simple_bonds 14 | :members: 15 | 16 | Bond Valuation using zero curve 17 | =============================== 18 | 19 | .. automodule:: bond_pricing.zero_curve_bond_price 20 | :members: 21 | 22 | Bond Valuation Key Rate Shifts 23 | ============================== 24 | 25 | .. automodule:: bond_pricing.key_rates 26 | :members: 27 | 28 | Present Value and Annuities 29 | =========================== 30 | 31 | .. automodule:: bond_pricing.present_value 32 | :members: 33 | 34 | Utility Functions 35 | ================= 36 | 37 | .. automodule:: bond_pricing.utils 38 | :members: 39 | 40 | Indices and tables 41 | ================== 42 | 43 | * :ref:`genindex` 44 | * :ref:`modindex` 45 | * :ref:`search` 46 | 47 | ``` 48 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["setuptools >= 61.0"] 3 | build-backend = "setuptools.build_meta" 4 | 5 | [project] 6 | name = "bond_pricing" 7 | version = "0.7.3" 8 | dynamic = ["dependencies"] 9 | authors = [{name = "Jayanth R. Varma", email = "jrvarma@gmail.com"}] 10 | maintainers = [{name = "Jayanth R. Varma", email = "jrvarma@gmail.com"}] 11 | description = "Bond Price with YTM/zero-curve & NPV, IRR, annuities" 12 | readme = "README.md" 13 | license = {text = "OSI Approved :: GNU General Public License v3 (GPLv3)"} 14 | keywords = ["Bond Pricing", "NPV and IRR", "Zero yield curve", 15 | "Annuities and Perpetuities"] 16 | classifiers=[ 17 | "Development Status :: 3 - Alpha", 18 | "Environment :: Console", 19 | "Intended Audience :: End Users/Desktop", 20 | "Programming Language :: Python :: 3", 21 | ] 22 | requires-python = ">= 3.0" 23 | 24 | [project.urls] 25 | Homepage = "https://github.com/jrvarma/bond_pricing" 26 | 27 | [tool.setuptools] 28 | packages = ["bond_pricing"] 29 | -------------------------------------------------------------------------------- /.readthedocs.yaml: -------------------------------------------------------------------------------- 1 | # Read the Docs configuration file for Sphinx projects 2 | # See https://docs.readthedocs.io/en/stable/config-file/v2.html for details 3 | 4 | # Required 5 | version: 2 6 | 7 | # Set the OS, Python version and other tools you might need 8 | build: 9 | os: ubuntu-22.04 10 | tools: 11 | python: "3.12" 12 | # You can also specify other tool versions: 13 | # nodejs: "20" 14 | # rust: "1.70" 15 | # golang: "1.20" 16 | 17 | # Build documentation in the "docs/" directory with Sphinx 18 | sphinx: 19 | configuration: docs/conf.py 20 | # You can configure Sphinx to use a different builder, for instance use the dirhtml builder for simpler URLs 21 | # builder: "dirhtml" 22 | # Fail on all warnings to avoid broken references 23 | # fail_on_warning: true 24 | 25 | # Optionally build your docs in additional formats such as PDF and ePub 26 | # formats: 27 | # - pdf 28 | # - epub 29 | 30 | # Optional but recommended, declare the Python requirements required 31 | # to build your documentation 32 | # See https://docs.readthedocs.io/en/stable/guides/reproducible-builds.html 33 | python: 34 | install: 35 | - requirements: docs/requirements.txt 36 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # Configuration file for the Sphinx documentation builder. 2 | # 3 | # This file only contains a selection of the most common options. For a full 4 | # list see the documentation: 5 | # https://www.sphinx-doc.org/en/master/usage/configuration.html 6 | 7 | # -- Path setup -------------------------------------------------------------- 8 | 9 | # If extensions (or modules to document with autodoc) are in another directory, 10 | # add these directories to sys.path here. If the directory is relative to the 11 | # documentation root, use os.path.abspath to make it absolute, like shown here. 12 | # 13 | import os 14 | import sys 15 | sys.path.insert(0, os.path.abspath('..')) 16 | 17 | 18 | # -- Project information ----------------------------------------------------- 19 | 20 | project = 'bond_pricing' 21 | copyright = '2020-2024 Prof. Jayanth R. Varma' 22 | author = 'Prof. Jayanth R. Varma' 23 | 24 | 25 | # -- General configuration --------------------------------------------------- 26 | 27 | # Add any Sphinx extension module names here, as strings. They can be 28 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 29 | # ones. 30 | extensions = [ 31 | 'sphinx.ext.autodoc', 32 | 'sphinx.ext.napoleon', 33 | # 'sphinx_mdinclude', 34 | 'myst_parser', 35 | ] 36 | 37 | myst_heading_anchors = 2 38 | 39 | source_suffix = { 40 | '.rst': 'restructuredtext', 41 | '.txt': 'markdown', 42 | '.md': 'markdown', 43 | } 44 | # source_suffix = ['.rst', '.md'] # https://github.com/CrossNox/m2r2 45 | 46 | master_doc = 'index' 47 | 48 | # Add any paths that contain templates here, relative to this directory. 49 | templates_path = ['_templates'] 50 | 51 | # List of patterns, relative to source directory, that match files and 52 | # directories to ignore when looking for source files. 53 | # This pattern also affects html_static_path and html_extra_path. 54 | exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] 55 | 56 | 57 | # -- Options for HTML output ------------------------------------------------- 58 | 59 | # The theme to use for HTML and HTML Help pages. See the documentation for 60 | # a list of builtin themes. 61 | # 62 | html_theme = 'alabaster' 63 | 64 | # Add any paths that contain custom static files (such as style sheets) here, 65 | # relative to this directory. They are copied after the builtin static files, 66 | # so a file named "default.css" will overwrite the builtin "default.css". 67 | html_static_path = ['_static'] 68 | -------------------------------------------------------------------------------- /bond_pricing/utils.py: -------------------------------------------------------------------------------- 1 | """Utility functions 2 | 3 | `newton_wrapper` is a wrapper for scipy.optimize.newton to return root or nan 4 | 5 | `edate` moves date(s) by specified no of months (similar to excel edate) 6 | 7 | `dataframe_like_dict` creates pandas DataFrame from dict like arguments 8 | 9 | """ 10 | import pandas as pd 11 | import numpy as np 12 | from bond_pricing.no_scipy_workarounds import my_irr, no_scipy 13 | 14 | 15 | def newton_wrapper(f, guess, warn=True): 16 | r"""Wrapper for `scipy.optimize.newton` to return root or `nan` 17 | 18 | If scipy cannot be imported, falls back on the my_irr function 19 | that uses root bracketing and bisection. 20 | 21 | Parameters 22 | ---------- 23 | f : callable 24 | The function whose zero is to be found 25 | guess : float 26 | An initial estimate of the zero somewhere near the actual zero. 27 | warn : bool, Optional 28 | If true, a warning is issued when returning nan. 29 | This happens when `scipy.optimize.newton` does not converge. 30 | 31 | Returns 32 | ------- 33 | float 34 | The root if found, numpy.nan otherwise. 35 | Examples 36 | -------- 37 | >>> newton_wrapper(lambda x: x**2 - x, 0.8).item() 38 | 1.0 39 | >>> newton_wrapper(lambda x: x**2 + 1, 1, warn=False) 40 | nan 41 | """ 42 | try: 43 | from scipy.optimize import newton 44 | except ImportError: 45 | no_scipy.warn("newton") 46 | return my_irr(f, guess=guess, warn=warn) 47 | root, status = newton(f, guess, full_output=True, disp=False) 48 | if status.converged: 49 | return root 50 | else: 51 | if warn: 52 | from warnings import warn 53 | warn("Newton root finder did not converge. Returning nan") 54 | return np.nan 55 | 56 | 57 | def _edate_0(dt, m): 58 | """Unvectorized form of edate 59 | 60 | Please see its documentation 61 | 62 | Examples 63 | -------- 64 | 65 | >>> _edate_0('2020-01-31', 1) 66 | Timestamp('2020-02-29 00:00:00') 67 | """ 68 | return pd.to_datetime(dt) + pd.tseries.offsets.DateOffset(months=m) 69 | 70 | 71 | _edate = np.vectorize(_edate_0) 72 | 73 | 74 | def edate(dt, m): 75 | """Move date(s) by specified no of months (similar to excel edate) 76 | 77 | Parameters 78 | ---------- 79 | dt : date, object convertible to date or sequence 80 | The date(s) to be shifted 81 | m : int or sequence 82 | Number of months to shift by 83 | 84 | Returns 85 | ------- 86 | date 87 | dt shifted by m months 88 | 89 | Examples 90 | -------- 91 | 92 | >>> edate('2020-01-31', 1) 93 | Timestamp('2020-02-29 00:00:00') 94 | 95 | 96 | >>> edate(['2020-01-31', '2020-03-31'], [1, 6]) 97 | array([Timestamp('2020-02-29 00:00:00'), Timestamp('2020-09-30 00:00:00')], 98 | dtype=object) 99 | """ 100 | return _edate(dt, np.array(m))[()] 101 | 102 | 103 | def dict_to_dataframe(d): 104 | lengths = [1] 105 | lengths += [len(x) for x in d.values() 106 | if hasattr(x, "len") 107 | and not isinstance(x, str)] 108 | lengths += [x.shape[0] for x in d.values() 109 | if hasattr(x, "shape") 110 | and len(x.shape) > 0] 111 | n = max(lengths) 112 | return pd.DataFrame(d, index=range(n)) 113 | -------------------------------------------------------------------------------- /bond_pricing/no_scipy_workarounds.py: -------------------------------------------------------------------------------- 1 | from numpy import abs, sign, nan, vectorize 2 | 3 | 4 | class no_scipy: 5 | warned = [] 6 | msgs = dict(CubicSpline="Using linear interpolation instead", 7 | newton="Using root bracketing and bisection") 8 | 9 | @staticmethod 10 | def warn(fn_name): 11 | if fn_name not in no_scipy.warned: 12 | no_scipy.warned += [fn_name] 13 | from warnings import warn 14 | if fn_name in no_scipy.msgs: 15 | msg = no_scipy.msgs[fn_name] 16 | else: 17 | msg = "" 18 | no_scipy_warning = ( 19 | "Could not import {:} from Scipy. {:}". 20 | format(fn_name, msg)) 21 | warn(no_scipy_warning) 22 | 23 | 24 | LOWER = -1 + 1e-6 # -100% (theoretical lower bound) 25 | UPPER = 1e4 # 1,000,000% (practical upper bound) 26 | 27 | 28 | def my_irr_0(f, lower=None, upper=None, guess=None, warn=True, 29 | toler=1e-6): 30 | if not guess: 31 | if lower and upper: 32 | guess = (lower + upper) / 2 33 | elif lower: 34 | guess = lower 35 | elif upper: 36 | guess = upper 37 | else: 38 | guess = 0 39 | lower = lower or LOWER 40 | upper = upper or UPPER 41 | if not(lower >= -1 and guess >= lower and guess <= upper): 42 | if warn: 43 | from warnings import warn 44 | warn("-1 <= lower <= guess <= upper is required") 45 | return None 46 | # we first bracket the root (f has opposite signs at L and R) 47 | L, R = bracket_root(f, lower, upper, guess) 48 | if L is None: 49 | print("failed to bracket root") 50 | return nan 51 | # Use bisection to find the root between L and R 52 | return bisection(f, L, R, toler) 53 | 54 | 55 | my_irr = vectorize(my_irr_0) 56 | 57 | 58 | def bracket_root(f, lower, upper, guess, nstep=100): 59 | def grid_search(step_pct, nstep=100): 60 | step = step_pct / 100 61 | guess_sign = sign(f(guess)) 62 | L = None 63 | R = None 64 | for n in range(nstep): 65 | # search for change of sign 66 | # moving in steps of size step_pct 67 | # stop if sign change found 68 | if(guess + n*step <= UPPER and 69 | (sign(f(guess + n*step)) != guess_sign)): 70 | R = guess + n*step 71 | L = R - step 72 | break 73 | if(guess - n*step >= LOWER and 74 | (sign(f(guess - n*step)) != guess_sign)): 75 | L = guess - n*step 76 | R = L + step 77 | break 78 | return L, R 79 | for step in [1, 5, 10, 25, 100]: 80 | # try steps of 1%, 5%, ... 81 | L, R = grid_search(step) 82 | if L is not None: 83 | break 84 | return L, R 85 | 86 | 87 | def bisection(f, a, b, tol): 88 | assert sign(f(a)) != sign(f(b)) 89 | m = (a + b)/2 90 | 91 | if abs(f(m)) < tol: 92 | # stopping condition, report m as root 93 | return m 94 | elif sign(f(a)) == sign(f(m)): 95 | # case where m is an improvement on a. 96 | # Make recursive call with a = m 97 | return bisection(f, m, b, tol) 98 | elif sign(f(b)) == sign(f(m)): 99 | # case where m is an improvement on b. 100 | # Make recursive call with b = m 101 | return bisection(f, a, m, tol) 102 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Installation 2 | 3 | `pip install bond_pricing` 4 | 5 | For installation without pulling in `scipy` as a dependency, see [below](#reducing-dependencies) 6 | 7 | The source code is at if you want to go that route. 8 | 9 | # Overview 10 | 11 | This package provides bond pricing functions as well as basic NPV/IRR functions. Bond valuation can be done using an yield to maturity or using a zero yield curve. There is a convenience function to construct a zero yield curve from a few points on the par bond or zero yield curve or from Nelson Siegel parameters. 12 | 13 | The documentation is available at 14 | 15 | The bond valuation functions can be used in two modes: 16 | 17 | * The first mode is similar to spreadsheet bond pricing functions. The settlement date and maturity date are given as dates and the software calculates the time to maturity and to each coupon payment date from these dates. For any `daycount` other than simple counting of days (ACT/365 in ISDA terminology), this packages relies on the `isda_daycounters` module that can be downloaded from 18 | 19 | * Maturity can be given in years (the `settle` parameter is set to `None` and is assumed to be time 0) and there are no dates at all. This mode is particularly convenient to price par bonds or price other bonds on issue date or coupon dates. For example, finding the price of a 7 year 3.5% coupon bond if the prevailing yield is 3.65% is easier in this mode as the maturity is simply given as 7.0 instead of providing a maturity date and specifying today's date. Using this mode between coupon dates is not so easy as the user has to basically compute the day count and year fraction and provide the maturity as say 6.7 years. 20 | 21 | * Bond Valuation 22 | - Bond price using YTM (`bond_price`) or using zero yield curve (`zero_curve_bond_price`) 23 | - Accrued interest and dirty bond prices using YTM (`bond_price_breakup`) or using zero yield curve (`zero_curve_bond_price_breakup`) 24 | - Duration using YTM (`bond_duration`) 25 | - Yield to maturity (`bond_yield`). 26 | 27 | * Zero curve construction 28 | - bootstrap zero yields from par yields (`par_yld_to_zero`) or vice versa (`zero_to_par`) 29 | - compute zero rates from Nelson Siegel parameters (`nelson_siegel_zero_rate`) 30 | - construct zero prices from par or zero yields at selected knot points using a cubic spline or assuming a flat yield curve (`make_zero_price_fun`) 31 | 32 | * Present Value functions 33 | - Net Present Value (`npv`) 34 | - Internal Rate of Return (`irr`) 35 | - Duration (`duration`). 36 | These functions allow different compounding frequencies: for example, the cash flows may be monthly while the interest rate is semi-annually compounded. The function `equiv_rate` converts between different compounding frequencies. 37 | 38 | * Annuity functions 39 | - Annuity present value (`annuity_pv`) 40 | - Future value (`annuity_fv`) 41 | - Implied interest rate (`annuity_rate`) 42 | - Number of periods to achieve given present value or terminal value (`annuity_periods`). 43 | - Periodic instalment to achieve given present value or terminal value (`annuity_instalment`). 44 | - Breakup of instalment into principal and interest (`annuity_instalment_breakup`) 45 | 46 | In these functions also, the cash flow frequency may be different from the compounding frequency. 47 | 48 | # Reducing Dependencies 49 | 50 | This module requires `numpy`, `pandas` and `scipy`. In some environments, installing `scipy` may be difficult, and only a couple of functions (the `newton` root finder and `CubicSpline` interpolation) are actually needed from the huge `scipy` package. So a provision has been made to avoid `scipy` with some loss of functionality (the `newton` root finder is replaced by a less sophisticated root bracketing and bisection algorithm and `CubicSpline` interpolation is replaced by the much cruder linear interpolation). At run time, the module checks for the availability of `scipy` and uses the cruder methods (with a suitable warning) if `scipy` is not available. 51 | 52 | To install this package without pulling in `scipy` as a dependency, do the following: 53 | 54 | ``` 55 | git clone https://github.com/jrvarma/bond_pricing.git 56 | export no_scipy=1 57 | pip install bond_pricing 58 | ``` 59 | -------------------------------------------------------------------------------- /bond_pricing/key_rates.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import pandas as pd 3 | from bond_pricing.zero_curve_bond_price import ( # noqa F401 4 | zero_to_par, par_yld_to_zero, make_zero_price_fun, 5 | zero_curve_bond_price) 6 | 7 | 8 | standard_krs_points = [2, 5, 10, 30] 9 | 10 | 11 | def _mat_sequence(T, freq): 12 | return np.arange(1/freq, T + 1/freq, 1/freq) 13 | 14 | 15 | def key_rate_shift(krs, mat=None, T=None, freq=2, 16 | krs_points=standard_krs_points): 17 | r"""Shift in various par bond yields for a key rate shift 18 | 19 | Mainly for internal use or pedagogical use. 20 | 21 | 22 | Parameters 23 | ---------- 24 | krs : int or string, optional 25 | The key rate segment of the curve to be shifted 26 | For example, 5 for shifting the 5 year segment. 27 | "all" and "none" are also accepted. 28 | mat : array 29 | The maturities for which the shift is to be computed 30 | T : Maximum maturity upto which shifted yields are to be returned. 31 | freq : Coupon or Compounding Frequency 32 | krs_points : sequence, optional 33 | The key rates to be used. 34 | 35 | Returns 36 | ------- 37 | array 38 | The shifts in each par bond yields for a one basis point 39 | shift in a key rate 40 | 41 | Examples 42 | -------- 43 | 44 | """ 45 | if mat is None: 46 | if T is None: 47 | T = krs_points[-1] 48 | mat = _mat_sequence(T, freq) 49 | if krs in krs_points: 50 | bump = [0] * len(krs_points) 51 | bump[krs_points.index(krs)] = 1 52 | return np.interp(mat, krs_points, bump) 53 | elif krs == "all": 54 | return np.ones_like(mat) 55 | elif krs == "none": 56 | return np.zeros_like(mat) 57 | else: 58 | raise(Exception("Invalid key rate shift")) 59 | 60 | 61 | def make_KRS(freq=2, krs_points=standard_krs_points): 62 | r"""Data Frame of par yield shifts for all key rate shifts 63 | 64 | Mainly for pedagogical use. 65 | 66 | Parameters 67 | ---------- 68 | freq : Coupon or Compounding Frequency 69 | krs_points : sequence, optional 70 | The key rates to be used. 71 | 72 | Returns 73 | ------- 74 | pandas DataFrame 75 | 76 | Examples 77 | -------- 78 | 79 | """ 80 | KRS = pd.DataFrame(index=_mat_sequence(krs_points[-1], freq)) 81 | for krs in list(krs_points) + ['all', 'none']: 82 | KRS[krs] = key_rate_shift(krs, freq=freq, krs_points=krs_points) 83 | return KRS 84 | 85 | 86 | def key_rate_shifted_zero_curve( 87 | initial_zero_fn=None, initial_zero_price=None, 88 | initial_zero_yld=None, initial_par_yld=None, 89 | krs='none', freq=2, T=None, what='zero_yields', 90 | krs_points=standard_krs_points): 91 | r"""Applies a key rate shift to an yield curve 92 | 93 | The initial yield curve can be given in many alternative ways. 94 | One of these must be non None: 95 | `initial_zero_fn`, `initial_zero_price`, `initial_zero_yld`, 96 | `initial_par_yld` 97 | 98 | Parameters 99 | ---------- 100 | initial_zero_fn : function, optional 101 | Function that returns zero prices for any maturity 102 | initial_zero_price : array, optional 103 | Zero prices for coupon dates up to some maturity 104 | initial_zero_yld : array, optional 105 | Zero yields for coupon dates up to some maturity 106 | initial_par_yld : array, optional 107 | Par yields for coupon dates up to some maturity 108 | krs : int or string, optional 109 | The key rate segment of the curve to be shifted 110 | For example, 5 for shifting the 5 year segment. 111 | "all" and "none" are also accepted. 112 | freq : Coupon or Compounding Frequency 113 | T : Maximum maturity upto which shifted yields are to be returned. 114 | what : str, optional 115 | What to return. Can be: 116 | `zero_yields`, `zero_prices`, `forward_rates` or `zero_fn` 117 | krs_points : sequence, optional 118 | The key rates to be used. 119 | Returns 120 | ------- 121 | array or function: 122 | If `what` is `zero_yields`, `zero_prices` or `forward_rates`, 123 | the corresponding array is return. If `what` is `zero_fn`, a 124 | function is returned. 125 | 126 | Examples 127 | -------- 128 | Compute KR01 of a 10-year 8% bond when initial yield curve is 129 | flat at 5%. Being a 10 year bond, the 10 year KR01 is the largest. 130 | But since it is not a par bond, the 5 year KR01 is also large. 131 | 132 | >>> fn0 = make_zero_price_fun(flat_curve=5e-2, freq=2) 133 | >>> P0 = zero_curve_bond_price(cpn=8e-2, mat=10, zero_price_fn=fn0) 134 | >>> fns = [key_rate_shifted_zero_curve( 135 | ... initial_zero_fn=fn0, krs=krs, what='zero_fn') 136 | ... for krs in standard_krs_points] 137 | >>> zero_curve_bond_price(cpn=8e-2, mat=10, zero_price_fn=fns) - P0 138 | array([-0.00121608, -0.00467591, -0.08307928, 0. ]) 139 | 140 | """ 141 | if initial_zero_fn is not None: 142 | if T is None: 143 | T = krs_points[-1] 144 | initial_zero_price = initial_zero_fn(_mat_sequence(T, freq)) 145 | if initial_zero_price is not None: 146 | initial_par_yld = zero_to_par(zero_prices=initial_zero_price, 147 | freq=freq) 148 | elif initial_zero_yld is not None: 149 | initial_par_yld = zero_to_par(zero_yields=initial_zero_yld, 150 | freq=freq) 151 | assert initial_par_yld is not None, ( 152 | "zero_fn, zero_yld, zero_price or par_yld must be given") 153 | if not isinstance(initial_par_yld, (np.ndarray, pd.Series)): 154 | initial_par_yld = np.asarray(initial_par_yld) 155 | shifted_par = initial_par_yld + key_rate_shift( 156 | krs, T=len(initial_par_yld)/freq, freq=freq, 157 | krs_points=krs_points) / 10000 158 | if what in "zero_yields zero_prices forward_rates".split(): 159 | return par_yld_to_zero(shifted_par, freq=freq)[what] 160 | elif what == "zero_fn": 161 | zyld = par_yld_to_zero(shifted_par, freq=freq)['zero_yields'] 162 | return make_zero_price_fun(zero_at_coupon_dates=zyld, freq=freq) 163 | else: 164 | raise(Exception("'what' must be one of zero_yields zero_prices " 165 | "forward_rates zero_fn")) 166 | -------------------------------------------------------------------------------- /bond_pricing/simple_bonds.py: -------------------------------------------------------------------------------- 1 | """Bond Valuation functions 2 | 3 | Important functions are `bond_price`, `bond_yield` and `bond_duration` 4 | for computing the price, yield to maturity and duration of one 5 | or more bonds. 6 | 7 | The settlement date and maturity date can be given as dates and the 8 | software calculates the time to maturity (and coupon dates) using a 9 | `daycount` convention to calculate year_fractions. 10 | For any `daycount` other than simple counting of days 11 | (ACT/365 in ISDA terminology), this packages relies on the 12 | `isda_daycounters` module that can be downloaded from 13 | 14 | 15 | Maturity can alternatively be given in years by setting `settle` 16 | to `None`. The trade/settlement date is then year 0. 17 | 18 | """ 19 | from numpy import array, where, vectorize, float64, ceil 20 | import pandas as pd 21 | from bond_pricing.utils import ( 22 | newton_wrapper, edate, dict_to_dataframe) 23 | from bond_pricing.present_value import pvaf, equiv_rate 24 | 25 | 26 | def _bond_coupon_periods_0(settle=None, mat=1, freq=2, daycount=None): 27 | r"""Unvectorized form of bond_coupon_periods. 28 | 29 | Please see its documentation 30 | 31 | """ 32 | if settle is not None: 33 | settle = pd.to_datetime(settle) 34 | mature = pd.to_datetime(mat) 35 | # approximate number of full coupon periods left 36 | n = int(freq * (mature - settle).days / 360) 37 | # the divisor of 360 guarantees this is an overestimate 38 | # we keep reducing n till it is right 39 | while (edate(mature, -n * 12 / freq) <= settle): 40 | n -= 1 41 | next_coupon = edate(mature, -n * 12 / freq) 42 | n += 1 # n is now number of full coupons since previous coupon 43 | prev_coupon = edate(mature, -n * 12 / freq) 44 | # old wrong code: prev_coupon = edate(next_coupon, -12/freq) 45 | # if prev_coupon != settle: 46 | # # we are in the middle of a coupon period 47 | # # no of coupons is One PLUS No of full coupon periods 48 | # n += 1 49 | if daycount is None: 50 | daycounter = default_daycounter 51 | else: 52 | assert daycount in daycounters, ( 53 | "Unknown daycount {:}. {:}".format( 54 | daycount, 55 | "isda_daycounters not available" 56 | if no_isda else "")) 57 | daycounter = daycounters[daycount] 58 | discounting_fraction = daycounter.year_fraction( 59 | settle, next_coupon) * freq 60 | accrual_fraction = daycounter.year_fraction( 61 | prev_coupon, settle) * freq 62 | else: 63 | n = ceil(mat*freq) 64 | accrual_fraction = n - freq * mat 65 | discounting_fraction = 1 - accrual_fraction 66 | next_coupon = None 67 | prev_coupon = None 68 | if accrual_fraction == 1: 69 | # We are on coupon date. Assume that bond is ex-interest 70 | # Remove today's coupon 71 | # This affects dirty price and accrued interest 72 | # but not clean price 73 | discounting_fraction += 1 74 | accrual_fraction -= 1 75 | return (n, discounting_fraction, accrual_fraction, 76 | next_coupon, prev_coupon) 77 | 78 | 79 | _bond_coupon_periods = vectorize(_bond_coupon_periods_0) 80 | 81 | 82 | def bond_coupon_periods(settle=None, mat=1, freq=2, daycount=None, 83 | return_dataframe=False): 84 | r""" Compute no of coupon, coupon dates and fractions 85 | 86 | Parameters 87 | ---------- 88 | settle : date or None 89 | The settlement date. None means maturity is in years. 90 | mat : int or date 91 | Maturity date or if settle is None, maturity in years 92 | freq : int 93 | Coupon frequency 94 | daycount : daycounter 95 | This class has day_count and year_fraction methods 96 | return_dataframe : bool 97 | whether to return pandas DataFrame instead of dict 98 | 99 | Returns 100 | ------- 101 | dict 102 | n : No of coupons left 103 | 104 | discounting_fraction: Fraction of coupon period to next coupon 105 | 106 | accrual_fraction: Fraction of coupon period to previous coupon 107 | 108 | next_coupon: Next coupon date (None if settle is None) 109 | 110 | prev_coupon Previous coupon date (None if settle is None) 111 | 112 | Examples 113 | -------- 114 | >>> bond_coupon_periods( 115 | ... settle='2020-03-13', mat='2030-01-01', freq=2, daycount=None 116 | ... ) # doctest: +NORMALIZE_WHITESPACE 117 | {'n': np.int64(20), 118 | 'discounting_fraction': np.float64(0.6), 119 | 'accrual_fraction': np.float64(0.4), 120 | 'next_coupon': Timestamp('2020-07-01 00:00:00'), 121 | 'prev_coupon': Timestamp('2020-01-01 00:00:00')} 122 | 123 | >>> bond_coupon_periods( 124 | ... mat=10.125, freq=2, daycount=None 125 | ... ) # doctest: +NORMALIZE_WHITESPACE 126 | {'n': np.float64(21.0), 127 | 'discounting_fraction': np.float64(0.25), 128 | 'accrual_fraction': np.float64(0.75), 129 | 'next_coupon': None, 130 | 'prev_coupon': None} 131 | 132 | """ 133 | res = array(_bond_coupon_periods(settle=settle, mat=mat, 134 | freq=freq, daycount=daycount)) 135 | if len(res.shape) > 1: 136 | result = dict(n=res[0, :], 137 | discounting_fraction=res[1, :], 138 | accrual_fraction=res[2, :], 139 | next_coupon=res[3, :], 140 | prev_coupon=res[4, :],) 141 | else: 142 | result = dict(n=res[0][()], 143 | discounting_fraction=res[1][()], 144 | accrual_fraction=res[2][()], 145 | next_coupon=res[3][()], 146 | prev_coupon=res[4][()],) 147 | if return_dataframe: 148 | return dict_to_dataframe(result) 149 | else: 150 | return result 151 | 152 | 153 | def bond_price_breakup(settle=None, cpn=0, mat=1, yld=0, freq=2, 154 | comp_freq=None, face=100, redeem=None, 155 | daycount=None, return_dataframe=False): 156 | r"""Compute clean/dirty price & accrued_interest of coupon bond using YTM 157 | 158 | Parameters 159 | ---------- 160 | settle : date or None 161 | The settlement date. None means maturity is in years. 162 | cpn : float 163 | The coupon rate in decimal 164 | mat : float or date 165 | Maturity date or if settle is None, maturity in years 166 | yld : float 167 | The yield to maturity in decimal 168 | freq : int 169 | Coupon frequency 170 | comp_freq : int 171 | Compounding frequency 172 | face : float 173 | Face value of the bond 174 | redeem : float 175 | Redemption value 176 | daycount : daycounter 177 | This class has day_count and year_fraction methods 178 | return_dataframe : bool 179 | whether to return pandas DataFrame instead of dict 180 | 181 | Returns 182 | ------- 183 | dict 184 | dirty: dirty price of the bond 185 | 186 | accrued: accrued interest 187 | 188 | clean: clean price of the bond 189 | 190 | next_coupon: Next coupon date (only if settle is None) 191 | 192 | prev_coupon: Previous coupon date (only if settle is None) 193 | 194 | Examples 195 | -------- 196 | >>> bond_price_breakup( 197 | ... settle="2012-04-15", mat="2022-01-01", cpn=8e-2, yld=8.8843e-2, 198 | ... freq=1) # doctest: +NORMALIZE_WHITESPACE 199 | {'DirtyPrice': np.float64(96.64322827099208), 200 | 'AccruedInterest': np.float64(2.311111111111111), 201 | 'CleanPrice': np.float64(94.33211715988098), 202 | 'NextCoupon': Timestamp('2013-01-01 00:00:00'), 203 | 'PreviousCoupon': Timestamp('2012-01-01 00:00:00')} 204 | 205 | >>> bond_price_breakup( 206 | ... mat=10.25, cpn=8e-2, yld=9e-2, 207 | ... freq=2) # doctest: +NORMALIZE_WHITESPACE 208 | {'DirtyPrice': np.float64(95.37373582338677), 209 | 'AccruedInterest': np.float64(2.0), 210 | 'CleanPrice': np.float64(93.37373582338677), 211 | 'NextCoupon': None, 212 | 'PreviousCoupon': None} 213 | 214 | >>> bond_price_breakup( 215 | ... settle="2012-04-15", mat="2022-01-01", cpn=8e-2, yld=8.8843e-2, 216 | ... freq=[1,2,4]) # doctest: +NORMALIZE_WHITESPACE 217 | {'DirtyPrice': array([96.64322827099208, 96.61560601490777, 218 | 94.59488828646788], dtype=object), 219 | 'AccruedInterest': array([2.311111111111111, 2.311111111111111, 220 | 0.3111111111111111], dtype=object), 221 | 'CleanPrice': array([94.33211715988098, 94.30449490379667, 222 | 94.28377717535678], dtype=object), 223 | 'NextCoupon': array([Timestamp('2013-01-01 00:00:00'), 224 | Timestamp('2012-07-01 00:00:00'), 225 | Timestamp('2012-07-01 00:00:00')], 226 | dtype=object), 227 | 'PreviousCoupon': array([Timestamp('2012-01-01 00:00:00'), 228 | Timestamp('2012-01-01 00:00:00'), 229 | Timestamp('2012-04-01 00:00:00')], 230 | dtype=object)} 231 | >>> bond_price_breakup( 232 | ... settle="2012-04-15", mat="2022-01-01", cpn=8e-2, yld=8.8843e-2, 233 | ... freq=[1,2,4], 234 | ... return_dataframe=True) 235 | DirtyPrice AccruedInterest CleanPrice NextCoupon PreviousCoupon 236 | 0 96.643228 2.311111 94.332117 2013-01-01 2012-01-01 237 | 1 96.615606 2.311111 94.304495 2012-07-01 2012-01-01 238 | 2 94.594888 0.311111 94.283777 2012-07-01 2012-04-01 239 | 240 | """ 241 | # None can make comp_freq an array of objects 242 | # Since log needs float, we use .astype(float64) 243 | freq, cpn = array(freq), array(cpn) 244 | comp_freq = where(comp_freq is None, freq, comp_freq).astype(float64) 245 | # find the equivalent yield that matches the coupon frequency 246 | yld = equiv_rate(yld, comp_freq, freq) 247 | redeem = where(redeem is None, face, redeem) 248 | red_by_face = redeem / face 249 | res = bond_coupon_periods(settle, mat, freq, daycount) 250 | # compounding factor from previous coupon date to settlement date 251 | fractional_CF = (1 + yld/freq)**res['accrual_fraction'] 252 | # calculate PV as at previous coupon date and compound to today 253 | dirty = fractional_CF * ( 254 | # PV of coupons as at previous coupon date 255 | cpn/freq * pvaf(yld/freq, res['n']) 256 | # PV of redemption as at previous coupon date 257 | + red_by_face * (1 + yld/freq)**-res['n']) 258 | accrued = cpn/freq * res['accrual_fraction'] 259 | clean = dirty - accrued 260 | result = dict(DirtyPrice=(face*dirty)[()], 261 | AccruedInterest=(face*accrued)[()], 262 | CleanPrice=(face*clean)[()], 263 | NextCoupon=res['next_coupon'], 264 | PreviousCoupon=res['prev_coupon']) 265 | if return_dataframe: 266 | return dict_to_dataframe(result) 267 | else: 268 | return result 269 | 270 | 271 | def bond_price(settle=None, cpn=0, mat=1, 272 | yld=0, freq=2, comp_freq=None, 273 | face=100, redeem=None, daycount=None): 274 | """ Compute clean price of coupon bond using YTM 275 | 276 | This is a wrapper for bond_price_breakup that extracts 277 | and returns only the clean price. 278 | 279 | Parameters 280 | ---------- 281 | settle : date or None 282 | The settlement date. None means maturity is in years. 283 | cpn : float 284 | The coupon rate in decimal 285 | mat : float or date 286 | Maturity date or if settle is None, maturity in years 287 | yld : float 288 | The yield to maturity in decimal 289 | freq : int 290 | Coupon frequency 291 | comp_freq : int 292 | Compounding frequency 293 | face : float 294 | Face value of the bond 295 | redeem : float 296 | Redemption value 297 | daycount : daycounter 298 | This class has day_count and year_fraction methods 299 | 300 | Returns 301 | ------- 302 | float 303 | clean price of the bond 304 | 305 | Examples 306 | -------- 307 | >>> bond_price(settle="2012-04-15", mat="2022-01-01", cpn=8e-2, 308 | ... yld=8.8843e-2, freq=1).item() 309 | 94.33211715988098 310 | 311 | >>> bond_price(mat=10.25, cpn=8e-2, yld=9e-2, freq=2).item() 312 | 93.37373582338677 313 | 314 | >>> bond_price(settle="2012-04-15", mat="2022-01-01", cpn=8e-2, 315 | ... yld=8.8843e-2,freq=[1, 2, 4]) 316 | array([94.33211715988098, 94.30449490379667, 94.28377717535678], 317 | dtype=object) 318 | 319 | >>> bond_price(settle = "2021-01-01", mat = "2031-01-01", 320 | ... yld = 1e-2, freq = 2, cpn = 5e-2).item() 321 | 137.9748382933389 322 | """ 323 | return bond_price_breakup( 324 | settle=settle, cpn=cpn, mat=mat, yld=yld, freq=freq, 325 | comp_freq=comp_freq, face=face, redeem=redeem, 326 | daycount=daycount)['CleanPrice'] 327 | 328 | 329 | def bond_duration(settle=None, cpn=0, mat=1, yld=0, freq=2, 330 | comp_freq=None, face=100, redeem=None, 331 | daycount=None, modified=False): 332 | r""" 333 | 334 | Parameters 335 | ---------- 336 | settle : date or None 337 | The settlement date. None means maturity is in years. 338 | cpn : float 339 | The coupon rate in decimal 340 | mat : float or date 341 | Maturity date or if settle is None, maturity in years 342 | yld : float 343 | The yield to maturity in decimal 344 | freq : int 345 | Coupon frequency 346 | comp_freq : int 347 | Compounding frequency 348 | face : float 349 | Face value of the bond 350 | redeem : float 351 | Redemption value 352 | daycount : daycounter 353 | This class has day_count and year_fraction methods 354 | modified : bool 355 | Whether to return modified duration 356 | 357 | Returns 358 | ------- 359 | float 360 | The duration (modified duration if modified is True) 361 | 362 | Examples 363 | -------- 364 | >>> bond_duration(settle="2012-04-15", mat="2022-01-01", cpn=8e-2, 365 | ... yld=8.8843e-2).item() 366 | 6.678708669753968 367 | 368 | >>> bond_duration(settle="2012-04-15", mat="2022-01-01", cpn=8e-2, 369 | ... yld=8.8843e-2, modified=True).item() 370 | 6.394648779016871 371 | 372 | >>> bond_duration(settle="2012-04-15", mat="2022-01-01", cpn=8e-2, 373 | ... yld=[7e-2, 8.8843e-2]) 374 | array([6.88872548, 6.67870867]) 375 | 376 | """ 377 | # consider a bond which has just paid a coupon 378 | # decompose it as a portfolio of three positions 379 | # Position PV Duration_minus_(1+y)/y 380 | # -------- -- ---------------------- 381 | # perpetuity of c c/y = cF/Fy 0 382 | # short perpetuity -c/y/F = -c/Fy T 383 | # Redemption of R R/F = Ry/Fy T-(1+y)/y 384 | # where F is Future Value Factor (1+y)^T 385 | # Portfolio Duration is (1+y)/y - N/D where 386 | # N = cT - RyT + R(1+y) = R[1+y + T(c/R-y)] 387 | # D = cF - c + Ry = R[c(F-1)/R + y] 388 | # where Fy has been eliminated from both N and D 389 | # Eliminating R gives 390 | # N = 1+y + T(c/R-y) 391 | # D = c(F-1)/R + y 392 | # we compute duration in coupon periods as on previous coupon date 393 | freq, cpn = array(freq), array(cpn) 394 | comp_freq = where(comp_freq is None, freq, comp_freq).astype(float64) 395 | # find the equivalent yield that matches the coupon frequency 396 | yld = equiv_rate(yld, comp_freq, freq) 397 | redeem = where(redeem is None, face, redeem) 398 | R = redeem / face 399 | res = bond_coupon_periods(settle=settle, mat=mat, freq=freq, 400 | daycount=daycount) 401 | y = yld/freq 402 | c = cpn/freq 403 | T = res['n'] 404 | # T += where(res['accrual_fraction'] > 0, 1, 0) 405 | F = (1+y)**T 406 | dur = (1+y)/y - (1+y + T*(c/R-y)) / (c*(F-1)/R + y) 407 | # now we subtract the fractional coupon period 408 | dur -= res['accrual_fraction'] 409 | # then we convert to years 410 | dur /= freq 411 | return where(modified, dur/(1+y), dur)[()] 412 | 413 | 414 | def _bond_yield_0(settle=None, cpn=0, mat=1, price=100, freq=2, comp_freq=None, 415 | face=100, redeem=None, daycount=None, guess=10e-2): 416 | r"""Unvectorized form of bond_yield. 417 | 418 | Please see its documentation 419 | 420 | """ 421 | return newton_wrapper( 422 | lambda yld: bond_price( 423 | settle, cpn, mat, yld, freq, comp_freq, face, redeem, 424 | daycount) - price, 425 | guess) 426 | 427 | 428 | def bond_yield(settle=None, cpn=0, mat=1, price=100, freq=2, comp_freq=None, 429 | face=100, redeem=None, daycount=None, guess=10e-2): 430 | r"""Find the yield to maturity of one or more bonds 431 | 432 | Parameters 433 | ---------- 434 | settle : date or None 435 | The settlement date. None means maturity is in years. 436 | cpn : float 437 | The coupon rate in decimal 438 | mat : float or date 439 | Maturity date or if settle is None, maturity in years 440 | price : 441 | The price of the bond 442 | freq : int 443 | Coupon frequency 444 | comp_freq : int 445 | Compounding frequency 446 | face : float 447 | Face value of the bond 448 | redeem : float 449 | Redemption value 450 | daycount : daycounter 451 | This class has day_count and year_fraction methods 452 | guess : float 453 | Initial guess of the yield for the root finder 454 | 455 | Returns 456 | ------- 457 | float : 458 | The yield to maturity of the bond. np.nan if the root finder failed. 459 | 460 | Examples 461 | -------- 462 | 463 | >>> bond_yield(settle="2012-04-15", mat="2022-01-01", cpn=8e-2, 464 | ... price=94.33, freq=1).item() 465 | 0.08884647275135965 466 | 467 | >>> bond_yield(mat=10.25, cpn=8e-2, price=93.37, freq=2).item() 468 | 0.09000591604105035 469 | 470 | >>> bond_yield(settle="2012-04-15", mat="2022-01-01", cpn=8e-2, 471 | ... price=[93, 94, 95], freq=1) 472 | array([0.09104904, 0.08938905, 0.08775269]) 473 | 474 | """ 475 | return vectorize(_bond_yield_0)( 476 | settle=settle, cpn=cpn, mat=mat, price=price, freq=freq, 477 | comp_freq=comp_freq, face=face, redeem=redeem, daycount=daycount, 478 | guess=guess)[()] 479 | 480 | 481 | def _import_isda_daycounters(): 482 | r"""Import isda_daycounters. Could raise ImportError 483 | 484 | Returns 485 | ------- 486 | daycounters : dict 487 | keys are the names of the daycounters, values are the classes 488 | default_daycounter : daycounter 489 | thirty360 490 | no_isda : bool 491 | Whether isda_daycounters unavailable (False) 492 | 493 | """ 494 | from isda_daycounters import (actual360, actual365, 495 | actualactual, thirty360, 496 | thirtyE360, thirtyE360ISDA) 497 | daycounters = {x.name: x for x in (actual360, actual365, 498 | actualactual, thirty360, 499 | thirtyE360, thirtyE360ISDA)} 500 | default_daycounter = thirty360 501 | no_isda = False 502 | return daycounters, default_daycounter, no_isda 503 | 504 | 505 | def _make_simple_day_counter(): 506 | r"""Create a simple daycounter (basically ACT/365) 507 | 508 | Returns 509 | ------- 510 | daycounters : dict 511 | only key is 'simple', value is SimpleDayCount 512 | default_daycounter : daycounter 513 | SimpleDayCount 514 | no_isda : bool 515 | Whether isda_daycounters available (True) 516 | 517 | """ 518 | class SimpleDayCount: 519 | def day_count(start_date, end_date): 520 | return (end_date - start_date).days 521 | 522 | def year_fraction(start_date, end_date): 523 | return (end_date - start_date).days / 365.0 524 | 525 | daycounters = {'simple': SimpleDayCount} 526 | default_daycounter = SimpleDayCount 527 | no_isda = True 528 | from warnings import warn 529 | warn("Module isda_daycounters is not installed.\n" 530 | "Only 'simple' daycount (basically ACT/365) is available.\n" 531 | "To use other daycounts, install isda_daycounters from\n" 532 | "https://github.com/miradulo/isda_daycounters") 533 | return daycounters, default_daycounter, no_isda 534 | 535 | 536 | try: 537 | daycounters, default_daycounter, no_isda = _import_isda_daycounters() 538 | except ImportError: 539 | daycounters, default_daycounter, no_isda = _make_simple_day_counter() 540 | -------------------------------------------------------------------------------- /bond_pricing/zero_curve_bond_price.py: -------------------------------------------------------------------------------- 1 | from numpy import (array, arange, empty_like, vectorize, # noqa E401 2 | ceil, log, exp, interp, nan, where, dot, 3 | concatenate) 4 | import numpy as np 5 | from bond_pricing.simple_bonds import bond_coupon_periods, equiv_rate 6 | from bond_pricing.utils import newton_wrapper, dict_to_dataframe 7 | from bond_pricing.no_scipy_workarounds import no_scipy 8 | 9 | 10 | def par_yld_to_zero(par, freq=1, return_dataframe=False): 11 | r"""Bootstrap a complete par bond yield curve to zero 12 | 13 | Parameters 14 | ---------- 15 | par : sequence of floats 16 | The par bond yields for various maturities in decimal 17 | Maturities are spaced 1/freq years apart 18 | freq : int, optional 19 | The coupon frequency (equals compounding frequency) 20 | return_dataframe : bool, optional 21 | whether to return pandas DataFrame instead of dict 22 | Returns 23 | ------- 24 | dict or DataFrame: 25 | 26 | zero_yields: array of zero yields in decimal 27 | 28 | zero_prices: array of zero prices 29 | 30 | forward_rates: array of forward rates in decimal 31 | 32 | (Maturities are spaced 1/freq years apart) 33 | 34 | Examples 35 | -------- 36 | >>> par_yld_to_zero( 37 | ... par=[1.0200e-2, 1.2000e-2, 1.4200e-2, 1.6400e-2, 1.9150e-2, 38 | ... 2.1900e-2, 2.4375e-2, 2.6850e-2, 2.9325e-2, 3.1800e-2], 39 | ... freq=2, return_dataframe=True) 40 | zero_yields zero_prices forward_rates 41 | 0 0.010200 0.994926 0.010200 42 | 1 0.012005 0.988102 0.013812 43 | 2 0.014220 0.978970 0.018656 44 | 3 0.016445 0.967776 0.023133 45 | 4 0.019245 0.953245 0.030487 46 | 5 0.022068 0.936279 0.036242 47 | 6 0.024630 0.917891 0.040066 48 | 7 0.027218 0.897504 0.045429 49 | 8 0.029837 0.875223 0.050915 50 | 9 0.032492 0.851159 0.056545 51 | 52 | """ 53 | annuity = 0 54 | prev_zero = 1 55 | zp = empty_like(par) 56 | zyld = empty_like(par) 57 | fwd = empty_like(par) 58 | for i, cpn in enumerate(par): 59 | n = i + 1 60 | pv_intermediate = annuity * cpn/freq 61 | pv_final = 1 - pv_intermediate 62 | zero_price = pv_final / (1 + cpn/freq) 63 | zp[i] = zero_price 64 | zyld[i] = (zero_price**(-1.0/n) - 1) * freq 65 | fwd[i] = (prev_zero / zero_price - 1) * freq 66 | prev_zero = zero_price 67 | annuity += zero_price 68 | result = dict(zero_yields=zyld, zero_prices=zp, forward_rates=fwd) 69 | if return_dataframe: 70 | return dict_to_dataframe(result) 71 | else: 72 | return result 73 | 74 | 75 | def zero_to_par(zero_prices=None, zero_yields=None, freq=1): 76 | r"""Convert zero yield curve into par curve 77 | 78 | The zero curve can be specified either as prices or as yields. 79 | One of `zero_prices` and `zero_yields` must not be None. 80 | 81 | Parameters 82 | ---------- 83 | zero_prices : sequence of floats, optional 84 | The zero prices for various maturities in decimal 85 | Either zero_prices or zero_yields must be provided 86 | If both are provided, zero_yields is ignored 87 | Maturities are spaced 1/freq years apart 88 | zero_yields : sequence of floats, optional 89 | The zero yields for various maturities in decimal 90 | Maturities are spaced 1/freq years apart 91 | freq : int, optional 92 | The coupon frequency (equals compounding frequency) 93 | 94 | Returns 95 | ------- 96 | par : array of floats 97 | The par yields for various maturities in decimal 98 | Maturities are spaced 1/freq years apart 99 | 100 | Examples 101 | -------- 102 | >>> zero_to_par( 103 | ... zero_yields=[0.0102 , 0.0120054 , 0.01421996, 0.01644462, 104 | ... 0.01924529, 0.02206823, 0.02462961, 0.02721789, 105 | ... 0.0298373 , 0.0324924 ], 106 | ... freq=2) # doctest: +NORMALIZE_WHITESPACE 107 | array([0.0102 , 0.012 , 0.0142 , 0.0164 , 0.01915 , 0.0219 , 108 | 0.024375, 0.02685 , 0.029325, 0.0318 ]) 109 | 110 | >>> zero_to_par( 111 | ... zero_prices=[0.99492588, 0.98810183, 0.97896982, 0.96777586, 112 | ... 0.9532451 , 0.9362787 , 0.91789052, 0.89750426, 113 | ... 0.87522337, 0.85115892], 114 | ... freq=2) # doctest: +NORMALIZE_WHITESPACE 115 | array([0.0102 , 0.012 , 0.0142 , 0.0164 , 0.01915 , 0.0219 , 116 | 0.024375, 0.02685 , 0.029325, 0.0318 ]) 117 | 118 | """ 119 | if zero_prices is None: 120 | zero_yields, freq = array(zero_yields), array(freq) 121 | t = arange(len(zero_yields)) + 1 122 | zero_prices = (1 + zero_yields/freq)**(-t) 123 | annuity = 0 124 | par = empty_like(zero_prices) 125 | for i, zero_price in enumerate(zero_prices): 126 | annuity = annuity + zero_price 127 | pv_redeem = zero_price 128 | pv_cpns = 1 - pv_redeem 129 | par[i] = (pv_cpns / annuity) * freq 130 | return par 131 | 132 | 133 | def nelson_siegel_zero_rate(beta0, beta1, beta2, tau, m): 134 | r"""Computes zero rate from Nelson Siegel parameters 135 | 136 | Parameters 137 | ---------- 138 | beta0 : float 139 | the long term rate 140 | beta1 : float 141 | the slope 142 | beta2 : float 143 | curvature 144 | tau : float 145 | location of the hump 146 | m : float 147 | maturity at which zero rate is to be found 148 | 149 | Returns 150 | ------- 151 | float : 152 | the continuously compounded zero yield for maturity m 153 | 154 | Examples 155 | -------- 156 | >>> nelson_siegel_zero_rate(0.128397, -0.024715, -0.050231, 2.0202, 157 | ... [0.25, 5, 15, 30]) 158 | array([0.10228692, 0.10489195, 0.11833924, 0.12335016]) 159 | 160 | >>> nelson_siegel_zero_rate(0.0893088, -0.0314768, -0.0130352, 161 | ... 3.51166, [0.25, 5, 15, 30]) 162 | array([0.05848376, 0.06871299, 0.07921554, 0.08410199]) 163 | 164 | """ 165 | m = array(m) 166 | old_settings = np.seterr(invalid='ignore') 167 | possible_0_by_0 = where(m == 0, 168 | 1, 169 | np.divide(1 - exp(-m/tau), m/tau)) 170 | np.seterr(**old_settings) 171 | return (beta0 + (beta1 + beta2) * possible_0_by_0 172 | - beta2 * exp(-m/tau))[()] 173 | 174 | 175 | def make_zero_price_fun(flat_curve=None, 176 | nelson_siegel=None, 177 | par_at_knots=None, 178 | par_at_coupon_dates=None, 179 | zero_at_knots=None, 180 | zero_at_coupon_dates=None, 181 | freq=1, max_maturity=None): 182 | r"""Create function that returns zero price for any maturity 183 | 184 | The zero curve can be specified in many alternative ways: 185 | `flat_curve`, `nelson_siegel`, `par_at_knots`, 186 | `par_at_coupon_dates`, `zero_at_knots`, `zero_at_coupon_dates`. 187 | One of these must not be None. 188 | 189 | 190 | Parameters 191 | ---------- 192 | flat_curve : float, optional 193 | Yield (flat yield curve) 194 | nelson_siegel : tuple of floats, optional 195 | tuple consists of beta0, beta1, beta2, tau 196 | par_at_knots : tuple of two sequences of floats, optional 197 | First element of tuple is a sequence of maturities 198 | Second element is a sequence of par yields for these maturities 199 | par_at_coupon_dates : sequence of floats, optional 200 | Par yields for maturities spaced 1/freq years apart 201 | zero_at_knots : tuple of two sequences of floats, optional 202 | First element of tuple is a sequence of maturities 203 | Second element is a sequence of zero rates for these maturities 204 | zero_at_coupon_dates : sequence, optional 205 | Zero yields for maturities spaced 1/freq years apart 206 | freq : int, optional 207 | The coupon frequency (equals compounding frequency) 208 | max_maturity : float, optional 209 | The maximum maturity upto which the yields are to be 210 | extrapolated. If None, no extrapolation is done. 211 | 212 | Returns 213 | ------- 214 | function : 215 | Function that takes float (maturity) as argument and 216 | returns float (zero price) 217 | 218 | Examples 219 | -------- 220 | >>> make_zero_price_fun(par_at_knots = ( 221 | ... [0, 1, 3, 5, 10], 222 | ... [3e-2, 3.5e-2, 4e-2, 4.5e-2, 4.75e-2]))([1, 5, 10]) 223 | array([0.96618357, 0.80065643, 0.62785397]) 224 | 225 | """ 226 | if flat_curve is not None: 227 | r = equiv_rate(flat_curve, freq, np.inf) 228 | return lambda t: exp(- r * array(t))[()] 229 | if nelson_siegel is not None: 230 | beta0, beta1, beta2, tau = nelson_siegel 231 | return lambda m: exp(- nelson_siegel_zero_rate( 232 | beta0, beta1, beta2, tau, m) * array(m))[()] 233 | if par_at_knots is not None: 234 | t, r = par_at_knots 235 | if min(t) != 0: 236 | from warnings import warn 237 | if min(t) < 0: 238 | warn("Knot point at negative maturity.") 239 | else: 240 | warn("A knot point at zero maturity is recommended.") 241 | if max_maturity is None: 242 | max_maturity = max(t) 243 | par_at_coupon_dates = interpolate( 244 | t, r, arange(ceil(max_maturity*freq))+1) 245 | if par_at_coupon_dates is not None: 246 | zero_at_coupon_dates = par_yld_to_zero(par_at_coupon_dates, 247 | freq)['zero_yields'] 248 | if zero_at_coupon_dates is None: 249 | assert zero_at_knots is not None, "No yield curve provided" 250 | t, r = zero_at_knots 251 | if min(t) != 0: 252 | from warnings import warn 253 | if min(t) < 0: 254 | warn("Knot point at negative maturity.") 255 | else: 256 | warn("A knot point at zero maturity is recommended.") 257 | if max_maturity is None: 258 | max_maturity = max(t) 259 | zero_at_coupon_dates = interpolate( 260 | t, r, arange(ceil(max_maturity*freq))+1) 261 | zero_at_coupon_dates = equiv_rate(zero_at_coupon_dates, 262 | from_freq=freq, to_freq=np.inf) 263 | t = arange(len(zero_at_coupon_dates) + 1) / freq 264 | log_zero_df = -concatenate([[0], zero_at_coupon_dates]) * t 265 | return lambda x: exp(interp(x, t, log_zero_df, left=nan, right=nan)) 266 | 267 | 268 | def zero_curve_bond_price_breakup( 269 | settle=None, cpn=0, mat=1, zero_price_fn=(lambda x: 1), 270 | freq=2, face=100, redeem=None, daycount=None, 271 | return_dataframe=False): 272 | r"""Clean/dirty price & accrued interest of coupon bond using zero yields 273 | 274 | Parameters 275 | ---------- 276 | settle : date or None 277 | The settlement date. None means maturity is in years. 278 | cpn : float 279 | The coupon rate in decimal 280 | mat : float or date 281 | Maturity date or if settle is None, maturity in years 282 | zero_price_fn : function 283 | takes float (maturity) as argument and 284 | returns float (zero price) 285 | freq : int 286 | Coupon frequency 287 | face : float 288 | Face value of the bond 289 | redeem : float 290 | Redemption value 291 | daycount : daycounter 292 | This class has day_count and year_fraction methods 293 | return_dataframe : bool 294 | whether to return pandas DataFrame instead of dict 295 | 296 | Returns 297 | ------- 298 | dict or DataFrame 299 | dirty: dirty price of the bond 300 | 301 | accrued: accrued interest 302 | 303 | clean: clean price of the bond 304 | 305 | next_coupon: Next coupon date (only if settle is None) 306 | 307 | prev_coupon: Previous coupon date (only if settle is None) 308 | 309 | Examples 310 | -------- 311 | >>> zero_curve_bond_price_breakup( 312 | ... cpn=10e-2, mat=10, freq=1, 313 | ... zero_price_fn=make_zero_price_fun( 314 | ... flat_curve=8e-2)) # doctest: +NORMALIZE_WHITESPACE 315 | {'DirtyPrice': np.float64(113.42016279788285), 316 | 'AccruedInterest': np.float64(0.0), 317 | 'CleanPrice': np.float64(113.42016279788285), 318 | 'NextCoupon': None, 319 | 'PreviousCoupon': None} 320 | 321 | >>> zero_curve_bond_price_breakup( 322 | ... cpn=5e-2, mat=2, freq=1, 323 | ... zero_price_fn=make_zero_price_fun( 324 | ... zero_at_coupon_dates=[3e-2, 10e-2]) 325 | ... ) # doctest: +NORMALIZE_WHITESPACE 326 | {'DirtyPrice': np.float64(91.63122843617106), 327 | 'AccruedInterest': np.float64(0.0), 328 | 'CleanPrice': np.float64(91.63122843617106), 329 | 'NextCoupon': None, 330 | 'PreviousCoupon': None} 331 | 332 | """ 333 | freq, cpn = array(freq), array(cpn) 334 | redeem = where(redeem is None, face, redeem) 335 | red_by_face = redeem / face 336 | res = bond_coupon_periods(settle, mat, freq, daycount) 337 | # print(res) 338 | 339 | def one_dirty_price(n, fraction, coupon, R_by_F, zp_fun): 340 | t = (arange(n) + fraction) / freq 341 | df = zp_fun(t) 342 | cf = [coupon/freq] * int(n-1) + [coupon/freq + R_by_F] 343 | # import pandas as pd 344 | # print(pd.DataFrame(dict(df=df, cf=cf), index=t)) 345 | return dot(df, cf) 346 | 347 | dirty_price = vectorize(one_dirty_price) 348 | dirty = dirty_price(n=res['n'], 349 | fraction=res['discounting_fraction'], 350 | coupon=cpn, 351 | R_by_F=red_by_face, 352 | zp_fun=zero_price_fn) 353 | accrued = cpn/freq * res['accrual_fraction'] 354 | clean = dirty - accrued 355 | result = dict(DirtyPrice=(face*dirty)[()], 356 | AccruedInterest=(face*accrued)[()], 357 | CleanPrice=(face*clean)[()], 358 | NextCoupon=res['next_coupon'], 359 | PreviousCoupon=res['prev_coupon']) 360 | if return_dataframe: 361 | return dict_to_dataframe(result) 362 | else: 363 | return result 364 | 365 | 366 | def zero_curve_bond_price(settle=None, cpn=0, mat=1, 367 | zero_price_fn=(lambda x: 1), 368 | freq=2, face=100, redeem=None, 369 | daycount=None): 370 | r"""Compute clean price of coupon bond using zero yields 371 | 372 | Parameters 373 | ---------- 374 | settle : date or None 375 | The settlement date. None means maturity is in years. 376 | cpn : float 377 | The coupon rate in decimal 378 | mat : float or date 379 | Maturity date or if settle is None, maturity in years 380 | zero_price_fn : function 381 | takes float (maturity) as argument and 382 | returns float (zero price) 383 | freq : int 384 | Coupon frequency 385 | face : float 386 | Face value of the bond 387 | redeem : float 388 | Redemption value 389 | daycount : daycounter 390 | This class has day_count and year_fraction methods 391 | 392 | Returns 393 | ------- 394 | float 395 | clean price of the bond 396 | 397 | Examples 398 | -------- 399 | >>> zero_curve_bond_price( 400 | ... cpn=10e-2, mat=10, freq=1, 401 | ... zero_price_fn=make_zero_price_fun( 402 | ... flat_curve=8e-2)).item() # doctest: +NORMALIZE_WHITESPACE 403 | 113.42016279788285 404 | 405 | >>> zero_curve_bond_price( 406 | ... cpn=5e-2, mat=2, freq=1, 407 | ... zero_price_fn=make_zero_price_fun( 408 | ... zero_at_coupon_dates=[3e-2, 10e-2]) 409 | ... ).item() # doctest: +NORMALIZE_WHITESPACE 410 | 91.63122843617106 411 | 412 | >>> zero_curve_bond_price( 413 | ... cpn=5.792982e-2, mat=6, freq=2, 414 | ... zero_price_fn=make_zero_price_fun( 415 | ... nelson_siegel=(6.784e-2, -3.8264e-2, -3.6631e-2, 0.7774)) 416 | ... ).item() 417 | 99.99999939355965 418 | 419 | """ 420 | return zero_curve_bond_price_breakup( 421 | settle=settle, cpn=cpn, mat=mat, zero_price_fn=zero_price_fn, 422 | freq=freq, face=face, redeem=redeem, 423 | daycount=daycount)['CleanPrice'] 424 | 425 | 426 | def zero_curve_bond_duration(settle=None, cpn=0, mat=1, 427 | zero_price_fn=(lambda x: 1), 428 | freq=2, face=100, redeem=None, 429 | daycount=None, modified=False): 430 | r"""Duration of coupon bond using zero yields 431 | 432 | Parameters 433 | ---------- 434 | settle : date or None 435 | The settlement date. None means maturity is in years. 436 | cpn : float 437 | The coupon rate in decimal 438 | mat : float or date 439 | Maturity date or if settle is None, maturity in years 440 | zero_price_fn : function 441 | takes float (maturity) as argument and 442 | returns float (zero price) 443 | freq : int 444 | Coupon frequency 445 | face : float 446 | Face value of the bond 447 | redeem : float 448 | Redemption value 449 | daycount : daycounter 450 | This class has day_count and year_fraction methods 451 | 452 | Returns 453 | ------- 454 | float 455 | duration or modified duration of the bond 456 | 457 | Examples 458 | -------- 459 | >>> zero_curve_bond_duration( 460 | ... cpn=10e-2, mat=10, freq=1, 461 | ... zero_price_fn=make_zero_price_fun( 462 | ... flat_curve=8e-2)).item() # doctest: +NORMALIZE_WHITESPACE 463 | 6.965803939497351 464 | >>> zero_curve_bond_duration( 465 | ... cpn=5e-2, mat=2, freq=1, 466 | ... zero_price_fn=make_zero_price_fun( 467 | ... zero_at_coupon_dates=[3e-2, 10e-2]) 468 | ... ).item() # doctest: +NORMALIZE_WHITESPACE 469 | 1.9470227670753064 470 | """ 471 | freq, cpn = array(freq), array(cpn) 472 | redeem = where(redeem is None, face, redeem) 473 | red_by_face = redeem / face 474 | res = bond_coupon_periods(settle, mat, freq, daycount) 475 | 476 | def one_duration(n, fraction, coupon, R_by_F, zp_fun): 477 | t = (arange(n) + fraction) / freq 478 | df = zp_fun(t) 479 | cf = [coupon/freq] * int(n-1) + [coupon/freq + R_by_F] 480 | # import pandas as pd 481 | # print(pd.DataFrame(dict(df=df, cf=cf), index=t)) 482 | return dot(df, cf * t) / dot(df, cf) 483 | 484 | duration = vectorize(one_duration) 485 | result = duration(n=res['n'], 486 | fraction=res['discounting_fraction'], 487 | coupon=cpn, 488 | R_by_F=red_by_face, 489 | zp_fun=zero_price_fn) 490 | return result[()] 491 | 492 | 493 | def static_zero_spread(settle=None, cpn=0, mat=1, price=None, 494 | zero_price_fn=(lambda x: 1), 495 | freq=2, face=100, redeem=None, 496 | daycount=None, guess=0.0): 497 | r"""Static spread (Z-spread) over zero curve to match bond price 498 | 499 | Parameters 500 | ---------- 501 | settle : date or None 502 | The settlement date. None means maturity is in years. 503 | cpn : float 504 | The coupon rate in decimal 505 | mat : float or date 506 | Maturity date or if settle is None, maturity in years 507 | price : float 508 | Market price of the bond 509 | zero_price_fn : function 510 | takes float (maturity) as argument and 511 | returns float (zero price) 512 | freq : int 513 | Coupon frequency 514 | face : float 515 | Face value of the bond 516 | redeem : float 517 | Redemption value 518 | daycount : daycounter 519 | This class has day_count and year_fraction methods 520 | guess : float 521 | Initial guess of the yield for the root finder 522 | 523 | Returns 524 | ------- 525 | float 526 | Static spread (Z-spread) 527 | 528 | Examples 529 | -------- 530 | >>> round(static_zero_spread( 531 | ... cpn=5e-2, mat=2, freq=1, price=91.63122843617106, 532 | ... zero_price_fn=make_zero_price_fun( 533 | ... zero_at_coupon_dates=[2.5e-2, 9.5e-2])), 534 | ... 6).item() 535 | 0.005 536 | """ 537 | 538 | def zero_price_fn_with_spread(spread, freq): 539 | def f(t): 540 | cc_yld = -log(zero_price_fn(t)) / t 541 | new_yld = equiv_rate(cc_yld, np.inf, freq) + spread 542 | new_cc_yld = equiv_rate(new_yld, freq, np.inf) 543 | return exp(-new_cc_yld * t) 544 | return f 545 | 546 | def one_spread(settle, cpn, mat, price, zero_price_fn, 547 | freq, face, redeem, daycount, guess): 548 | return newton_wrapper( 549 | lambda spread: zero_curve_bond_price( 550 | settle=settle, cpn=cpn, mat=mat, 551 | zero_price_fn=zero_price_fn_with_spread(spread, freq), 552 | freq=freq, face=face, 553 | redeem=redeem, daycount=daycount) - price, 554 | guess) 555 | spread = vectorize(one_spread) 556 | result = spread(settle=settle, cpn=cpn, mat=mat, price=price, 557 | zero_price_fn=zero_price_fn, freq=freq, face=face, 558 | redeem=redeem, daycount=daycount, guess=guess) 559 | return result[()] 560 | 561 | 562 | def interpolate(t, r, x): 563 | try: 564 | from scipy.interpolate import CubicSpline 565 | except ImportError: 566 | no_scipy.warn("CubicSpline") 567 | return np.interp(x, t, r) 568 | return CubicSpline(t, r)(x) 569 | -------------------------------------------------------------------------------- /bond_pricing/present_value.py: -------------------------------------------------------------------------------- 1 | """Present value module in bond_pricing 2 | 3 | This module includes `npv`, `irr` and `duration` for 4 | arbitrary cash flows. The functions for annuities include 5 | `annuity_pv`, `annuity_pv`, `annuity_rate`, `annuity_instalment`, 6 | `annuity_instalment_breakup`, `annuity_periods`. The helper functions 7 | `pvaf` and `fvaf` are intended for use by the annuity functions, but 8 | can be used directly if desired. 9 | 10 | """ 11 | import numpy as np 12 | from numpy import array, log, exp, where, vectorize 13 | from bond_pricing.utils import newton_wrapper, dict_to_dataframe 14 | 15 | 16 | def pvaf(r, n): 17 | """ Compute Present Value of Annuity Factor 18 | 19 | Parameters 20 | ---------- 21 | r : float or sequence of floats 22 | per period interest rate in decimal 23 | n : float or sequence of floats 24 | number of periods 25 | 26 | Returns 27 | ------- 28 | float or array of floats 29 | The present value of annuity factor 30 | 31 | Examples 32 | -------- 33 | >>> pvaf(r=0.1, n=10).item() 34 | 6.144567105704685 35 | 36 | >>> pvaf(10e-2, [5, 10]) 37 | array([3.79078677, 6.14456711]) 38 | 39 | """ 40 | r, n = array(r), array(n) 41 | # We use numpy.where to handle r == 0, but numpy.where evaluates 42 | # both expressions and so 0/0 will still happen. Suppress the error. 43 | old_settings = np.seterr(invalid='ignore') 44 | result = where(r == 0, n, np.divide(1 - (1+r)**-n, r)) 45 | np.seterr(**old_settings) 46 | return result[()] 47 | 48 | 49 | def fvaf(r, n): 50 | """ Compute Future Value of Annuity Factor 51 | 52 | Parameters 53 | ---------- 54 | r : float or sequence of floats 55 | per period interest rate in decimal 56 | n : float or sequence of floats 57 | number of periods 58 | 59 | Returns 60 | ------- 61 | float or array of floats 62 | The future value of annuity factor 63 | 64 | Examples 65 | -------- 66 | >>> fvaf(r=0.1, n=10).item() 67 | 15.937424601000023 68 | >>> fvaf(r=[0, 0.1], n=10) 69 | array([10. , 15.9374246]) 70 | 71 | """ 72 | r, n = array(r), array(n) 73 | old_settings = np.seterr(invalid='ignore') 74 | result = where(r == 0, n, np.divide((1+r)**n - 1, r)) 75 | np.seterr(**old_settings) 76 | return result[()] 77 | 78 | 79 | def npv(cf, rate, cf_freq=1, comp_freq=1, cf_t=None, 80 | immediate_start=False): 81 | r"""NPV of a sequence of cash flows 82 | 83 | Parameters 84 | ---------- 85 | cf : float or sequence of floats 86 | array of cash flows 87 | rate : float or sequence of floats 88 | discount rate 89 | cf_freq : float or sequence of floats, optional 90 | cash flow frequency (for example, 2 for semi-annual) 91 | comp_freq : float or sequence of floats, optional 92 | compounding frequency (for example, 2 for semi-annual) 93 | cf_t : float or sequence of floats or None, optional 94 | The timing of cash flows. 95 | If None, equally spaced cash flows are assumed 96 | immediate_start : bool or sequence of bool, optional 97 | If True, cash flows start immediately 98 | Else, the first cash flow is at the end of the first period. 99 | 100 | Returns 101 | ------- 102 | float or array of floats 103 | The net present value of the cash flows 104 | 105 | Examples 106 | -------- 107 | >>> npv(cf=[-100, 150, -50, 75], rate=5e-2).item() 108 | 59.327132213429586 109 | 110 | >>> npv(cf=[-100, 150, -50, 75], rate=5e-2, comp_freq=[1, 2]) 111 | array([59.32713221, 59.15230661]) 112 | 113 | >>> npv(cf=[-100, 150, -50, 75], rate=5e-2, 114 | ... immediate_start=[False, True]) 115 | array([59.32713221, 62.29348882]) 116 | 117 | >>> npv(cf=[-100, 150, -50, 75], cf_t=[0, 2, 5, 7], rate=[5e-2, 8e-2]) 118 | array([50.17921321, 38.33344284]) 119 | 120 | """ 121 | 122 | def one_npv(rate, cf_freq, comp_freq, immediate_start): 123 | if cf_t is None: 124 | start = 0 if immediate_start else 1/cf_freq 125 | stop = start + len(cf) / cf_freq 126 | cf_ta = np.arange(start=start, step=1/cf_freq, stop=stop) 127 | else: 128 | cf_ta = array(cf_t) 129 | cc_rate = equiv_rate(rate, from_freq=comp_freq, to_freq=np.inf) 130 | df = exp(-cc_rate * cf_ta) 131 | return np.dot(cf, df) 132 | 133 | cf = array(cf) 134 | return vectorize(one_npv)( 135 | rate=rate, cf_freq=cf_freq, comp_freq=comp_freq, 136 | immediate_start=immediate_start)[()] 137 | 138 | 139 | def equiv_rate(rate, from_freq=1, to_freq=1): 140 | r"""Convert interest rate from one compounding frequency to another 141 | 142 | Parameters 143 | ---------- 144 | rate : float or sequence of floats 145 | discount rate in decimal 146 | from_freq : float or sequence of floats 147 | compounding frequency of input rate 148 | to_freq : float or sequence of floats 149 | compounding frequency of output rate 150 | 151 | Returns 152 | ------- 153 | float or array of floats 154 | The discount rate for the desired compounding frequency 155 | 156 | Examples 157 | -------- 158 | >>> equiv_rate( 159 | ... rate=10e-2, from_freq=1, to_freq=[1, 2, 12, 365, np.inf]) 160 | array([0.1 , 0.0976177 , 0.09568969, 0.09532262, 0.09531018]) 161 | 162 | >>> equiv_rate( 163 | ... rate=10e-2, from_freq=[1, 2, 12, 365, np.inf], to_freq=1) 164 | array([0.1 , 0.1025 , 0.10471307, 0.10515578, 0.10517092]) 165 | 166 | """ 167 | rate, from_freq, to_freq = array(rate), array(from_freq), array(to_freq) 168 | # the use of where prevents nan from being returned for 0/0 169 | # but since where evaluates both expressions the error still occurs 170 | # we run np.seterr and np.divide to catch 0/0 errors 171 | old_settings = np.seterr(invalid='ignore') 172 | cc_rate = where(from_freq == np.inf, rate, 173 | log(1 + np.divide(rate, from_freq)) * from_freq) 174 | res = where(from_freq == to_freq, 175 | rate, 176 | where(to_freq == np.inf, 177 | cc_rate, 178 | (exp(np.divide(cc_rate, to_freq)) - 1) * to_freq))[()] 179 | np.seterr(**old_settings) 180 | return res 181 | 182 | 183 | def duration(cf, rate, cf_freq=1, comp_freq=1, cf_t=None, 184 | immediate_start=False, modified=False): 185 | r"""Duration of arbitrary sequence of cash flows 186 | 187 | Parameters 188 | ---------- 189 | cf : sequence of floats 190 | array of cash flows 191 | rate : float or sequence of floats 192 | discount rate 193 | cf_freq : float or sequence of floats, optional 194 | cash flow frequency (for example, 2 for semi-annual) 195 | comp_freq : float or sequence of floats, optional 196 | compounding frequency (for example, 2 for semi-annual) 197 | cf_t : float or sequence of floats or None, optional 198 | The timing of cash flows. 199 | If None, equally spaced cash flows are assumed 200 | immediate_start : bool or sequence of bool, optional 201 | If True, cash flows start immediately 202 | Else, the first cash flow is at the end of the first period. 203 | modified : bool or sequence of bool, optional 204 | If True, modified duration is returned 205 | 206 | Returns 207 | ------- 208 | float or array of floats 209 | The duration of the cash flows 210 | 211 | Examples 212 | -------- 213 | >>> duration(cf=[100, 50, 75, 25], rate=10e-2).item() 214 | 1.9980073065426769 215 | 216 | >>> duration(cf=[100, 50, 75, 25], rate=10e-2, 217 | ... immediate_start=[True, False]) 218 | array([0.99800731, 1.99800731]) 219 | 220 | """ 221 | 222 | def one_duration(rate, cf_freq, comp_freq, immediate_start): 223 | if cf_t is None: 224 | start = 0 if immediate_start else 1/cf_freq 225 | stop = start + len(cf) / cf_freq 226 | cf_ta = np.arange(start=start, step=1/cf_freq, stop=stop) 227 | else: 228 | cf_ta = cf_t 229 | cc_rate = equiv_rate(rate, from_freq=comp_freq, to_freq=np.inf) 230 | df = exp(-cc_rate * cf_ta) 231 | return np.dot(cf*df, cf_ta) / np.dot(cf, df) 232 | 233 | D = vectorize(one_duration)( 234 | rate=rate, cf_freq=cf_freq, comp_freq=comp_freq, 235 | immediate_start=immediate_start) 236 | D /= where(modified, 1 + rate/comp_freq, 1) 237 | return D[()] 238 | 239 | 240 | def irr(cf, cf_freq=1, comp_freq=1, cf_t=None, r_guess=10e-2): 241 | r"""IRR of a sequence of cash flows 242 | 243 | Multiple IRRs can be found by giving multiple values of r_guess 244 | as shown in one of the examples below. 245 | 246 | Parameters 247 | ---------- 248 | cf : float or sequence of floats 249 | array of cash flows 250 | cf_freq : float or sequence of floats, optional 251 | cash flow frequency (for example, 2 for semi-annual) 252 | comp_freq : float or sequence of floats, optional 253 | compounding frequency (for example, 2 for semi-annual) 254 | cf_t : float or sequence of floats or None, optional 255 | The timing of cash flows. 256 | If None, equally spaced cash flows are assumed 257 | immediate_start : bool or sequence of bool, optional 258 | If True, cash flows start immediately 259 | Else, the first cash flow is at the end of the first period. 260 | r_guess : float or sequence of floats, optional 261 | Starting value (guess) for root finder 262 | 263 | Returns 264 | ------- 265 | float or array of floats 266 | The internal rate of return (IRR) of the cash flows 267 | 268 | Examples 269 | -------- 270 | >>> irr(cf=[-100, 150, -50, 75]).item() 271 | 0.4999999999999994 272 | 273 | >>> irr(cf=[-100, 150, -50, 75], cf_freq=1, comp_freq=2).item() 274 | 0.4494897427831782 275 | 276 | >>> irr(cf=[-100, 150, -50, 75], cf_t=[0, 2, 5, 7]).item() 277 | 0.2247448713915599 278 | 279 | >>> irr(cf=(-100, 230, -132), r_guess=[0.13, 0.18]) 280 | array([0.1, 0.2]) 281 | 282 | """ 283 | if np.sign(max(cf)) == np.sign(min(cf)): 284 | return(np.nan) 285 | 286 | def one_irr(cf_freq, comp_freq, r_guess): 287 | 288 | def f(r): 289 | return npv(cf=cf, rate=r, cf_freq=cf_freq, 290 | comp_freq=comp_freq, cf_t=cf_t) 291 | return newton_wrapper(f, r_guess) 292 | 293 | return vectorize(one_irr)( 294 | cf_freq=cf_freq, comp_freq=comp_freq, r_guess=r_guess)[()] 295 | 296 | 297 | def annuity_pv(rate, n_periods=np.inf, instalment=1, terminal_payment=0, 298 | immediate_start=False, cf_freq=1, comp_freq=1): 299 | r"""Present value of annuity 300 | 301 | Parameters 302 | ---------- 303 | rate : float or sequence of floats 304 | per period discount rate in decimal 305 | n_periods : float or sequence of floats 306 | number of periods of annuity 307 | instalment : float or sequence of floats 308 | instalment per period 309 | terminal_payment : float or sequence of floats 310 | baloon payment at the end of the annuity 311 | immediate_start : bool or sequence of bool 312 | If True, cash flows start immediately 313 | Else, the first cash flow is at the end of the first period. 314 | cf_freq : float or sequence of floats 315 | cash flow frequency (for example, 2 for semi-annual) 316 | comp_freq : float or sequence of floats 317 | compounding frequency (for example, 2 for semi-annual) 318 | 319 | Returns 320 | ------- 321 | float or array of floats 322 | The present value of the annuity 323 | 324 | Examples 325 | -------- 326 | >>> annuity_pv(rate=10e-2, n_periods=15, instalment=500).item() 327 | 3803.039753154183 328 | >>> annuity_pv(rate=10e-2, n_periods=[10, 15], instalment=500) 329 | array([3072.28355285, 3803.03975315]) 330 | 331 | """ 332 | rate, n_periods, instalment, terminal_payment, immediate_start = ( 333 | array(rate), array(n_periods), array(instalment), 334 | array(terminal_payment), array(immediate_start)) 335 | cf_freq, comp_freq = array(cf_freq), array(comp_freq) 336 | r = equiv_rate(rate, comp_freq, cf_freq) / cf_freq 337 | pv = pvaf(r, n_periods) * instalment + ( 338 | terminal_payment / (1 + r)**n_periods) 339 | pv *= where(immediate_start, 1 + r, 1) 340 | return pv[()] 341 | 342 | 343 | def annuity_fv(rate, n_periods=np.inf, instalment=1, terminal_payment=0, 344 | immediate_start=False, cf_freq=1, comp_freq=1): 345 | r"""Future value of annuity 346 | 347 | Parameters 348 | ---------- 349 | rate : float or sequence of floats 350 | per period discount rate in decimal 351 | n_periods : float or sequence of floats 352 | number of periods of annuity 353 | instalment : float or sequence of floats 354 | instalment per period 355 | terminal_payment : float or sequence of floats 356 | baloon payment at the end of the annuity 357 | immediate_start : bool or sequence of bool 358 | If True, cash flows start immediately 359 | Else, the first cash flow is at the end of the first period. 360 | cf_freq : float or sequence of floats 361 | cash flow frequency (for example, 2 for semi-annual) 362 | comp_freq : float or sequence of floats 363 | compounding frequency (for example, 2 for semi-annual) 364 | 365 | Returns 366 | ------- 367 | float or array of floats 368 | The future value of the annuity 369 | 370 | Examples 371 | -------- 372 | >>> annuity_fv(rate=10e-2, n_periods=15, instalment=500).item() 373 | 15886.240847078281 374 | >>> annuity_fv(rate=10e-2, n_periods=[10, 15], instalment=500) 375 | array([ 7968.7123005 , 15886.24084708]) 376 | 377 | """ 378 | rate, n_periods, instalment, terminal_payment, immediate_start = ( 379 | array(rate), array(n_periods), array(instalment), 380 | array(terminal_payment), array(immediate_start)) 381 | cf_freq, comp_freq = array(cf_freq), array(comp_freq) 382 | r = equiv_rate(rate, comp_freq, cf_freq)/cf_freq 383 | tv = fvaf(r, n_periods) * instalment + terminal_payment 384 | tv *= where(immediate_start, 1 + r, 1) 385 | return tv[()] 386 | 387 | 388 | def annuity_instalment(rate, n_periods=np.inf, pv=None, fv=None, 389 | terminal_payment=0, immediate_start=False, 390 | cf_freq=1, comp_freq=1): 391 | r"""Periodic instalment to get desired PV or FV 392 | 393 | Parameters 394 | ---------- 395 | rate : float or sequence of floats 396 | per period discount rate in decimal 397 | n_periods : float or sequence of floats 398 | number of periods of annuity 399 | pv : float or sequence of floats 400 | desired present value of annuity 401 | fv : float or sequence of floats 402 | desired future value of annuity 403 | If pv and fv are given, discounted value of fv is added to pv 404 | terminal_payment : float or sequence of floats 405 | baloon payment at the end of the annuity 406 | immediate_start : bool or sequence of bool 407 | If True, cash flows start immediately 408 | Else, the first cash flow is at the end of the first period. 409 | cf_freq : float or sequence of floats 410 | cash flow frequency (for example, 2 for semi-annual) 411 | comp_freq : float or sequence of floats 412 | compounding frequency (for example, 2 for semi-annual) 413 | 414 | Returns 415 | ------- 416 | float or array of floats 417 | The instalment 418 | 419 | 420 | Examples 421 | -------- 422 | >>> annuity_instalment(rate=10e-2, n_periods=15, pv=3803.04).item() 423 | 500.0000324537518 424 | 425 | >>> annuity_instalment(rate=10e-2, n_periods=[10, 15], pv=3803.04) 426 | array([618.92724655, 500.00003245]) 427 | 428 | """ 429 | if fv is None: 430 | pv = pv or 1 431 | fv = 0 432 | else: 433 | pv = pv or 0 434 | fv, pv, n_periods = array(fv), array(pv), array(n_periods) 435 | r = equiv_rate(rate, comp_freq, cf_freq)/cf_freq 436 | reqd_annuity_pv = pv + (fv - terminal_payment) / (1 + r)**n_periods 437 | return (reqd_annuity_pv / pvaf(r, n_periods))[()] 438 | 439 | 440 | def annuity_periods(rate, instalment=1, pv=None, fv=None, 441 | terminal_payment=0, immediate_start=False, 442 | cf_freq=1, comp_freq=1, round2int_digits=6): 443 | r"""Number of periods of annuity to get desired PV or FV 444 | 445 | Parameters 446 | ---------- 447 | rate : float or sequence of floats 448 | per period discount rate in decimal 449 | instalment : float or sequence of floats 450 | instalment per period 451 | pv : float or sequence of floats 452 | desired present value of annuity 453 | fv : float or sequence of floats 454 | desired future value of annuity 455 | If pv and fv are given, discounted value of fv is added to pv 456 | terminal_payment : float or sequence of floats 457 | baloon payment at the end of the annuity 458 | immediate_start : bool or sequence of bool 459 | If True, cash flows start immediately 460 | Else, the first cash flow is at the end of the first period. 461 | cf_freq : float or sequence of floats 462 | cash flow frequency (for example, 2 for semi-annual) 463 | comp_freq : float or sequence of floats 464 | compounding frequency (for example, 2 for semi-annual) 465 | round2int_digits: float or sequence of floats 466 | answer is rounded to integer if round2int_digits after the 467 | decimal point are zero 468 | 469 | Returns 470 | ------- 471 | float or array of floats 472 | The number of periods 473 | 474 | Examples 475 | -------- 476 | >>> annuity_periods(rate=10e-2, instalment=500, pv=3803.04).item() 477 | 15.000002163748604 478 | 479 | >>> annuity_periods(rate=10e-2, instalment=500, pv=3803.04, 480 | ... round2int_digits=4).item() 481 | 15.0 482 | 483 | >>> annuity_periods(rate=[0, 10e-2], instalment=500, pv=3803.04) 484 | array([ 7.60608 , 15.00000216]) 485 | 486 | """ 487 | if fv is None: 488 | pv = pv or 1 489 | fv = 0 490 | else: 491 | pv = pv or 0 492 | fv, pv, instalment, terminal_payment = ( 493 | array(fv), array(pv), array(instalment), array(terminal_payment)) 494 | # if immediate_start 495 | # makes it a deferred annuity (with one less period) 496 | pv -= where(immediate_start, instalment, 0) 497 | # pv + fv * df 498 | # = terminal_payment * df + instalment * (1 - df) / r 499 | # pv + fv * df 500 | # = terminal_payment * df + instalment / r - instalment * df / r 501 | # fv * df - terminal_payment * df + instalment * df / r 502 | # = instalment / r - pv 503 | # df * (fv - terminal_payment + instalment / r) 504 | # = instalment / r - pv 505 | r = equiv_rate(rate, comp_freq, cf_freq) / cf_freq 506 | # We use numpy.where to handle r == 0 or df == 0 507 | # but numpy.where evaluates both expressions and so 508 | # we must suppress the error. 509 | old_settings = np.seterr(divide='ignore', invalid='ignore') 510 | perpetuity = instalment / r 511 | df = np.divide(perpetuity - pv, fv - terminal_payment + perpetuity) 512 | n = where(r == 0, 513 | (pv + fv) / instalment, 514 | where((df < 0) | (df > 1), 515 | np.nan, 516 | where(df == 0, 517 | np.inf, 518 | -log(df) / log(1 + r)))) 519 | np.seterr(**old_settings) 520 | # if immediate_start 521 | # add back the one period that we removed 522 | n += where(immediate_start, 1, 0) 523 | # if the result is close to an integer, then round to the integer 524 | # the tolerance for this is given by round2int_digits 525 | return where(np.abs(n - n.round(0)) < 10**-round2int_digits, 526 | n.round(0).astype(int), n)[()] 527 | 528 | 529 | def annuity_rate(n_periods=np.inf, instalment=1, pv=None, fv=None, 530 | terminal_payment=0, immediate_start=False, 531 | cf_freq=1, comp_freq=1, r_guess=0): 532 | r"""Discount rate to get desired PV or FV of annuity 533 | 534 | Parameters 535 | ---------- 536 | n_periods : float or sequence of floats 537 | number of periods of annuity 538 | instalment : float or sequence of floats 539 | instalment per period 540 | pv : float or sequence of floats 541 | desired present value of annuity 542 | fv : float or sequence of floats 543 | desired future value of annuity 544 | If pv and fv are given, discounted value of fv is added to pv 545 | terminal_payment : float or sequence of floats 546 | baloon payment at the end of the annuity 547 | immediate_start : bool or sequence of bool 548 | If True, cash flows start immediately 549 | Else, the first cash flow is at the end of the first period. 550 | cf_freq : float or sequence of floats 551 | cash flow frequency (for example, 2 for semi-annual) 552 | comp_freq : float or sequence of floats 553 | compounding frequency (for example, 2 for semi-annual) 554 | r_guess : float, optional 555 | Starting value (guess) for root finder 556 | 557 | Returns 558 | ------- 559 | float or array of floats 560 | The discount rate 561 | 562 | Examples 563 | -------- 564 | >>> annuity_rate(n_periods=15, instalment=500, pv=3803.04).item() 565 | 0.09999998862890495 566 | 567 | >>> annuity_rate(n_periods=[9, 10, 15], instalment=100, pv=1000) 568 | array([-0.0205697 , 0. , 0.05556497]) 569 | 570 | """ 571 | if fv is None: 572 | pv = pv or 1 573 | fv = 0 574 | else: 575 | pv = pv or 0 576 | 577 | def one_rate(n_periods, instalment, pv, terminal_payment, 578 | immediate_start, cf_freq, comp_freq): 579 | if (n_periods == np.inf): 580 | return (pv/instalment) 581 | 582 | def f(r): 583 | return annuity_pv( 584 | r, n_periods=n_periods, instalment=instalment, 585 | terminal_payment=terminal_payment, 586 | immediate_start=immediate_start, cf_freq=cf_freq, 587 | comp_freq=comp_freq) - pv 588 | 589 | return newton_wrapper(f, r_guess) 590 | 591 | return vectorize(one_rate)( 592 | n_periods=n_periods, instalment=instalment, pv=pv, 593 | terminal_payment=terminal_payment, 594 | immediate_start=immediate_start, cf_freq=cf_freq, 595 | comp_freq=comp_freq)[()] 596 | 597 | 598 | def annuity_instalment_breakup( 599 | rate, n_periods=np.inf, pv=None, fv=None, 600 | terminal_payment=0, immediate_start=False, 601 | cf_freq=1, comp_freq=1, period_no=1, 602 | return_dataframe=False): 603 | r"""Break up instalment into principal and interest parts 604 | 605 | Parameters 606 | ---------- 607 | rate : float or sequence of floats 608 | per period discount rate in decimal 609 | n_periods : float or sequence of floats 610 | number of periods of annuity 611 | pv : float or sequence of floats 612 | desired present value of annuity 613 | fv : float or sequence of floats 614 | desired future value of annuity 615 | If pv and fv are given, discounted value of fv is added to pv 616 | terminal_payment : float or sequence of floats 617 | baloon payment at the end of the annuity 618 | immediate_start : bool or sequence of bool 619 | If True, cash flows start immediately 620 | Else, the first cash flow is at the end of the first period. 621 | cf_freq : float or sequence of floats 622 | cash flow frequency (for example, 2 for semi-annual) 623 | comp_freq : float or sequence of floats 624 | compounding frequency (for example, 2 for semi-annual) 625 | return_dataframe : bool 626 | whether to return pandas DataFrame instead of dict 627 | 628 | Returns 629 | ------- 630 | dict 631 | Opening Principal 632 | 633 | Instalment 634 | 635 | Interest Part 636 | 637 | Principal Part 638 | 639 | Closing Principal 640 | 641 | Examples 642 | -------- 643 | >>> {k: v.item() for k,v in 644 | ... annuity_instalment_breakup(rate=10e-2, n_periods=15, pv=3803.04, 645 | ... period_no=6).items()} # doctest: +NORMALIZE_WHITESPACE 646 | {'Period No': 6, 647 | 'Opening Principal': 3072.283752266599, 648 | 'Instalment': 500.0000324537518, 649 | 'Interest Part': 307.2283752266599, 650 | 'Principal Part': 192.7716572270919, 651 | 'Closing Principal': 2879.512095039507} 652 | 653 | >>> d = annuity_instalment_breakup(rate=10e-2, n_periods=15, pv=3803.04, 654 | ... period_no=range(1, 4), return_dataframe=True 655 | ... ); print(d.iloc[:, :4]); print(d.iloc[:, 4:]) 656 | Period No Opening Principal Instalment Interest Part 657 | 0 1 3803.040000 500.000032 380.304000 658 | 1 2 3683.343968 500.000032 368.334397 659 | 2 3 3551.678332 500.000032 355.167833 660 | Principal Part Closing Principal 661 | 0 119.696032 3683.343968 662 | 1 131.665636 3551.678332 663 | 2 144.832199 3406.846133 664 | 665 | """ 666 | fv, pv, n_periods = array(fv), array(pv), array(n_periods) 667 | cf_freq, comp_freq = array(cf_freq), array(comp_freq) 668 | period_no = array(period_no) 669 | assert (np.all(period_no > 0) and 670 | np.all(period_no > 0) and 671 | np.all(period_no <= n_periods) and 672 | np.all(period_no.astype(int) == period_no) 673 | ), "Invalid period_no" 674 | instalment = annuity_instalment( 675 | rate=rate, n_periods=n_periods, pv=pv, 676 | immediate_start=immediate_start, cf_freq=cf_freq, 677 | comp_freq=comp_freq) 678 | r = equiv_rate(rate, comp_freq, cf_freq)/cf_freq 679 | df = (1 + r)**(period_no-1) 680 | opening_principal = pv * df - annuity_fv( 681 | rate=rate, n_periods=period_no-1, instalment=instalment, 682 | immediate_start=immediate_start, 683 | cf_freq=cf_freq, comp_freq=comp_freq) 684 | result = {"Period No": period_no[()], 685 | "Opening Principal": opening_principal, 686 | "Instalment": instalment, 687 | "Interest Part": opening_principal * r, 688 | "Principal Part": instalment - opening_principal * r, 689 | "Closing Principal": 690 | opening_principal + opening_principal * r - instalment} 691 | if return_dataframe: 692 | return dict_to_dataframe(result) 693 | else: 694 | return result 695 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------