Skip to content

Commit

Permalink
DOC: Add example_heston_iv.py (#403)
Browse files Browse the repository at this point in the history
  • Loading branch information
simaki committed Nov 23, 2021
1 parent 30750dd commit 1b489f1
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 1 deletion.
43 changes: 43 additions & 0 deletions examples/example_heston_iv.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import sys
from math import exp

import matplotlib.pyplot as plt
import torch

sys.path.append("..")
from pfhedge.instruments import EuropeanOption
from pfhedge.instruments import HestonStock
from pfhedge.nn import BlackScholes

LOG_MONEYNESS_MIN = -0.1
LOG_MONEYNESS_MAX = 0.1
LOG_MONEYNESS_STEPS = 20
LOG_MONEYNESS_RANGE = torch.linspace(
LOG_MONEYNESS_MIN, LOG_MONEYNESS_MAX, LOG_MONEYNESS_STEPS
)


def compute_iv(log_moneyness: float, rho: float) -> float:
torch.manual_seed(42)

d = EuropeanOption(HestonStock(rho=rho))
spot = exp(log_moneyness) * d.strike
d.simulate(n_paths=int(1e5), init_state=(spot, d.ul().theta))
p = d.payoff().mean(0)

return BlackScholes(d).implied_volatility(log_moneyness, d.maturity, p).item()


def main():
plt.figure()
for rho in [-0.7, 0.0, 0.7]:
y = [compute_iv(s, rho) for s in LOG_MONEYNESS_RANGE]
plt.plot(LOG_MONEYNESS_RANGE, y, label=f"rho={rho}")
plt.xlabel("Log moneyness")
plt.ylabel("Implied volatility")
plt.legend()
plt.savefig("output/heston-iv.png")


if __name__ == "__main__":
main()
2 changes: 2 additions & 0 deletions examples/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
matplotlib
tqdm
1 change: 0 additions & 1 deletion tests/nn/bs/test_european_binary.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,6 @@ def test_check_price_monte_carlo(self):
input = torch.tensor([[0.0, d.maturity, d.ul().sigma]])
result = compute_price(m, input)
expect = d.payoff().mean(0, keepdim=True)
print(result, expect)
assert_close(result, expect, rtol=1e-2, atol=0.0)

def test_forward(self):
Expand Down

0 comments on commit 1b489f1

Please sign in to comment.