Ejemplo n.º 1
0
 def test_error_percentile(self):
     # 1 is allowed
     _ = ExpectedShortfall(1)
     with pytest.raises(ValueError):
         _ = ExpectedShortfall(0)
     with pytest.raises(ValueError):
         _ = ExpectedShortfall(-1)
     with pytest.raises(ValueError):
         _ = ExpectedShortfall(1.1)
Ejemplo n.º 2
0
    def test_value(self, percentile):
        n_paths = 100
        k = int(n_paths * percentile)
        loss = ExpectedShortfall(percentile)

        x = torch.randn(n_paths)

        result = loss(x)
        expect = -torch.mean(torch.tensor(sorted(x)[:k]))

        assert torch.isclose(result, expect)
Ejemplo n.º 3
0
 def test_shape(self):
     loss = ExpectedShortfall()
     self.assert_shape(loss)
Ejemplo n.º 4
0
 def test_repr(self):
     loss = ExpectedShortfall(0.1)
     assert repr(loss) == "ExpectedShortfall(0.1)"
     loss = ExpectedShortfall(0.5)
     assert repr(loss) == "ExpectedShortfall(0.5)"
Ejemplo n.º 5
0
 def test_cash_equivalent(self, n_paths, p, eta):
     loss = ExpectedShortfall(p)
     self.assert_cash_equivalent(loss, torch.randn(n_paths), eta)
Ejemplo n.º 6
0
 def test_cash(self, n_paths, p):
     loss = ExpectedShortfall(p)
     x = torch.randn(n_paths)
     self.assert_cash(loss, x)
Ejemplo n.º 7
0
 def test_convex(self, n_paths, p, a):
     loss = ExpectedShortfall(p)
     x1 = torch.randn(n_paths)
     x2 = torch.randn(n_paths)
     self.assert_convex(loss, x1, x2, a)
Ejemplo n.º 8
0
 def test_nonincreasing(self, n_paths, p, a):
     loss = ExpectedShortfall(p)
     x = torch.randn(n_paths)
     self.assert_nonincreasing(loss, x, a)
Ejemplo n.º 9
0
sys.path.append("..")

from pfhedge import Hedger  # noqa: E402
from pfhedge.instruments import BrownianStock  # noqa: E402
from pfhedge.instruments import EuropeanOption  # noqa: E402
from pfhedge.nn import ExpectedShortfall
from pfhedge.nn import MultiLayerPerceptron  # noqa: E402

if __name__ == "__main__":
    torch.manual_seed(42)

    # Prepare a derivative to hedge
    deriv = EuropeanOption(BrownianStock(cost=1e-4))

    # Expected shortfall with the quantile level of 10%
    expected_shortfall = ExpectedShortfall(0.1)

    # Create your hedger
    model = MultiLayerPerceptron()
    hedger = Hedger(
        model,
        ["log_moneyness", "expiry_time", "volatility", "prev_hedge"],
        criterion=expected_shortfall,
    )

    # Fit and price
    hedger.fit(deriv, n_paths=10000, n_epochs=200)
    price = hedger.price(deriv, n_paths=10000)
    print(f"Price={price:.5e}")