Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: drop pysen #627

Merged
merged 6 commits into from
Aug 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions .flexci/config.pbtxt
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ configs {
requirement {
cpu: 2
gpu: 1
memory: 20
memory: 30
disk: 10
}
time_limit: {
Expand All @@ -20,7 +20,7 @@ configs {
requirement {
cpu: 2
gpu: 1
memory: 20
memory: 30
disk: 10
}
time_limit: {
Expand All @@ -36,7 +36,7 @@ configs {
requirement {
cpu: 2
gpu: 1
memory: 20
memory: 30
disk: 10
}
time_limit: {
Expand Down
16 changes: 4 additions & 12 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ test-cov:
$(RUN) pytest --cov=$(PROJECT_NAME) --cov-report=xml -m "not gpu"

.PHONY: lint
lint: lint-pysen
lint: lint-black lint-isort flake8 mypy

.PHONY: lint-black
lint-black:
Expand All @@ -40,27 +40,19 @@ mypy:

.PHONY: flake8
flake8:
$(RUN) flake8 $(PROJECT_NAME)
$(RUN) pflake8 $(PROJECT_NAME)

.PHONY: format
format: format-pysen
format: format-black format-isort

.PHONY: format-black
format-black:
$(RUN) black --quiet --skip-magic-trailing-comma .
$(RUN) black --quiet .

.PHONY: format-isort
format-isort:
$(RUN) isort --force-single-line-imports --quiet .

.PHONY: format-pysen
format-pysen:
$(RUN) pysen run format

.PHONY: lint-pysen
lint-pysen:
$(RUN) pysen run lint

.PHONY: doc
doc:
@cd docs && make html
Expand Down
2 changes: 1 addition & 1 deletion examples/example_hedging_variance_swap.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
total_vega = torch.zeros_like(spot)
for option, strike in zip(options_list, strikes_list):
lm = (spot / strike).log()
vega = BlackScholes(option).vega(lm, t, v) / (strike**2)
vega = BlackScholes(option).vega(lm, t, v) / (strike ** 2)
total_vega += vega
if option.call:
# 2 is for call and put
Expand Down
25 changes: 0 additions & 25 deletions lint.py

This file was deleted.

2 changes: 1 addition & 1 deletion pfhedge/features/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def is_state_dependent(self) -> bool:
# If a feature uses the state of a hedger, it is state dependent.
return getattr(self, "hedger") is not None

def __str__(self):
def __str__(self) -> str:
return self.name

# TODO(simaki) Remove later
Expand Down
2 changes: 1 addition & 1 deletion pfhedge/features/_getter.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ class FeatureFactory:
_features: Dict[str, Type[Feature]]

# singleton
def __new__(cls, *args, **kwargs):
def __new__(cls, *args: Any, **kwargs: Any) -> "FeatureFactory":
if not hasattr(cls, "_instance"):
cls._instance = super().__new__(cls)
cls._instance._features = OrderedDict()
Expand Down
16 changes: 8 additions & 8 deletions pfhedge/features/features.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ def __str__(self) -> str:

def get(self, time_step: Optional[int] = None) -> Tensor:
index = [time_step] if isinstance(time_step, int) else ...
output = self.derivative.ul().spot[:, index].unsqueeze(-1)
output = self.derivative.ul().spot[:, index].unsqueeze(-1) # type: ignore
if self.log:
output.log_()
return output
Expand All @@ -147,7 +147,7 @@ class UnderlierLogSpot(UnderlierSpot):
``'underlier_log_spot'``
"""

def __init__(self):
def __init__(self) -> None:
super().__init__(log=True)


Expand All @@ -167,7 +167,7 @@ def __str__(self) -> str:

def get(self, time_step: Optional[int] = None) -> Tensor:
index = [time_step] if isinstance(time_step, int) else ...
output = self.derivative.spot[:, index].unsqueeze(-1)
output = self.derivative.spot[:, index].unsqueeze(-1) # type: ignore
if self.log:
output.log_()
return output
Expand All @@ -186,7 +186,7 @@ class Volatility(StateIndependentFeature):

def get(self, time_step: Optional[int] = None) -> Tensor:
index = [time_step] if isinstance(time_step, int) else ...
return self.derivative.ul().volatility[:, index].unsqueeze(-1)
return self.derivative.ul().volatility[:, index].unsqueeze(-1) # type: ignore


class Variance(StateIndependentFeature):
Expand All @@ -200,7 +200,7 @@ class Variance(StateIndependentFeature):

def get(self, time_step: Optional[int]) -> Tensor:
index = [time_step] if isinstance(time_step, int) else ...
return self.derivative.ul().variance[:, index].unsqueeze(-1)
return self.derivative.ul().variance[:, index].unsqueeze(-1) # type: ignore


class PrevHedge(Feature):
Expand Down Expand Up @@ -305,7 +305,7 @@ class Zeros(StateIndependentFeature):

def get(self, time_step: Optional[int] = None) -> Tensor:
index = [time_step] if time_step is not None else ...
return torch.zeros_like(self.derivative.ul().spot[..., index]).unsqueeze(-1)
return torch.zeros_like(self.derivative.ul().spot[..., index]).unsqueeze(-1) # type: ignore


class Ones(StateIndependentFeature):
Expand Down Expand Up @@ -335,7 +335,7 @@ class Ones(StateIndependentFeature):

def get(self, time_step: Optional[int] = None) -> Tensor:
index = [time_step] if time_step is not None else ...
return torch.ones_like(self.derivative.ul().spot[..., index]).unsqueeze(-1)
return torch.ones_like(self.derivative.ul().spot[..., index]).unsqueeze(-1) # type: ignore


class Empty(StateIndependentFeature):
Expand Down Expand Up @@ -365,7 +365,7 @@ class Empty(StateIndependentFeature):

def get(self, time_step: Optional[int] = None) -> Tensor:
index = [time_step] if time_step is not None else ...
return torch.empty_like(self.derivative.ul().spot[..., index]).unsqueeze(-1)
return torch.empty_like(self.derivative.ul().spot[..., index]).unsqueeze(-1) # type: ignore


class MaxMoneyness(StateIndependentFeature):
Expand Down
4 changes: 2 additions & 2 deletions pfhedge/instruments/derivative/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -305,7 +305,7 @@ def moneyness(self, time_step: Optional[int] = None, log: bool = False) -> Tenso
torch.Tensor
"""
index = ... if time_step is None else [time_step]
output = self.underlier.spot[..., index] / self.strike
output = self.underlier.spot[..., index] / self.strike # type: ignore
if log:
output = output.log()
return output
Expand Down Expand Up @@ -389,7 +389,7 @@ def max_log_moneyness(self, time_step: Optional[int] = None) -> Tensor:
class BaseOption(BaseDerivative, OptionMixin):
"""(deprecated) Base class for options."""

def __init__(self):
def __init__(self) -> None:
super().__init__()
raise DeprecationWarning(
"BaseOption is deprecated. Inherit `BaseDerivative` and `OptionMixin` instead."
Expand Down
4 changes: 3 additions & 1 deletion pfhedge/nn/modules/bs/american_binary.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,9 @@ def __init__(
self.derivative = derivative

@classmethod
def from_derivative(cls, derivative):
def from_derivative(
cls, derivative: AmericanBinaryOption
) -> "BSAmericanBinaryOption":
"""Initialize a module from a derivative.

Args:
Expand Down
7 changes: 4 additions & 3 deletions pfhedge/nn/modules/bs/black_scholes.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from collections import OrderedDict
from typing import Any
from typing import Callable
from typing import Dict
from typing import Iterator
Expand All @@ -17,7 +18,7 @@ class BlackScholesModuleFactory:
_modules: Dict[str, Type[Module]]

# singleton
def __new__(cls, *args, **kwargs):
def __new__(cls, *args: Any, **kwargs: Any) -> "BlackScholesModuleFactory":
if not hasattr(cls, "_instance"):
cls._instance = super().__new__(cls)
cls._instance._modules = OrderedDict()
Expand Down Expand Up @@ -97,5 +98,5 @@ class BlackScholes(Module):
vega: Callable[..., Tensor] # vega(self, ...) -> Tensor
theta: Callable[..., Tensor] # theta(self, ...) -> Tensor

def __new__(cls, derivative):
return BlackScholesModuleFactory().get_class_from_derivative(derivative)
def __new__(cls, derivative: "Derivative") -> "BlackScholes":
return BlackScholesModuleFactory().get_class_from_derivative(derivative) # type: ignore
2 changes: 1 addition & 1 deletion pfhedge/nn/modules/bs/european.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ def __init__(
self.derivative = derivative

@classmethod
def from_derivative(cls, derivative):
def from_derivative(cls, derivative: EuropeanOption) -> "BSEuropeanOption":
"""Initialize a module from a derivative.

Args:
Expand Down
4 changes: 3 additions & 1 deletion pfhedge/nn/modules/bs/european_binary.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,9 @@ def __init__(
self.derivative = derivative

@classmethod
def from_derivative(cls, derivative):
def from_derivative(
cls, derivative: EuropeanBinaryOption
) -> "BSEuropeanBinaryOption":
"""Initialize a module from a derivative.

Args:
Expand Down
2 changes: 1 addition & 1 deletion pfhedge/nn/modules/bs/lookback.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ def __init__(
self.derivative = derivative

@classmethod
def from_derivative(cls, derivative):
def from_derivative(cls, derivative: LookbackOption) -> "BSLookbackOption":
"""Initialize a module from a derivative.

Args:
Expand Down
4 changes: 2 additions & 2 deletions pfhedge/nn/modules/hedger.py
Original file line number Diff line number Diff line change
Expand Up @@ -475,7 +475,7 @@ def compute_loss(
"""
with torch.set_grad_enabled(enable_grad):

def _get_loss():
def _get_loss() -> Tensor:
derivative.simulate(n_paths=n_paths, init_state=init_state)
portfolio = self.compute_portfolio(derivative, hedge=hedge)
return self.criterion(portfolio, derivative.payoff())
Expand Down Expand Up @@ -666,7 +666,7 @@ def price(
"""
with torch.set_grad_enabled(enable_grad):

def _get_price():
def _get_price() -> Tensor:
derivative.simulate(n_paths=n_paths, init_state=init_state)
portfolio = self.compute_portfolio(derivative, hedge)
# Negative because selling
Expand Down
3 changes: 3 additions & 0 deletions pfhedge/nn/modules/loss.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from abc import ABC
from abc import abstractmethod
from typing import Callable

import torch
Expand All @@ -20,6 +21,7 @@
class HedgeLoss(Module, ABC):
"""Base class for hedging criteria."""

@abstractmethod
def forward(self, input: Tensor, target: TensorOrScalar = 0.0) -> Tensor:
"""Returns the loss of the profit-loss distribution.

Expand All @@ -39,6 +41,7 @@ def forward(self, input: Tensor, target: TensorOrScalar = 0.0) -> Tensor:
Returns:
torch.Tensor
"""
pass

def cash(self, input: Tensor, target: TensorOrScalar = 0.0) -> Tensor:
"""Returns the cash amount which is as preferable as
Expand Down
4 changes: 1 addition & 3 deletions pfhedge/stochastic/rough_bergomi.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,9 +122,7 @@ def discrete_TBSS_fn(k: torch.Tensor, a: TensorOrScalar) -> torch.Tensor:
_gamma = torch.cat([torch.zeros(2, dtype=dtype, device=device), _gamma], dim=0)
_Xi = dW1[:, :, 0]
_GXi_convolve = torch.nn.functional.conv1d(
_gamma.flip(0)[None, None, :],
_Xi[:, None, :],
padding=_Xi.size(1) - 1,
_gamma.flip(0)[None, None, :], _Xi[:, None, :], padding=_Xi.size(1) - 1
)[0, :, :]
_Y2 = _GXi_convolve[:, -n_steps:].flip(1)
Y = torch.sqrt(2 * alpha_tensor + 1) * (_Y1 + _Y2)
Expand Down
4 changes: 0 additions & 4 deletions poetry.toml

This file was deleted.

Loading
Loading