pyoptionpricing 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,23 @@
1
+ from .base import Option # abstract base: inputs, validation, price()/greeks()
2
+ from .european import EuropeanOption # exercise only at maturity
3
+ from .american import AmericanOption # exercise any time
4
+
5
+ from .path_dependent import PathDependentOption # payoff depends on price path
6
+ from .black_scholes import BlackScholesOption # closed form price and Greeks
7
+
8
+ from .binomial import BinomialEuropeanOption, BinomialAmericanOption # CRR tree
9
+ from .monte_carlo import MonteCarloEuropeanOption # simulation
10
+
11
+ from .asian import AsianOption # average price payoff
12
+ from .barrier import BarrierOption # barrier-based payoff
13
+ from .factory import OptionFactory # creates an option from model/style/type
14
+ from .engine import PricingEngine # prices any Option through one interface
15
+ from .implied_vol import implied_volatility, volatility_smile # vol from market price; smile
16
+
17
+ from .analysis import (
18
+ binomial_convergence, # tree price vs number of steps
19
+ monte_carlo_convergence, # mc price vs number of paths
20
+ payoff_curve, # payoff vs spot price at maturity
21
+ sample_paths, # sample paths
22
+ volatility_surface, # volatility surface
23
+ )
@@ -0,0 +1,4 @@
1
+ from .base import Option
2
+
3
+ class AmericanOption(Option):
4
+ """exercised at any time before maturity"""
@@ -0,0 +1,112 @@
1
+ import math
2
+
3
+ import numpy as np
4
+
5
+ from .black_scholes import BlackScholesOption
6
+ from .binomial import BinomialAmericanOption, BinomialEuropeanOption
7
+ from .implied_vol import volatility_smile
8
+ from .monte_carlo import MonteCarloEuropeanOption
9
+ from .paths import simulate_paths, standard_normals, vanilla_payoff
10
+
11
+ DEFAULT_STEPS = (5, 10, 20, 50, 100, 200, 500, 1000)
12
+ DEFAULT_PATH_COUNTS = (500, 1_000, 5_000, 10_000, 50_000, 100_000)
13
+
14
+
15
+ def binomial_convergence(spot, strike, maturity, rate, volatility, option_type,
16
+ steps_list=DEFAULT_STEPS, american=False):
17
+ """Binomial price for each tree depth, next to the Black-Scholes price.
18
+
19
+ For an American option the Black-Scholes value is the European reference,
20
+ so the gap that remains is the early-exercise premium.
21
+ """
22
+ tree_cls = BinomialAmericanOption if american else BinomialEuropeanOption
23
+ reference = BlackScholesOption(
24
+ spot, strike, maturity, rate, volatility, option_type
25
+ ).price()
26
+ points = []
27
+ for steps in steps_list:
28
+ price = tree_cls(
29
+ spot, strike, maturity, rate, volatility, option_type, steps=steps
30
+ ).price()
31
+ points.append({"steps": int(steps), "price": float(price)})
32
+ return {"black_scholes": float(reference), "points": points}
33
+
34
+
35
+ def monte_carlo_convergence(spot, strike, maturity, rate, volatility, option_type,
36
+ path_counts=DEFAULT_PATH_COUNTS, seed=42):
37
+ """Monte Carlo price and standard error for each path count."""
38
+ reference = BlackScholesOption(
39
+ spot, strike, maturity, rate, volatility, option_type
40
+ ).price()
41
+ points = []
42
+ for n_paths in path_counts:
43
+ option = MonteCarloEuropeanOption(
44
+ spot, strike, maturity, rate, volatility, option_type,
45
+ n_paths=n_paths, seed=seed,
46
+ )
47
+ points.append({
48
+ "n_paths": int(n_paths),
49
+ "price": option.price(),
50
+ "standard_error": option.standard_error(),
51
+ })
52
+ return {"black_scholes": float(reference), "points": points}
53
+
54
+
55
+ def payoff_curve(strike, option_type, premium=0.0, spot_min=None, spot_max=None,
56
+ n_points=101):
57
+ """Payoff and profit at maturity across a range of terminal spot prices."""
58
+ if strike <= 0:
59
+ raise ValueError("Strike price must be positive.")
60
+ if option_type not in ("call", "put"):
61
+ raise ValueError("option_type must be either 'call' or 'put'.")
62
+ if n_points < 2:
63
+ raise ValueError("n_points must be at least 2.")
64
+ spot_min = 0.5 * strike if spot_min is None else spot_min
65
+ spot_max = 1.5 * strike if spot_max is None else spot_max
66
+ if not 0 <= spot_min < spot_max:
67
+ raise ValueError("Need 0 <= spot_min < spot_max.")
68
+
69
+ spots = np.linspace(spot_min, spot_max, n_points)
70
+ payoffs = vanilla_payoff(spots, strike, option_type)
71
+ return [
72
+ {"spot": float(s), "payoff": float(p), "profit": float(p - premium)}
73
+ for s, p in zip(spots, payoffs)
74
+ ]
75
+
76
+
77
+ def sample_paths(spot, maturity, rate, volatility, n_paths=20, n_steps=100, seed=42):
78
+ """A few simulated GBM paths for plotting. Each path starts at the spot."""
79
+ if spot <= 0 or maturity <= 0 or volatility <= 0:
80
+ raise ValueError("spot, maturity and volatility must be positive.")
81
+ z = standard_normals(n_paths, n_steps, seed)
82
+ paths = simulate_paths(spot, rate, volatility, maturity, z)
83
+ paths = np.hstack([np.full((paths.shape[0], 1), float(spot)), paths])
84
+ times = np.linspace(0.0, maturity, n_steps + 1)
85
+ return {"times": times.tolist(), "paths": paths.tolist()}
86
+
87
+
88
+ def volatility_surface(spot, rate, strikes, maturities, option_type="call",
89
+ model="black_scholes", style="european",
90
+ atm_vol=0.20, skew=-0.15, **kwargs):
91
+ """Implied-volatility smiles for several maturities.
92
+
93
+ The synthetic skew at maturity T is skew / √T, so short-dated smiles are
94
+ steeper than long-dated ones, as in equity markets.
95
+ """
96
+ maturities = [float(t) for t in maturities]
97
+ if not maturities:
98
+ raise ValueError("maturities must not be empty.")
99
+ if any(t <= 0 for t in maturities):
100
+ raise ValueError("Every maturity must be positive.")
101
+
102
+ return [
103
+ {
104
+ "maturity": t,
105
+ "smile": volatility_smile(
106
+ strikes, spot, t, rate, option_type=option_type,
107
+ model=model, style=style, atm_vol=atm_vol,
108
+ skew=skew / math.sqrt(t), **kwargs,
109
+ ),
110
+ }
111
+ for t in maturities
112
+ ]
@@ -0,0 +1,20 @@
1
+ import math
2
+
3
+ from .path_dependent import _PathMonteCarlo
4
+ from .paths import vanilla_payoff
5
+
6
+
7
+ class AsianOption(_PathMonteCarlo):
8
+ """Arithmetic-average Asian option priced by Monte Carlo.
9
+
10
+ The average is the mean of the simulated spots. S0 is not included.
11
+ A call pays max(average − K, 0) and a put pays max(K − average, 0).
12
+ """
13
+
14
+ def _discounted_payoffs(self, spot=None, maturity=None, rate=None, volatility=None):
15
+ paths = self._paths(spot, maturity, rate, volatility)
16
+ maturity = self.maturity if maturity is None else maturity
17
+ rate = self.rate if rate is None else rate
18
+ average = paths.mean(axis=1)
19
+ payoff = vanilla_payoff(average, self.strike, self.option_type)
20
+ return math.exp(-rate * maturity) * payoff
@@ -0,0 +1,83 @@
1
+ import math
2
+
3
+ import numpy as np
4
+
5
+ from .path_dependent import _PathMonteCarlo
6
+ from .paths import vanilla_payoff
7
+
8
+
9
+ _BARRIER_TYPES = {
10
+ "up-and-out": "up-and-out",
11
+ "up-out": "up-and-out",
12
+ "uo": "up-and-out",
13
+ "up-and-in": "up-and-in",
14
+ "up-in": "up-and-in",
15
+ "ui": "up-and-in",
16
+ "down-and-out": "down-and-out",
17
+ "down-out": "down-and-out",
18
+ "do": "down-and-out",
19
+ "down-and-in": "down-and-in",
20
+ "down-in": "down-and-in",
21
+ "di": "down-and-in",
22
+ }
23
+
24
+
25
+ def normalize_barrier_type(barrier_type):
26
+ if not isinstance(barrier_type, str):
27
+ raise ValueError("barrier_type must be a string.")
28
+ key = barrier_type.strip().lower().replace("_", "-").replace(" ", "-")
29
+ while "--" in key:
30
+ key = key.replace("--", "-")
31
+ canonical = _BARRIER_TYPES.get(key)
32
+ if canonical is None:
33
+ raise ValueError(
34
+ f"Unknown barrier type '{barrier_type}'. "
35
+ "Expected up-and-out, up-and-in, down-and-out, or down-and-in."
36
+ )
37
+ return canonical
38
+
39
+
40
+ class BarrierOption(_PathMonteCarlo):
41
+ """Single-barrier option priced by Monte Carlo with discrete monitoring.
42
+
43
+ The barrier is checked at S0 and at every simulated spot. A knock-out pays
44
+ the vanilla terminal payoff only if the barrier was not touched. A knock-in
45
+ pays it only if the barrier was touched. On the same paths, knock-in plus
46
+ knock-out equals the vanilla European payoff.
47
+ """
48
+
49
+ def __init__(self, spot, strike, maturity, rate, volatility, option_type,
50
+ barrier, barrier_type, n_paths=20_000, n_steps=50, seed=42):
51
+ super().__init__(
52
+ spot, strike, maturity, rate, volatility, option_type,
53
+ n_paths=n_paths, n_steps=n_steps, seed=seed,
54
+ )
55
+ if barrier <= 0:
56
+ raise ValueError("Barrier must be positive.")
57
+ self._barrier = float(barrier)
58
+ self._barrier_type = normalize_barrier_type(barrier_type)
59
+
60
+ @property
61
+ def barrier(self):
62
+ return self._barrier
63
+
64
+ @property
65
+ def barrier_type(self):
66
+ return self._barrier_type
67
+
68
+ def _hit(self, paths, spot, barrier):
69
+ direction = self.barrier_type.split("-")[0]
70
+ if direction == "up":
71
+ return (spot >= barrier) | np.any(paths >= barrier, axis=1)
72
+ return (spot <= barrier) | np.any(paths <= barrier, axis=1)
73
+
74
+ def _discounted_payoffs(self, spot=None, maturity=None, rate=None, volatility=None):
75
+ paths = self._paths(spot, maturity, rate, volatility)
76
+ spot = self.spot if spot is None else spot
77
+ maturity = self.maturity if maturity is None else maturity
78
+ rate = self.rate if rate is None else rate
79
+ vanilla = vanilla_payoff(paths[:, -1], self.strike, self.option_type)
80
+ hit = self._hit(paths, spot, self.barrier)
81
+ knocked_out = self.barrier_type.endswith("out")
82
+ payoff = np.where(hit, 0.0, vanilla) if knocked_out else np.where(hit, vanilla, 0.0)
83
+ return math.exp(-rate * maturity) * payoff
@@ -0,0 +1,66 @@
1
+ from abc import ABC, abstractmethod
2
+
3
+ class Option(ABC):
4
+ """
5
+ Abstract base class for financial options.
6
+ """
7
+
8
+ def __init__(self, spot, strike, maturity, rate, volatility, option_type):
9
+
10
+ if spot <= 0:
11
+ raise ValueError("Spot price must be positive.")
12
+ if strike <= 0:
13
+ raise ValueError("Strike price must be positive.")
14
+ if maturity <= 0:
15
+ raise ValueError("Maturity must be positive.")
16
+ if volatility <= 0:
17
+ raise ValueError("Volatility must be positive.")
18
+ if option_type.lower() not in ['call', 'put']:
19
+ raise ValueError("option_type must be either 'call' or 'put'.")
20
+
21
+ self._spot = spot
22
+ self._strike = strike
23
+ self._maturity = maturity
24
+ self._rate = rate
25
+ self._volatility = volatility
26
+ self._option_type = option_type.lower()
27
+
28
+ @property
29
+ def spot(self):
30
+ return self._spot
31
+
32
+ @property
33
+ def strike(self):
34
+ return self._strike
35
+
36
+ @property
37
+ def maturity(self):
38
+ return self._maturity
39
+
40
+ @property
41
+ def rate(self):
42
+ return self._rate
43
+
44
+ @property
45
+ def volatility(self):
46
+ return self._volatility
47
+
48
+ @property
49
+ def option_type(self):
50
+ return self._option_type
51
+
52
+ @abstractmethod
53
+ def price(self):
54
+ """
55
+ Abstract method to calculate the price of the option.
56
+ Must be implemented by subclasses.
57
+ """
58
+ pass
59
+
60
+ @abstractmethod
61
+ def greeks(self):
62
+ """
63
+ Abstract method to calculate the Greeks of the option.
64
+ Must be implemented by subclasses.
65
+ """
66
+ pass
@@ -0,0 +1,115 @@
1
+ import math
2
+ import numpy as np
3
+ from .european import EuropeanOption
4
+ from .american import AmericanOption
5
+
6
+
7
+ def _crr_tree(spot, strike, maturity, rate, vol, option_type, steps, american):
8
+
9
+ dt = maturity/steps
10
+ u = math.exp(vol*math.sqrt(dt))
11
+ d = 1/u
12
+ p = (math.exp(rate * dt)- d) / (u -d)
13
+ disc = math.exp(-rate *dt)
14
+
15
+ j = np.arange(steps + 1)
16
+ terminal_spot = spot * u**j * d**(steps - j)
17
+ if option_type == "call":
18
+ values = np.maximum(terminal_spot - strike, 0)
19
+ else:
20
+ values = np.maximum(strike - terminal_spot, 0)
21
+
22
+ values_at_2 = values.copy() if steps == 2 else None
23
+ values_at_1 = None
24
+ value_at_0 = None
25
+ for i in range(steps - 1, -1, -1):
26
+ values = disc * (p * values[1:] + (1 - p) * values[:-1])
27
+ if american:
28
+ j = np.arange(i + 1)
29
+ current_spot = spot * u**j * d**(i - j)
30
+ if option_type == "call":
31
+ intrinsic = np.maximum(current_spot - strike, 0)
32
+ else:
33
+ intrinsic = np.maximum(strike - current_spot, 0)
34
+ values = np.maximum(values, intrinsic)
35
+
36
+ if i == 2:
37
+ values_at_2 = values.copy()
38
+ elif i == 1:
39
+ values_at_1 = values.copy()
40
+ elif i == 0:
41
+ value_at_0 = values.copy()
42
+
43
+ return value_at_0[0], values_at_1, values_at_2, u, d
44
+
45
+
46
+ class _BinomialOption:
47
+ def __init__(self, spot, strike, maturity, rate, volatility, option_type, steps=100):
48
+ super().__init__(spot, strike, maturity, rate, volatility, option_type)
49
+ if steps < 2:
50
+ raise ValueError("steps must be at least 2.")
51
+ self._steps = steps
52
+
53
+ @property
54
+ def steps(self):
55
+ return self._steps
56
+
57
+ def _tree(self, volatility=None, rate=None):
58
+ return _crr_tree(
59
+ self.spot,
60
+ self.strike,
61
+ self.maturity,
62
+ self.rate if rate is None else rate,
63
+ self.volatility if volatility is None else volatility,
64
+ self.option_type,
65
+ self.steps,
66
+ self._american,
67
+ )
68
+
69
+ def price(self):
70
+ return self._tree()[0]
71
+
72
+ def greeks(self):
73
+ price, values_at_1, values_at_2, u, d = self._tree()
74
+ dt = self.maturity / self.steps
75
+ delta = (values_at_1[1] - values_at_1[0]) / (self.spot * u - self.spot * d)
76
+ delta_up = (values_at_2[2] - values_at_2[1]) / (self.spot * u**2 - self.spot)
77
+ delta_down = (values_at_2[1] - values_at_2[0]) / (self.spot - self.spot * d**2)
78
+ gamma = (delta_up - delta_down) / (0.5 * (self.spot * u**2 - self.spot * d**2))
79
+ theta = (values_at_2[1] - price) / (2 * dt)
80
+
81
+ h = 0.001
82
+ vega_up = type(self)(
83
+ self.spot, self.strike, self.maturity, self.rate,
84
+ self.volatility + h, self.option_type, steps=self.steps,
85
+ ).price()
86
+ vega_down = type(self)(
87
+ self.spot, self.strike, self.maturity, self.rate,
88
+ self.volatility - h, self.option_type, steps=self.steps,
89
+ ).price()
90
+ rho_up = type(self)(
91
+ self.spot, self.strike, self.maturity, self.rate + h,
92
+ self.volatility, self.option_type, steps=self.steps,
93
+ ).price()
94
+ rho_down = type(self)(
95
+ self.spot, self.strike, self.maturity, self.rate - h,
96
+ self.volatility, self.option_type, steps=self.steps,
97
+ ).price()
98
+ vega = (vega_up - vega_down) / (2 * h)
99
+ rho = (rho_up - rho_down) / (2 * h)
100
+
101
+ return {
102
+ "delta": delta,
103
+ "gamma": gamma,
104
+ "theta": theta,
105
+ "vega": vega,
106
+ "rho": rho,
107
+ }
108
+
109
+
110
+ class BinomialEuropeanOption(_BinomialOption, EuropeanOption):
111
+ _american = False
112
+
113
+
114
+ class BinomialAmericanOption(_BinomialOption, AmericanOption):
115
+ _american = True
@@ -0,0 +1,54 @@
1
+ import math
2
+ from scipy.stats import norm
3
+ from .european import EuropeanOption
4
+
5
+ #_d1(self): d1 = [ ln(S/K) + (r + σ²/2) · T ] / ( σ · √T )
6
+ # _d2(self): d2 = d1 − σ · √T
7
+
8
+ class BlackScholesOption(EuropeanOption):
9
+ """Class for Black-Scholes option pricing model."""
10
+
11
+ def _d1(self):
12
+ """Calculate d1 for the Black-Scholes formula."""
13
+ S = self.spot
14
+ K = self.strike
15
+ r = self.rate
16
+ sigma = self.volatility
17
+ T = self.maturity
18
+ return (math.log(S / K) + (r + 0.5 * sigma ** 2) * T) / (sigma * math.sqrt(T))
19
+
20
+ def _d2(self):
21
+ """Calculate d2 for the Black-Scholes formula."""
22
+ return self._d1() - self.volatility * math.sqrt(self.maturity)
23
+
24
+ def price(self):
25
+ #Call: S · N(d1) − K · e^(−rT) · N(d2)
26
+ # Put: K · e^(−rT) · N(−d2) − S · N(−d1)
27
+ d1 = self._d1()
28
+ d2 = self._d2()
29
+ call_price = self.spot * norm.cdf(d1) - self.strike * math.exp(-self.rate * self.maturity) * norm.cdf(d2)
30
+ put_price = self.strike * math.exp(-self.rate * self.maturity) * norm.cdf(-d2) - self.spot * norm.cdf(-d1)
31
+ return call_price if self.option_type == "call" else put_price
32
+
33
+ def greeks(self):
34
+
35
+ # Delta N(d1) N(d1) − 1
36
+ # Gamma φ(d1) / (S · σ · √T) same as call
37
+ # Vega S · φ(d1) · √T same as call
38
+ # Theta −S · φ(d1) · σ / (2√T) − r · K · e^(−rT) · N(d2) −S · φ(d1) · σ / (2√T) + r · K · e^(−rT) · N(−d2)
39
+ # Rho K · T · e^(−rT) · N(d2) −K · T · e^(−rT) · N(−d2)
40
+ d1 = self._d1()
41
+ d2 = self._d2()
42
+ delta = norm.cdf(d1) if self.option_type == "call" else norm.cdf(d1) - 1
43
+ gamma = norm.pdf(d1) / (self.spot * self.volatility * math.sqrt(self.maturity))
44
+ vega = self.spot * norm.pdf(d1) * math.sqrt(self.maturity)
45
+ theta = (-self.spot * norm.pdf(d1) * self.volatility / (2 * math.sqrt(self.maturity)) - self.rate * self.strike * math.exp(-self.rate * self.maturity) * norm.cdf(d2)) if self.option_type == "call" else (-self.spot * norm.pdf(d1) * self.volatility / (2 * math.sqrt(self.maturity)) + self.rate * self.strike * math.exp(-self.rate * self.maturity) * norm.cdf(-d2))
46
+ rho = self.strike * self.maturity * math.exp(-self.rate * self.maturity) * norm.cdf(d2) if self.option_type == "call" else -self.strike * self.maturity * math.exp(-self.rate * self.maturity) * norm.cdf(-d2)
47
+
48
+ return {
49
+ "delta": delta,
50
+ "gamma": gamma,
51
+ "vega": vega,
52
+ "theta": theta,
53
+ "rho": rho
54
+ }
@@ -0,0 +1,31 @@
1
+ from .base import Option
2
+
3
+
4
+ class PricingEngine:
5
+ """Prices any Option through its own price() and greeks() methods."""
6
+
7
+ def __init__(self, option):
8
+ if not isinstance(option, Option):
9
+ raise TypeError("PricingEngine expects an Option instance.")
10
+ self._option = option
11
+
12
+ @property
13
+ def option(self):
14
+ return self._option
15
+
16
+ def price(self):
17
+ return self._option.price()
18
+
19
+ def greeks(self):
20
+ return self._option.greeks()
21
+
22
+ def run(self):
23
+ """Price, Greeks, and the standard error for simulation-based models."""
24
+ result = {
25
+ "model": type(self._option).__name__,
26
+ "price": self.price(),
27
+ "greeks": self.greeks(),
28
+ }
29
+ if hasattr(self._option, "standard_error"):
30
+ result["standard_error"] = self._option.standard_error()
31
+ return result
@@ -0,0 +1,4 @@
1
+ from .base import Option
2
+
3
+ class EuropeanOption(Option):
4
+ """exercised only at maturity"""
@@ -0,0 +1,61 @@
1
+ from .black_scholes import BlackScholesOption
2
+ from .binomial import BinomialEuropeanOption, BinomialAmericanOption
3
+ from .monte_carlo import MonteCarloEuropeanOption
4
+ from .asian import AsianOption
5
+ from .barrier import BarrierOption
6
+
7
+
8
+ class OptionFactory:
9
+ """Builds the right Option subclass from a (model, style) pair."""
10
+
11
+ _MODEL_ALIASES = {
12
+ "black_scholes": "black_scholes",
13
+ "black-scholes": "black_scholes",
14
+ "bs": "black_scholes",
15
+ "binomial": "binomial",
16
+ "crr": "binomial",
17
+ "monte_carlo": "monte_carlo",
18
+ "monte-carlo": "monte_carlo",
19
+ "mc": "monte_carlo",
20
+ "asian": "asian",
21
+ "barrier": "barrier",
22
+ }
23
+
24
+ _REGISTRY = {
25
+ ("black_scholes", "european"): BlackScholesOption,
26
+ ("binomial", "european"): BinomialEuropeanOption,
27
+ ("binomial", "american"): BinomialAmericanOption,
28
+ ("monte_carlo", "european"): MonteCarloEuropeanOption,
29
+ ("asian", "european"): AsianOption,
30
+ ("barrier", "european"): BarrierOption,
31
+ }
32
+
33
+ @classmethod
34
+ def option_class(cls, model, style):
35
+ """The Option subclass registered for (model, style)."""
36
+ model_key = cls._MODEL_ALIASES.get(model.lower())
37
+ if model_key is None:
38
+ raise ValueError(f"Unknown model '{model}'.")
39
+
40
+ style_key = style.lower()
41
+ option_cls = cls._REGISTRY.get((model_key, style_key))
42
+ if option_cls is None:
43
+ supported = sorted(s for m, s in cls._REGISTRY if m == model_key)
44
+ raise ValueError(
45
+ f"Model '{model}' does not support style '{style}'. "
46
+ f"Supported styles: {supported}."
47
+ )
48
+ return option_cls
49
+
50
+ @classmethod
51
+ def create(cls, model, style, spot, strike, maturity, rate,
52
+ volatility, option_type, **kwargs):
53
+ option_cls = cls.option_class(model, style)
54
+ return option_cls(
55
+ spot, strike, maturity, rate, volatility, option_type, **kwargs
56
+ )
57
+
58
+ @classmethod
59
+ def available(cls):
60
+ """List of supported (model, style) pairs, useful for the API later."""
61
+ return sorted(cls._REGISTRY)
@@ -0,0 +1,140 @@
1
+ import math
2
+
3
+ from scipy.optimize import brentq
4
+
5
+ from .black_scholes import BlackScholesOption
6
+ from .factory import OptionFactory
7
+
8
+
9
+ _VOL_LOW = 0.001
10
+ _VOL_HIGH = 5.0
11
+
12
+
13
+ def implied_volatility(market_price, model, style, option_type,
14
+ spot, strike, maturity, rate, **kwargs):
15
+ """Volatility that matches market_price, using the chosen model's price().
16
+
17
+ Solves model_price(σ) − market_price = 0 with Brent's method on a
18
+ bracket inside [0.001, 5]. The option is built through OptionFactory,
19
+ so the same solver works for Black-Scholes, the binomial tree, and
20
+ Monte Carlo. Volatilities whose model price is not finite are skipped.
21
+ That happens when a binomial tree's risk-neutral probability leaves
22
+ (0, 1). Monte Carlo needs a fixed seed in kwargs or the objective is noisy.
23
+ """
24
+ if "volatility" in kwargs:
25
+ raise ValueError("Pass the market price, not a volatility. implied_volatility solves for it.")
26
+ if market_price is None or not math.isfinite(market_price):
27
+ raise ValueError("Market price must be a finite number.")
28
+ if market_price < 0:
29
+ raise ValueError("Market price must be non-negative.")
30
+
31
+ def model_price(sigma):
32
+ option = OptionFactory.create(
33
+ model, style,
34
+ spot, strike, maturity, rate, sigma, option_type,
35
+ **kwargs,
36
+ )
37
+ return float(option.price())
38
+
39
+ def usable_price(sigma):
40
+ # A tiny volatility makes the CRR risk-neutral probability leave (0, 1),
41
+ # and the tree price explodes. Skip those volatilities.
42
+ try:
43
+ price = model_price(sigma)
44
+ except ValueError:
45
+ return None
46
+ if not math.isfinite(price) or price < 0 or price > max(spot, strike) * 2:
47
+ return None
48
+ return price
49
+
50
+ sigmas = []
51
+ sigma = _VOL_LOW
52
+ while True:
53
+ sigmas.append(sigma)
54
+ if sigma >= _VOL_HIGH:
55
+ break
56
+ sigma = min(_VOL_HIGH, sigma * 2)
57
+
58
+ priced = [(sigma, usable_price(sigma)) for sigma in sigmas]
59
+ priced = [(sigma, price) for sigma, price in priced if price is not None]
60
+ if len(priced) < 2:
61
+ raise ValueError(
62
+ "Model prices are not finite for volatilities between "
63
+ f"{_VOL_LOW} and {_VOL_HIGH}."
64
+ )
65
+
66
+ for sigma, price in priced:
67
+ if price == market_price:
68
+ return sigma
69
+
70
+ bracket = None
71
+ for (left, left_price), (right, right_price) in zip(priced, priced[1:]):
72
+ if (left_price - market_price) * (right_price - market_price) <= 0:
73
+ bracket = (left, right)
74
+ break
75
+ if bracket is None:
76
+ prices = [price for _, price in priced]
77
+ raise ValueError(
78
+ f"Market price {market_price} is outside the prices this model can produce "
79
+ f"for volatilities between {priced[0][0]} and {priced[-1][0]} "
80
+ f"(model prices {min(prices):.4f} to {max(prices):.4f}). "
81
+ "That is outside no-arbitrage bounds for this contract."
82
+ )
83
+
84
+ return float(brentq(
85
+ lambda sigma: model_price(sigma) - market_price, bracket[0], bracket[1]
86
+ ))
87
+
88
+
89
+ def _skewed_volatility(strike, spot, atm_vol, skew):
90
+ """σ(K) = σ_atm + skew · ln(K / S). Negative skew raises vol at low strikes."""
91
+ sigma = atm_vol + skew * math.log(strike / spot)
92
+ if sigma <= 0:
93
+ raise ValueError(
94
+ f"Skewed volatility at strike {strike} is {sigma}, which is not positive. "
95
+ "Use strikes closer to the spot or a smaller skew."
96
+ )
97
+ return sigma
98
+
99
+
100
+ def volatility_smile(strikes, spot, maturity, rate, option_type="call",
101
+ model="black_scholes", style="european",
102
+ atm_vol=0.20, skew=-0.15, market_prices=None, **kwargs):
103
+ """Implied volatility at each strike.
104
+
105
+ When market_prices is omitted, prices are Black-Scholes prices from a
106
+ skewed volatility, σ(K) = atm_vol + skew · ln(K / spot). Each price is
107
+ then inverted with implied_volatility. The returned points are what a
108
+ smile chart plots: strike on the x-axis and implied_vol on the y-axis.
109
+ """
110
+ strikes = [float(strike) for strike in strikes]
111
+ if not strikes:
112
+ raise ValueError("strikes must not be empty.")
113
+ if any(strike <= 0 for strike in strikes):
114
+ raise ValueError("Every strike must be positive.")
115
+
116
+ if market_prices is None:
117
+ market_prices = []
118
+ for strike in strikes:
119
+ sigma = _skewed_volatility(strike, spot, atm_vol, skew)
120
+ price = BlackScholesOption(
121
+ spot, strike, maturity, rate, sigma, option_type
122
+ ).price()
123
+ market_prices.append(price)
124
+ else:
125
+ market_prices = [float(price) for price in market_prices]
126
+ if len(market_prices) != len(strikes):
127
+ raise ValueError("market_prices must have one price per strike.")
128
+
129
+ smile = []
130
+ for strike, market_price in zip(strikes, market_prices):
131
+ iv = implied_volatility(
132
+ market_price, model, style, option_type,
133
+ spot, strike, maturity, rate, **kwargs,
134
+ )
135
+ smile.append({
136
+ "strike": strike,
137
+ "market_price": market_price,
138
+ "implied_vol": iv,
139
+ })
140
+ return smile
@@ -0,0 +1,71 @@
1
+ import math
2
+ import numpy as np
3
+ from .european import EuropeanOption
4
+
5
+ # S_T = S · exp[(r − σ²/2)·T + σ·√T·Z]
6
+ # price = e^(−rT) · mean(payoff), standard error = e^(−rT) · std(payoff) / √n
7
+
8
+
9
+ class MonteCarloEuropeanOption(EuropeanOption):
10
+ """European option priced by simulating the terminal spot price."""
11
+
12
+ def __init__(self, spot, strike, maturity, rate, volatility, option_type,
13
+ n_paths=100_000, seed=42):
14
+ super().__init__(spot, strike, maturity, rate, volatility, option_type)
15
+ if n_paths < 2:
16
+ raise ValueError("n_paths must be at least 2.")
17
+ self._n_paths = int(n_paths)
18
+ self._seed = seed
19
+ self._z = np.random.default_rng(seed).standard_normal(self._n_paths)
20
+
21
+ @property
22
+ def n_paths(self):
23
+ return self._n_paths
24
+
25
+ @property
26
+ def seed(self):
27
+ return self._seed
28
+
29
+ def _discounted_payoffs(self, spot=None, maturity=None, rate=None, volatility=None):
30
+ S = self.spot if spot is None else spot
31
+ T = self.maturity if maturity is None else maturity
32
+ r = self.rate if rate is None else rate
33
+ sigma = self.volatility if volatility is None else volatility
34
+
35
+ terminal_spot = S * np.exp((r - 0.5 * sigma**2) * T + sigma * math.sqrt(T) * self._z)
36
+ if self.option_type == "call":
37
+ payoff = np.maximum(terminal_spot - self.strike, 0)
38
+ else:
39
+ payoff = np.maximum(self.strike - terminal_spot, 0)
40
+ return math.exp(-r * T) * payoff
41
+
42
+ def price(self):
43
+ return float(self._discounted_payoffs().mean())
44
+
45
+ def standard_error(self):
46
+ return float(self._discounted_payoffs().std(ddof=1) / math.sqrt(self.n_paths))
47
+
48
+ def greeks(self):
49
+ # Bumped prices reuse the same normals so the noise mostly cancels.
50
+ def p(**kwargs):
51
+ return self._discounted_payoffs(**kwargs).mean()
52
+
53
+ S, T, r, sigma = self.spot, self.maturity, self.rate, self.volatility
54
+ dS = 0.01 * S
55
+ h = 0.001
56
+ dT = min(h, T / 2)
57
+
58
+ up, mid, down = p(spot=S + dS), p(), p(spot=S - dS)
59
+ delta = (up - down) / (2 * dS)
60
+ gamma = (up - 2 * mid + down) / dS**2
61
+ vega = (p(volatility=sigma + h) - p(volatility=sigma - h)) / (2 * h)
62
+ rho = (p(rate=r + h) - p(rate=r - h)) / (2 * h)
63
+ theta = -(p(maturity=T + dT) - p(maturity=T - dT)) / (2 * dT)
64
+
65
+ return {
66
+ "delta": float(delta),
67
+ "gamma": float(gamma),
68
+ "vega": float(vega),
69
+ "theta": float(theta),
70
+ "rho": float(rho),
71
+ }
@@ -0,0 +1,77 @@
1
+ import math
2
+ from abc import abstractmethod
3
+
4
+ from .base import Option
5
+ from .paths import simulate_paths, standard_normals, validate_simulation
6
+
7
+
8
+ class PathDependentOption(Option):
9
+ """payoff depends on the full price path, not just the final price"""
10
+
11
+
12
+ class _PathMonteCarlo(PathDependentOption):
13
+ """Shared seeded path simulation, price, standard error, and finite-difference Greeks."""
14
+
15
+ def __init__(self, spot, strike, maturity, rate, volatility, option_type,
16
+ n_paths=20_000, n_steps=50, seed=42):
17
+ super().__init__(spot, strike, maturity, rate, volatility, option_type)
18
+ self._n_paths, self._n_steps = validate_simulation(n_paths, n_steps)
19
+ self._seed = seed
20
+ self._z = standard_normals(self._n_paths, self._n_steps, seed)
21
+
22
+ @property
23
+ def n_paths(self):
24
+ return self._n_paths
25
+
26
+ @property
27
+ def n_steps(self):
28
+ return self._n_steps
29
+
30
+ @property
31
+ def seed(self):
32
+ return self._seed
33
+
34
+ def _paths(self, spot=None, maturity=None, rate=None, volatility=None):
35
+ return simulate_paths(
36
+ self.spot if spot is None else spot,
37
+ self.rate if rate is None else rate,
38
+ self.volatility if volatility is None else volatility,
39
+ self.maturity if maturity is None else maturity,
40
+ self._z,
41
+ )
42
+
43
+ @abstractmethod
44
+ def _discounted_payoffs(self, spot=None, maturity=None, rate=None, volatility=None):
45
+ """Discounted payoff on each stored path, so bumps reuse the same normals."""
46
+
47
+ def price(self):
48
+ return float(self._discounted_payoffs().mean())
49
+
50
+ def standard_error(self):
51
+ payoffs = self._discounted_payoffs()
52
+ return float(payoffs.std(ddof=1) / math.sqrt(self.n_paths))
53
+
54
+ def greeks(self):
55
+ # Bumped prices reuse the same normals so the noise mostly cancels.
56
+ def p(**kwargs):
57
+ return self._discounted_payoffs(**kwargs).mean()
58
+
59
+ S, T, r, sigma = self.spot, self.maturity, self.rate, self.volatility
60
+ dS = 0.01 * S
61
+ h = 0.001
62
+ dT = min(h, T / 2)
63
+
64
+ up, mid, down = p(spot=S + dS), p(), p(spot=S - dS)
65
+ delta = (up - down) / (2 * dS)
66
+ gamma = (up - 2 * mid + down) / dS**2
67
+ vega = (p(volatility=sigma + h) - p(volatility=sigma - h)) / (2 * h)
68
+ rho = (p(rate=r + h) - p(rate=r - h)) / (2 * h)
69
+ theta = -(p(maturity=T + dT) - p(maturity=T - dT)) / (2 * dT)
70
+
71
+ return {
72
+ "delta": float(delta),
73
+ "gamma": float(gamma),
74
+ "vega": float(vega),
75
+ "theta": float(theta),
76
+ "rho": float(rho),
77
+ }
@@ -0,0 +1,36 @@
1
+ import math
2
+
3
+ import numpy as np
4
+
5
+
6
+ def validate_simulation(n_paths, n_steps):
7
+ """Shared checks for Monte Carlo path counts."""
8
+ if n_paths < 2:
9
+ raise ValueError("n_paths must be at least 2.")
10
+ if n_steps < 2:
11
+ raise ValueError("n_steps must be at least 2.")
12
+ return int(n_paths), int(n_steps)
13
+
14
+
15
+ def standard_normals(n_paths, n_steps, seed):
16
+ """Seeded standard normals with shape (n_paths, n_steps)."""
17
+ n_paths, n_steps = validate_simulation(n_paths, n_steps)
18
+ return np.random.default_rng(seed).standard_normal((n_paths, n_steps))
19
+
20
+
21
+ def simulate_paths(spot, rate, volatility, maturity, z):
22
+ """Discrete geometric Brownian motion. Each row is one path and omits S0.
23
+
24
+ S grows by exp[(r − σ²/2) dt + σ√dt · Z] at every step.
25
+ """
26
+ n_steps = z.shape[1]
27
+ dt = maturity / n_steps
28
+ increments = (rate - 0.5 * volatility**2) * dt + volatility * math.sqrt(dt) * z
29
+ return spot * np.exp(np.cumsum(increments, axis=1))
30
+
31
+
32
+ def vanilla_payoff(level, strike, option_type):
33
+ """Call or put payoff on a price level (a terminal spot or an average)."""
34
+ if option_type == "call":
35
+ return np.maximum(level - strike, 0.0)
36
+ return np.maximum(strike - level, 0.0)
@@ -0,0 +1,295 @@
1
+ Metadata-Version: 2.4
2
+ Name: pyoptionpricing
3
+ Version: 0.1.0
4
+ Summary: Object-oriented option pricing: Black-Scholes, binomial tree and Monte Carlo behind one interface, with Asian and barrier options and implied volatility.
5
+ Author: Maadhini Narayanakumar
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/MaadhiniNarayanaKumar/pyoptionpricing
8
+ Project-URL: Demo, https://pyoptionpricingui.vercel.app
9
+ Project-URL: API docs, https://pyoptionpricing.vercel.app/docs
10
+ Keywords: options,derivatives,black-scholes,binomial-tree,monte-carlo,implied-volatility,quantitative-finance
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Education
13
+ Classifier: Intended Audience :: Financial and Insurance Industry
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.9
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Topic :: Office/Business :: Financial :: Investment
20
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
21
+ Requires-Python: >=3.9
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: numpy>=1.24
25
+ Requires-Dist: scipy>=1.10
26
+ Provides-Extra: api
27
+ Requires-Dist: fastapi; extra == "api"
28
+ Requires-Dist: pydantic; extra == "api"
29
+ Requires-Dist: uvicorn; extra == "api"
30
+ Provides-Extra: dev
31
+ Requires-Dist: fastapi; extra == "dev"
32
+ Requires-Dist: pydantic; extra == "dev"
33
+ Requires-Dist: uvicorn; extra == "dev"
34
+ Requires-Dist: httpx; extra == "dev"
35
+ Requires-Dist: pytest; extra == "dev"
36
+ Requires-Dist: pytest-cov; extra == "dev"
37
+ Dynamic: license-file
38
+
39
+ # OptionPricing
40
+
41
+ An object-oriented Python library and web platform for interactive option valuation and Greeks analysis.
42
+
43
+ **Course:** Object-Oriented Programming II (22:839:615:40), Master of Quantitative Finance, Rutgers University
44
+ **Professor:** Dr. Hseu-Ming Chen
45
+ **Author:** Maadhini Narayanakumar
46
+
47
+ ---
48
+
49
+ ## Overview
50
+
51
+ **Live demo:** https://pyoptionpricingui.vercel.app · **API docs:** https://pyoptionpricing.vercel.app/docs
52
+
53
+ `pyoptionpricing` is a modular Python library that prices vanilla and path-dependent options through a single, model-independent interface. Client code can price any option with `price()` and `greeks()` without knowing whether the underlying method is Black-Scholes, a Binomial Tree or Monte Carlo.
54
+
55
+ The library is exposed through a FastAPI backend and explored through a Next.js frontend, where you can enter parameters once, compare pricing models side by side, and visualize Greeks, payoffs, convergence and implied volatility.
56
+
57
+ > Live market data feeds are out of scope. The volatility surface is built from synthetic market prices.
58
+
59
+ ## Features
60
+
61
+ - Black-Scholes pricing with analytical Greeks (Delta, Gamma, Theta, Vega, Rho) for European calls and puts
62
+ - Binomial Tree (CRR) pricing for European and American options
63
+ - Monte Carlo pricing for European options, with standard error estimation
64
+ - Monte Carlo pricing for path-dependent options (Asian and Barrier)
65
+ - Implied volatility via root finding (Brent's method), working across all pricing models
66
+ - Implied volatility smile/surface across strikes
67
+ - Side-by-side model comparison (Black-Scholes vs Binomial vs Monte Carlo)
68
+ - American vs European price comparison
69
+ - Binomial convergence chart against the Black-Scholes price
70
+ - Payoff diagrams and simulated price path visualization
71
+ - Input validation with meaningful error messages
72
+ - Swagger/OpenAPI documentation
73
+
74
+ ## OOP Design
75
+
76
+ ```
77
+ Option (abstract)
78
+ ├── EuropeanOption (abstract)
79
+ │ ├── BlackScholesOption
80
+ │ ├── BinomialEuropeanOption
81
+ │ └── MonteCarloEuropeanOption
82
+ ├── AmericanOption (abstract)
83
+ │ └── BinomialAmericanOption
84
+ └── PathDependentOption (abstract)
85
+ ├── AsianOption
86
+ └── BarrierOption
87
+ ```
88
+
89
+ | Principle | How it is demonstrated |
90
+ | --- | --- |
91
+ | Abstraction | `Option` and its abstract subclasses define a common `price()` / `greeks()` interface and hide implementation details |
92
+ | Inheritance | Concrete option classes extend the shared behavior of their parents |
93
+ | Polymorphism | `PricingEngine` prices any `Option` object through the same interface |
94
+ | Encapsulation | Tree nodes, probabilities, simulated paths and intermediate math are internal to each class |
95
+ | Factory pattern | `OptionFactory` builds the right option object from model, exercise style, option type and extra parameters (e.g. barrier level) |
96
+
97
+ ## Tech Stack
98
+
99
+ | Layer | Technology |
100
+ | --- | --- |
101
+ | Core library | Python, NumPy, SciPy |
102
+ | Backend | FastAPI, Pydantic, Swagger/OpenAPI |
103
+ | Frontend | Next.js, React, TypeScript, Recharts |
104
+ | Testing | pytest, pytest-cov |
105
+ | Deployment | Vercel (backend and frontend, as two projects) |
106
+
107
+ ## Project Structure
108
+
109
+ ```
110
+ .
111
+ ├── pyoptionpricing/ # Core OOP library
112
+ ├── backend/ # FastAPI application
113
+ ├── frontend/ # Next.js application
114
+ ├── tests/ # pytest test suite
115
+ ├── docs/ # UML and architecture diagrams, report
116
+ ├── pyproject.toml
117
+ └── README.md
118
+ ```
119
+
120
+ ## Getting Started
121
+
122
+ ### Install the package
123
+
124
+ pip install git+https://github.com/MaadhiniNarayanaKumar/pyoptionpricing.git
125
+
126
+ To run the API as well: `pip install "pyoptionpricing[api] @ git+https://github.com/MaadhiniNarayanaKumar/pyoptionpricing.git"`
127
+
128
+ ### Prerequisites
129
+
130
+ - Python 3.9+
131
+ - Node.js 18+
132
+ - Git
133
+
134
+ ### 1. Clone the repository
135
+
136
+ ```bash
137
+ git clone https://github.com/<your-username>/<your-repo>.git
138
+ cd <your-repo>
139
+ ```
140
+
141
+ ### 2. Set up the Python environment
142
+
143
+ ```bash
144
+ python -m venv .venv
145
+ source .venv/bin/activate # Windows: .venv\Scripts\activate
146
+ pip install -e ".[dev]" # or: pip install -r requirements-dev.txt
147
+ ```
148
+
149
+ The library itself depends only on NumPy and SciPy, so `pip install .` is enough to use it from Python. The `api` extra (`pip install ".[api]"`) adds FastAPI, Pydantic and Uvicorn for the backend, and `dev` adds the test tools.
150
+
151
+ ### 3. Run the backend
152
+
153
+ ```bash
154
+ uvicorn backend.main:app --reload
155
+ ```
156
+
157
+ - API: http://localhost:8000
158
+ - Swagger docs: http://localhost:8000/docs
159
+
160
+ ### 4. Run the frontend
161
+
162
+ ```bash
163
+ cd frontend
164
+ npm install
165
+ cp .env.example .env.local # set NEXT_PUBLIC_API_URL=http://localhost:8000
166
+ npm run dev
167
+ ```
168
+
169
+ - App: http://localhost:3000
170
+
171
+ ## Usage Example
172
+
173
+ ```python
174
+ from pyoptionpricing import OptionFactory, PricingEngine
175
+
176
+ option = OptionFactory.create(
177
+ model="black_scholes",
178
+ style="european",
179
+ option_type="call",
180
+ spot=100, strike=100, maturity=1.0, rate=0.05, volatility=0.20,
181
+ )
182
+
183
+ engine = PricingEngine(option)
184
+ print(engine.price()) # ~10.4506
185
+ print(engine.greeks()) # delta, gamma, theta, vega, rho
186
+ print(engine.run()) # model name, price, Greeks (+ standard error for Monte Carlo)
187
+ ```
188
+
189
+ Swapping `model="binomial"` or `model="monte_carlo"` requires no other change to the client code.
190
+
191
+ ### Demo script
192
+
193
+ ```bash
194
+ python demo.py
195
+ ```
196
+
197
+ This walks through one example per feature: Black-Scholes and parity, validation, every model through the factory and engine, binomial convergence, American vs European, Monte Carlo error, Asian and Barrier, implied volatility, and the smile.
198
+
199
+ ## API Endpoints
200
+
201
+ | Method | Endpoint | Description |
202
+ | --- | --- | --- |
203
+ | POST | `/price` | Price an option with the chosen model (plus standard error for simulations) |
204
+ | POST | `/greeks` | Compute Greeks |
205
+ | POST | `/compare` | Price the same contract with every model side by side |
206
+ | POST | `/convergence` | Binomial price by tree depth and Monte Carlo price by path count, against Black-Scholes |
207
+ | POST | `/payoff` | Payoff and profit at maturity across terminal spot prices |
208
+ | POST | `/paths` | Sample simulated GBM price paths |
209
+ | POST | `/implied-vol` | Implied volatility from a market price, with any model |
210
+ | POST | `/vol-surface` | Implied volatility across strikes and maturities from synthetic skewed prices |
211
+ | GET | `/models` | Supported (model, style) pairs and the extra inputs each needs |
212
+ | GET | `/health` | Health check |
213
+
214
+ Every request takes `spot`, `strike`, `maturity`, `rate`, `volatility`, `option_type`, `model` and `style`. Model-specific inputs are optional (`steps`; `n_paths`, `n_steps`, `seed`; `barrier`, `barrier_type`) and are ignored by models that do not use them. Invalid inputs return HTTP 422 with a readable message.
215
+
216
+ Full request and response schemas are available in Swagger at `/docs`. Allowed frontend origins can be set with `FRONTEND_ORIGINS` (comma-separated, default `http://localhost:3000`).
217
+
218
+ ## Testing
219
+
220
+ ```bash
221
+ pytest --cov=pyoptionpricing --cov=backend --cov-report=term-missing
222
+ ```
223
+
224
+ The suite covers the library and every API endpoint. Current coverage is about 99%.
225
+
226
+ Correctness checks include:
227
+
228
+ - Put-call parity
229
+ - Binomial Tree convergence to Black-Scholes
230
+ - Greeks validated against finite-difference bumps
231
+ - Monte Carlo prices within standard error of Black-Scholes
232
+ - American put price at least the European put price
233
+ - Barrier knock-in plus knock-out equals the vanilla price
234
+ - Asian call price at most the European call price
235
+
236
+ Target coverage: 80%+
237
+
238
+ ## Documentation
239
+
240
+ - [UML class diagram](docs/uml.md)
241
+ - [Architecture and request flow](docs/architecture.md)
242
+ - [Final report](docs/report.md): OOP principles mapped to classes and files, results, challenges
243
+
244
+ ## Deployment
245
+
246
+ Both parts run on Vercel as two separate projects from this one repository.
247
+
248
+ ### Backend (FastAPI on Vercel)
249
+
250
+ Create a Vercel project from the repository with **Root Directory** left at the repository root and **Framework Preset** set to FastAPI (or Other). No build command is needed.
251
+
252
+ - `pyproject.toml` sets `[tool.vercel] entrypoint = "backend.main:app"`. Vercel installs from `pyproject.toml` and ignores `requirements.txt` when both exist, and its `uv sync --no-dev` skips optional extras. So the API packages are also listed in the `api` dependency group, which `[tool.uv] default-groups` installs. Keep that group in step with the `api` extra.
253
+ - `vercel.json` sets the function timeout and leaves the frontend, tests and docs out of the bundle.
254
+ - Set the environment variable `FRONTEND_ORIGINS` to the frontend's URL (comma-separated for more than one), for example `https://your-frontend.vercel.app`. Redeploy after changing it.
255
+ - Vercel gives each deployment its own URL, so you can also set `FRONTEND_ORIGIN_REGEX` to a pattern that matches all of them, for example `https://pyoptionpricing-.*-maadhinis-projects\.vercel\.app`.
256
+
257
+ With the Vercel CLI instead of Git:
258
+
259
+ ```bash
260
+ npm i -g vercel
261
+ vercel # preview deployment
262
+ vercel --prod # production deployment
263
+ ```
264
+
265
+ Check it with `https://<your-backend>.vercel.app/health` and `https://<your-backend>.vercel.app/docs`.
266
+
267
+ ### Frontend (Next.js on Vercel)
268
+
269
+ Create a second project with **Root Directory** set to `frontend`, and set `NEXT_PUBLIC_API_URL` to the backend URL.
270
+
271
+ ### Links
272
+
273
+ - **Backend:** https://pyoptionpricing.vercel.app (Swagger docs at https://pyoptionpricing.vercel.app/docs)
274
+ - **Frontend / demo:** https://pyoptionpricingui.vercel.app
275
+
276
+ ## Deliverables
277
+
278
+ - `pyoptionpricing` package with the full option hierarchy
279
+ - Black-Scholes, Binomial and Monte Carlo pricing models plus Asian/Barrier options
280
+ - Implied volatility and volatility surface utilities
281
+ - FastAPI backend with Swagger documentation
282
+ - Next.js frontend with convergence and volatility charts
283
+ - Test suite with coverage report
284
+ - UML and system architecture diagrams (`docs/`)
285
+ - Final report
286
+
287
+ ## Roadmap
288
+
289
+ - Variance reduction for Monte Carlo (antithetic and control variates)
290
+ - Volatility surface across maturities
291
+ - Scheduled data ingestion and calibration (e.g. Airflow)
292
+
293
+ ## License
294
+
295
+ Released under the MIT License. See [LICENSE](LICENSE). Developed as coursework at Rutgers University.
@@ -0,0 +1,20 @@
1
+ pyoptionpricing/__init__.py,sha256=51DAYI4ElZglOwo0rlQVN16C4LU-mG_x7XzZaCEkRcU,1283
2
+ pyoptionpricing/american.py,sha256=mYUjRVXWTFZVvhIethD-x9zJPU26SJ2y4GlYqOmv6iA,103
3
+ pyoptionpricing/analysis.py,sha256=bhzeR2lDN_MriI-Ra3-xllsjhXBEsWNbqLZGLiioJ8s,4557
4
+ pyoptionpricing/asian.py,sha256=-4QfXVIrk_bj8FHKiQ_JFD7zdnVvrUucWohLidwpnBA,778
5
+ pyoptionpricing/barrier.py,sha256=1IVgac3ZYu81VrJn4vlAW7LLiAAiNzsgr7pQQdfS7q0,2991
6
+ pyoptionpricing/base.py,sha256=8eiGsAsDjOnAW8Y9B9B6pPKGOz51LOF9JScDrzG8r9w,1696
7
+ pyoptionpricing/binomial.py,sha256=JL2nX1RT65KFVJRWtaTCBf83x11UcZTXcwi2gSc4RsQ,3816
8
+ pyoptionpricing/black_scholes.py,sha256=SI9FusyuEOPcUeztdigzSvv1xlT72hprcD1BsJJr5Hc,2631
9
+ pyoptionpricing/engine.py,sha256=Zz8GCknhtVIpJKMZ8_rZ__oyMRuwminDl1W9eZ_utFI,879
10
+ pyoptionpricing/european.py,sha256=pU2HUC_jnuWNxAWcDjCHROIj7HcB0RoQdWQ-iOkdhto,92
11
+ pyoptionpricing/factory.py,sha256=9MdSe_PNbXWDFh1mIHy6Ito3kIIIsEGLyAZ3nMe-gZI,2168
12
+ pyoptionpricing/implied_vol.py,sha256=dgRCT09tFzyUNFWs9GecV4rPaNWI2JMG5CYCd4JkEVg,5264
13
+ pyoptionpricing/monte_carlo.py,sha256=OpMgA8rAZocFBo7qOGk6qjzYEDnDtxwQnsin0R_91-Y,2588
14
+ pyoptionpricing/path_dependent.py,sha256=rhJV5xvEFBit0Mr2US-bGapvbIOHV2cCyBK0fEIjJlQ,2636
15
+ pyoptionpricing/paths.py,sha256=LwA_nJvoifBIl13hCSduK4iBoh8FhoCmqMKo1cGR31k,1225
16
+ pyoptionpricing-0.1.0.dist-info/licenses/LICENSE,sha256=DPQF_pl8vQ-NTYW5xm5L9hnz6uZS2JTlJWQ7kHdv4Yw,1078
17
+ pyoptionpricing-0.1.0.dist-info/METADATA,sha256=WbTecri3AAiy0xgqnPhb2rsVKhp4tMJb1TZhBPddudw,11793
18
+ pyoptionpricing-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
19
+ pyoptionpricing-0.1.0.dist-info/top_level.txt,sha256=RgxjBG1GWbh62Emi6g6R0x3kMcXoHTTJAo58hFGPEas,16
20
+ pyoptionpricing-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 MaadhiniNarayanaKumar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ pyoptionpricing