samplepaths 0.2.0__tar.gz → 0.3.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.
Files changed (113) hide show
  1. {samplepaths-0.2.0 → samplepaths-0.3.0}/PKG-INFO +23 -4
  2. {samplepaths-0.2.0 → samplepaths-0.3.0}/README.md +22 -3
  3. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/base/base_process.py +32 -0
  4. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/base/base_time_process.py +10 -0
  5. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/continuous/bessel_process.py +7 -0
  6. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/continuous/brownian_bridge.py +11 -0
  7. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/continuous/brownian_excursion.py +14 -0
  8. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/continuous/brownian_meander.py +18 -1
  9. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/continuous/brownian_motion.py +17 -0
  10. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/continuous/cauchy_process.py +23 -0
  11. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/continuous/fractional_brownian_motion.py +5 -0
  12. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/continuous/gamma_process.py +14 -0
  13. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/continuous/geometric_brownian_motion.py +35 -0
  14. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/continuous/inverse_gaussian_process.py +32 -9
  15. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/continuous/mixed_poisson_process.py +7 -0
  16. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/continuous/multifractional_brownian_motion.py +60 -11
  17. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/continuous/poisson_process.py +8 -0
  18. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/continuous/squared_bessel_process.py +7 -0
  19. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/continuous/variance_gamma_process.py +16 -0
  20. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/diffusion/constant_elasticity_variance_process.py +1 -2
  21. samplepaths-0.3.0/src/samplepaths/diffusion/diffusion_process.py +307 -0
  22. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/discrete/bernoulli_process.py +7 -0
  23. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/discrete/chinese_restaurant_process.py +34 -1
  24. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/discrete/markov_chain.py +38 -0
  25. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/discrete/moran_process.py +14 -0
  26. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/discrete/random_walk.py +11 -0
  27. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/noise/colored/colored_noise.py +40 -6
  28. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/noise/fractional_gaussian_noise.py +85 -20
  29. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/noise/gaussian_noise.py +12 -0
  30. samplepaths-0.3.0/tests/diffusion/test_constant_elasticity_variance_process.py +23 -0
  31. samplepaths-0.3.0/tests/diffusion/test_diffusion_process.py +198 -0
  32. samplepaths-0.3.0/tests/test_sample_paths.py +248 -0
  33. samplepaths-0.2.0/src/samplepaths/diffusion/diffusion_process.py +0 -175
  34. samplepaths-0.2.0/tests/diffusion/test_constant_elasticity_variance_process.py +0 -10
  35. samplepaths-0.2.0/tests/diffusion/test_diffusion_process.py +0 -95
  36. {samplepaths-0.2.0 → samplepaths-0.3.0}/.gitignore +0 -0
  37. {samplepaths-0.2.0 → samplepaths-0.3.0}/LICENSE +0 -0
  38. {samplepaths-0.2.0 → samplepaths-0.3.0}/pyproject.toml +0 -0
  39. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/__init__.py +0 -0
  40. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/base/__init__.py +0 -0
  41. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/base/base_sequence_process.py +0 -0
  42. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/continuous/__init__.py +0 -0
  43. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/continuous/wiener_process.py +0 -0
  44. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/diffusion/__init__.py +0 -0
  45. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/diffusion/cox_ingersoll_ross_process.py +0 -0
  46. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/diffusion/extended_vasicek_process.py +0 -0
  47. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/diffusion/ornstein_uhlenbeck_process.py +0 -0
  48. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/diffusion/vasicek_process.py +0 -0
  49. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/discrete/__init__.py +0 -0
  50. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/discrete/dirichlet_process.py +0 -0
  51. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/noise/__init__.py +0 -0
  52. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/noise/colored/__init__.py +0 -0
  53. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/noise/colored/blue_noise.py +0 -0
  54. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/noise/colored/brownian_noise.py +0 -0
  55. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/noise/colored/pink_noise.py +0 -0
  56. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/noise/colored/red_noise.py +0 -0
  57. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/noise/colored/violet_noise.py +0 -0
  58. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/noise/colored/white_noise.py +0 -0
  59. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/py.typed +0 -0
  60. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/random.py +0 -0
  61. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/utils/__init__.py +0 -0
  62. {samplepaths-0.2.0 → samplepaths-0.3.0}/src/samplepaths/utils/validation.py +0 -0
  63. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/__init__.py +0 -0
  64. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/base/__init__.py +0 -0
  65. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/base/test_base_process.py +0 -0
  66. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/base/test_base_sequence_process.py +0 -0
  67. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/base/test_base_time_process.py +0 -0
  68. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/continuous/__init__.py +0 -0
  69. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/continuous/test_bessel_process.py +0 -0
  70. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/continuous/test_brownian_bridge.py +0 -0
  71. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/continuous/test_brownian_excursion.py +0 -0
  72. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/continuous/test_brownian_meander.py +0 -0
  73. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/continuous/test_brownian_motion.py +0 -0
  74. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/continuous/test_cauchy_process.py +0 -0
  75. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/continuous/test_fractional_brownian_motion.py +0 -0
  76. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/continuous/test_gamma_process.py +0 -0
  77. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/continuous/test_geometric_brownian_motion.py +0 -0
  78. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/continuous/test_inverse_gaussian_process.py +0 -0
  79. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/continuous/test_mixed_poisson_process.py +0 -0
  80. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/continuous/test_multifractional_brownian_motion.py +0 -0
  81. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/continuous/test_poisson_process.py +0 -0
  82. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/continuous/test_squared_bessel_process.py +0 -0
  83. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/continuous/test_variance_gamma_process.py +0 -0
  84. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/continuous/test_wiener_process.py +0 -0
  85. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/diffusion/__init__.py +0 -0
  86. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/diffusion/test_cox_ingersoll_ross_process.py +0 -0
  87. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/diffusion/test_extended_vasicek_process.py +0 -0
  88. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/diffusion/test_ornstein_uhlenbeck_process.py +0 -0
  89. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/diffusion/test_vasicek_process.py +0 -0
  90. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/discrete/__init__.py +0 -0
  91. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/discrete/test_bernoulli_process.py +0 -0
  92. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/discrete/test_chinese_restaurant_process.py +0 -0
  93. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/discrete/test_dirichlet_process.py +0 -0
  94. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/discrete/test_markov_chain.py +0 -0
  95. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/discrete/test_moran_process.py +0 -0
  96. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/discrete/test_random_walk.py +0 -0
  97. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/noise/__init__.py +0 -0
  98. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/noise/colored/__init__.py +0 -0
  99. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/noise/colored/test_blue_noise.py +0 -0
  100. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/noise/colored/test_brownian_noise.py +0 -0
  101. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/noise/colored/test_colored_noise.py +0 -0
  102. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/noise/colored/test_pink_noise.py +0 -0
  103. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/noise/colored/test_red_noise.py +0 -0
  104. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/noise/colored/test_violet_noise.py +0 -0
  105. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/noise/colored/test_white_noise.py +0 -0
  106. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/noise/test_fractional_gaussian_noise.py +0 -0
  107. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/noise/test_gaussian_noise.py +0 -0
  108. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/test_import.py +0 -0
  109. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/test_random.py +0 -0
  110. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/test_times.py +0 -0
  111. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/utils/__init__.py +0 -0
  112. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/utils/test_utils.py +0 -0
  113. {samplepaths-0.2.0 → samplepaths-0.3.0}/tests/utils/test_validation.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: samplepaths
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: Generate realizations of stochastic processes
5
5
  Project-URL: Homepage, https://github.com/samplepaths/samplepaths
6
6
  Project-URL: Documentation, https://samplepaths.readthedocs.io/
@@ -49,10 +49,12 @@ from samplepaths import BrownianMotion
49
49
 
50
50
  bm = BrownianMotion(drift=1, scale=2, t=10)
51
51
  path = bm.sample(1000) # 1001 values on [0, 10]
52
+ paths = bm.sample_paths(1000, paths=5000) # 5000 realizations at once
52
53
  ```
53
54
 
54
55
  - **37 processes** in four families: continuous-time, diffusion, discrete-time and noise
55
- - **One interface**: every process is a class with a `sample(n)` method
56
+ - **One interface**: every process is a class with `sample(n)` and `sample_paths(n, paths)` methods
57
+ - **Fast**: vectorized with NumPy; 1000 Vasicek realizations of 256 steps take about 2 ms
56
58
  - **Reproducible**: built on `numpy.random.Generator`, per process or through a seedable default
57
59
  - **Typed**: type hints throughout, checked with mypy in strict mode
58
60
  - **Light**: depends only on NumPy and SciPy
@@ -124,6 +126,22 @@ arrivals = PoissonProcess(rate=2.0).sample_with_length(10.0)
124
126
  noise = FractionalGaussianNoise(hurst=0.6).sample_hosking(32)
125
127
  ```
126
128
 
129
+ ### Many realizations at once
130
+
131
+ `sample_paths(n, paths)` returns a two-dimensional array with one realization per row.
132
+ For most processes it is 2 to 13 times faster than a loop over `sample()`.
133
+
134
+ ```python
135
+ import numpy as np
136
+ from samplepaths import GeometricBrownianMotion
137
+
138
+ gbm = GeometricBrownianMotion(drift=0.05, volatility=0.2, rng=np.random.default_rng(1))
139
+ prices = gbm.sample_paths_with_initial(n=64, paths=100_000, initial=100.0)
140
+
141
+ payoffs = np.maximum(prices[:, -1] - 105.0, 0.0)
142
+ print(np.exp(-0.05) * payoffs.mean()) # a European call price, close to 8.02
143
+ ```
144
+
127
145
  ### Generic simulation code
128
146
 
129
147
  Because the interface is shared, simulation code does not depend on the process it simulates.
@@ -137,7 +155,7 @@ from samplepaths.base import BaseTimeProcess
137
155
 
138
156
  def final_values(process: BaseTimeProcess, n: int, paths: int) -> np.ndarray:
139
157
  """Simulate a number of paths and collect the last value of each."""
140
- return np.array([process.sample(n)[-1] for _ in range(paths)])
158
+ return process.sample_paths(n, paths)[:, -1]
141
159
 
142
160
 
143
161
  final_values(GeometricBrownianMotion(drift=0.05, volatility=0.2), n=64, paths=1000)
@@ -164,7 +182,8 @@ Diffusion processes are approximated with the Euler-Maruyama method.
164
182
  The documentation at https://samplepaths.readthedocs.io/ contains:
165
183
 
166
184
  - a [quickstart](https://samplepaths.readthedocs.io/en/latest/getting-started/quickstart.html)
167
- - a user guide for [sampling](https://samplepaths.readthedocs.io/en/latest/guide/usage.html), [random number generation](https://samplepaths.readthedocs.io/en/latest/guide/random.html) and every family of processes
185
+ - a user guide for [sampling](https://samplepaths.readthedocs.io/en/latest/guide/usage.html), [simulating many realizations](https://samplepaths.readthedocs.io/en/latest/guide/paths.html), [random number generation](https://samplepaths.readthedocs.io/en/latest/guide/random.html) and every family of processes
186
+ - measured [sampling times](https://samplepaths.readthedocs.io/en/latest/guide/performance.html) and a [changelog](https://samplepaths.readthedocs.io/en/latest/project/changelog.html)
168
187
  - an [API reference](https://samplepaths.readthedocs.io/en/latest/reference/index.html) for every class, method and function
169
188
 
170
189
  ## Coming from stochastic
@@ -17,10 +17,12 @@ from samplepaths import BrownianMotion
17
17
 
18
18
  bm = BrownianMotion(drift=1, scale=2, t=10)
19
19
  path = bm.sample(1000) # 1001 values on [0, 10]
20
+ paths = bm.sample_paths(1000, paths=5000) # 5000 realizations at once
20
21
  ```
21
22
 
22
23
  - **37 processes** in four families: continuous-time, diffusion, discrete-time and noise
23
- - **One interface**: every process is a class with a `sample(n)` method
24
+ - **One interface**: every process is a class with `sample(n)` and `sample_paths(n, paths)` methods
25
+ - **Fast**: vectorized with NumPy; 1000 Vasicek realizations of 256 steps take about 2 ms
24
26
  - **Reproducible**: built on `numpy.random.Generator`, per process or through a seedable default
25
27
  - **Typed**: type hints throughout, checked with mypy in strict mode
26
28
  - **Light**: depends only on NumPy and SciPy
@@ -92,6 +94,22 @@ arrivals = PoissonProcess(rate=2.0).sample_with_length(10.0)
92
94
  noise = FractionalGaussianNoise(hurst=0.6).sample_hosking(32)
93
95
  ```
94
96
 
97
+ ### Many realizations at once
98
+
99
+ `sample_paths(n, paths)` returns a two-dimensional array with one realization per row.
100
+ For most processes it is 2 to 13 times faster than a loop over `sample()`.
101
+
102
+ ```python
103
+ import numpy as np
104
+ from samplepaths import GeometricBrownianMotion
105
+
106
+ gbm = GeometricBrownianMotion(drift=0.05, volatility=0.2, rng=np.random.default_rng(1))
107
+ prices = gbm.sample_paths_with_initial(n=64, paths=100_000, initial=100.0)
108
+
109
+ payoffs = np.maximum(prices[:, -1] - 105.0, 0.0)
110
+ print(np.exp(-0.05) * payoffs.mean()) # a European call price, close to 8.02
111
+ ```
112
+
95
113
  ### Generic simulation code
96
114
 
97
115
  Because the interface is shared, simulation code does not depend on the process it simulates.
@@ -105,7 +123,7 @@ from samplepaths.base import BaseTimeProcess
105
123
 
106
124
  def final_values(process: BaseTimeProcess, n: int, paths: int) -> np.ndarray:
107
125
  """Simulate a number of paths and collect the last value of each."""
108
- return np.array([process.sample(n)[-1] for _ in range(paths)])
126
+ return process.sample_paths(n, paths)[:, -1]
109
127
 
110
128
 
111
129
  final_values(GeometricBrownianMotion(drift=0.05, volatility=0.2), n=64, paths=1000)
@@ -132,7 +150,8 @@ Diffusion processes are approximated with the Euler-Maruyama method.
132
150
  The documentation at https://samplepaths.readthedocs.io/ contains:
133
151
 
134
152
  - a [quickstart](https://samplepaths.readthedocs.io/en/latest/getting-started/quickstart.html)
135
- - a user guide for [sampling](https://samplepaths.readthedocs.io/en/latest/guide/usage.html), [random number generation](https://samplepaths.readthedocs.io/en/latest/guide/random.html) and every family of processes
153
+ - a user guide for [sampling](https://samplepaths.readthedocs.io/en/latest/guide/usage.html), [simulating many realizations](https://samplepaths.readthedocs.io/en/latest/guide/paths.html), [random number generation](https://samplepaths.readthedocs.io/en/latest/guide/random.html) and every family of processes
154
+ - measured [sampling times](https://samplepaths.readthedocs.io/en/latest/guide/performance.html) and a [changelog](https://samplepaths.readthedocs.io/en/latest/project/changelog.html)
136
155
  - an [API reference](https://samplepaths.readthedocs.io/en/latest/reference/index.html) for every class, method and function
137
156
 
138
157
  ## Coming from stochastic
@@ -7,6 +7,7 @@ import numpy.typing as npt
7
7
  from numpy.random import Generator
8
8
 
9
9
  from .. import random
10
+ from ..utils.validation import check_positive_integer
10
11
 
11
12
 
12
13
  class BaseProcess(ABC):
@@ -50,3 +51,34 @@ class BaseProcess(ABC):
50
51
  :returns: the realization. Processes with integer values, such as
51
52
  the state of a Markov chain, return an array of integers.
52
53
  """
54
+
55
+ def sample_paths(
56
+ self,
57
+ n: int,
58
+ paths: int,
59
+ ) -> npt.NDArray[np.float64] | npt.NDArray[np.int64]:
60
+ """Generate several independent realizations at once.
61
+
62
+ The realizations have the distribution of those of :py:meth:`sample`.
63
+ Many processes generate them together, which is much faster than
64
+ calling :py:meth:`sample` repeatedly. For a given seed, the values
65
+ differ from those of repeated calls to :py:meth:`sample`, because the
66
+ random numbers are drawn in a different order.
67
+
68
+ :param n: the number of increments of each realization
69
+ :param paths: the number of realizations
70
+ :returns: a two-dimensional array with one realization per row
71
+ """
72
+ return self._sample_paths_one_by_one(n, paths)
73
+
74
+ def _sample_paths_one_by_one(
75
+ self,
76
+ n: int,
77
+ paths: int,
78
+ ) -> npt.NDArray[np.float64] | npt.NDArray[np.int64]:
79
+ """Generate several realizations with one call to sample for each."""
80
+ check_positive_integer(n=paths, name="Number of paths")
81
+ stacked: npt.NDArray[np.float64] | npt.NDArray[np.int64] = np.array(
82
+ [self.sample(n) for _ in range(paths)]
83
+ )
84
+ return stacked
@@ -1,6 +1,7 @@
1
1
  """Base class of the processes defined on a time interval."""
2
2
 
3
3
  from abc import abstractmethod
4
+ from typing import override
4
5
 
5
6
  import numpy as np
6
7
  import numpy.typing as npt
@@ -122,3 +123,12 @@ class BaseTimeProcess(BaseProcess):
122
123
  f"{type(self).__name__} cannot be sampled at specified times. "
123
124
  "Use the sample method with a number of increments."
124
125
  )
126
+
127
+ @override
128
+ def sample_paths(self, n: int, paths: int) -> npt.NDArray[np.float64]:
129
+ return self._stack_paths(n, paths)
130
+
131
+ def _stack_paths(self, n: int, paths: int) -> npt.NDArray[np.float64]:
132
+ """Generate several realizations with one call to sample for each."""
133
+ check_positive_integer(n=paths, name="Number of paths")
134
+ return np.array([self.sample(n) for _ in range(paths)], dtype=np.float64)
@@ -88,3 +88,10 @@ class BesselProcess(BrownianMotion):
88
88
  times: npt.NDArray[np.float64],
89
89
  ) -> npt.NDArray[np.float64]:
90
90
  return self._sample_bessel_process_at(times)
91
+
92
+ @override
93
+ def sample_paths(self, n: int, paths: int) -> npt.NDArray[np.float64]:
94
+ samples = np.array([self._sample_brownian_motion_paths(n, paths) for _ in range(self.dim)])
95
+
96
+ norms: npt.NDArray[np.float64] = np.sqrt(np.sum(np.square(samples), axis=0))
97
+ return norms
@@ -91,3 +91,14 @@ class BrownianBridge(BrownianMotion):
91
91
  times: npt.NDArray[np.float64],
92
92
  ) -> npt.NDArray[np.float64]:
93
93
  return self._sample_brownian_bridge_at(times)
94
+
95
+ def _sample_brownian_bridge_paths(self, n: int, paths: int) -> npt.NDArray[np.float64]:
96
+ """Generate several realizations of a Brownian bridge, one per row."""
97
+ bm = self._sample_brownian_motion_paths(n, paths)
98
+
99
+ bridges: npt.NDArray[np.float64] = bm + self.times * (self.b - bm[:, -1:]) / self.t
100
+ return bridges
101
+
102
+ @override
103
+ def sample_paths(self, n: int, paths: int) -> npt.NDArray[np.float64]:
104
+ return self._sample_brownian_bridge_paths(n, paths)
@@ -89,3 +89,17 @@ class BrownianExcursion(BrownianBridge):
89
89
  times: npt.NDArray[np.float64],
90
90
  ) -> npt.NDArray[np.float64]:
91
91
  return self._sample_brownian_excursion_at(times)
92
+
93
+ @override
94
+ def sample_paths(self, n: int, paths: int) -> npt.NDArray[np.float64]:
95
+ bridges = self._sample_brownian_bridge_paths(n, paths)
96
+
97
+ # Rotate every bridge to start at its minimum.
98
+ idx_min = np.argmin(bridges, axis=1)
99
+ indices = (idx_min[:, np.newaxis] + np.arange(n + 1)) % n
100
+ minimums = bridges[np.arange(paths), idx_min][:, np.newaxis]
101
+
102
+ excursions: npt.NDArray[np.float64] = (
103
+ np.take_along_axis(bridges, indices, axis=1) - minimums
104
+ )
105
+ return excursions
@@ -6,7 +6,7 @@ import numpy as np
6
6
  import numpy.typing as npt
7
7
  from numpy.random import Generator
8
8
 
9
- from ..utils.validation import check_nonnegative_number
9
+ from ..utils.validation import check_nonnegative_number, check_positive_integer
10
10
  from .brownian_bridge import BrownianBridge
11
11
 
12
12
 
@@ -146,3 +146,20 @@ class BrownianMeander(BrownianBridge):
146
146
  :returns: the realization
147
147
  """
148
148
  return self._sample_brownian_meander_at(times, b)
149
+
150
+ @override
151
+ def sample_paths(self, n: int, paths: int) -> npt.NDArray[np.float64]:
152
+ check_positive_integer(n=n, name="Number of increments")
153
+ check_positive_integer(n=paths, name="Number of paths")
154
+
155
+ # One random endpoint per realization.
156
+ b = np.sqrt(2 * self.t * self.rng.exponential(size=(paths, 1)))
157
+
158
+ bridge_1 = self._sample_brownian_bridge_paths(n, paths)
159
+ bridge_2 = self._sample_brownian_bridge_paths(n, paths)
160
+ bridge_3 = self._sample_brownian_bridge_paths(n, paths)
161
+
162
+ meanders: npt.NDArray[np.float64] = np.sqrt(
163
+ (b * self.times / self.t + bridge_1) ** 2 + bridge_2**2 + bridge_3**2
164
+ )
165
+ return meanders
@@ -114,3 +114,20 @@ class BrownianMotion(GaussianNoise):
114
114
  times: npt.NDArray[np.float64],
115
115
  ) -> npt.NDArray[np.float64]:
116
116
  return self._sample_brownian_motion_at(times)
117
+
118
+ def _sample_brownian_motion_paths(self, n: int, paths: int) -> npt.NDArray[np.float64]:
119
+ """Generate several realizations of Brownian motion, one per row."""
120
+ noise = self._sample_gaussian_noise_paths(n, paths)
121
+
122
+ bm = np.concatenate(
123
+ (np.zeros((paths, 1)), np.cumsum(self.scale * noise, axis=1)),
124
+ axis=1,
125
+ )
126
+ if self.drift != 0:
127
+ bm += self.drift * self.times
128
+
129
+ return bm
130
+
131
+ @override
132
+ def sample_paths(self, n: int, paths: int) -> npt.NDArray[np.float64]:
133
+ return self._sample_brownian_motion_paths(n, paths)
@@ -116,3 +116,26 @@ class CauchyProcess(BrownianMotion):
116
116
  times: npt.NDArray[np.float64],
117
117
  ) -> npt.NDArray[np.float64]:
118
118
  return self._sample_cauchy_process_at(times)
119
+
120
+ @override
121
+ def sample_paths(self, n: int, paths: int) -> npt.NDArray[np.float64]:
122
+ check_positive_integer(n=n, name="Number of increments")
123
+ check_positive_integer(n=paths, name="Number of paths")
124
+ self.set_times(n)
125
+
126
+ delta_t = 1.0 * self.t / n
127
+ levys = np.asarray(
128
+ levy.rvs(
129
+ loc=0,
130
+ scale=delta_t**2 / 2,
131
+ size=(paths, n),
132
+ random_state=self.rng,
133
+ ),
134
+ dtype=np.float64,
135
+ )
136
+
137
+ samples = np.cumsum(self.scale * self.rng.normal(scale=np.sqrt(levys)), axis=1)
138
+ if self.drift != 0:
139
+ samples += self.drift * np.cumsum(levys, axis=1)
140
+
141
+ return np.concatenate((np.zeros((paths, 1)), samples), axis=1)
@@ -56,3 +56,8 @@ class FractionalBrownianMotion(FractionalGaussianNoise):
56
56
  @override
57
57
  def sample(self, n: int) -> npt.NDArray[np.float64]:
58
58
  return self._sample_fractional_brownian_motion(n)
59
+
60
+ @override
61
+ def sample_paths(self, n: int, paths: int) -> npt.NDArray[np.float64]:
62
+ fgn = self._davies_harte_paths(n, paths)
63
+ return np.concatenate((np.zeros((paths, 1)), np.cumsum(fgn, axis=1)), axis=1)
@@ -159,3 +159,17 @@ class GammaProcess(BaseTimeProcess):
159
159
  @override
160
160
  def sample_at(self, times: npt.NDArray[np.float64]) -> npt.NDArray[np.float64]:
161
161
  return self._sample_gamma_process_at(times)
162
+
163
+ @override
164
+ def sample_paths(self, n: int, paths: int) -> npt.NDArray[np.float64]:
165
+ check_positive_integer(n=n, name="Number of increments")
166
+ check_positive_integer(n=paths, name="Number of paths")
167
+ self.set_times(n)
168
+
169
+ delta_t = 1.0 * self.t / n
170
+
171
+ shape = 1.0 * self.mean**2 * delta_t / self.variance
172
+ scale = 1.0 * self.variance / self.mean
173
+
174
+ increments = self.rng.gamma(shape=shape, scale=scale, size=(paths, n))
175
+ return np.concatenate((np.zeros((paths, 1)), np.cumsum(increments, axis=1)), axis=1)
@@ -164,3 +164,38 @@ class GeometricBrownianMotion(BrownianMotion):
164
164
  :returns: the realization
165
165
  """
166
166
  return self._sample_geometric_brownian_motion_at(times, initial)
167
+
168
+ def _sample_geometric_brownian_motion_paths(
169
+ self,
170
+ n: int,
171
+ paths: int,
172
+ initial: float,
173
+ ) -> npt.NDArray[np.float64]:
174
+ """Generate several realizations of geometric Brownian motion."""
175
+ check_positive_number(value=initial, name="Initial")
176
+
177
+ noise = self._sample_gaussian_noise_paths(n, paths)
178
+ wiener = np.concatenate((np.zeros((paths, 1)), np.cumsum(noise, axis=1)), axis=1)
179
+
180
+ line = (self.drift - self.volatility**2 / 2.0) * self.times
181
+ realizations: npt.NDArray[np.float64] = initial * np.exp(line + self.volatility * wiener)
182
+ return realizations
183
+
184
+ @override
185
+ def sample_paths(self, n: int, paths: int) -> npt.NDArray[np.float64]:
186
+ return self._sample_geometric_brownian_motion_paths(n, paths, 1.0)
187
+
188
+ def sample_paths_with_initial(
189
+ self,
190
+ n: int,
191
+ paths: int,
192
+ initial: float = 1.0,
193
+ ) -> npt.NDArray[np.float64]:
194
+ """Generate several realizations starting from an initial value.
195
+
196
+ :param n: the number of increments of each realization
197
+ :param paths: the number of realizations
198
+ :param initial: the initial value of the process :math:`S_0`
199
+ :returns: a two-dimensional array with one realization per row
200
+ """
201
+ return self._sample_geometric_brownian_motion_paths(n, paths, initial)
@@ -8,9 +8,8 @@ import numpy as np
8
8
  import numpy.typing as npt
9
9
  from numpy.random import Generator
10
10
 
11
- from samplepaths.utils.validation import check_positive_number
12
-
13
11
  from ..base import BaseTimeProcess
12
+ from ..utils.validation import check_positive_integer, check_positive_number
14
13
 
15
14
 
16
15
  class InverseGaussianProcess(BaseTimeProcess):
@@ -105,6 +104,16 @@ class InverseGaussianProcess(BaseTimeProcess):
105
104
 
106
105
  return delta
107
106
 
107
+ def _update_mean_increments(self, n: int) -> None:
108
+ """Compute the increments of the mean function for n increments."""
109
+ if self.set_times(n):
110
+ self.__ms = np.zeros(n)
111
+ for k in range(n):
112
+ self.__ms[k] = self._check_mean(
113
+ self.times[k],
114
+ self.times[k + 1],
115
+ )
116
+
108
117
  def _sample_inverse_gaussian_process(
109
118
  self,
110
119
  n: int,
@@ -113,13 +122,7 @@ class InverseGaussianProcess(BaseTimeProcess):
113
122
 
114
123
  Generate an inverse Gaussian process realization with n increments.
115
124
  """
116
- if self.set_times(n):
117
- self.__ms = np.zeros(n)
118
- for k in range(n):
119
- self.__ms[k] = self._check_mean(
120
- self.times[k],
121
- self.times[k + 1],
122
- )
125
+ self._update_mean_increments(n)
123
126
 
124
127
  assert self.__ms is not None
125
128
  ls = self.scale * self.__ms**2
@@ -177,3 +180,23 @@ class InverseGaussianProcess(BaseTimeProcess):
177
180
  times: npt.NDArray[np.float64],
178
181
  ) -> npt.NDArray[np.float64]:
179
182
  return self._sample_inverse_gaussian_process_at(times)
183
+
184
+ @override
185
+ def sample_paths(self, n: int, paths: int) -> npt.NDArray[np.float64]:
186
+ check_positive_integer(n=paths, name="Number of paths")
187
+ self._update_mean_increments(n)
188
+
189
+ ms = self.__ms
190
+ assert ms is not None
191
+ ls = self.scale * ms**2
192
+
193
+ gn = self.rng.normal(size=(paths, n))
194
+ ys = gn**2
195
+
196
+ xs = ms + ms**2 * ys / 2 / ls - ms / 2 / ys * np.sqrt(4 * ms * ls * ys + ms**2 * ys**2)
197
+
198
+ zs = self.rng.uniform(size=(paths, n))
199
+
200
+ ign = np.where(zs <= ms / (ms + xs), xs, ms**2 / xs)
201
+
202
+ return np.concatenate((np.zeros((paths, 1)), np.cumsum(ign, axis=1)), axis=1)
@@ -7,6 +7,7 @@ import numpy as np
7
7
  import numpy.typing as npt
8
8
  from numpy.random import Generator
9
9
 
10
+ from ..utils.validation import check_positive_integer
10
11
  from .poisson_process import PoissonProcess
11
12
 
12
13
 
@@ -112,3 +113,9 @@ class MixedPoissonProcess(PoissonProcess):
112
113
  ) -> npt.NDArray[np.float64]:
113
114
  self.rate = self._sample_rate()
114
115
  return self._sample_poisson_process(length=length)
116
+
117
+ @override
118
+ def sample_paths(self, n: int, paths: int) -> npt.NDArray[np.float64]:
119
+ # Every realization draws its own random rate.
120
+ check_positive_integer(n=paths, name="Number of paths")
121
+ return np.array([self.sample(n) for _ in range(paths)], dtype=np.float64)
@@ -10,6 +10,11 @@ from numpy.random import Generator
10
10
  from scipy.special import gamma
11
11
 
12
12
  from ..base import BaseTimeProcess
13
+ from ..utils.validation import check_positive_integer
14
+
15
+ #: Largest number of increments for which the weights are kept between
16
+ #: realizations. The weights take 4 n squared bytes: 17 MB at this limit.
17
+ _CACHE_MAX_INCREMENTS = 2048
13
18
 
14
19
 
15
20
  class MultifractionalBrownianMotion(BaseTimeProcess):
@@ -53,6 +58,9 @@ class MultifractionalBrownianMotion(BaseTimeProcess):
53
58
  ) -> None:
54
59
  super().__init__(t=t, rng=rng)
55
60
 
61
+ self.__weights_key: tuple[int, float, Callable[[float], float]] | None = None
62
+ self.__weights: list[npt.NDArray[np.float64]] = []
63
+
56
64
  self.hurst = hurst if hurst is not None else lambda x: 0.5
57
65
 
58
66
  def __str__(self) -> str:
@@ -97,25 +105,66 @@ class MultifractionalBrownianMotion(BaseTimeProcess):
97
105
  self.set_times(n)
98
106
 
99
107
  dt = 1.0 * self.t / self.n
100
- hs = self._get_hurst(self.hurst)
101
-
102
108
  coefs = (gn / np.sqrt(dt)) * dt
103
- times = self.times
109
+
110
+ weights = self._weights(n, dt)
104
111
 
105
112
  mbm = np.zeros(self.n + 1)
106
113
  for k in range(1, self.n + 1):
107
- # The weights of the Riemann-Liouville method for the Hurst value
108
- # at time k, for the times 1 to k, applied to the increments in
109
- # reverse order.
114
+ # The weights of time k apply to the increments in reverse order.
115
+ mbm[k] = coefs[:k] @ weights[k][::-1]
116
+
117
+ return mbm
118
+
119
+ def _weights(self, n: int, dt: float) -> list[npt.NDArray[np.float64]]:
120
+ """Return the weights of the Riemann-Liouville method for every time.
121
+
122
+ Entry k holds the weights of the times 1 to k for the Hurst value at
123
+ time k. The weights depend on the number of increments, the end time
124
+ and the Hurst function only, so they are kept for the next realization
125
+ unless they would take too much memory.
126
+ """
127
+ key = (n, self.t, self._hurst)
128
+ cached = self.__weights_key
129
+ if cached is not None and cached[:2] == key[:2] and cached[2] is key[2]:
130
+ return self.__weights
131
+
132
+ hs = self._get_hurst(self.hurst)
133
+ times = self.times
134
+
135
+ weights = [np.zeros(0)]
136
+ for k in range(1, n + 1):
110
137
  hurst = hs[k]
111
138
  elapsed = times[1 : k + 1]
112
- weights = np.sqrt(
113
- (elapsed ** (2 * hurst) - (elapsed - dt) ** (2 * hurst)) / (2 * hurst * dt)
114
- ) / gamma(hurst + 0.5)
115
- mbm[k] = coefs[:k] @ weights[::-1]
139
+ weights.append(
140
+ np.sqrt((elapsed ** (2 * hurst) - (elapsed - dt) ** (2 * hurst)) / (2 * hurst * dt))
141
+ / gamma(hurst + 0.5)
142
+ )
116
143
 
117
- return mbm
144
+ if n <= _CACHE_MAX_INCREMENTS:
145
+ self.__weights_key = key
146
+ self.__weights = weights
147
+
148
+ return weights
118
149
 
119
150
  @override
120
151
  def sample(self, n: int) -> npt.NDArray[np.float64]:
121
152
  return self._sample_multifractional_brownian_motion(n)
153
+
154
+ @override
155
+ def sample_paths(self, n: int, paths: int) -> npt.NDArray[np.float64]:
156
+ check_positive_integer(n=n, name="Number of increments")
157
+ check_positive_integer(n=paths, name="Number of paths")
158
+
159
+ gn = self.rng.normal(0.0, 1.0, (paths, n))
160
+ self.set_times(n)
161
+
162
+ dt = 1.0 * self.t / n
163
+ coefs = (gn / np.sqrt(dt)) * dt
164
+ weights = self._weights(n, dt)
165
+
166
+ mbm = np.zeros((paths, n + 1))
167
+ for k in range(1, n + 1):
168
+ mbm[:, k] = coefs[:, :k] @ weights[k][::-1]
169
+
170
+ return mbm
@@ -110,3 +110,11 @@ class PoissonProcess(BaseProcess):
110
110
  arrival after ``length``
111
111
  """
112
112
  return self._sample_poisson_process(length=length)
113
+
114
+ @override
115
+ def sample_paths(self, n: int, paths: int) -> npt.NDArray[np.float64]:
116
+ check_positive_integer(n=n)
117
+ check_positive_integer(n=paths, name="Number of paths")
118
+
119
+ exponentials = self.rng.exponential(scale=1.0 / self.rate, size=(paths, n))
120
+ return np.concatenate((np.zeros((paths, 1)), np.cumsum(exponentials, axis=1)), axis=1)
@@ -61,3 +61,10 @@ class SquaredBesselProcess(BesselProcess):
61
61
  @override
62
62
  def sample_at(self, times: npt.NDArray[np.float64]) -> npt.NDArray[np.float64]:
63
63
  return self._sample_squared_bessel_process_at(times)
64
+
65
+ @override
66
+ def sample_paths(self, n: int, paths: int) -> npt.NDArray[np.float64]:
67
+ samples = np.array([self._sample_brownian_motion_paths(n, paths) for _ in range(self.dim)])
68
+
69
+ squares: npt.NDArray[np.float64] = np.sum(np.square(samples), axis=0)
70
+ return squares
@@ -145,3 +145,19 @@ class VarianceGammaProcess(GaussianNoise):
145
145
  @override
146
146
  def sample_at(self, times: npt.NDArray[np.float64]) -> npt.NDArray[np.float64]:
147
147
  return self._sample_variance_gamma_process_at(times)
148
+
149
+ @override
150
+ def sample_paths(self, n: int, paths: int) -> npt.NDArray[np.float64]:
151
+ check_positive_integer(n=n, name="n")
152
+ check_positive_integer(n=paths, name="Number of paths")
153
+
154
+ delta_t = 1.0 * self.t / n
155
+ shape = delta_t / self.variance
156
+ scale = self.variance
157
+
158
+ gammas = self.rng.gamma(shape=shape, scale=scale, size=(paths, n))
159
+ gn = self._sample_gaussian_noise_paths(n, paths)
160
+
161
+ increments = self.drift * gammas + self.scale * np.sqrt(gammas) * gn
162
+
163
+ return np.concatenate((np.zeros((paths, 1)), np.cumsum(increments, axis=1)), axis=1)
@@ -4,7 +4,6 @@ from collections.abc import Callable
4
4
 
5
5
  from numpy.random import Generator
6
6
 
7
- from ..utils import ensure_single_arg_constant_function
8
7
  from ..utils.validation import check_numeric
9
8
  from .diffusion_process import DiffusionProcess
10
9
 
@@ -78,4 +77,4 @@ class ConstantElasticityVarianceProcess(DiffusionProcess):
78
77
  @drift.setter
79
78
  def drift(self, value: float) -> None:
80
79
  check_numeric(value=value, name="Drift coefficient.")
81
- self.speed = ensure_single_arg_constant_function(value=-value)
80
+ self.speed = -value