fiqua 0.1.0__tar.gz
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.
- fiqua-0.1.0/PKG-INFO +10 -0
- fiqua-0.1.0/README.md +0 -0
- fiqua-0.1.0/pyproject.toml +27 -0
- fiqua-0.1.0/src/fiqua/__init__.py +0 -0
- fiqua-0.1.0/src/fiqua/core/__init__.py +6 -0
- fiqua-0.1.0/src/fiqua/core/instrument.py +65 -0
- fiqua-0.1.0/src/fiqua/core/portfolio.py +89 -0
- fiqua-0.1.0/src/fiqua/core/position.py +39 -0
- fiqua-0.1.0/src/fiqua/core/result.py +28 -0
- fiqua-0.1.0/src/fiqua/equities/__init__.py +5 -0
- fiqua-0.1.0/src/fiqua/equities/option.py +129 -0
- fiqua-0.1.0/src/fiqua/equities/portfolio_surface.py +78 -0
- fiqua-0.1.0/src/fiqua/equities/stock.py +66 -0
- fiqua-0.1.0/src/fiqua/py.typed +0 -0
fiqua-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
|
+
Name: fiqua
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Quantitative finance library: option pricing and portfolio-of-strategies analysis, built on numanlib.
|
|
5
|
+
Author: Fabio Nicotra
|
|
6
|
+
Author-email: Fabio Nicotra <nicotra.fabio@icloud.com>
|
|
7
|
+
Requires-Dist: numanlib[interactive]==0.2.1
|
|
8
|
+
Requires-Python: >=3.12
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
|
fiqua-0.1.0/README.md
ADDED
|
File without changes
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "fiqua"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Quantitative finance library: option pricing and portfolio-of-strategies analysis, built on numanlib."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
authors = [
|
|
7
|
+
{ name = "Fabio Nicotra", email = "nicotra.fabio@icloud.com" }
|
|
8
|
+
]
|
|
9
|
+
requires-python = ">=3.12"
|
|
10
|
+
dependencies = [
|
|
11
|
+
"numanlib[interactive]==0.2.1",
|
|
12
|
+
]
|
|
13
|
+
|
|
14
|
+
[build-system]
|
|
15
|
+
requires = ["uv_build>=0.10.2,<0.11.0"]
|
|
16
|
+
build-backend = "uv_build"
|
|
17
|
+
|
|
18
|
+
[dependency-groups]
|
|
19
|
+
dev = [
|
|
20
|
+
"ipykernel>=7.3.0",
|
|
21
|
+
"nbformat>=5.10.4",
|
|
22
|
+
"pytest>=9.0.2",
|
|
23
|
+
"pytest-cov>=7.0.0",
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
[tool.pytest.ini_options]
|
|
27
|
+
testpaths = ["tests"]
|
|
File without changes
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
from abc import ABC, abstractmethod
|
|
2
|
+
from typing import SupportsFloat, Tuple
|
|
3
|
+
|
|
4
|
+
from .result import PricerResult
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class _Combinable:
|
|
8
|
+
"""Shared +, -, *, unary - for Instrument and Position: addition/
|
|
9
|
+
subtraction combine into a Portfolio via _position_tuple(), which each
|
|
10
|
+
side implements to describe itself as a tuple of (weighted) legs.
|
|
11
|
+
Internal mixin, not part of the public API. Portfolio must override
|
|
12
|
+
__mul__ specifically (see portfolio.py) to keep the "+/- always
|
|
13
|
+
flatten" invariant for - and unary - too; don't remove that override
|
|
14
|
+
to "simplify" this mixin."""
|
|
15
|
+
|
|
16
|
+
def _position_tuple(self) -> Tuple["Position", ...]:
|
|
17
|
+
raise NotImplementedError
|
|
18
|
+
|
|
19
|
+
def __add__(self, other):
|
|
20
|
+
if not isinstance(other, _Combinable):
|
|
21
|
+
return NotImplemented
|
|
22
|
+
from .portfolio import Portfolio
|
|
23
|
+
return Portfolio(positions=self._position_tuple() + other._position_tuple())
|
|
24
|
+
|
|
25
|
+
def __radd__(self, other):
|
|
26
|
+
# supports sum([call, put, stock]): sum()'s default start=0 calls
|
|
27
|
+
# (0).__add__(instrument) -> NotImplemented -> instrument.__radd__(0)
|
|
28
|
+
if isinstance(other, int) and other == 0:
|
|
29
|
+
return self
|
|
30
|
+
return NotImplemented
|
|
31
|
+
|
|
32
|
+
def __sub__(self, other):
|
|
33
|
+
if not isinstance(other, _Combinable):
|
|
34
|
+
return NotImplemented
|
|
35
|
+
return self + (-other)
|
|
36
|
+
|
|
37
|
+
def __rsub__(self, other):
|
|
38
|
+
if isinstance(other, int) and other == 0:
|
|
39
|
+
return -self
|
|
40
|
+
return NotImplemented
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class Instrument(_Combinable, ABC):
|
|
44
|
+
@abstractmethod
|
|
45
|
+
def price(self) -> PricerResult:
|
|
46
|
+
"""Compute this instrument's own price."""
|
|
47
|
+
pass
|
|
48
|
+
|
|
49
|
+
def _position_tuple(self):
|
|
50
|
+
from .position import Position
|
|
51
|
+
return (Position(self, 1.0),)
|
|
52
|
+
|
|
53
|
+
def __mul__(self, scalar: SupportsFloat):
|
|
54
|
+
try:
|
|
55
|
+
scalar = float(scalar)
|
|
56
|
+
except (TypeError, ValueError):
|
|
57
|
+
return NotImplemented
|
|
58
|
+
from .position import Position
|
|
59
|
+
return Position(self, scalar)
|
|
60
|
+
|
|
61
|
+
def __rmul__(self, scalar):
|
|
62
|
+
return self.__mul__(scalar)
|
|
63
|
+
|
|
64
|
+
def __neg__(self):
|
|
65
|
+
return self * -1.0
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
from typing import Iterable, List, SupportsFloat, Tuple, Union
|
|
2
|
+
|
|
3
|
+
from .instrument import Instrument
|
|
4
|
+
from .position import Position
|
|
5
|
+
from .result import PricerResult
|
|
6
|
+
|
|
7
|
+
# A Portfolio may itself hold Portfolios as positions (portfolio-of-strategies
|
|
8
|
+
# nesting) with no special-case code: Portfolio is an Instrument like any
|
|
9
|
+
# other, price() failure aggregation is already recursive (a nested
|
|
10
|
+
# Portfolio's failure is just "one leg that didn't price"), and self-reference
|
|
11
|
+
# cycles are unreachable through the public API since positions are
|
|
12
|
+
# constructor-only/immutable (no mutator exists to inject a Portfolio into
|
|
13
|
+
# its own positions after construction).
|
|
14
|
+
#
|
|
15
|
+
# Operators (+, -, *, unary -) always flatten to a single flat list of legs,
|
|
16
|
+
# regardless of operand types - only the constructor (Portfolio(positions=
|
|
17
|
+
# [(sub_portfolio, qty)])) produces genuine nesting.
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class Portfolio(Instrument):
|
|
21
|
+
def __init__(
|
|
22
|
+
self,
|
|
23
|
+
positions: Iterable[Union[Position, Tuple[Instrument, SupportsFloat]]] = (),
|
|
24
|
+
) -> None:
|
|
25
|
+
try:
|
|
26
|
+
positions = tuple(positions)
|
|
27
|
+
except TypeError:
|
|
28
|
+
raise TypeError(
|
|
29
|
+
"Positions must be an iterable of Position instances or (instrument, quantity) pairs."
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
resolved: List[Position] = []
|
|
33
|
+
for p in positions:
|
|
34
|
+
if isinstance(p, Position):
|
|
35
|
+
resolved.append(p)
|
|
36
|
+
continue
|
|
37
|
+
try:
|
|
38
|
+
instrument, quantity = p
|
|
39
|
+
except (TypeError, ValueError):
|
|
40
|
+
raise TypeError(
|
|
41
|
+
"Each position must be a Position instance or an (instrument, quantity) pair."
|
|
42
|
+
)
|
|
43
|
+
resolved.append(Position(instrument, quantity))
|
|
44
|
+
|
|
45
|
+
self._positions = tuple(resolved)
|
|
46
|
+
|
|
47
|
+
@property
|
|
48
|
+
def positions(self) -> Tuple[Position, ...]:
|
|
49
|
+
return self._positions
|
|
50
|
+
|
|
51
|
+
def _position_tuple(self):
|
|
52
|
+
return self._positions
|
|
53
|
+
|
|
54
|
+
def __mul__(self, scalar: SupportsFloat):
|
|
55
|
+
# Required override, not optional: without it, Portfolio would
|
|
56
|
+
# inherit Instrument.__mul__/__neg__ unchanged, which wrap the whole
|
|
57
|
+
# portfolio as one nested leg instead of scaling each leg - silently
|
|
58
|
+
# breaking the "+/- always flatten" invariant for - and unary -
|
|
59
|
+
# (since a - b is a + (-b), and negating a Portfolio would otherwise
|
|
60
|
+
# go through the generic wrap-based __neg__).
|
|
61
|
+
try:
|
|
62
|
+
scalar = float(scalar)
|
|
63
|
+
except (TypeError, ValueError):
|
|
64
|
+
return NotImplemented
|
|
65
|
+
return Portfolio(positions=[Position(p.instrument, p.quantity * scalar) for p in self._positions])
|
|
66
|
+
|
|
67
|
+
def price(self) -> PricerResult:
|
|
68
|
+
leg_results: List[Tuple[Position, PricerResult]] = []
|
|
69
|
+
total = 0.0
|
|
70
|
+
n_failed = 0
|
|
71
|
+
|
|
72
|
+
for position in self._positions:
|
|
73
|
+
leg_result = position.instrument.price()
|
|
74
|
+
leg_results.append((position, leg_result))
|
|
75
|
+
if leg_result.priced:
|
|
76
|
+
total += position.quantity * leg_result.price
|
|
77
|
+
else:
|
|
78
|
+
n_failed += 1
|
|
79
|
+
|
|
80
|
+
metadata = {"positions": leg_results}
|
|
81
|
+
|
|
82
|
+
if n_failed:
|
|
83
|
+
return PricerResult.failure(
|
|
84
|
+
pricing_method="quantity-weighted-sum",
|
|
85
|
+
error_msg=f"{n_failed} of {len(self._positions)} position(s) failed to price.",
|
|
86
|
+
metadata=metadata,
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
return PricerResult.success(price=total, pricing_method="quantity-weighted-sum", metadata=metadata)
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
from typing import SupportsFloat
|
|
3
|
+
|
|
4
|
+
from .instrument import Instrument, _Combinable
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
@dataclass(frozen=True)
|
|
8
|
+
class Position(_Combinable):
|
|
9
|
+
"""A quantity-weighted Instrument. * and unary - rescale the existing
|
|
10
|
+
quantity; + combines with another Instrument/Position/Portfolio into a
|
|
11
|
+
flat Portfolio (see Instrument's _Combinable mixin)."""
|
|
12
|
+
|
|
13
|
+
instrument: Instrument
|
|
14
|
+
quantity: SupportsFloat
|
|
15
|
+
|
|
16
|
+
def __post_init__(self) -> None:
|
|
17
|
+
if not isinstance(self.instrument, Instrument):
|
|
18
|
+
raise TypeError("Instrument must be an Instrument instance.")
|
|
19
|
+
try:
|
|
20
|
+
quantity = float(self.quantity)
|
|
21
|
+
except (TypeError, ValueError):
|
|
22
|
+
raise TypeError("Quantity must be a numeric value.")
|
|
23
|
+
object.__setattr__(self, "quantity", quantity)
|
|
24
|
+
|
|
25
|
+
def _position_tuple(self):
|
|
26
|
+
return (self,)
|
|
27
|
+
|
|
28
|
+
def __mul__(self, scalar: SupportsFloat):
|
|
29
|
+
try:
|
|
30
|
+
scalar = float(scalar)
|
|
31
|
+
except (TypeError, ValueError):
|
|
32
|
+
return NotImplemented
|
|
33
|
+
return Position(self.instrument, self.quantity * scalar)
|
|
34
|
+
|
|
35
|
+
def __rmul__(self, scalar):
|
|
36
|
+
return self.__mul__(scalar)
|
|
37
|
+
|
|
38
|
+
def __neg__(self):
|
|
39
|
+
return self * -1.0
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
from dataclasses import dataclass, field
|
|
2
|
+
from typing import Any, Dict, Optional
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
@dataclass(frozen=True)
|
|
6
|
+
class PricerResult:
|
|
7
|
+
price: Optional[float]
|
|
8
|
+
priced: bool
|
|
9
|
+
pricing_method: str
|
|
10
|
+
metadata: Dict[str, Any] = field(default_factory=dict)
|
|
11
|
+
error_msg: Optional[str] = None
|
|
12
|
+
|
|
13
|
+
def __repr__(self) -> str:
|
|
14
|
+
status = "priced" if self.priced else "failed"
|
|
15
|
+
ret = f"{self.pricing_method} {status}\n"
|
|
16
|
+
if self.price is not None:
|
|
17
|
+
ret += f"Price: {self.price:.8g}\n"
|
|
18
|
+
if self.error_msg:
|
|
19
|
+
ret += f"Error: {self.error_msg}\n"
|
|
20
|
+
return ret
|
|
21
|
+
|
|
22
|
+
@classmethod
|
|
23
|
+
def success(cls, price: float, pricing_method: str, metadata: Optional[Dict[str, Any]] = None) -> "PricerResult":
|
|
24
|
+
return cls(price=price, priced=True, pricing_method=pricing_method, metadata=metadata or {})
|
|
25
|
+
|
|
26
|
+
@classmethod
|
|
27
|
+
def failure(cls, pricing_method: str, error_msg: str, metadata: Optional[Dict[str, Any]] = None) -> "PricerResult":
|
|
28
|
+
return cls(price=None, priced=False, pricing_method=pricing_method, error_msg=error_msg, metadata=metadata or {})
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import math
|
|
2
|
+
from typing import Callable, Optional, SupportsFloat
|
|
3
|
+
|
|
4
|
+
from numanlib.interpolation import CubicSpline
|
|
5
|
+
from numanlib.pdes import BlackScholesEquationSolver, ParabolicBCs, ParabolicResult, SpatiotemporalDomain1D
|
|
6
|
+
|
|
7
|
+
from ..core import Instrument, PricerResult
|
|
8
|
+
from .stock import Stock
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class EuropeanOption(Instrument):
|
|
12
|
+
def __init__(self, underlying: Stock, strike: SupportsFloat, maturity: SupportsFloat, option_type: str) -> None:
|
|
13
|
+
self.underlying = underlying
|
|
14
|
+
self.strike = strike
|
|
15
|
+
self.maturity = maturity
|
|
16
|
+
self.option_type = option_type
|
|
17
|
+
|
|
18
|
+
@property
|
|
19
|
+
def underlying(self) -> Stock:
|
|
20
|
+
return self._underlying
|
|
21
|
+
|
|
22
|
+
@underlying.setter
|
|
23
|
+
def underlying(self, value: Stock) -> None:
|
|
24
|
+
if not isinstance(value, Stock):
|
|
25
|
+
raise TypeError("Underlying must be a Stock instance.")
|
|
26
|
+
self._underlying = value
|
|
27
|
+
|
|
28
|
+
@property
|
|
29
|
+
def strike(self) -> float:
|
|
30
|
+
return self._strike
|
|
31
|
+
|
|
32
|
+
@strike.setter
|
|
33
|
+
def strike(self, value: SupportsFloat) -> None:
|
|
34
|
+
try:
|
|
35
|
+
value = float(value)
|
|
36
|
+
except (TypeError, ValueError):
|
|
37
|
+
raise TypeError("Strike must be a numeric value.")
|
|
38
|
+
if value <= 0:
|
|
39
|
+
raise ValueError("Strike must be a positive number.")
|
|
40
|
+
self._strike = value
|
|
41
|
+
|
|
42
|
+
@property
|
|
43
|
+
def maturity(self) -> float:
|
|
44
|
+
return self._maturity
|
|
45
|
+
|
|
46
|
+
@maturity.setter
|
|
47
|
+
def maturity(self, value: SupportsFloat) -> None:
|
|
48
|
+
try:
|
|
49
|
+
value = float(value)
|
|
50
|
+
except (TypeError, ValueError):
|
|
51
|
+
raise TypeError("Maturity must be a numeric value.")
|
|
52
|
+
if value <= 0:
|
|
53
|
+
raise ValueError("Maturity must be a positive number.")
|
|
54
|
+
self._maturity = value
|
|
55
|
+
|
|
56
|
+
@property
|
|
57
|
+
def option_type(self) -> str:
|
|
58
|
+
return self._option_type
|
|
59
|
+
|
|
60
|
+
@option_type.setter
|
|
61
|
+
def option_type(self, value: str) -> None:
|
|
62
|
+
if not isinstance(value, str):
|
|
63
|
+
raise TypeError("Option type must be a string.")
|
|
64
|
+
value = value.lower()
|
|
65
|
+
if value not in ("call", "put"):
|
|
66
|
+
raise ValueError('Option type must be "call" or "put".')
|
|
67
|
+
self._option_type = value
|
|
68
|
+
|
|
69
|
+
@property
|
|
70
|
+
def payoff(self) -> Callable[[SupportsFloat], float]:
|
|
71
|
+
if self.option_type == "call":
|
|
72
|
+
return lambda spot: max(spot - self.strike, 0.0)
|
|
73
|
+
return lambda spot: max(self.strike - spot, 0.0)
|
|
74
|
+
|
|
75
|
+
def solve(
|
|
76
|
+
self,
|
|
77
|
+
*,
|
|
78
|
+
domain: Optional[SpatiotemporalDomain1D] = None,
|
|
79
|
+
m: Optional[int] = None,
|
|
80
|
+
N: Optional[int] = None,
|
|
81
|
+
) -> ParabolicResult:
|
|
82
|
+
if domain is None:
|
|
83
|
+
S_max = 3.0 * max(self.strike, self.underlying.spot)
|
|
84
|
+
domain = SpatiotemporalDomain1D(l=S_max, T=self.maturity)
|
|
85
|
+
if m is None:
|
|
86
|
+
m = 100
|
|
87
|
+
if N is None:
|
|
88
|
+
N = 50
|
|
89
|
+
|
|
90
|
+
r = self.underlying.rate
|
|
91
|
+
sigma = self.underlying.volatility
|
|
92
|
+
|
|
93
|
+
if self.option_type == "call":
|
|
94
|
+
boundary_conditions = ParabolicBCs(
|
|
95
|
+
g0=lambda t: 0.0,
|
|
96
|
+
g1=lambda t: domain.l - self.strike * math.exp(-r * (self.maturity - t)),
|
|
97
|
+
)
|
|
98
|
+
else:
|
|
99
|
+
boundary_conditions = ParabolicBCs(
|
|
100
|
+
g0=lambda t: self.strike * math.exp(-r * (self.maturity - t)),
|
|
101
|
+
g1=lambda t: 0.0,
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
solver = BlackScholesEquationSolver(
|
|
105
|
+
domain, r=r, sigma=sigma,
|
|
106
|
+
terminal_condition=self.payoff,
|
|
107
|
+
boundary_conditions=boundary_conditions,
|
|
108
|
+
m=m, N=N, method="backward-difference",
|
|
109
|
+
)
|
|
110
|
+
return solver.solve()
|
|
111
|
+
|
|
112
|
+
def price(self) -> PricerResult:
|
|
113
|
+
result = self.solve()
|
|
114
|
+
|
|
115
|
+
if not result.solved:
|
|
116
|
+
return PricerResult.failure(
|
|
117
|
+
pricing_method="black-scholes-pde",
|
|
118
|
+
error_msg=result.error_msg,
|
|
119
|
+
metadata={"parabolic_result": result},
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
spline = CubicSpline(result.grid_x, result.solution[:, 0]).interpolate()
|
|
123
|
+
price = spline(self.underlying.spot)
|
|
124
|
+
|
|
125
|
+
return PricerResult.success(
|
|
126
|
+
price=price,
|
|
127
|
+
pricing_method="black-scholes-pde",
|
|
128
|
+
metadata={"parabolic_result": result},
|
|
129
|
+
)
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
from typing import Optional
|
|
2
|
+
|
|
3
|
+
from numanlib.pdes import ParabolicResult, SpatiotemporalDomain1D
|
|
4
|
+
|
|
5
|
+
from ..core import Portfolio
|
|
6
|
+
from .option import EuropeanOption
|
|
7
|
+
from .stock import Stock
|
|
8
|
+
|
|
9
|
+
# Lives here (not core/portfolio.py) deliberately: combining grids requires
|
|
10
|
+
# knowing about EuropeanOption/Stock specifically (strikes, underlying, PDE
|
|
11
|
+
# domains), and fiqua.core must stay equities-agnostic - the same separation
|
|
12
|
+
# CLAUDE.md establishes between numanlib (generic) and fiqua (financial
|
|
13
|
+
# domain). Portfolio itself is untouched; this is a standalone function that
|
|
14
|
+
# operates on a plain Portfolio from outside.
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def portfolio_surface(
|
|
18
|
+
portfolio: Portfolio,
|
|
19
|
+
*,
|
|
20
|
+
domain: Optional[SpatiotemporalDomain1D] = None,
|
|
21
|
+
m: Optional[int] = None,
|
|
22
|
+
N: Optional[int] = None,
|
|
23
|
+
) -> ParabolicResult:
|
|
24
|
+
positions = portfolio.positions
|
|
25
|
+
|
|
26
|
+
option_positions = [p for p in positions if isinstance(p.instrument, EuropeanOption)]
|
|
27
|
+
non_option_positions = [p for p in positions if not isinstance(p.instrument, EuropeanOption)]
|
|
28
|
+
for p in non_option_positions:
|
|
29
|
+
if not isinstance(p.instrument, Stock):
|
|
30
|
+
raise TypeError("Portfolio surface requires only EuropeanOption and Stock positions.")
|
|
31
|
+
|
|
32
|
+
if not option_positions:
|
|
33
|
+
raise ValueError("Portfolio surface requires at least one EuropeanOption position.")
|
|
34
|
+
|
|
35
|
+
shared_underlying = option_positions[0].instrument.underlying
|
|
36
|
+
shared_maturity = option_positions[0].instrument.maturity
|
|
37
|
+
for p in option_positions:
|
|
38
|
+
if p.instrument.underlying is not shared_underlying:
|
|
39
|
+
raise ValueError("All EuropeanOption positions must share the same underlying.")
|
|
40
|
+
if p.instrument.maturity != shared_maturity:
|
|
41
|
+
raise ValueError("All EuropeanOption positions must share the same maturity.")
|
|
42
|
+
for p in non_option_positions:
|
|
43
|
+
if p.instrument is not shared_underlying:
|
|
44
|
+
raise ValueError("All Stock positions must be the shared underlying.")
|
|
45
|
+
|
|
46
|
+
if domain is None:
|
|
47
|
+
S_max = 3.0 * max(max(p.instrument.strike for p in option_positions), shared_underlying.spot)
|
|
48
|
+
domain = SpatiotemporalDomain1D(l=S_max, T=shared_maturity)
|
|
49
|
+
m = 100 if m is None else m
|
|
50
|
+
N = 50 if N is None else N
|
|
51
|
+
|
|
52
|
+
results_by_index = [None] * len(positions)
|
|
53
|
+
combined_solution = None
|
|
54
|
+
grid_x = grid_t = None
|
|
55
|
+
|
|
56
|
+
for i, p in enumerate(positions):
|
|
57
|
+
if not isinstance(p.instrument, EuropeanOption):
|
|
58
|
+
continue
|
|
59
|
+
leg_result = p.instrument.solve(domain=domain, m=m, N=N)
|
|
60
|
+
results_by_index[i] = leg_result
|
|
61
|
+
if not leg_result.solved:
|
|
62
|
+
return ParabolicResult.failure(
|
|
63
|
+
grid_x=leg_result.grid_x,
|
|
64
|
+
grid_t=leg_result.grid_t,
|
|
65
|
+
method_name="portfolio-quantity-weighted-sum",
|
|
66
|
+
error_msg=leg_result.error_msg,
|
|
67
|
+
metadata={"failed_position": p, "failed_result": leg_result},
|
|
68
|
+
)
|
|
69
|
+
grid_x, grid_t = leg_result.grid_x, leg_result.grid_t
|
|
70
|
+
contribution = p.quantity * leg_result.solution
|
|
71
|
+
combined_solution = contribution if combined_solution is None else combined_solution + contribution
|
|
72
|
+
|
|
73
|
+
for i, p in enumerate(positions):
|
|
74
|
+
if isinstance(p.instrument, Stock):
|
|
75
|
+
combined_solution = combined_solution + p.quantity * grid_x[:, None]
|
|
76
|
+
|
|
77
|
+
metadata = {"positions": list(zip(positions, results_by_index))}
|
|
78
|
+
return ParabolicResult.success(combined_solution, grid_x, grid_t, "portfolio-quantity-weighted-sum", metadata=metadata)
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
from typing import Optional, SupportsFloat
|
|
2
|
+
|
|
3
|
+
from ..core import Instrument, PricerResult
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class Stock(Instrument):
|
|
7
|
+
def __init__(
|
|
8
|
+
self,
|
|
9
|
+
spot: SupportsFloat,
|
|
10
|
+
rate: SupportsFloat,
|
|
11
|
+
volatility: SupportsFloat,
|
|
12
|
+
symbol: Optional[str] = None,
|
|
13
|
+
) -> None:
|
|
14
|
+
self.spot = spot
|
|
15
|
+
self.rate = rate
|
|
16
|
+
self.volatility = volatility
|
|
17
|
+
self.symbol = symbol
|
|
18
|
+
|
|
19
|
+
@property
|
|
20
|
+
def spot(self) -> float:
|
|
21
|
+
return self._spot
|
|
22
|
+
|
|
23
|
+
@spot.setter
|
|
24
|
+
def spot(self, value: SupportsFloat) -> None:
|
|
25
|
+
try:
|
|
26
|
+
value = float(value)
|
|
27
|
+
except (TypeError, ValueError):
|
|
28
|
+
raise TypeError("Spot must be a numeric value.")
|
|
29
|
+
if value <= 0:
|
|
30
|
+
raise ValueError("Spot must be a positive number.")
|
|
31
|
+
self._spot = value
|
|
32
|
+
|
|
33
|
+
@property
|
|
34
|
+
def rate(self) -> float:
|
|
35
|
+
return self._rate
|
|
36
|
+
|
|
37
|
+
@rate.setter
|
|
38
|
+
def rate(self, value: SupportsFloat) -> None:
|
|
39
|
+
# Modeled per-stock for now (bundled with spot/volatility as "this
|
|
40
|
+
# underlying's assumed risk-neutral process"), even though a risk-free
|
|
41
|
+
# rate is really a funding-curve concept shared across a whole
|
|
42
|
+
# portfolio, not specific to any one stock. Revisit if/when a shared
|
|
43
|
+
# market-data abstraction is introduced. No positivity check: real
|
|
44
|
+
# risk-free rates can be negative.
|
|
45
|
+
try:
|
|
46
|
+
value = float(value)
|
|
47
|
+
except (TypeError, ValueError):
|
|
48
|
+
raise TypeError("Rate must be a numeric value.")
|
|
49
|
+
self._rate = value
|
|
50
|
+
|
|
51
|
+
@property
|
|
52
|
+
def volatility(self) -> float:
|
|
53
|
+
return self._volatility
|
|
54
|
+
|
|
55
|
+
@volatility.setter
|
|
56
|
+
def volatility(self, value: SupportsFloat) -> None:
|
|
57
|
+
try:
|
|
58
|
+
value = float(value)
|
|
59
|
+
except (TypeError, ValueError):
|
|
60
|
+
raise TypeError("Volatility must be a numeric value.")
|
|
61
|
+
if value <= 0:
|
|
62
|
+
raise ValueError("Volatility must be a positive number.")
|
|
63
|
+
self._volatility = value
|
|
64
|
+
|
|
65
|
+
def price(self) -> PricerResult:
|
|
66
|
+
return PricerResult.success(price=self.spot, pricing_method="market-observed")
|
|
File without changes
|