samplepaths 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.
Files changed (55) hide show
  1. samplepaths/__init__.py +96 -0
  2. samplepaths/base/__init__.py +11 -0
  3. samplepaths/base/base_process.py +52 -0
  4. samplepaths/base/base_sequence_process.py +10 -0
  5. samplepaths/base/base_time_process.py +124 -0
  6. samplepaths/continuous/__init__.py +37 -0
  7. samplepaths/continuous/bessel_process.py +87 -0
  8. samplepaths/continuous/brownian_bridge.py +93 -0
  9. samplepaths/continuous/brownian_excursion.py +99 -0
  10. samplepaths/continuous/brownian_meander.py +148 -0
  11. samplepaths/continuous/brownian_motion.py +116 -0
  12. samplepaths/continuous/cauchy_process.py +106 -0
  13. samplepaths/continuous/fractional_brownian_motion.py +58 -0
  14. samplepaths/continuous/gamma_process.py +162 -0
  15. samplepaths/continuous/geometric_brownian_motion.py +166 -0
  16. samplepaths/continuous/inverse_gaussian_process.py +193 -0
  17. samplepaths/continuous/mixed_poisson_process.py +114 -0
  18. samplepaths/continuous/multifractional_brownian_motion.py +128 -0
  19. samplepaths/continuous/poisson_process.py +114 -0
  20. samplepaths/continuous/squared_bessel_process.py +61 -0
  21. samplepaths/continuous/variance_gamma_process.py +156 -0
  22. samplepaths/continuous/wiener_process.py +36 -0
  23. samplepaths/diffusion/__init__.py +17 -0
  24. samplepaths/diffusion/constant_elasticity_variance_process.py +81 -0
  25. samplepaths/diffusion/cox_ingersoll_ross_process.py +70 -0
  26. samplepaths/diffusion/diffusion_process.py +175 -0
  27. samplepaths/diffusion/extended_vasicek_process.py +72 -0
  28. samplepaths/diffusion/ornstein_uhlenbeck_process.py +61 -0
  29. samplepaths/diffusion/vasicek_process.py +66 -0
  30. samplepaths/discrete/__init__.py +17 -0
  31. samplepaths/discrete/bernoulli_process.py +78 -0
  32. samplepaths/discrete/chinese_restaurant_process.py +194 -0
  33. samplepaths/discrete/dirichlet_process.py +97 -0
  34. samplepaths/discrete/markov_chain.py +131 -0
  35. samplepaths/discrete/moran_process.py +122 -0
  36. samplepaths/discrete/random_walk.py +115 -0
  37. samplepaths/noise/__init__.py +25 -0
  38. samplepaths/noise/colored/__init__.py +19 -0
  39. samplepaths/noise/colored/blue_noise.py +32 -0
  40. samplepaths/noise/colored/brownian_noise.py +18 -0
  41. samplepaths/noise/colored/colored_noise.py +120 -0
  42. samplepaths/noise/colored/pink_noise.py +32 -0
  43. samplepaths/noise/colored/red_noise.py +32 -0
  44. samplepaths/noise/colored/violet_noise.py +32 -0
  45. samplepaths/noise/colored/white_noise.py +32 -0
  46. samplepaths/noise/fractional_gaussian_noise.py +219 -0
  47. samplepaths/noise/gaussian_noise.py +78 -0
  48. samplepaths/py.typed +0 -0
  49. samplepaths/random.py +50 -0
  50. samplepaths/utils/__init__.py +48 -0
  51. samplepaths/utils/validation.py +176 -0
  52. samplepaths-0.1.0.dist-info/METADATA +159 -0
  53. samplepaths-0.1.0.dist-info/RECORD +55 -0
  54. samplepaths-0.1.0.dist-info/WHEEL +4 -0
  55. samplepaths-0.1.0.dist-info/licenses/LICENSE +22 -0
@@ -0,0 +1,114 @@
1
+ """Poisson process."""
2
+
3
+ from typing import override
4
+
5
+ import numpy as np
6
+ import numpy.typing as npt
7
+ from numpy.random import Generator
8
+
9
+ from ..base import BaseProcess
10
+ from ..utils.validation import (
11
+ check_nonnegative_number,
12
+ check_positive_integer,
13
+ check_positive_number,
14
+ )
15
+
16
+
17
+ class PoissonProcess(BaseProcess):
18
+ r"""Poisson process.
19
+
20
+ .. image:: /_static/poisson_process.png
21
+ :scale: 50%
22
+
23
+ A Poisson process with rate :math:`\lambda` is a count of occurrences of
24
+ i.i.d. exponential random variables with mean :math:`1/\lambda`. This class
25
+ generates samples of times for which cumulative exponential random
26
+ variables occur.
27
+
28
+ :param rate: the parameter :math:`\lambda` which defines the rate of
29
+ occurrences of the process
30
+ :param rng: a custom random number generator
31
+ """
32
+
33
+ def __init__(
34
+ self,
35
+ *,
36
+ rate: float = 1.0,
37
+ rng: Generator | None = None,
38
+ ) -> None:
39
+ super().__init__(rng=rng)
40
+
41
+ self.rate = rate
42
+
43
+ def __str__(self) -> str:
44
+ return f"Poisson process with rate {self.rate}."
45
+
46
+ def __repr__(self) -> str:
47
+ return f"PoissonProcess(rate={self.rate})"
48
+
49
+ @property
50
+ def rate(self) -> float:
51
+ """Rate parameter."""
52
+ return self.__rate
53
+
54
+ @rate.setter
55
+ def rate(self, value: float) -> None:
56
+ check_nonnegative_number(value=value, name="Arrival rate")
57
+
58
+ self.__rate = value
59
+
60
+ def _sample_poisson_process(
61
+ self,
62
+ n: int | None = None,
63
+ length: float | None = None,
64
+ ) -> npt.NDArray[np.float64]:
65
+ """Generate a realization of a Poisson process.
66
+
67
+ Generate a poisson process sample up to count of length if time=False,
68
+ otherwise generate a sample up to time t=length if time=True
69
+ """
70
+ if n is not None:
71
+ check_positive_integer(n=n)
72
+
73
+ exponentials = self.rng.exponential(
74
+ scale=1.0 / self.rate,
75
+ size=n,
76
+ )
77
+
78
+ s = np.array([0.0] + list(np.cumsum(exponentials)))
79
+
80
+ return s
81
+
82
+ if length is not None:
83
+ check_positive_number(value=length, name="Sample length")
84
+
85
+ t = 0.0
86
+ times = [0.0]
87
+ exp_rate = 1.0 / self.rate
88
+
89
+ while t < length:
90
+ t += self.rng.exponential(scale=exp_rate)
91
+ times.append(t)
92
+
93
+ return np.array(times)
94
+
95
+ raise ValueError("Must provide either argument n or length.")
96
+
97
+ @override
98
+ def sample(
99
+ self,
100
+ n: int,
101
+ ) -> npt.NDArray[np.float64]:
102
+ return self._sample_poisson_process(n=n)
103
+
104
+ def sample_with_length(
105
+ self,
106
+ length: float,
107
+ ) -> npt.NDArray[np.float64]:
108
+ """Generate the arrival times over a length of time.
109
+
110
+ :param length: the length of time to simulate
111
+ :returns: the arrival times, starting at zero and ending with the first
112
+ arrival after ``length``
113
+ """
114
+ return self._sample_poisson_process(length=length)
@@ -0,0 +1,61 @@
1
+ """Squared Bessel process."""
2
+
3
+ from typing import override
4
+
5
+ import numpy as np
6
+ import numpy.typing as npt
7
+
8
+ from ..utils.validation import check_positive_integer
9
+ from .bessel_process import BesselProcess
10
+
11
+
12
+ class SquaredBesselProcess(BesselProcess):
13
+ r"""Squared Bessel process.
14
+
15
+ .. image:: /_static/squared_bessel_process.png
16
+ :scale: 50%
17
+
18
+ The square of a Bessel process: :math:`\|\mathbf{W}_t\|^2`.
19
+
20
+ The Bessel process is the Euclidean norm of an :math:`n`-dimensional
21
+ Wiener process, e.g. :math:`\|\mathbf{W}_t\|`
22
+
23
+ :param dim: the number of underlying independent Brownian motions to
24
+ use
25
+ :param t: the right hand endpoint of the time interval :math:`[0,t]`
26
+ for the process
27
+ """
28
+
29
+ def __str__(self) -> str:
30
+ return f"Squared Bessel process of {self.dim} Wiener processes on [0, {self.t}]"
31
+
32
+ def __repr__(self) -> str:
33
+ return f"SquaredBesselProcess(dim={self.dim}, t={self.t})"
34
+
35
+ def _sample_squared_bessel_process(
36
+ self,
37
+ n: int,
38
+ ) -> npt.NDArray[np.float64]:
39
+ """Generate a realization of a squared Bessel process."""
40
+ check_positive_integer(n=n)
41
+
42
+ samples = [self._sample_brownian_motion(n) for _ in range(self.dim)]
43
+
44
+ return np.array([sum(map(lambda x: x**2, coord)) for coord in zip(*samples, strict=True)])
45
+
46
+ def _sample_squared_bessel_process_at(
47
+ self,
48
+ times: npt.NDArray[np.float64],
49
+ ) -> npt.NDArray[np.float64]:
50
+ """Generate a realization of a squared Bessel process."""
51
+ samples = [self._sample_brownian_motion_at(times) for _ in range(self.dim)]
52
+
53
+ return np.array([sum(map(lambda x: x**2, coord)) for coord in zip(*samples, strict=True)])
54
+
55
+ @override
56
+ def sample(self, n: int) -> npt.NDArray[np.float64]:
57
+ return self._sample_squared_bessel_process(n)
58
+
59
+ @override
60
+ def sample_at(self, times: npt.NDArray[np.float64]) -> npt.NDArray[np.float64]:
61
+ return self._sample_squared_bessel_process_at(times)
@@ -0,0 +1,156 @@
1
+ """Variance Gamma process."""
2
+
3
+ from typing import override
4
+
5
+ import numpy as np
6
+ import numpy.typing as npt
7
+ from numpy.random import Generator
8
+
9
+ from ..noise import GaussianNoise
10
+ from ..utils.validation import (
11
+ check_numeric,
12
+ check_positive_integer,
13
+ check_positive_number,
14
+ )
15
+
16
+
17
+ class VarianceGammaProcess(GaussianNoise):
18
+ r"""Variance Gamma process.
19
+
20
+ .. image:: /_static/variance_gamma_process.png
21
+ :scale: 50%
22
+
23
+ A variance gamma process has independent increments which follow the
24
+ variance-gamma distribution. It can be represented as a Brownian motion
25
+ with drift subordinated by a Gamma process:
26
+
27
+ .. math::
28
+
29
+ \theta \Gamma(t; 1, \nu) + \sigma W(\Gamma(t; 1, \nu))
30
+
31
+ :param drift: the drift parameter of the Brownian motion,
32
+ or :math:`\theta` above
33
+ :param variance: the variance parameter of the Gamma subordinator,
34
+ or :math:`\nu` above
35
+ :param scale: the scale parameter of the Brownian motion,
36
+ or :math:`\sigma` above
37
+ :param t: the right hand endpoint of the time interval :math:`[0,t]`
38
+ for the process
39
+ :param rng: a custom random number generator
40
+ """
41
+
42
+ def __init__(
43
+ self,
44
+ *,
45
+ drift: float = 0.0,
46
+ variance: float = 1.0,
47
+ scale: float = 1.0,
48
+ t: float = 1.0,
49
+ rng: Generator | None = None,
50
+ ) -> None:
51
+ super().__init__(t=t, rng=rng)
52
+
53
+ self.drift = drift
54
+ self.variance = variance
55
+ self.scale = scale
56
+
57
+ def __str__(self) -> str:
58
+ return (
59
+ f"Variance Gamma process on interval [0, {self.t}] with drift "
60
+ f"{self.drift}, variance {self.variance}, and scale {self.scale}."
61
+ )
62
+
63
+ def __repr__(self) -> str:
64
+ return (
65
+ f"VarianceGammaProcess(drift={self.drift}, variance={self.variance}, "
66
+ f"scale={self.scale}, t={self.t})"
67
+ )
68
+
69
+ @property
70
+ def drift(self) -> float:
71
+ """Drift parameter."""
72
+ return self.__drift
73
+
74
+ @drift.setter
75
+ def drift(self, value: float) -> None:
76
+ check_numeric(value=value, name="Drift")
77
+
78
+ self.__drift = value
79
+
80
+ @property
81
+ def variance(self) -> float:
82
+ """Variance parameter."""
83
+ return self.__variance
84
+
85
+ @variance.setter
86
+ def variance(self, value: float) -> None:
87
+ check_positive_number(value=value, name="Variance")
88
+ self.__variance = value
89
+
90
+ @property
91
+ def scale(self) -> float:
92
+ """Scale parameter."""
93
+ return self.__scale
94
+
95
+ @scale.setter
96
+ def scale(self, value: float) -> None:
97
+ check_positive_number(value=value, name="Scale")
98
+ self.__scale = value
99
+
100
+ def _sample_variance_gamma_process(self, n: int) -> npt.NDArray[np.float64]:
101
+ """Generate a realization of a variance gamma process."""
102
+ check_positive_integer(n=n, name="n")
103
+
104
+ delta_t = 1.0 * self.t / n
105
+ shape = delta_t / self.variance
106
+ scale = self.variance
107
+
108
+ gammas = self.rng.gamma(shape=shape, scale=scale, size=n)
109
+ gn = super().sample(n)
110
+
111
+ increments = self.drift * gammas + self.scale * np.sqrt(gammas) * gn
112
+
113
+ samples = np.cumsum(increments)
114
+
115
+ return np.concatenate(([0], samples))
116
+
117
+ def _sample_variance_gamma_process_at(
118
+ self,
119
+ times: npt.NDArray[np.float64],
120
+ ) -> npt.NDArray[np.float64]:
121
+ """Generate a realization of a variance gamma process."""
122
+ if times[0] != 0:
123
+ zero = False
124
+ times = np.array([0] + list(times))
125
+ else:
126
+ zero = True
127
+
128
+ shapes = np.diff(times) / self.variance
129
+ scale = self.variance
130
+
131
+ gammas = np.array(
132
+ [
133
+ self.rng.gamma(
134
+ shape=shape,
135
+ scale=scale,
136
+ size=1,
137
+ )[0]
138
+ for shape in shapes
139
+ ]
140
+ )
141
+ gn = super().sample_at(times)
142
+
143
+ increments = self.drift * gammas + self.scale * np.sqrt(gammas) * gn
144
+
145
+ samples = np.cumsum(increments)
146
+ if zero:
147
+ samples = np.insert(samples, 0, [0])
148
+ return samples
149
+
150
+ @override
151
+ def sample(self, n: int) -> npt.NDArray[np.float64]:
152
+ return self._sample_variance_gamma_process(n)
153
+
154
+ @override
155
+ def sample_at(self, times: npt.NDArray[np.float64]) -> npt.NDArray[np.float64]:
156
+ return self._sample_variance_gamma_process_at(times)
@@ -0,0 +1,36 @@
1
+ """Wiener process, or standard Brownian motion."""
2
+
3
+ from numpy.random import Generator
4
+
5
+ from .brownian_motion import BrownianMotion
6
+
7
+
8
+ class WienerProcess(BrownianMotion):
9
+ """Wiener process, or standard Brownian motion.
10
+
11
+ .. image:: /_static/wiener_process.png
12
+ :scale: 50%
13
+
14
+ :param t: the right hand endpoint of the time interval :math:`[0,t]`
15
+ for the process
16
+ :param rng: a custom random number generator
17
+ """
18
+
19
+ def __init__(
20
+ self,
21
+ *,
22
+ t: float = 1.0,
23
+ rng: Generator | None = None,
24
+ ) -> None:
25
+ super().__init__(
26
+ drift=0.0,
27
+ scale=1.0,
28
+ t=t,
29
+ rng=rng,
30
+ )
31
+
32
+ def __str__(self) -> str:
33
+ return f"Wiener process on [0, {self.t}]"
34
+
35
+ def __repr__(self) -> str:
36
+ return f"WienerProcess(t={self.t})"
@@ -0,0 +1,17 @@
1
+ """Diffusion processes, sampled with the Euler-Maruyama method."""
2
+
3
+ from .constant_elasticity_variance_process import ConstantElasticityVarianceProcess
4
+ from .cox_ingersoll_ross_process import CoxIngersollRossProcess
5
+ from .diffusion_process import DiffusionProcess
6
+ from .extended_vasicek_process import ExtendedVasicekProcess
7
+ from .ornstein_uhlenbeck_process import OrnsteinUhlenbeckProcess
8
+ from .vasicek_process import VasicekProcess
9
+
10
+ __all__ = [
11
+ "ConstantElasticityVarianceProcess",
12
+ "CoxIngersollRossProcess",
13
+ "DiffusionProcess",
14
+ "ExtendedVasicekProcess",
15
+ "OrnsteinUhlenbeckProcess",
16
+ "VasicekProcess",
17
+ ]
@@ -0,0 +1,81 @@
1
+ """Constant elasticity of variance process."""
2
+
3
+ from collections.abc import Callable
4
+
5
+ from numpy.random import Generator
6
+
7
+ from ..utils import ensure_single_arg_constant_function
8
+ from ..utils.validation import check_numeric
9
+ from .diffusion_process import DiffusionProcess
10
+
11
+
12
+ class ConstantElasticityVarianceProcess(DiffusionProcess):
13
+ r"""Constant elasticity of variance process.
14
+
15
+ .. image:: /_static/constant_elasticity_variance_process.png
16
+ :scale: 50%
17
+
18
+ The process :math:`X_t` that satisfies the following stochastic
19
+ differential equation with Wiener process :math:`W_t`:
20
+
21
+ .. math::
22
+
23
+ dX_t = \mu X_t dt + \sigma X_t^\gamma dW_t
24
+
25
+ Realizations are generated using the Euler-Maruyama method.
26
+
27
+ .. note::
28
+
29
+ Since the family of diffusion processes have parameters which
30
+ generalize to functions of ``t``, parameter attributes will be returned
31
+ as callables, even if they are initialized as constants. e.g. a
32
+ ``speed`` parameter of 1 accessed from an instance attribute will return
33
+ a function which accepts a single argument and always returns 1.
34
+
35
+ :param drift: the drift coefficient, or :math:`\mu` above
36
+ :param vol: the volatility coefficient, or :math:`\sigma` above
37
+ :param volexp: the volatility-price exponent, or :math:`\gamma` above
38
+ :param t: the right hand endpoint of the time interval :math:`[0,t]`
39
+ for the process
40
+ :param rng: a custom random number generator
41
+ """
42
+
43
+ def __init__(
44
+ self,
45
+ *,
46
+ drift: float = 1.0,
47
+ vol: float = 1.0,
48
+ volexp: float = 1.0,
49
+ t: float = 1.0,
50
+ rng: Generator | None = None,
51
+ ) -> None:
52
+ super().__init__(
53
+ speed=-drift,
54
+ mean=1.0,
55
+ vol=vol,
56
+ volexp=volexp,
57
+ t=t,
58
+ rng=rng,
59
+ )
60
+
61
+ def __str__(self) -> str:
62
+ return (
63
+ f"Constant elasticity of variance process with drift={self.drift}, "
64
+ f"vol={self.vol}, volexp={self.volexp} on [0, {self.t}]"
65
+ )
66
+
67
+ def __repr__(self) -> str:
68
+ return (
69
+ f"ConstantElasticityVarianceProcess(drift={self.drift}, vol={self.vol}, "
70
+ f"volexp={self.volexp}, t={self.t})"
71
+ )
72
+
73
+ @property
74
+ def drift(self) -> Callable[[float], float]:
75
+ """Drift, or Mu."""
76
+ return lambda t: -self.speed(t)
77
+
78
+ @drift.setter
79
+ def drift(self, value: float) -> None:
80
+ check_numeric(value=value, name="Drift coefficient.")
81
+ self.speed = ensure_single_arg_constant_function(value=-value)
@@ -0,0 +1,70 @@
1
+ """Cox-Ingersoll-Ross process."""
2
+
3
+ from numpy.random import Generator
4
+
5
+ from .diffusion_process import DiffusionProcess
6
+
7
+
8
+ class CoxIngersollRossProcess(DiffusionProcess):
9
+ r"""Cox-Ingersoll-Ross process.
10
+
11
+ .. image:: /_static/cox_ingersoll_ross_process.png
12
+ :scale: 50%
13
+
14
+ A model for instantaneous interest rate.
15
+
16
+ The process :math:`X_t` that satisfies the following stochastic
17
+ differential equation with Wiener process :math:`W_t`:
18
+
19
+ .. math::
20
+
21
+ dX_t = \theta (\mu - X_t) dt + \sigma \sqrt{X_t} dW_t
22
+
23
+ Realizations are generated using the Euler-Maruyama method.
24
+
25
+ .. note::
26
+
27
+ Since the family of diffusion processes have parameters which
28
+ generalize to functions of ``t``, parameter attributes will be returned
29
+ as callables, even if they are initialized as constants. e.g. a
30
+ ``speed`` parameter of 1 accessed from an instance attribute will return
31
+ a function which accepts a single argument and always returns 1.
32
+
33
+ :param speed: the speed of reversion, or :math:`\theta` above
34
+ :param mean: the mean of the process, or :math:`\mu` above
35
+ :param vol: volatility coefficient of the process, or :math:`\sigma`
36
+ above
37
+ :param t: the right hand endpoint of the time interval :math:`[0,t]`
38
+ for the process
39
+ :param rng: a custom random number generator
40
+ """
41
+
42
+ def __init__(
43
+ self,
44
+ *,
45
+ speed: float = 1.0,
46
+ mean: float = 0.0,
47
+ vol: float = 1.0,
48
+ t: float = 1.0,
49
+ rng: Generator | None = None,
50
+ ) -> None:
51
+ super().__init__(
52
+ speed=speed,
53
+ mean=mean,
54
+ vol=vol,
55
+ volexp=0.5,
56
+ t=t,
57
+ rng=rng,
58
+ )
59
+
60
+ def __str__(self) -> str:
61
+ return (
62
+ f"Cox-Ingersoll-Ross process with speed={self.speed}, mean={self.mean}, "
63
+ f"vol={self.vol} on [0, {self.t}]"
64
+ )
65
+
66
+ def __repr__(self) -> str:
67
+ return (
68
+ f"CoxIngersollRossProcess(speed={self.speed}, mean={self.mean}, "
69
+ f"vol={self.vol}, t={self.t})"
70
+ )