python-synthetica 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.
@@ -0,0 +1,28 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2024, ActurialCapital
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright notice, this
9
+ list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation
13
+ and/or other materials provided with the distribution.
14
+
15
+ 3. Neither the name of the copyright holder nor the names of its
16
+ contributors may be used to endorse or promote products derived from
17
+ this software without specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,154 @@
1
+ Metadata-Version: 2.1
2
+ Name: python-synthetica
3
+ Version: 0.1.0
4
+ Summary: Generate synthetic time series data.
5
+ Home-page: https://github.com/ActurialCapital/synthetica
6
+ License: BSD 3-Clause License
7
+ Author: ActurialCapital
8
+ Requires-Python: >=3.11,<4.0
9
+ Classifier: License :: Other/Proprietary License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.11
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Requires-Dist: numpy (>=1.26.4,<2.0.0)
14
+ Requires-Dist: pandas (>=2.2.2,<3.0.0)
15
+ Requires-Dist: scipy (>=1.13.1,<2.0.0)
16
+ Requires-Dist: statsmodels (>=0.14.2,<0.15.0)
17
+ Project-URL: Repository, https://github.com/ActurialCapital/synthetica
18
+ Description-Content-Type: text/markdown
19
+
20
+ <a name="readme-top"></a>
21
+
22
+ <!-- PROJECT LOGO -->
23
+ <p align="center"><img src="docs/static/logo.png" alt="logo" width="90%" height="90%"></p>
24
+
25
+ <!-- TABLE OF CONTENTS -->
26
+ <details>
27
+ <summary>Table of Contents</summary>
28
+ <ol>
29
+ <li>
30
+ <a href="#about-the-project">About The Project</a>
31
+ <ul>
32
+ <li><a href="#introduction">Introduction</a></li>
33
+ </ul>
34
+ <ul>
35
+ <li><a href="#built-with">Built With</a></li>
36
+ </ul>
37
+ </li>
38
+ <li><a href="#installation">Installation</a></li>
39
+ <li><a href="#getting-started">Getting Started</a></li>
40
+ <li><a href="#contributing">Contributing</a></li>
41
+ <li><a href="#license">License</a></li>
42
+ </ol>
43
+ </details>
44
+
45
+
46
+
47
+ <!-- ABOUT THE PROJECT -->
48
+ ## About The Project
49
+
50
+ ### Introduction
51
+
52
+ `Synthetica` is a versatile and robust tool for generating synthetic time series data. Whether you are engaged in financial modeling, IoT data simulation, or any project requiring realistic time series data to create correlated or uncorrelated signals, `Synthetica` provides high-quality, customizable generated datasets. Leveraging advanced statistical techniques and machine learning algorithms, `Synthetica` produces synthetic data that closely replicates the characteristics and patterns of real-world data.
53
+
54
+ The project latest version incorporates a wide array of models, offering an extensive toolkit for generating synthetic time series data. This version includes features like:
55
+
56
+ * `GeometricBrownianMotion`
57
+ * `AR` (Auto Regressive)
58
+ * `NARMA` (Non-Linear Auto Regressive Moving Average)
59
+ * `Heston`
60
+ * `CIR` (Cox–Ingersoll–Ross)
61
+ * `LevyStable`
62
+ * `MeanReverting` (Ornstein–Uhlenbeck)
63
+ * `Merton`
64
+ * `Poisson`
65
+ * `Seasonal`
66
+
67
+ However, the `SyntheticaAdvenced` version elevates the capabilities further, integrating more sophisticated deep learning data-driven algorithms, such as `TimeGAN`.
68
+
69
+ <p align="right">(<a href="#readme-top">back to top</a>)</p>
70
+
71
+ ### Built With
72
+
73
+ * `numpy = "^1.26.4"`
74
+ * `pandas = "^2.2.2"`
75
+ * `scipy = "^1.13.1"`
76
+
77
+ <p align="right">(<a href="#readme-top">back to top</a>)</p>
78
+
79
+ <!-- GETTING STARTED -->
80
+ ## Installation
81
+
82
+ ```sh
83
+ $ pip install python-synthetica
84
+ ```
85
+
86
+ <p align="right">(<a href="#readme-top">back to top</a>)</p>
87
+
88
+ <!-- USAGE EXAMPLES -->
89
+ ## Getting Started
90
+
91
+ Once you have cloned the repository, you can start using `Synthetica` to generate synthetic time series data. Here are some initial steps to help you kickstart your exploration:
92
+
93
+ ```python
94
+ >>> import synthetica as sth
95
+ ```
96
+
97
+ In this example, we are using the following parameters for illustration purposes:
98
+
99
+ * `length=252`: The length of the time series
100
+ * `num_paths=5`: The number of paths to generate
101
+ * `seed=123`: Reseed the `numpy` singleton `RandomState` instance for reproduction
102
+
103
+ **Initialize the model**: Using the `GeometricBrownianMotion` (GBM) model: This approach initializes the model with a specified path length, number of paths, and a fixed random seed:
104
+
105
+ ```python
106
+ >>> model = sth.GeometricBrownianMotion(length=252, num_paths=5, seed=123)
107
+ ```
108
+
109
+ **Generate random signals**: The transform method then generates the random signals accordingly:
110
+
111
+ ```python
112
+ >>> model.transform() # Generate random signals
113
+ ```
114
+
115
+ <p align="center"><img src="docs/static/gbm_random_transform.png" alt="chart-1" width="75%" height="75%"></p>
116
+
117
+ **Generate correlated paths**: This process ensures that the resulting features are highly positively correlated, leveraging the Cholesky decomposition method to achieve the desired `matrix` correlation structure:
118
+
119
+ ```python
120
+ >>> model.transform(matrix) # Produces highly positively correlated features
121
+ ```
122
+
123
+
124
+
125
+ <p align="center"><img src="docs/static/gbm_corr_transform.png" alt="chart-2" width="75%" height="75%"></p>
126
+
127
+
128
+ <p align="right">(<a href="#readme-top">back to top</a>)</p>
129
+
130
+ <!-- CONTRIBUTING -->
131
+ ## Contributing
132
+
133
+ Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are **greatly appreciated**.
134
+
135
+ If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement".
136
+ Don't forget to give the project a star! Thanks again!
137
+
138
+ 1. Fork the Project
139
+ 2. Create your Feature Branch (`git checkout -b feature/AmazingFeature`)
140
+ 3. Commit your Changes (`git commit -m 'Add some AmazingFeature'`)
141
+ 4. Push to the Branch (`git push origin feature/AmazingFeature`)
142
+ 5. Open a Pull Request
143
+
144
+ <p align="right">(<a href="#readme-top">back to top</a>)</p>
145
+
146
+
147
+ <!-- LICENSE -->
148
+ ## License
149
+
150
+ Distributed under the BSD-3 License. See `LICENSE.txt` for more information.
151
+
152
+ <p align="right">(<a href="#readme-top">back to top</a>)</p>
153
+
154
+
@@ -0,0 +1,134 @@
1
+ <a name="readme-top"></a>
2
+
3
+ <!-- PROJECT LOGO -->
4
+ <p align="center"><img src="docs/static/logo.png" alt="logo" width="90%" height="90%"></p>
5
+
6
+ <!-- TABLE OF CONTENTS -->
7
+ <details>
8
+ <summary>Table of Contents</summary>
9
+ <ol>
10
+ <li>
11
+ <a href="#about-the-project">About The Project</a>
12
+ <ul>
13
+ <li><a href="#introduction">Introduction</a></li>
14
+ </ul>
15
+ <ul>
16
+ <li><a href="#built-with">Built With</a></li>
17
+ </ul>
18
+ </li>
19
+ <li><a href="#installation">Installation</a></li>
20
+ <li><a href="#getting-started">Getting Started</a></li>
21
+ <li><a href="#contributing">Contributing</a></li>
22
+ <li><a href="#license">License</a></li>
23
+ </ol>
24
+ </details>
25
+
26
+
27
+
28
+ <!-- ABOUT THE PROJECT -->
29
+ ## About The Project
30
+
31
+ ### Introduction
32
+
33
+ `Synthetica` is a versatile and robust tool for generating synthetic time series data. Whether you are engaged in financial modeling, IoT data simulation, or any project requiring realistic time series data to create correlated or uncorrelated signals, `Synthetica` provides high-quality, customizable generated datasets. Leveraging advanced statistical techniques and machine learning algorithms, `Synthetica` produces synthetic data that closely replicates the characteristics and patterns of real-world data.
34
+
35
+ The project latest version incorporates a wide array of models, offering an extensive toolkit for generating synthetic time series data. This version includes features like:
36
+
37
+ * `GeometricBrownianMotion`
38
+ * `AR` (Auto Regressive)
39
+ * `NARMA` (Non-Linear Auto Regressive Moving Average)
40
+ * `Heston`
41
+ * `CIR` (Cox–Ingersoll–Ross)
42
+ * `LevyStable`
43
+ * `MeanReverting` (Ornstein–Uhlenbeck)
44
+ * `Merton`
45
+ * `Poisson`
46
+ * `Seasonal`
47
+
48
+ However, the `SyntheticaAdvenced` version elevates the capabilities further, integrating more sophisticated deep learning data-driven algorithms, such as `TimeGAN`.
49
+
50
+ <p align="right">(<a href="#readme-top">back to top</a>)</p>
51
+
52
+ ### Built With
53
+
54
+ * `numpy = "^1.26.4"`
55
+ * `pandas = "^2.2.2"`
56
+ * `scipy = "^1.13.1"`
57
+
58
+ <p align="right">(<a href="#readme-top">back to top</a>)</p>
59
+
60
+ <!-- GETTING STARTED -->
61
+ ## Installation
62
+
63
+ ```sh
64
+ $ pip install python-synthetica
65
+ ```
66
+
67
+ <p align="right">(<a href="#readme-top">back to top</a>)</p>
68
+
69
+ <!-- USAGE EXAMPLES -->
70
+ ## Getting Started
71
+
72
+ Once you have cloned the repository, you can start using `Synthetica` to generate synthetic time series data. Here are some initial steps to help you kickstart your exploration:
73
+
74
+ ```python
75
+ >>> import synthetica as sth
76
+ ```
77
+
78
+ In this example, we are using the following parameters for illustration purposes:
79
+
80
+ * `length=252`: The length of the time series
81
+ * `num_paths=5`: The number of paths to generate
82
+ * `seed=123`: Reseed the `numpy` singleton `RandomState` instance for reproduction
83
+
84
+ **Initialize the model**: Using the `GeometricBrownianMotion` (GBM) model: This approach initializes the model with a specified path length, number of paths, and a fixed random seed:
85
+
86
+ ```python
87
+ >>> model = sth.GeometricBrownianMotion(length=252, num_paths=5, seed=123)
88
+ ```
89
+
90
+ **Generate random signals**: The transform method then generates the random signals accordingly:
91
+
92
+ ```python
93
+ >>> model.transform() # Generate random signals
94
+ ```
95
+
96
+ <p align="center"><img src="docs/static/gbm_random_transform.png" alt="chart-1" width="75%" height="75%"></p>
97
+
98
+ **Generate correlated paths**: This process ensures that the resulting features are highly positively correlated, leveraging the Cholesky decomposition method to achieve the desired `matrix` correlation structure:
99
+
100
+ ```python
101
+ >>> model.transform(matrix) # Produces highly positively correlated features
102
+ ```
103
+
104
+
105
+
106
+ <p align="center"><img src="docs/static/gbm_corr_transform.png" alt="chart-2" width="75%" height="75%"></p>
107
+
108
+
109
+ <p align="right">(<a href="#readme-top">back to top</a>)</p>
110
+
111
+ <!-- CONTRIBUTING -->
112
+ ## Contributing
113
+
114
+ Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are **greatly appreciated**.
115
+
116
+ If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement".
117
+ Don't forget to give the project a star! Thanks again!
118
+
119
+ 1. Fork the Project
120
+ 2. Create your Feature Branch (`git checkout -b feature/AmazingFeature`)
121
+ 3. Commit your Changes (`git commit -m 'Add some AmazingFeature'`)
122
+ 4. Push to the Branch (`git push origin feature/AmazingFeature`)
123
+ 5. Open a Pull Request
124
+
125
+ <p align="right">(<a href="#readme-top">back to top</a>)</p>
126
+
127
+
128
+ <!-- LICENSE -->
129
+ ## License
130
+
131
+ Distributed under the BSD-3 License. See `LICENSE.txt` for more information.
132
+
133
+ <p align="right">(<a href="#readme-top">back to top</a>)</p>
134
+
@@ -0,0 +1,20 @@
1
+ [tool.poetry]
2
+ name = "python-synthetica"
3
+ version = "0.1.0"
4
+ description = "Generate synthetic time series data."
5
+ authors = ["ActurialCapital"]
6
+ license = "BSD 3-Clause License"
7
+ readme = "README.md"
8
+ repository = "https://github.com/ActurialCapital/synthetica"
9
+ packages = [ {include = "synthetica"} ]
10
+
11
+ [tool.poetry.dependencies]
12
+ python = "^3.11"
13
+ numpy = "^1.26.4"
14
+ pandas = "^2.2.2"
15
+ scipy = "^1.13.1"
16
+ statsmodels = "^0.14.2"
17
+
18
+ [build-system]
19
+ requires = ["poetry-core"]
20
+ build-backend = "poetry.core.masonry.api"
@@ -0,0 +1 @@
1
+ # =============================================================================
2
  "SyntheticConfig",
1
3
  "BaseSynthetic",
2
4
  "GeometricBrownianMotion",
3
5
  "Heston",
4
6
  "Merton",
5
7
  "Poisson",
6
8
  "LevyStable",
7
9
  "CIR",
8
10
  "MeanReverting",
9
11
  "CAR",
10
12
  "OrnsteinUhlenbeck",
11
13
  "AR",
12
14
  "NARMA",
13
15
  "Seasonal"
@@ -0,0 +1,325 @@
1
+ from abc import ABC, abstractmethod
2
+ from typing import Iterable
3
+ from functools import cached_property
4
+ import numpy as np
5
+ import pandas as pd
6
+ from datetime import datetime, timedelta
7
+ import synthetica as sth
8
+
9
+
10
+ class BaseSynthetic(ABC):
11
+ """
12
+ A base class for synthetic data generation methods.
13
+
14
+ This mixin class provides methods for synthetic data generation using
15
+ Cholesky decomposition and other related calculations.
16
+
17
+ Attributes
18
+ ----------
19
+ length : int | pd.DatetimeIndex
20
+ The length of the time series or a pandas DatetimeIndex.
21
+ num_paths : int, optional
22
+ The number of paths to generate. Default is 1.
23
+ mean : float, optional
24
+ Mean (“centre”) of the distribution. Defaults to 0.
25
+ delta : float, optional
26
+ The time step size (e.g., 1/252 for daily data). Default is 1/252.
27
+ sigma : float, optional
28
+ The volatility of the stochastic processes. Default is 0.125.
29
+ freq : str, optional
30
+ The frequency of the data. Default is 'D'.
31
+ seed : int, optional
32
+ The random seed for reproducibility. Default is None.
33
+
34
+ """
35
+
36
+ def __init__(
37
+ self,
38
+ length: int | pd.DatetimeIndex = 252,
39
+ num_paths: int = 1,
40
+ mean: float = 0,
41
+ delta: float = 1/252,
42
+ sigma: float = 0.125,
43
+ freq: str = 'D',
44
+ seed: int = None
45
+ ):
46
+ # Generic
47
+ self._length = length
48
+ self._freq = freq
49
+ self._num_paths = num_paths
50
+ if seed is not None:
51
+ np.random.seed(seed)
52
+
53
+ # White noise params
54
+ self._mean = mean
55
+ self._delta = delta
56
+ self._sigma = sigma
57
+
58
+ def __repr__(self):
59
+ return f'{self.__class__.__name__}'
60
+
61
+ @property
62
+ def freq(self) -> str:
63
+ return self._freq
64
+
65
+ @property
66
+ def index(self) -> pd.DatetimeIndex:
67
+ if isinstance(self._length, pd.DatetimeIndex):
68
+ return self._length
69
+ else:
70
+ # Calculate the nt ago from today
71
+ end_date = datetime.now().date()
72
+ start_date = end_date - timedelta(days=self._length - 1)
73
+ return pd.date_range(start=start_date, end=end_date, freq=self.freq)
74
+
75
+ @property
76
+ def length(self) -> int:
77
+ return len(self.index)
78
+
79
+ @property
80
+ def num_paths(self) -> int:
81
+ return self._num_paths
82
+
83
+ @abstractmethod
84
+ def transform(self, *args, **kwargs) -> pd.Series | pd.DataFrame:
85
+ pass
86
+
87
+ @cached_property
88
+ def white_noise(self) -> np.ndarray:
89
+ """
90
+ Generate white noise (Wiener process).
91
+
92
+ Note
93
+ ----
94
+ White noise has zero mean, constant variance, and is uncorrelated in
95
+ time. As its name suggests, white noise has a power spectrum which is
96
+ uniformly spread across all allowable frequencies.
97
+
98
+ Returns
99
+ -------
100
+ np.ndarray
101
+ White noise (Wiener process) paths.
102
+ """
103
+ return np.random.normal(
104
+ loc=self.mean,
105
+ scale=np.sqrt(self.delta) * self.sigma,
106
+ size=(self.length, self.num_paths)
107
+ )
108
+
109
+ @property
110
+ def mean(self) -> float:
111
+ """Mean value"""
112
+ return self._mean
113
+
114
+ @mean.setter
115
+ @sth.callback('white_noise')
116
+ def mean(self, value) -> float:
117
+ """Mean value update"""
118
+ if value != self._mean:
119
+ self._mean = value
120
+
121
+ @property
122
+ def delta(self) -> float:
123
+ """Delta value"""
124
+ return self._delta
125
+
126
+ @delta.setter
127
+ @sth.callback('white_noise')
128
+ def delta(self, value) -> float:
129
+ """Delta value update"""
130
+ if value != self._delta:
131
+ self._delta = value
132
+
133
+ @property
134
+ def sigma(self) -> float:
135
+ """Sigma value"""
136
+ return self._sigma
137
+
138
+ @sigma.setter
139
+ @sth.callback('white_noise')
140
+ def sigma(self, value) -> float:
141
+ """Sigma value update"""
142
+ if value != self._sigma:
143
+ self._sigma = value
144
+
145
+ @cached_property
146
+ def red_noise(self) -> np.ndarray:
147
+ """
148
+ Generate red noise (correlated noise).
149
+
150
+ Note
151
+ ----
152
+ Red noise has zero mean, constant variance, and is serially correlated
153
+ in time, such that the lag-1 autocorrelation between two successive
154
+ time samples has correlation coefficient 0 < r < 1. Red noise has a
155
+ power spectrum weighted toward low frequencies, but has no single
156
+ preferred period.
157
+
158
+ Returns
159
+ -------
160
+ np.ndarray
161
+ Red noise paths.
162
+ """
163
+ if not hasattr(self, 'tau'):
164
+ raise AttributeError(f"{self} does not integrate red noise.")
165
+
166
+ # Initialize the red noise array
167
+ red_noise = np.zeros((self.length, self.num_paths))
168
+ previous_value = None
169
+
170
+ for i, noise in enumerate(self.white_noise):
171
+ time_diff = self.delta # Assuming constant time intervals
172
+
173
+ if previous_value is None:
174
+ previous_value = noise
175
+ else:
176
+ red_noise[i] = (
177
+ (self.tau / (self.tau + time_diff)) *
178
+ (time_diff * noise + previous_value)
179
+ )
180
+
181
+ previous_value = red_noise[i]
182
+
183
+ return red_noise
184
+
185
+ # #### Cholesky #### #
186
+
187
+ def create_corr_returns(self, matrix) -> pd.Series | pd.DataFrame:
188
+ """
189
+ This method can construct a basket of correlated asset paths using the
190
+ Cholesky decomposition method.
191
+
192
+ Parameters
193
+ ----------
194
+ matrix : pd.DataFrame or np.array
195
+ The matrix applied in Cholesky decomposition.
196
+
197
+ Returns
198
+ -------
199
+ pd.Series or pd.DataFrame:
200
+ Data representing correlated log returns.
201
+ """
202
+ try:
203
+ decomposition = np.linalg.cholesky(matrix)
204
+
205
+ except:
206
+ updated_matrix = sth.nearest_positive_definite(matrix)
207
+ decomposition = np.linalg.cholesky(updated_matrix)
208
+
209
+ sqrt_delta_sigma = np.sqrt(self.delta) * self.sigma
210
+
211
+ # Construct uncorrelated paths to convert into correlated paths
212
+ uncorrelated_paths = [
213
+ np.array(
214
+ # Uncorrelated random numbers
215
+ [np.random.normal(0, sqrt_delta_sigma)
216
+ for _ in range(self.num_paths)]
217
+ )
218
+ for _ in range(self.length + 1)
219
+ ]
220
+
221
+ uncorrelated_matrix = np.matrix(uncorrelated_paths)
222
+ correlated_matrix = uncorrelated_matrix * decomposition
223
+ extracted_paths = [[] for _ in range(1, self.num_paths + 1)]
224
+ for j in range(0, len(correlated_matrix) * self.num_paths - self.num_paths, self.num_paths):
225
+ for i in range(self.num_paths):
226
+ extracted_paths[i].append(correlated_matrix.item(j + i))
227
+
228
+ return self.to_pandas(np.array(extracted_paths).T)
229
+
230
+ def cholesky_transform(self, rvs: np.array, matrix: np.array) -> np.ndarray:
231
+ """
232
+ Perform Cholesky transformation on random variables.
233
+
234
+ Parameters
235
+ ----------
236
+ rvs : np.array
237
+ Random variables to transform.
238
+ matrix : np.array
239
+ The matrix for Cholesky decomposition.
240
+
241
+ Returns
242
+ -------
243
+ np.ndarray
244
+ Transformed random variables.
245
+ """
246
+ try:
247
+ decomposition = np.linalg.cholesky(matrix)
248
+
249
+ except:
250
+ # raise Warning('Covariance is not positive definite.')
251
+ positive_definite_matrix = sth.nearest_positive_definite(matrix)
252
+ decomposition = np.linalg.cholesky(positive_definite_matrix)
253
+
254
+ # return (decomposition @ rvs.T).T
255
+ return np.matmul(decomposition, rvs.T).T
256
+
257
+ # #### Converter #### #
258
+
259
+ @staticmethod
260
+ def to_returns(log_returns: Iterable) -> np.ndarray:
261
+ """
262
+ This method exponentiates a sequence of log-returns to returns.
263
+
264
+ Parameters
265
+ ----------
266
+ log_returns : Iterable
267
+ An iterable containing log returns.
268
+
269
+ Returns
270
+ -------
271
+ np.ndarray
272
+ An array of returns.
273
+ """
274
+ return np.exp(log_returns)
275
+
276
+ def to_prices(
277
+ self,
278
+ log_returns: Iterable,
279
+ start_value: float = 100.0
280
+ ) -> np.ndarray:
281
+ """
282
+ This method converts a sequence of log returns into normal returns
283
+ (exponentiation) and then computes a price sequence given a starting
284
+ price, start_value.
285
+
286
+ Parameters
287
+ ----------
288
+ log_returns : Iterable
289
+ An iterable containing log returns.
290
+ start_value : float, optional
291
+ The starting value of the price sequence. Default is 100.0.
292
+
293
+ Returns
294
+ -------
295
+ np.ndarray
296
+ An array of price sequences.
297
+ """
298
+
299
+ log_returns = np.cumsum(log_returns, axis=0)
300
+
301
+ returns = self.to_returns(log_returns)
302
+ # A sequence of prices starting with start_value
303
+ return returns * start_value
304
+
305
+ def to_pandas(self, output) -> pd.Series | pd.DataFrame:
306
+ """
307
+ Convert synthetic output to a pandas DataFrame or Series.
308
+
309
+ Parameters
310
+ ----------
311
+ output : np.ndarray
312
+ The synthetic output to convert.
313
+
314
+ Returns
315
+ -------
316
+ pd.DataFrame or pd.Series
317
+ A pandas DataFrame or Series containing the converted data.
318
+ """
319
+ return (
320
+ pd.Series(output[:, 0], index=self.index, name='symbol')
321
+ if output.shape[1] == 1
322
+ else pd.DataFrame(output, index=self.index, columns=['path_' + str(i+1) for i in range(self.num_paths)])
323
+ .rename_axis('Date', axis=0)
324
+ .rename_axis('symbol', axis=1)
325
+ )