optPricing 2.0.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.
Files changed (92) hide show
  1. optpricing-2.0.0.dist-info/METADATA +105 -0
  2. optpricing-2.0.0.dist-info/RECORD +92 -0
  3. optpricing-2.0.0.dist-info/WHEEL +5 -0
  4. optpricing-2.0.0.dist-info/entry_points.txt +3 -0
  5. optpricing-2.0.0.dist-info/licenses/LICENSE +9 -0
  6. optpricing-2.0.0.dist-info/top_level.txt +1 -0
  7. quantfin/__init__.py +101 -0
  8. quantfin/atoms/__init__.py +21 -0
  9. quantfin/atoms/bond.py +28 -0
  10. quantfin/atoms/option.py +70 -0
  11. quantfin/atoms/rate.py +46 -0
  12. quantfin/atoms/stock.py +39 -0
  13. quantfin/calibration/__init__.py +25 -0
  14. quantfin/calibration/calibrator.py +155 -0
  15. quantfin/calibration/fit_jump_parameters.py +66 -0
  16. quantfin/calibration/fit_market_params.py +120 -0
  17. quantfin/calibration/iv_surface.py +155 -0
  18. quantfin/calibration/technique_selector.py +47 -0
  19. quantfin/calibration/vectorized_bsm_iv.py +93 -0
  20. quantfin/calibration/vectorized_integration_iv.py +143 -0
  21. quantfin/cli.py +372 -0
  22. quantfin/config.py +57 -0
  23. quantfin/dashboard/__init__.py +14 -0
  24. quantfin/dashboard/app.py +26 -0
  25. quantfin/dashboard/pages/1_Calibration.py +57 -0
  26. quantfin/dashboard/pages/2_Pricer_and_Greeks.py +150 -0
  27. quantfin/dashboard/pages/3_Financial_Tools.py +69 -0
  28. quantfin/dashboard/pages/__init__.py +0 -0
  29. quantfin/dashboard/plots.py +157 -0
  30. quantfin/dashboard/service.py +176 -0
  31. quantfin/dashboard/widgets.py +87 -0
  32. quantfin/data/__init__.py +26 -0
  33. quantfin/data/historical_manager.py +86 -0
  34. quantfin/data/market_data_manager.py +236 -0
  35. quantfin/models/__init__.py +54 -0
  36. quantfin/models/base/__init__.py +16 -0
  37. quantfin/models/base/base_model.py +198 -0
  38. quantfin/models/base/validators.py +95 -0
  39. quantfin/models/bates.py +192 -0
  40. quantfin/models/blacks_approx.py +134 -0
  41. quantfin/models/bsm.py +262 -0
  42. quantfin/models/cev.py +109 -0
  43. quantfin/models/cgmy.py +189 -0
  44. quantfin/models/cir.py +90 -0
  45. quantfin/models/dupire_local.py +67 -0
  46. quantfin/models/heston.py +204 -0
  47. quantfin/models/hyperbolic.py +170 -0
  48. quantfin/models/kou.py +148 -0
  49. quantfin/models/merton_jump.py +225 -0
  50. quantfin/models/nig.py +180 -0
  51. quantfin/models/perpetual_put.py +115 -0
  52. quantfin/models/sabr.py +64 -0
  53. quantfin/models/sabr_jump.py +68 -0
  54. quantfin/models/vasicek.py +88 -0
  55. quantfin/models/vg.py +178 -0
  56. quantfin/parity/__init__.py +13 -0
  57. quantfin/parity/implied_rate.py +110 -0
  58. quantfin/parity/parity_model.py +178 -0
  59. quantfin/techniques/__init__.py +31 -0
  60. quantfin/techniques/base/__init__.py +21 -0
  61. quantfin/techniques/base/base_technique.py +54 -0
  62. quantfin/techniques/base/greek_mixin.py +265 -0
  63. quantfin/techniques/base/iv_mixin.py +116 -0
  64. quantfin/techniques/base/lattice_technique.py +129 -0
  65. quantfin/techniques/base/pricing_result.py +27 -0
  66. quantfin/techniques/base/random_utils.py +31 -0
  67. quantfin/techniques/closed_form.py +296 -0
  68. quantfin/techniques/crr.py +59 -0
  69. quantfin/techniques/fft.py +178 -0
  70. quantfin/techniques/integration.py +202 -0
  71. quantfin/techniques/kernels/__init__.py +37 -0
  72. quantfin/techniques/kernels/lattice_kernels.py +286 -0
  73. quantfin/techniques/kernels/mc_kernels.py +337 -0
  74. quantfin/techniques/leisen_reimer.py +59 -0
  75. quantfin/techniques/monte_carlo.py +259 -0
  76. quantfin/techniques/pde.py +155 -0
  77. quantfin/techniques/topm.py +59 -0
  78. quantfin/workflows/__init__.py +14 -0
  79. quantfin/workflows/backtest_workflow.py +133 -0
  80. quantfin/workflows/configs/__init__.py +51 -0
  81. quantfin/workflows/configs/bates_config.py +25 -0
  82. quantfin/workflows/configs/bsm_config.py +9 -0
  83. quantfin/workflows/configs/cev_config.py +16 -0
  84. quantfin/workflows/configs/cgmy_config.py +18 -0
  85. quantfin/workflows/configs/heston_config.py +21 -0
  86. quantfin/workflows/configs/hyperbolic_config.py +18 -0
  87. quantfin/workflows/configs/kou_config.py +16 -0
  88. quantfin/workflows/configs/merton_config.py +18 -0
  89. quantfin/workflows/configs/nig_config.py +13 -0
  90. quantfin/workflows/configs/sabr_config.py +19 -0
  91. quantfin/workflows/configs/vg_config.py +9 -0
  92. quantfin/workflows/daily_workflow.py +150 -0
@@ -0,0 +1,110 @@
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ from typing import Any
5
+
6
+ from scipy.optimize import brentq
7
+
8
+ from quantfin.models.base import BaseModel
9
+
10
+ __doc__ = """
11
+ This module defines a model to find the risk-free rate implied by put-call parity.
12
+ """
13
+
14
+
15
+ class ImpliedRateModel(BaseModel):
16
+ """
17
+ Calculates the risk-free rate implied by put-call parity for European options.
18
+
19
+ This model solves for the risk-free rate `r` that satisfies the equation:
20
+ C - P = S*exp(-qT) - K*exp(-rT)
21
+ """
22
+
23
+ name: str = "Implied Rate"
24
+ has_closed_form: bool = True
25
+
26
+ # Define inputs for the closed-form solver.
27
+ cf_kwargs = ("call_price", "put_price")
28
+
29
+ def _validate_params(self) -> None:
30
+ """This model has no intrinsic parameters to validate."""
31
+ pass
32
+
33
+ def _closed_form_impl(
34
+ self,
35
+ *,
36
+ call_price: float,
37
+ put_price: float,
38
+ spot: float,
39
+ strike: float,
40
+ t: float,
41
+ q: float = 0.0,
42
+ **_: Any,
43
+ ) -> float:
44
+ """
45
+ Solves for the implied risk-free rate using a root-finding algorithm.
46
+
47
+ Parameters
48
+ ----------
49
+ call_price : float
50
+ The market price of the call option.
51
+ put_price : float
52
+ The market price of the put option.
53
+ spot : float
54
+ The current price of the underlying asset.
55
+ strike : float
56
+ The strike price of the options.
57
+ t : float
58
+ The time to maturity of the options.
59
+ q : float, optional
60
+ The continuously compounded dividend yield, by default 0.0.
61
+
62
+ Returns
63
+ -------
64
+ float
65
+ The implied continuously compounded risk-free rate.
66
+
67
+ Raises
68
+ ------
69
+ ValueError
70
+ If a root cannot be bracketed within a reasonable range.
71
+ """
72
+ discounted_spot = spot * math.exp(-q * t)
73
+ price_difference = call_price - put_price
74
+
75
+ def objective_func(
76
+ r: float,
77
+ ) -> float:
78
+ """The put-call parity equation rearranged to equal zero."""
79
+ return discounted_spot - strike * math.exp(-r * t) - price_difference
80
+
81
+ # Attempt to find a bracket for the root
82
+ low, high = -0.5, 0.5 # reasonable range for interest rates
83
+ f_low, f_high = objective_func(low), objective_func(high)
84
+
85
+ for _ in range(10): # Try up to 10 times to expand the bracket
86
+ if f_low * f_high < 0:
87
+ break
88
+ low -= 0.5
89
+ high += 0.5
90
+ f_low, f_high = objective_func(low), objective_func(high)
91
+ else:
92
+ raise ValueError(
93
+ "Unable to bracket a root for implied rate. Check input for arbitrage."
94
+ )
95
+
96
+ return brentq(objective_func, low, high, xtol=1e-9, maxiter=100)
97
+
98
+ # Abstract Method Implementations
99
+ def _cf_impl(
100
+ self,
101
+ *args: Any,
102
+ **kwargs: Any,
103
+ ) -> Any:
104
+ raise NotImplementedError
105
+
106
+ def _sde_impl(self) -> Any:
107
+ raise NotImplementedError
108
+
109
+ def _pde_impl(self) -> Any:
110
+ raise NotImplementedError
@@ -0,0 +1,178 @@
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ from typing import Any
5
+
6
+ from quantfin.models.base import BaseModel
7
+
8
+ __doc__ = """
9
+ This module provides a utility model for calculations based on Put-Call Parity.
10
+ """
11
+
12
+
13
+ class ParityModel(BaseModel):
14
+ """
15
+ A utility model providing calculations based on Put-Call Parity.
16
+
17
+ This class is not a traditional pricing model but uses the `BaseModel`
18
+ interface to provide parity-based calculations, such as finding a
19
+ complementary option price.
20
+ """
21
+
22
+ name: str = "Put-Call Parity"
23
+ has_closed_form: bool = True
24
+
25
+ # Define inputs for the closed-form solver.
26
+ cf_kwargs = ("option_price",)
27
+
28
+ def _validate_params(self) -> None:
29
+ """This model has no intrinsic parameters to validate."""
30
+ pass
31
+
32
+ def _closed_form_impl(
33
+ self,
34
+ *,
35
+ spot: float,
36
+ strike: float,
37
+ r: float,
38
+ t: float,
39
+ call: bool,
40
+ option_price: float,
41
+ q: float = 0.0,
42
+ **_: Any,
43
+ ) -> float:
44
+ """
45
+ Return the complementary price implied by put-call parity.
46
+
47
+ Parameters
48
+ ----------
49
+ spot : float
50
+ The current price of the underlying asset.
51
+ strike : float
52
+ The strike price of the option.
53
+ r : float
54
+ The risk-free rate.
55
+ t : float
56
+ The time to maturity.
57
+ call : bool
58
+ True if `option_price` is for a call, False if it's for a put.
59
+ option_price : float
60
+ The price of the known option.
61
+ q : float, optional
62
+ The continuously compounded dividend yield, by default 0.0.
63
+
64
+ Returns
65
+ -------
66
+ float
67
+ The price of the complementary option (i.e. put -> call).
68
+ """
69
+ discounted_spot = spot * math.exp(-q * t)
70
+ discounted_strike = strike * math.exp(-r * t)
71
+
72
+ # Parity: C - P = S*exp(-qT) - K*exp(-rT)
73
+ parity_difference = discounted_spot - discounted_strike
74
+
75
+ if call:
76
+ return option_price - parity_difference
77
+ else:
78
+ return option_price + parity_difference
79
+
80
+ def price_bounds(
81
+ self,
82
+ *,
83
+ spot: float,
84
+ strike: float,
85
+ r: float,
86
+ t: float,
87
+ call: bool,
88
+ option_price: float, # noqa: F841
89
+ ) -> tuple[float, float]:
90
+ """
91
+ Return absolute (lower, upper) no-arbitrage bounds for an option.
92
+
93
+ Parameters
94
+ ----------
95
+ spot : float
96
+ The current price of the underlying asset.
97
+ strike : float
98
+ The strike price of the option.
99
+ r : float
100
+ The risk-free rate.
101
+ t : float
102
+ The time to maturity.
103
+ call : bool
104
+ True if `option_price` is for a call, False if it's for a put.
105
+ option_price : float
106
+ The price of the known option. In this case it is a place holder.
107
+
108
+ Returns
109
+ -------
110
+ tuple[float, float]
111
+ A tuple containing the (lower_bound, upper_bound) for the option price.
112
+ """
113
+ discounted_strike = strike * math.exp(-r * t)
114
+
115
+ if call:
116
+ lower_bound = max(0, spot - discounted_strike)
117
+ upper_bound = spot
118
+ else: # Put
119
+ lower_bound = max(0, discounted_strike - spot)
120
+ upper_bound = discounted_strike
121
+
122
+ return lower_bound, upper_bound
123
+
124
+ def lower_bound_rate(
125
+ self,
126
+ *,
127
+ call_price: float,
128
+ put_price: float,
129
+ spot: float,
130
+ strike: float,
131
+ t: float,
132
+ ) -> float:
133
+ """
134
+ Calculates the minimum risk-free rate `r` to avoid arbitrage.
135
+
136
+ Parameters
137
+ ----------
138
+ call_price : float
139
+ The price of the call option.
140
+ put_price : float
141
+ The price of the put option.
142
+ spot : float
143
+ The current price of the underlying asset.
144
+ strike : float
145
+ The strike price of the option.
146
+ t : float
147
+ The time to maturity.
148
+
149
+ Returns
150
+ -------
151
+ float
152
+ The minimum continuously compounded risk-free rate to avoid arbitrage.
153
+
154
+ Raises
155
+ ------
156
+ ValueError
157
+ If an arbitrage opportunity already exists (S - C + P >= K).
158
+ """
159
+ val = strike / (spot - call_price + put_price)
160
+ if val <= 0:
161
+ raise ValueError(
162
+ "Arbitrage exists (S - C + P >= K). Cannot compute implied rate."
163
+ )
164
+ return math.log(val) / t
165
+
166
+ # Abstract Method Implementations
167
+ def _cf_impl(
168
+ self,
169
+ *args: Any,
170
+ **kwargs: Any,
171
+ ) -> Any:
172
+ raise NotImplementedError
173
+
174
+ def _sde_impl(self) -> Any:
175
+ raise NotImplementedError
176
+
177
+ def _pde_impl(self) -> Any:
178
+ raise NotImplementedError
@@ -0,0 +1,31 @@
1
+ from __future__ import annotations
2
+
3
+ __doc__ = """
4
+ The `techniques` package provides the various numerical and analytical
5
+ methods for pricing options.
6
+ """
7
+
8
+ from .base import BaseTechnique, GreekMixin, IVMixin, PricingResult
9
+ from .closed_form import ClosedFormTechnique
10
+ from .crr import CRRTechnique
11
+ from .fft import FFTTechnique
12
+ from .integration import IntegrationTechnique
13
+ from .leisen_reimer import LeisenReimerTechnique
14
+ from .monte_carlo import MonteCarloTechnique
15
+ from .pde import PDETechnique
16
+ from .topm import TOPMTechnique
17
+
18
+ __all__ = [
19
+ "BaseTechnique",
20
+ "PricingResult",
21
+ "GreekMixin",
22
+ "IVMixin",
23
+ "ClosedFormTechnique",
24
+ "FFTTechnique",
25
+ "IntegrationTechnique",
26
+ "CRRTechnique",
27
+ "LeisenReimerTechnique",
28
+ "TOPMTechnique",
29
+ "PDETechnique",
30
+ "MonteCarloTechnique",
31
+ ]
@@ -0,0 +1,21 @@
1
+ from __future__ import annotations
2
+
3
+ __doc__ = """
4
+ Provides the base classes and mixins for all pricing techniques.
5
+ """
6
+
7
+ from .base_technique import BaseTechnique
8
+ from .greek_mixin import GreekMixin
9
+ from .iv_mixin import IVMixin
10
+ from .lattice_technique import LatticeTechnique
11
+ from .pricing_result import PricingResult
12
+ from .random_utils import crn
13
+
14
+ __all__ = [
15
+ "BaseTechnique",
16
+ "GreekMixin",
17
+ "IVMixin",
18
+ "LatticeTechnique",
19
+ "PricingResult",
20
+ "crn",
21
+ ]
@@ -0,0 +1,54 @@
1
+ from __future__ import annotations
2
+
3
+ from abc import ABC, abstractmethod
4
+
5
+ import numpy as np
6
+
7
+ from quantfin.atoms import Option, Rate, Stock
8
+ from quantfin.models import BaseModel
9
+ from quantfin.techniques.base.pricing_result import PricingResult
10
+
11
+ __doc__ = """
12
+ Defines the abstract base class for all pricing techniques.
13
+ """
14
+
15
+
16
+ class BaseTechnique(ABC):
17
+ """
18
+ Abstract base class for all pricing methodologies.
19
+
20
+ A technique defines the algorithm used to compute a price from the core
21
+ 'atoms' (Option, Stock, Rate) and a given financial 'Model'.
22
+ """
23
+
24
+ @abstractmethod
25
+ def price(
26
+ self,
27
+ option: Option | np.ndarray,
28
+ stock: Stock,
29
+ model: BaseModel,
30
+ rate: Rate,
31
+ **kwargs,
32
+ ) -> PricingResult | np.ndarray:
33
+ """
34
+ Calculate the price of an option.
35
+
36
+ Parameters
37
+ ----------
38
+ option : Option | np.ndarray
39
+ The option contract(s) to be priced.
40
+ stock : Stock
41
+ The underlying asset's properties.
42
+ model : BaseModel
43
+ The financial model to use for the calculation.
44
+ rate : Rate
45
+ The risk-free rate structure.
46
+ **kwargs : Any
47
+ Additional keyword arguments required by specific techniques or models.
48
+
49
+ Returns
50
+ -------
51
+ PricingResult
52
+ An object containing the calculated price and potentially other metrics.
53
+ """
54
+ raise NotImplementedError
@@ -0,0 +1,265 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import replace
4
+ from typing import TYPE_CHECKING, Any
5
+
6
+ import numpy as np
7
+
8
+ from quantfin.techniques.base.random_utils import crn
9
+
10
+ __doc__ = """
11
+ Provides a mixin class with default numerical implementations for option Greeks.
12
+ """
13
+
14
+ if TYPE_CHECKING:
15
+ from quantfin.atoms import Option, Rate, Stock
16
+ from quantfin.models import BaseModel
17
+
18
+
19
+ class GreekMixin:
20
+ """
21
+ Provides finite-difference calculations for Greeks.
22
+
23
+ This mixin is designed to be side-effect-free. It creates modified copies
24
+ of the input objects for shifted calculations rather than mutating them in place.
25
+ It also supports Common Random Numbers (CRN) for variance reduction in
26
+ Monte Carlo-based calculations by checking for a `self.rng` attribute.
27
+ """
28
+
29
+ def delta(
30
+ self,
31
+ option: Option,
32
+ stock: Stock,
33
+ model: BaseModel,
34
+ rate: Rate,
35
+ h_frac: float = 1e-3,
36
+ **kwargs: Any,
37
+ ) -> float:
38
+ """
39
+ Calculates delta using a central difference formula.
40
+
41
+ Parameters
42
+ ----------
43
+ option : Option
44
+ The option contract to be priced.
45
+ stock : Stock
46
+ The underlying asset's properties.
47
+ model : BaseModel
48
+ The financial model to use for the calculation.
49
+ rate : Rate
50
+ The risk-free rate structure.
51
+ h_frac : float, optional
52
+ The fractional step size for shifting the spot price, by default 1e-3.
53
+
54
+ Returns
55
+ -------
56
+ float
57
+ The calculated delta.
58
+ """
59
+ h = stock.spot * h_frac
60
+ stock_up = replace(stock, spot=stock.spot + h)
61
+ stock_dn = replace(stock, spot=stock.spot - h)
62
+
63
+ rng = getattr(self, "rng", None)
64
+ if isinstance(rng, np.random.Generator):
65
+ with crn(rng):
66
+ p_up = self.price(option, stock_up, model, rate, **kwargs).price
67
+ with crn(rng):
68
+ p_dn = self.price(option, stock_dn, model, rate, **kwargs).price
69
+ else:
70
+ p_up = self.price(option, stock_up, model, rate, **kwargs).price
71
+ p_dn = self.price(option, stock_dn, model, rate, **kwargs).price
72
+
73
+ return (p_up - p_dn) / (2 * h)
74
+
75
+ def gamma(
76
+ self,
77
+ option: Option,
78
+ stock: Stock,
79
+ model: BaseModel,
80
+ rate: Rate,
81
+ h_frac: float = 1e-3,
82
+ **kw: Any,
83
+ ) -> float:
84
+ """
85
+ Calculates gamma using a central difference formula.
86
+
87
+ Parameters
88
+ ----------
89
+ option : Option
90
+ The option contract to be priced.
91
+ stock : Stock
92
+ The underlying asset's properties.
93
+ model : BaseModel
94
+ The financial model to use for the calculation.
95
+ rate : Rate
96
+ The risk-free rate structure.
97
+ h_frac : float, optional
98
+ The fractional step size for shifting the spot price, by default 1e-3.
99
+
100
+ Returns
101
+ -------
102
+ float
103
+ The calculated gamma.
104
+ """
105
+ h = stock.spot * h_frac
106
+ stock_up = replace(stock, spot=stock.spot + h)
107
+ stock_dn = replace(stock, spot=stock.spot - h)
108
+
109
+ rng = getattr(self, "rng", None)
110
+ if isinstance(rng, np.random.Generator):
111
+ with crn(rng):
112
+ p_up = self.price(option, stock_up, model, rate, **kw).price
113
+ with crn(rng):
114
+ p_0 = self.price(option, stock, model, rate, **kw).price
115
+ with crn(rng):
116
+ p_dn = self.price(option, stock_dn, model, rate, **kw).price
117
+ else:
118
+ p_up = self.price(option, stock_up, model, rate, **kw).price
119
+ p_0 = self.price(option, stock, model, rate, **kw).price
120
+ p_dn = self.price(option, stock_dn, model, rate, **kw).price
121
+
122
+ return (p_up - 2 * p_0 + p_dn) / (h * h)
123
+
124
+ def vega(
125
+ self,
126
+ option: Option,
127
+ stock: Stock,
128
+ model: BaseModel,
129
+ rate: Rate,
130
+ h: float = 1e-4,
131
+ **kw: Any,
132
+ ) -> float:
133
+ """
134
+ Calculates vega using a central difference formula.
135
+
136
+ Returns `np.nan` if the model does not have a 'sigma' parameter.
137
+
138
+ Parameters
139
+ ----------
140
+ option : Option
141
+ The option contract to be priced.
142
+ stock : Stock
143
+ The underlying asset's properties.
144
+ model : BaseModel
145
+ The financial model to use for the calculation.
146
+ rate : Rate
147
+ The risk-free rate structure.
148
+ h : float, optional
149
+ The absolute step size for shifting volatility, by default 1e-4.
150
+
151
+ Returns
152
+ -------
153
+ float
154
+ The calculated vega.
155
+ """
156
+ if "sigma" not in model.params:
157
+ return np.nan
158
+
159
+ sigma = model.params["sigma"]
160
+ model_up = model.with_params(sigma=sigma + h)
161
+ model_dn = model.with_params(sigma=sigma - h)
162
+
163
+ rng = getattr(self, "rng", None)
164
+ if isinstance(rng, np.random.Generator):
165
+ with crn(rng):
166
+ p_up = self.price(option, stock, model_up, rate, **kw).price
167
+ with crn(rng):
168
+ p_dn = self.price(option, stock, model_dn, rate, **kw).price
169
+ else:
170
+ p_up = self.price(option, stock, model_up, rate, **kw).price
171
+ p_dn = self.price(option, stock, model_dn, rate, **kw).price
172
+
173
+ return (p_up - p_dn) / (2 * h)
174
+
175
+ def theta(
176
+ self,
177
+ option: Option,
178
+ stock: Stock,
179
+ model: BaseModel,
180
+ rate: Rate,
181
+ h: float = 1e-5,
182
+ **kw: Any,
183
+ ) -> float:
184
+ """
185
+ Calculates theta using a central difference formula.
186
+
187
+ Parameters
188
+ ----------
189
+ option : Option
190
+ The option contract to be priced.
191
+ stock : Stock
192
+ The underlying asset's properties.
193
+ model : BaseModel
194
+ The financial model to use for the calculation.
195
+ rate : Rate
196
+ The risk-free rate structure.
197
+ h : float, optional
198
+ The absolute step size for shifting maturity, by default 1e-5.
199
+
200
+ Returns
201
+ -------
202
+ float
203
+ The calculated theta.
204
+ """
205
+ T0 = option.maturity
206
+ opt_up = replace(option, maturity=T0 + h)
207
+ opt_dn = replace(option, maturity=max(T0 - h, 1e-12)) # Avoid maturity of 0
208
+
209
+ rng = getattr(self, "rng", None)
210
+ if isinstance(rng, np.random.Generator):
211
+ with crn(rng):
212
+ p_up = self.price(opt_up, stock, model, rate, **kw).price
213
+ with crn(rng):
214
+ p_dn = self.price(opt_dn, stock, model, rate, **kw).price
215
+ else:
216
+ p_up = self.price(opt_up, stock, model, rate, **kw).price
217
+ p_dn = self.price(opt_dn, stock, model, rate, **kw).price
218
+
219
+ return (p_dn - p_up) / (2 * h)
220
+
221
+ def rho(
222
+ self,
223
+ option: Option,
224
+ stock: Stock,
225
+ model: BaseModel,
226
+ rate: Rate,
227
+ h: float = 1e-4,
228
+ **kw: Any,
229
+ ) -> float:
230
+ """
231
+ Calculates rho using a central difference formula.
232
+
233
+ Parameters
234
+ ----------
235
+ option : Option
236
+ The option contract to be priced.
237
+ stock : Stock
238
+ The underlying asset's properties.
239
+ model : BaseModel
240
+ The financial model to use for the calculation.
241
+ rate : Rate
242
+ The risk-free rate structure.
243
+ h : float, optional
244
+ The absolute step size for shifting the interest rate, by default 1e-4.
245
+
246
+ Returns
247
+ -------
248
+ float
249
+ The calculated rho.
250
+ """
251
+ r0 = rate.get_rate(option.maturity)
252
+ rate_up = replace(rate, rate=r0 + h)
253
+ rate_dn = replace(rate, rate=r0 - h)
254
+
255
+ rng = getattr(self, "rng", None)
256
+ if isinstance(rng, np.random.Generator):
257
+ with crn(rng):
258
+ p_up = self.price(option, stock, model, rate_up, **kw).price
259
+ with crn(rng):
260
+ p_dn = self.price(option, stock, model, rate_dn, **kw).price
261
+ else:
262
+ p_up = self.price(option, stock, model, rate_up, **kw).price
263
+ p_dn = self.price(option, stock, model, rate_dn, **kw).price
264
+
265
+ return (p_up - p_dn) / (2 * h)