|
| 1 | +from crank_nicholson import crank_nicholson |
| 2 | +import numpy as np |
| 3 | +from math import log, exp, sqrt |
| 4 | +from scipy.stats import norm |
| 5 | +import scipy |
| 6 | + |
| 7 | +from distutils.version import LooseVersion |
| 8 | + |
| 9 | +if LooseVersion(scipy.__version__)>=LooseVersion("0.18.0"): |
| 10 | + have_CubicSpline = True |
| 11 | + from scipy.interpolate import CubicSpline |
| 12 | +else: |
| 13 | + have_CubicSpline = False |
| 14 | + from scipy.interpolate import spline |
| 15 | + |
| 16 | + |
| 17 | +def priceOptionBS(term, vol, rate, spot, strike, put=False): |
| 18 | + fwd = spot * exp(rate*term) |
| 19 | + d1 = (log(fwd/strike)+0.5*vol*vol*term)/(vol*sqrt(term)) |
| 20 | + d2 = d1-vol*sqrt(term) |
| 21 | + if put: |
| 22 | + price = norm.cdf(-d2)*strike*exp(-rate*term) - norm.cdf(-d1)*spot |
| 23 | + itm_prob = norm.cdf(-d2) |
| 24 | + else: |
| 25 | + price = norm.cdf(d1)*spot - norm.cdf(d2)*strike*exp(-rate*term) |
| 26 | + itm_prob = norm.cdf(d2) |
| 27 | + return price, itm_prob |
| 28 | + |
| 29 | +def priceEuropeanWithPDE(spot,payoff,gridCentre,stdDevs,term,vol,rate, |
| 30 | + do_discounting=True): |
| 31 | + nx=100 |
| 32 | + nt=100 |
| 33 | + centralLogSpot=log(gridCentre) |
| 34 | + sd=vol*sqrt(term) |
| 35 | + minGridLogSpot=centralLogSpot-sd*stdDevs |
| 36 | + maxGridLogSpot=centralLogSpot+sd*stdDevs |
| 37 | + logGrid = np.linspace(minGridLogSpot,maxGridLogSpot,nx) |
| 38 | + payoff_values=payoff(np.exp(logGrid)) |
| 39 | + growth = lambda v: (-rate if do_discounting else 0)*v |
| 40 | + |
| 41 | + time_0_vals = crank_nicholson(payoff_values, |
| 42 | + maxGridLogSpot-minGridLogSpot, |
| 43 | + term, |
| 44 | + nt, |
| 45 | + 0.5*vol*vol, |
| 46 | + rate-0.5*vol*vol, |
| 47 | + growth |
| 48 | + ) |
| 49 | + if have_CubicSpline: |
| 50 | + val = CubicSpline(logGrid,time_0_vals)(log(spot)).item() |
| 51 | + else: |
| 52 | + val = spline(xk=logGrid,yk=time_0_vals,xnew=log(spot)).item() |
| 53 | + return val |
| 54 | + |
| 55 | +if __name__=="__main__": |
| 56 | + vol=0.12 |
| 57 | + term = 4 |
| 58 | + rate=0.01 |
| 59 | + spot=100 |
| 60 | + strike=99 |
| 61 | + put=True |
| 62 | + |
| 63 | + print(priceOptionBS(term,vol,rate,spot,strike,put)) |
| 64 | + |
| 65 | + payoff = lambda x: np.maximum(0,strike-x if put else x-strike) |
| 66 | + #payoff = lambda x : np.ones_like(x) |
| 67 | + pde_val = priceEuropeanWithPDE(spot, payoff, |
| 68 | + strike,4,term,vol, rate) |
| 69 | + itm_payoff = lambda x:(strike>x if put else x>strike) |
| 70 | + itm_prob = priceEuropeanWithPDE(spot, itm_payoff, |
| 71 | + strike,4,term,vol, rate, False) |
| 72 | + |
| 73 | + print((pde_val, itm_prob)) |
| 74 | + |
| 75 | + |
0 commit comments