python-synthetica 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.
- python_synthetica-0.1.0.dist-info/LICENSE +28 -0
- python_synthetica-0.1.0.dist-info/METADATA +154 -0
- python_synthetica-0.1.0.dist-info/RECORD +10 -0
- python_synthetica-0.1.0.dist-info/WHEEL +4 -0
- synthetica/__init__.py +1 -0
- synthetica/base.py +325 -0
- synthetica/config.py +144 -0
- synthetica/decorators.py +23 -0
- synthetica/models.py +1170 -0
- synthetica/stats.py +92 -0
|
@@ -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,10 @@
|
|
|
1
|
+
synthetica/__init__.py,sha256=99jkGjWUHeLLcXJrwjXry0LnPYcDwCAZTX6qrq7uJ_o,661
|
|
2
|
+
synthetica/base.py,sha256=gKDPkZffmxULl-lwlLrONqOinf1tEAbArrjs0_4ndh4,9659
|
|
3
|
+
synthetica/config.py,sha256=1BMBX-_jgcAwTx5ScDOKxo1o_vhjdb5aPNkqoiKGtWs,5419
|
|
4
|
+
synthetica/decorators.py,sha256=UviOzuakWxYJhIrk45pCSiXQ31k_THP7D51G5dI3XNE,685
|
|
5
|
+
synthetica/models.py,sha256=MkhOsUHZatCXUK-KVmIp63DdhtEMmdcoRRD6lwmeds0,36326
|
|
6
|
+
synthetica/stats.py,sha256=sCCOnMQW-u8RjF9qt_thMRiDuK9Go1zXKt1E747dDgk,4539
|
|
7
|
+
python_synthetica-0.1.0.dist-info/LICENSE,sha256=21uLyapFHtmAwFu9xSuBgWtL49QtMIzTmI9Lq0w94MI,1502
|
|
8
|
+
python_synthetica-0.1.0.dist-info/METADATA,sha256=eyIJ13E0a8yzJtaetpNaFJL-nGJ4olr4oRDOtjBXT8w,5410
|
|
9
|
+
python_synthetica-0.1.0.dist-info/WHEEL,sha256=FMvqSimYX_P7y0a7UY-_Mc83r5zkBZsCYPm7Lr0Bsq4,88
|
|
10
|
+
python_synthetica-0.1.0.dist-info/RECORD,,
|
synthetica/__init__.py
ADDED
|
@@ -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"
|
synthetica/base.py
ADDED
|
@@ -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
|
+
)
|
synthetica/config.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
@dataclass
|
|
5
|
+
class SyntheticConfig:
|
|
6
|
+
"""
|
|
7
|
+
A data class for configuration parameters used in synthetic data
|
|
8
|
+
generation.
|
|
9
|
+
|
|
10
|
+
This data class defines various configuration parameters that can be used
|
|
11
|
+
in synthetic data generation methods.
|
|
12
|
+
|
|
13
|
+
Attributes:
|
|
14
|
+
----------
|
|
15
|
+
start_value : float, optional
|
|
16
|
+
The starting asset value. Default is 100.0.
|
|
17
|
+
start_rate : float, optional
|
|
18
|
+
The starting interest rate value. Default is 0.5.
|
|
19
|
+
num_paths : int, optional
|
|
20
|
+
The number of paths to simulate. Default is 1.
|
|
21
|
+
length : int, optional
|
|
22
|
+
The length of the simulation. Default is 252.
|
|
23
|
+
delta : float, optional
|
|
24
|
+
The rate of time (e.g., 1/252 for daily). Default is 1/252.
|
|
25
|
+
sigma : float, optional
|
|
26
|
+
The volatility of the stochastic processes. Default is 0.125.
|
|
27
|
+
matrix : np.ndarray or pd.DataFrame, optional
|
|
28
|
+
The matrix applied in Cholesky decomposition (optional).
|
|
29
|
+
gbm_mu : float, optional
|
|
30
|
+
The annual drift factor for geometric Brownian motion. Default is
|
|
31
|
+
0.058.
|
|
32
|
+
jumps_lambda : float, optional
|
|
33
|
+
The probability of a jump happening at each point in time for Merton
|
|
34
|
+
model. Default is 0.00025.
|
|
35
|
+
jumps_sigma : float, optional
|
|
36
|
+
The volatility of the jump size for Merton model. Default is 0.001.
|
|
37
|
+
jumps_mu : float, optional
|
|
38
|
+
The average jump size for Merton model. Default is 0.2.
|
|
39
|
+
cir_kappa : float, optional
|
|
40
|
+
The rate of mean reversion for Cox Ingersoll Ross model.
|
|
41
|
+
Default is 3.0.
|
|
42
|
+
cir_mu : float, optional
|
|
43
|
+
The long-run average interest rate for Cox Ingersoll Ross model.
|
|
44
|
+
Default is 0.5.
|
|
45
|
+
cir_rho : float, optional
|
|
46
|
+
The correlation between the Wiener processes of the Heston model.
|
|
47
|
+
Default is 0.5.
|
|
48
|
+
ou_kappa : float, optional
|
|
49
|
+
The rate of mean reversion for Ornstein Uhlenbeck model.
|
|
50
|
+
Default is 3.0.
|
|
51
|
+
ou_mu : float, optional
|
|
52
|
+
The long-run average interest rate for Ornstein Uhlenbeck model.
|
|
53
|
+
Default is 0.5.
|
|
54
|
+
heston_kappa : float, optional
|
|
55
|
+
The rate of mean reversion for volatility in the Heston model.
|
|
56
|
+
Default is 3.
|
|
57
|
+
heston_theta : float, optional
|
|
58
|
+
The long-run average volatility for the Heston model.
|
|
59
|
+
Default is 0.20^2.
|
|
60
|
+
heston_vol0 : float, optional
|
|
61
|
+
The starting volatility value for the Heston model.
|
|
62
|
+
Default is 0.25^2.
|
|
63
|
+
heston_sigma : float, optional
|
|
64
|
+
The vol of vol / volatility of variance process for the Heston model.
|
|
65
|
+
Default is 0.6.
|
|
66
|
+
heston_rf : float, optional
|
|
67
|
+
The risk-free rate for the Heston model. Default is 0.02.
|
|
68
|
+
heston_rho : float, optional
|
|
69
|
+
The correlation between asset returns and variance for the Heston
|
|
70
|
+
model. Default is 0.7.
|
|
71
|
+
levy_alpha : float, optional
|
|
72
|
+
The alpha parameter in the Levy Stable diffusion. Default is 1.68.
|
|
73
|
+
levy_beta : float, optional
|
|
74
|
+
The beta parameter in the Levy Stable diffusion. Default is 0.01.
|
|
75
|
+
|
|
76
|
+
"""
|
|
77
|
+
# General params
|
|
78
|
+
|
|
79
|
+
# This is the starting asset value
|
|
80
|
+
start_value: float = 100.0
|
|
81
|
+
# This is the starting interest rate value
|
|
82
|
+
start_rate: float = 0.5
|
|
83
|
+
# This is the amount of time to simulate for
|
|
84
|
+
num_paths: int = 1
|
|
85
|
+
# This is the time decay to iterate through
|
|
86
|
+
length: int = 252
|
|
87
|
+
# This is the delta, the rate of time e.g. 1/252 = daily, 1/12 = monthly
|
|
88
|
+
delta: float = 1/252
|
|
89
|
+
# This is the volatility of the stochastic processes
|
|
90
|
+
sigma: float = 0.125
|
|
91
|
+
# This is the matrix applied on the cholesky decomposition (optional)
|
|
92
|
+
matrix = None
|
|
93
|
+
|
|
94
|
+
# GBM
|
|
95
|
+
# ---
|
|
96
|
+
# This is the annual drift factor for geometric brownian motion
|
|
97
|
+
gbm_mu: float = 0.058
|
|
98
|
+
|
|
99
|
+
# Merton
|
|
100
|
+
# ------
|
|
101
|
+
# This is the probability of a jump happening at each point in time
|
|
102
|
+
jumps_lambda: float = 0.00025
|
|
103
|
+
# This is the volatility of the jump size
|
|
104
|
+
jumps_sigma: float = 0.001
|
|
105
|
+
# This is the average jump size
|
|
106
|
+
jumps_mu: float = 0.2
|
|
107
|
+
|
|
108
|
+
# CIR
|
|
109
|
+
# ---
|
|
110
|
+
# This is the rate of mean reversion for Cox Ingersoll Ross
|
|
111
|
+
cir_kappa: float = 3.0
|
|
112
|
+
# This is the long run average interest rate for Cox Ingersoll Ross
|
|
113
|
+
cir_mu: float = 0.5
|
|
114
|
+
# This is the correlation between the wiener processes of the Heston model
|
|
115
|
+
cir_rho: float = 0.5
|
|
116
|
+
|
|
117
|
+
# Ornstein Uhlenbeck
|
|
118
|
+
# ------------------
|
|
119
|
+
# This is the rate of mean reversion for Ornstein Uhlenbeck
|
|
120
|
+
ou_kappa: float = 3.0
|
|
121
|
+
# This is the long run average interest rate for Ornstein Uhlenbeck
|
|
122
|
+
ou_mu: float = 0.5
|
|
123
|
+
|
|
124
|
+
# Heston
|
|
125
|
+
# ------
|
|
126
|
+
# This is the rate of mean reversion for volatility in the Heston model
|
|
127
|
+
heston_kappa: float = 3
|
|
128
|
+
# This is the long run average volatility for the Heston model
|
|
129
|
+
heston_theta: float = 0.20**2
|
|
130
|
+
# This is the starting volatility value for the Heston model
|
|
131
|
+
heston_vol0: float = 0.25**2
|
|
132
|
+
# This is the vol of vol / volatility of variance process for the Heston model
|
|
133
|
+
heston_sigma: float = 0.6
|
|
134
|
+
# This is the risk-free rate for the Heston model
|
|
135
|
+
heston_rf: float = 0.02
|
|
136
|
+
# This is the correlation between asset returns and variance for the Heston model
|
|
137
|
+
heston_rho: float = 0.7
|
|
138
|
+
|
|
139
|
+
# Levy Stable
|
|
140
|
+
# -----------
|
|
141
|
+
# This is the alpha parameter in the Levy Stable diffusion
|
|
142
|
+
levy_alpha: float = 1.68
|
|
143
|
+
# This is the beta parameter in the Levy Stable diffusion
|
|
144
|
+
levy_beta: float = 0.01
|