Skip to content

Commit

Permalink
Release/0.13.2 (#365)
Browse files Browse the repository at this point in the history
* MAINT: Fix buffer key (#353)

* MAINT: Fix prevention of zero division (#359)

* DOC: Miscellaneous updates (#358) (#360) (#361) (#362)

* CHORE: Run CI and building documentation in Poetry environment (#363)

* TEST: Fix typo in test of spot (#354)

Co-authored-by: GitHub Actions <[email protected]>
Co-authored-by: Masanori HIRANO <[email protected]>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: GitHub Actions <[email protected]>
  • Loading branch information
4 people authored Oct 1, 2021
1 parent 7f2d979 commit c5fd733
Show file tree
Hide file tree
Showing 20 changed files with 116 additions and 84 deletions.
11 changes: 4 additions & 7 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -39,17 +39,14 @@ jobs:
python-version: ${{ matrix.python-version }}

- name: Install
run: |
python3 -m pip install --upgrade pip
python3 -m pip install .
python3 -m pip install pytest pytest-cov codecov
run: pip install poetry && poetry install

- name: Run doctest
run: python3 -m pytest --doctest-modules ${PROJECT_NAME}
run: make doctest
if: always()

- name: Run pytest
run: python3 -m pytest --cov=${PROJECT_NAME} tests
run: make test-cov
if: always()

- name: Upload codecov report
Expand All @@ -70,7 +67,7 @@ jobs:

- run: pip install poetry && poetry install

- run: poetry run python -m mypy ${PROJECT_NAME}
- run: make mypy

lint:

Expand Down
4 changes: 1 addition & 3 deletions .github/workflows/doc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,7 @@ jobs:

- uses: actions/setup-python@v2

- run: pip install .

- run: pip install -r docs/requirements.txt
- run: pip install poetry && poetry install

- run: cd docs && make html

Expand Down
13 changes: 7 additions & 6 deletions docs/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,25 @@
# You can set these variables from the command line, and also
# from the environment for the first two.
SPHINXOPTS ?=
SPHINXBUILD ?= sphinx-build
SPHINXBUILD ?= poetry run sphinx-build
SPHINXAUTOBUILD ?= poetry run sphinx-autobuild
SOURCEDIR = source
BUILDDIR = build

# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)

.PHONY: help Makefile

# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)

clean:
@echo "Removing everything under 'build' and 'source/generated'.."
@rm -rf $(BUILDDIR)/html/ $(BUILDDIR)/doctrees $(SOURCEDIR)/generated
echo "Removing everything under 'build' and 'source/generated'.."
rm -rf $(BUILDDIR)/html/ $(BUILDDIR)/doctrees $(SOURCEDIR)/generated

livehtml:
sphinx-autobuild "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) --open-browser $(O)
$(SPHINXAUTOBUILD) "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) --open-browser $(O)
4 changes: 0 additions & 4 deletions docs/requirements.txt

This file was deleted.

1 change: 0 additions & 1 deletion pfhedge/features/_base.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import copy
import warnings
from abc import ABC
from abc import abstractmethod
from typing import Optional
Expand Down
1 change: 0 additions & 1 deletion pfhedge/features/container.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import copy
from typing import List
from typing import Optional
from typing import Type
from typing import TypeVar
from typing import Union

Expand Down
3 changes: 1 addition & 2 deletions pfhedge/instruments/primary/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@

import torch
from torch import Tensor
from torch.nn import Module

from pfhedge._utils.doc import _set_attr_and_docstring
from pfhedge._utils.doc import _set_docstring
Expand Down Expand Up @@ -150,7 +149,7 @@ def spot(self) -> Tensor:
if "_buffers" in self.__dict__:
_buffers = self.__dict__["_buffers"]
if name in _buffers:
return _buffers["spot"]
return _buffers[name]
raise AttributeError(
f"'{self._get_name()}' object has no attribute '{name}'. "
"Asset may not be simulated."
Expand Down
1 change: 0 additions & 1 deletion pfhedge/instruments/primary/brownian.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from math import ceil
from typing import Optional
from typing import Tuple
from typing import Union
from typing import cast

import torch
Expand Down
2 changes: 0 additions & 2 deletions pfhedge/instruments/primary/cir.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
from math import ceil
from typing import Optional
from typing import Tuple
from typing import Union

import torch
from torch import Tensor

from pfhedge._utils.doc import _set_attr_and_docstring
from pfhedge._utils.doc import _set_docstring
Expand Down
75 changes: 50 additions & 25 deletions pfhedge/nn/functional.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,13 +108,13 @@ def european_binary_payoff(


def exp_utility(input: Tensor, a: float = 1.0) -> Tensor:
"""Applies an exponential utility function.
r"""Applies an exponential utility function.
An exponential utility function is defined as:
.. math::
u(x) = -\\exp(-a x) \\,.
u(x) = -\exp(-a x) \,.
Args:
input (torch.Tensor): The input tensor.
Expand All @@ -128,16 +128,16 @@ def exp_utility(input: Tensor, a: float = 1.0) -> Tensor:


def isoelastic_utility(input: Tensor, a: float) -> Tensor:
"""Applies an isoelastic utility function.
r"""Applies an isoelastic utility function.
An isoelastic utility function is defined as:
.. math::
u(x) = \\begin{cases}
x^{1 - a} & a \\neq 1 \\\\
\\log{x} & a = 1
\\end{cases} \\,.
u(x) = \begin{cases}
x^{1 - a} & a \neq 1 \\
\log{x} & a = 1
\end{cases} \,.
Args:
input (torch.Tensor): The input tensor.
Expand Down Expand Up @@ -201,12 +201,13 @@ def expected_shortfall(input: Tensor, p: float, dim: Optional[int] = None) -> Te
dim (int, optional): The dimension to sort along.
Examples:
>>> from pfhedge.nn.functional import expected_shortfall
>>>
>>> input = -torch.arange(1., 6.)
>>> expected_shortfall(input, 3 / 5)
tensor(4.)
>>> input = -torch.arange(1.0, 10.0)
>>> input
tensor([-1., -2., -3., -4., -5., -6., -7., -8., -9.])
>>> expected_shortfall(input, 0.3)
tensor(8.)
Returns:
torch.Tensor
Expand All @@ -224,7 +225,7 @@ def leaky_clamp(
clamped_slope: float = 0.01,
inverted_output: str = "mean",
) -> Tensor:
"""Leakily clamp all elements in ``input`` into the range :math:`[\\min, \\max]`.
r"""Leakily clamp all elements in ``input`` into the range :math:`[\min, \max]`.
See :class:`pfhedge.nn.LeakyClamp` for details.
"""
Expand Down Expand Up @@ -256,7 +257,7 @@ def clamp(
max: Optional[Tensor] = None,
inverted_output: str = "mean",
) -> Tensor:
"""Clamp all elements in ``input`` into the range :math:`[\\min, \\max]`.
r"""Clamp all elements in ``input`` into the range :math:`[\min, \max]`.
See :class:`pfhedge.nn.Clamp` for details.
"""
Expand All @@ -270,14 +271,14 @@ def clamp(


def realized_variance(input: Tensor, dt: TensorOrScalar) -> Tensor:
"""Returns the realized variance of the price.
r"""Returns the realized variance of the price.
Realized variance :math:`\\sigma^2` of the stock price :math:`S` is defined as:
Realized variance :math:`\sigma^2` of the stock price :math:`S` is defined as:
.. math::
\\sigma^2 = \\frac{1}{T - 1} \\sum_{i = 1}^{T - 1}
\\frac{1}{dt} \\log(S_{i + 1} / S_i)^2
\sigma^2 = \frac{1}{T - 1} \sum_{i = 1}^{T - 1}
\frac{1}{dt} \log(S_{i + 1} / S_i)^2
where :math:`T` is the number of time steps.
Expand Down Expand Up @@ -327,19 +328,19 @@ def terminal_value(
payoff: Optional[Tensor] = None,
deduct_first_cost: bool = True,
):
"""Returns the terminal portfolio value.
r"""Returns the terminal portfolio value.
The terminal value of a hedger's portfolio is given by
.. math::
\\text{PL}(Z, \\delta, S) =
\text{PL}(Z, \delta, S) =
- Z
+ \\sum_{i = 0}^{T - 2} \\delta_{i - 1} (S_{i} - S_{i - 1})
- c \\sum_{i = 0}^{T - 1} |\\delta_{i} - \\delta_{i - 1}| S_{i}
+ \sum_{i = 0}^{T - 2} \delta_{i - 1} (S_{i} - S_{i - 1})
- c \sum_{i = 0}^{T - 1} |\delta_{i} - \delta_{i - 1}| S_{i}
where :math:`Z` is the payoff of the derivative, :math:`T` is the number of
time steps, :math:`S` is the spot price, :math:`\\delta` is the signed number
time steps, :math:`S` is the spot price, :math:`\delta` is the signed number
of shares held at each time step.
We define :math:`\delta_0 = 0` for notational convenience.
Expand All @@ -358,7 +359,7 @@ def terminal_value(
Args:
spot (torch.Tensor): The spot price of the underlying asset :math:`S`.
unit (torch.Tensor): The signed number of shares of the underlying asset
:math:`\\delta`.
:math:`\delta`.
cost (float, default=0.0): The proportional transaction cost rate of
the underlying asset :math:`c`.
payoff (torch.Tensor, optional): The payoff of the derivative :math:`Z`.
Expand Down Expand Up @@ -434,7 +435,19 @@ def npdf(input: Tensor) -> Tensor:


def d1(log_moneyness: Tensor, time_to_maturity: Tensor, volatility: Tensor) -> Tensor:
"""Returns :math:`d_1` in the Black-Scholes formula.
r"""Returns :math:`d_1` in the Black-Scholes formula.
.. math::
d_1 = \frac{s + \frac12 \sigma^2 t}{\sigma \sqrt{t}}
where
:math:`s` is the log moneyness,
:math:`t` is the time to maturity, and
:math:`\sigma` is the volatility.
Note:
Risk-free rate is set to zero.
Args:
log_moneyness (torch.Tensor or float): Log moneyness of the underlying asset.
Expand All @@ -449,7 +462,19 @@ def d1(log_moneyness: Tensor, time_to_maturity: Tensor, volatility: Tensor) -> T


def d2(log_moneyness: Tensor, time_to_maturity: Tensor, volatility: Tensor) -> Tensor:
"""Returns :math:`d_2` in the Black-Scholes formula.
r"""Returns :math:`d_2` in the Black-Scholes formula.
.. math::
d_2 = \frac{s - \frac12 \sigma^2 t}{\sigma \sqrt{t}}
where
:math:`s` is the log moneyness,
:math:`t` is the time to maturity, and
:math:`\sigma` is the volatility.
Note:
Risk-free rate is set to zero.
Args:
log_moneyness (torch.Tensor or float): Log moneyness of the underlying asset.
Expand Down
1 change: 0 additions & 1 deletion pfhedge/nn/modules/bs/_base.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import abc
from inspect import signature
from typing import List
from typing import no_type_check
Expand Down
6 changes: 5 additions & 1 deletion pfhedge/nn/modules/bs/american_binary.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
from torch import Tensor
from torch.distributions.utils import broadcast_all

import pfhedge.autogreek as autogreek
from pfhedge._utils.bisect import find_implied_volatility
from pfhedge._utils.doc import _set_attr_and_docstring
from pfhedge._utils.str import _format_float
Expand All @@ -19,6 +18,9 @@
class BSAmericanBinaryOption(BSModuleMixin):
"""Black-Scholes formula for an American Binary Option.
Note:
Risk-free rate is set to zero.
Args:
call (bool, default=True): Specifies whether the option is call or put.
strike (float, default=1.0): The strike price of the option.
Expand All @@ -33,6 +35,8 @@ class BSAmericanBinaryOption(BSModuleMixin):
.. seealso::
- :class:`pfhedge.nn.BlackScholes`:
Initialize Black-Scholes formula module from a derivative.
- :class:`pfhedge.instruments.AmericanBinaryOption`:
Corresponding derivative.
References:
- Dai, M., 2000. A closed-form solution for perpetual American floating strike
Expand Down
6 changes: 5 additions & 1 deletion pfhedge/nn/modules/bs/european.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@
class BSEuropeanOption(BSModuleMixin):
"""Black-Scholes formula for a European option.
Note:
Risk-free rate is set to zero.
Args:
call (bool, default=True): Specifies whether the option is call or put.
strike (float, default=1.0): The strike price of the option.
Expand All @@ -28,9 +31,10 @@ class BSEuropeanOption(BSModuleMixin):
All but the last dimension are the same shape as the input.
.. seealso::
- :class:`pfhedge.nn.BlackScholes`:
Initialize Black-Scholes formula module from a derivative.
- :class:`pfhedge.instruments.EuropeanOption`:
Corresponding derivative.
References:
- John C. Hull, 2003. Options futures and other derivatives. Pearson.
Expand Down
5 changes: 5 additions & 0 deletions pfhedge/nn/modules/bs/european_binary.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@
class BSEuropeanBinaryOption(BSModuleMixin):
"""Black-Scholes formula for a European binary option.
Note:
Risk-free rate is set to zero.
Args:
call (bool, default=True): Specifies whether the option is call or put.
strike (float, default=1.0): The strike price of the option.
Expand All @@ -33,6 +36,8 @@ class BSEuropeanBinaryOption(BSModuleMixin):
.. seealso::
- :class:`pfhedge.nn.BlackScholes`:
Initialize Black-Scholes formula module from a derivative.
- :class:`pfhedge.instruments.EuropeanBinaryOption`:
Corresponding derivative.
References:
- John C. Hull, 2003. Options futures and other derivatives. Pearson.
Expand Down
7 changes: 5 additions & 2 deletions pfhedge/nn/modules/bs/lookback.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import torch
from torch import Tensor
from torch.distributions.utils import broadcast_all

from pfhedge._utils.bisect import find_implied_volatility
from pfhedge._utils.doc import _set_attr_and_docstring
Expand All @@ -19,6 +18,9 @@
class BSLookbackOption(BSModuleMixin):
"""Black-Scholes formula for a lookback option with a fixed strike.
Note:
Risk-free rate is set to zero.
Args:
call (bool, default=True): Specifies whether the option is call or put.
strike (float, default=1.0): The strike price of the option.
Expand All @@ -31,9 +33,10 @@ class BSLookbackOption(BSModuleMixin):
All but the last dimension are the same shape as the input.
.. seealso::
- :class:`pfhedge.nn.BlackScholes`:
Initialize Black-Scholes formula module from a derivative.
- :class:`pfhedge.instruments.LookBackOption`:
Corresponding derivative.
References:
- Conze, A., 1991. Path dependent options: The case of lookback options.
Expand Down
Loading

0 comments on commit c5fd733

Please sign in to comment.