python-synthetica 0.1.3__tar.gz → 0.1.4__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: python-synthetica
3
- Version: 0.1.3
3
+ Version: 0.1.4
4
4
  Summary: Generate synthetic time series data.
5
5
  Home-page: https://github.com/ActurialCapital/synthetica
6
6
  License: BSD 3-Clause License
@@ -132,9 +132,89 @@ In this example, we are using the following parameters for illustration purposes
132
132
 
133
133
  <p align="right">(<a href="#readme-top">back to top</a>)</p>
134
134
 
135
- ## Positive Definiteness
135
+ ## Notes
136
136
 
137
- ### What positive definite means in a covariance matrix
137
+ ### Cholesky Decomposition
138
+
139
+ The Cholesky transformation (or Cholesky decomposition) is a mathematical technique used to decompose a positive definite matrix into the product of a lower triangular matrix and its transpose. This is particularly useful in various fields such as numerical analysis, optimization, and financial modeling.
140
+
141
+ #### Mathematical Definition
142
+
143
+ Given a positive definite matrix $\(A\)$, the Cholesky decomposition is a factorization such that:
144
+ $\[ A = L L^T \]$
145
+ where:
146
+ - $\(A\)$ is a positive definite matrix.
147
+ - $\(L\)$ is a lower triangular matrix.
148
+ - $\(L^T\)$ is the transpose of $\(L\)$.
149
+
150
+ ### Applications
151
+
152
+ 1. **Numerical Stability**: The Cholesky decomposition is more numerically stable than other decomposition methods for positive definite matrices.
153
+ 2. **Solving Linear Systems**: It is used to solve linear systems of equations efficiently.
154
+ 3. **Simulating Correlated Random Variables**: In finance and statistics, it is used to generate correlated random variables from uncorrelated ones.
155
+
156
+ ### Implementation
157
+
158
+ In the context of synthetic data generation, the Cholesky transformation can be used to apply a correlation structure to a set of uncorrelated random variables.
159
+
160
+ ### Example Implementation in Python
161
+
162
+ Here's a simple example of how to implement and use the Cholesky transformation in Python:
163
+
164
+ ```python
165
+ import numpy as np
166
+
167
+ # Generate a positive definite matrix (covariance matrix)
168
+ def generate_positive_definite_matrix(size):
169
+ A = np.random.rand(size, size)
170
+ return np.dot(A, A.T) + size * np.eye(size)
171
+
172
+ # Apply Cholesky decomposition
173
+ def cholesky_transform(data, cov_matrix):
174
+ # Perform Cholesky decomposition
175
+ L = np.linalg.cholesky(cov_matrix)
176
+ # Transform the data
177
+ transformed_data = np.dot(data, L.T)
178
+ return transformed_data
179
+
180
+ # Example usage
181
+ np.random.seed(42)
182
+ size = 5 # Size of the covariance matrix
183
+ cov_matrix = generate_positive_definite_matrix(size)
184
+
185
+ # Generate synthetic data (uncorrelated random variables)
186
+ data = np.random.randn(100, size)
187
+
188
+ # Apply Cholesky transformation to impose the correlation structure
189
+ transformed_data = cholesky_transform(data, cov_matrix)
190
+
191
+ print("Original Data:\n", data[:5])
192
+ print("Transformed Data:\n", transformed_data[:5])
193
+ ```
194
+
195
+ ### Explanation
196
+
197
+ 1. **generate_positive_definite_matrix**:
198
+ - Generates a random positive definite matrix. This can be a covariance matrix in practical scenarios.
199
+
200
+ 2. **cholesky_transform**:
201
+ - Performs Cholesky decomposition on the covariance matrix to obtain the lower triangular matrix \(L\).
202
+ - Transforms the original uncorrelated data by multiplying it with \(L^T\) to introduce the desired correlation structure.
203
+
204
+ 3. **Example Usage**:
205
+ - Generates synthetic uncorrelated data.
206
+ - Applies the Cholesky transformation to this data using the generated covariance matrix.
207
+ - The transformed data now exhibits the correlation structure defined by the covariance matrix.
208
+
209
+ ### In the Context of the `LevyStable` Class
210
+
211
+ The `cholesky_transform` method in the `LevyStable` class would be used to apply a correlation structure to the generated synthetic data. This would allow for the generation of more realistic synthetic data that incorporates correlations between different paths or time series.
212
+
213
+ Here is how you could integrate and test the `cholesky_transform` method in the `LevyStable` class:
214
+
215
+ ### Positive Definiteness
216
+
217
+ #### What positive definite means in a covariance matrix
138
218
 
139
219
  A covariance matrix is considered positive definite if it satisfies the following key properties:
140
220
 
@@ -153,14 +233,14 @@ A covariance matrix that is positive semi-definite (allowing for eigenvalues to
153
233
 
154
234
  In practice, sample covariance matrices are often positive definite if the number of observations exceeds the number of variables and there are no perfect linear relationships among the variables.
155
235
 
156
- ### Implementation
236
+ #### Implementation
157
237
 
158
238
  `synthetica` automatically finds the nearest positive-definite matrix to input using `nearest_positive_definite` python function. it is directly sourced from [Computing a nearest symmetric positive semidefinite matrix](https://doi.org/10.1016/0024-3795(88)90223-6).
159
239
 
160
- ### Other Sources
240
+ #### Other Sources
161
241
 
162
- * [Matlab code](https://www.mathworks.com/matlabcentral/fileexchange/42885-nearestspd)
163
- * [Stackoverflow](https://stackoverflow.com/.../python-convert-matrix-to-positive-semi-definite)
242
+ * [MatLab](https://www.mathworks.com/matlabcentral/fileexchange/42885-nearestspd)
243
+ * [StackOverflow](https://stackoverflow.com/questions/43238173/python-convert-matrix-to-positive-semi-definite)
164
244
  * [Gist](https://gist.github.com/fasiha/fdb5cec2054e6f1c6ae35476045a0bbd)
165
245
 
166
246
  <!-- CONTRIBUTING -->
@@ -114,9 +114,89 @@ In this example, we are using the following parameters for illustration purposes
114
114
 
115
115
  <p align="right">(<a href="#readme-top">back to top</a>)</p>
116
116
 
117
- ## Positive Definiteness
117
+ ## Notes
118
118
 
119
- ### What positive definite means in a covariance matrix
119
+ ### Cholesky Decomposition
120
+
121
+ The Cholesky transformation (or Cholesky decomposition) is a mathematical technique used to decompose a positive definite matrix into the product of a lower triangular matrix and its transpose. This is particularly useful in various fields such as numerical analysis, optimization, and financial modeling.
122
+
123
+ #### Mathematical Definition
124
+
125
+ Given a positive definite matrix $\(A\)$, the Cholesky decomposition is a factorization such that:
126
+ $\[ A = L L^T \]$
127
+ where:
128
+ - $\(A\)$ is a positive definite matrix.
129
+ - $\(L\)$ is a lower triangular matrix.
130
+ - $\(L^T\)$ is the transpose of $\(L\)$.
131
+
132
+ ### Applications
133
+
134
+ 1. **Numerical Stability**: The Cholesky decomposition is more numerically stable than other decomposition methods for positive definite matrices.
135
+ 2. **Solving Linear Systems**: It is used to solve linear systems of equations efficiently.
136
+ 3. **Simulating Correlated Random Variables**: In finance and statistics, it is used to generate correlated random variables from uncorrelated ones.
137
+
138
+ ### Implementation
139
+
140
+ In the context of synthetic data generation, the Cholesky transformation can be used to apply a correlation structure to a set of uncorrelated random variables.
141
+
142
+ ### Example Implementation in Python
143
+
144
+ Here's a simple example of how to implement and use the Cholesky transformation in Python:
145
+
146
+ ```python
147
+ import numpy as np
148
+
149
+ # Generate a positive definite matrix (covariance matrix)
150
+ def generate_positive_definite_matrix(size):
151
+ A = np.random.rand(size, size)
152
+ return np.dot(A, A.T) + size * np.eye(size)
153
+
154
+ # Apply Cholesky decomposition
155
+ def cholesky_transform(data, cov_matrix):
156
+ # Perform Cholesky decomposition
157
+ L = np.linalg.cholesky(cov_matrix)
158
+ # Transform the data
159
+ transformed_data = np.dot(data, L.T)
160
+ return transformed_data
161
+
162
+ # Example usage
163
+ np.random.seed(42)
164
+ size = 5 # Size of the covariance matrix
165
+ cov_matrix = generate_positive_definite_matrix(size)
166
+
167
+ # Generate synthetic data (uncorrelated random variables)
168
+ data = np.random.randn(100, size)
169
+
170
+ # Apply Cholesky transformation to impose the correlation structure
171
+ transformed_data = cholesky_transform(data, cov_matrix)
172
+
173
+ print("Original Data:\n", data[:5])
174
+ print("Transformed Data:\n", transformed_data[:5])
175
+ ```
176
+
177
+ ### Explanation
178
+
179
+ 1. **generate_positive_definite_matrix**:
180
+ - Generates a random positive definite matrix. This can be a covariance matrix in practical scenarios.
181
+
182
+ 2. **cholesky_transform**:
183
+ - Performs Cholesky decomposition on the covariance matrix to obtain the lower triangular matrix \(L\).
184
+ - Transforms the original uncorrelated data by multiplying it with \(L^T\) to introduce the desired correlation structure.
185
+
186
+ 3. **Example Usage**:
187
+ - Generates synthetic uncorrelated data.
188
+ - Applies the Cholesky transformation to this data using the generated covariance matrix.
189
+ - The transformed data now exhibits the correlation structure defined by the covariance matrix.
190
+
191
+ ### In the Context of the `LevyStable` Class
192
+
193
+ The `cholesky_transform` method in the `LevyStable` class would be used to apply a correlation structure to the generated synthetic data. This would allow for the generation of more realistic synthetic data that incorporates correlations between different paths or time series.
194
+
195
+ Here is how you could integrate and test the `cholesky_transform` method in the `LevyStable` class:
196
+
197
+ ### Positive Definiteness
198
+
199
+ #### What positive definite means in a covariance matrix
120
200
 
121
201
  A covariance matrix is considered positive definite if it satisfies the following key properties:
122
202
 
@@ -135,14 +215,14 @@ A covariance matrix that is positive semi-definite (allowing for eigenvalues to
135
215
 
136
216
  In practice, sample covariance matrices are often positive definite if the number of observations exceeds the number of variables and there are no perfect linear relationships among the variables.
137
217
 
138
- ### Implementation
218
+ #### Implementation
139
219
 
140
220
  `synthetica` automatically finds the nearest positive-definite matrix to input using `nearest_positive_definite` python function. it is directly sourced from [Computing a nearest symmetric positive semidefinite matrix](https://doi.org/10.1016/0024-3795(88)90223-6).
141
221
 
142
- ### Other Sources
222
+ #### Other Sources
143
223
 
144
- * [Matlab code](https://www.mathworks.com/matlabcentral/fileexchange/42885-nearestspd)
145
- * [Stackoverflow](https://stackoverflow.com/.../python-convert-matrix-to-positive-semi-definite)
224
+ * [MatLab](https://www.mathworks.com/matlabcentral/fileexchange/42885-nearestspd)
225
+ * [StackOverflow](https://stackoverflow.com/questions/43238173/python-convert-matrix-to-positive-semi-definite)
146
226
  * [Gist](https://gist.github.com/fasiha/fdb5cec2054e6f1c6ae35476045a0bbd)
147
227
 
148
228
  <!-- CONTRIBUTING -->
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "python-synthetica"
3
- version = "0.1.3"
3
+ version = "0.1.4"
4
4
  description = "Generate synthetic time series data."
5
5
  authors = ["ActurialCapital"]
6
6
  license = "BSD 3-Clause License"
@@ -1,5 +1,5 @@
1
1
  from abc import ABC, abstractmethod
2
- from typing import Iterable
2
+ from typing import Iterable, Optional
3
3
  from functools import cached_property
4
4
  import numpy as np
5
5
  import pandas as pd
@@ -35,21 +35,20 @@ class BaseSynthetic(ABC):
35
35
 
36
36
  def __init__(
37
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
38
+ length: Optional[int | pd.DatetimeIndex] = 252,
39
+ num_paths: Optional[int] = 1,
40
+ mean: Optional[float] = 0,
41
+ delta: Optional[float] = 1/252,
42
+ sigma: Optional[float] = 0.125,
43
+ freq: Optional[str] = 'D',
44
+ seed: Optional[int] = None
45
45
  ):
46
46
  # Generic
47
47
  self._length = length
48
48
  self._freq = freq
49
49
  self._num_paths = num_paths
50
- if seed is not None:
51
- np.random.seed(seed)
52
-
50
+ self._seed = seed
51
+
53
52
  # White noise params
54
53
  self._mean = mean
55
54
  self._delta = delta
@@ -106,6 +105,20 @@ class BaseSynthetic(ABC):
106
105
  size=(self.length, self.num_paths)
107
106
  )
108
107
 
108
+ @property
109
+ def seed(self) -> int:
110
+ if self._seed is not None:
111
+ np.random.seed(self._seed)
112
+ return self._seed
113
+
114
+ @seed.setter
115
+ @sth.callback('white_noise')
116
+ def seed(self, value: int) -> float:
117
+ """Random seed value update"""
118
+ self._seed = value
119
+ if self._seed is not None:
120
+ np.random.seed(self._seed)
121
+
109
122
  @property
110
123
  def mean(self) -> float:
111
124
  """Mean value"""
@@ -113,7 +126,7 @@ class BaseSynthetic(ABC):
113
126
 
114
127
  @mean.setter
115
128
  @sth.callback('white_noise')
116
- def mean(self, value) -> float:
129
+ def mean(self, value: float) -> float:
117
130
  """Mean value update"""
118
131
  if value != self._mean:
119
132
  self._mean = value
@@ -125,7 +138,7 @@ class BaseSynthetic(ABC):
125
138
 
126
139
  @delta.setter
127
140
  @sth.callback('white_noise')
128
- def delta(self, value) -> float:
141
+ def delta(self, value: float) -> float:
129
142
  """Delta value update"""
130
143
  if value != self._delta:
131
144
  self._delta = value
@@ -137,7 +150,7 @@ class BaseSynthetic(ABC):
137
150
 
138
151
  @sigma.setter
139
152
  @sth.callback('white_noise')
140
- def sigma(self, value) -> float:
153
+ def sigma(self, value: float) -> float:
141
154
  """Sigma value update"""
142
155
  if value != self._sigma:
143
156
  self._sigma = value
@@ -184,20 +197,22 @@ class BaseSynthetic(ABC):
184
197
 
185
198
  # #### Cholesky #### #
186
199
 
187
- def create_corr_returns(self, matrix) -> pd.Series | pd.DataFrame:
200
+ @staticmethod
201
+ def cholesky_transform(rvs: np.array, matrix: np.array) -> np.ndarray:
188
202
  """
189
- This method can construct a basket of correlated asset paths using the
190
- Cholesky decomposition method.
203
+ Perform Cholesky transformation on random variables.
191
204
 
192
205
  Parameters
193
206
  ----------
194
- matrix : pd.DataFrame or np.array
195
- The matrix applied in Cholesky decomposition.
207
+ rvs : np.array
208
+ Random variables to transform.
209
+ matrix : np.array
210
+ The matrix for Cholesky decomposition.
196
211
 
197
212
  Returns
198
213
  -------
199
- pd.Series or pd.DataFrame:
200
- Data representing correlated log returns.
214
+ np.ndarray
215
+ Transformed random variables.
201
216
  """
202
217
  try:
203
218
  decomposition = np.linalg.cholesky(matrix)
@@ -206,54 +221,43 @@ class BaseSynthetic(ABC):
206
221
  updated_matrix = sth.nearest_positive_definite(matrix)
207
222
  decomposition = np.linalg.cholesky(updated_matrix)
208
223
 
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)
224
+ # return (decomposition @ rvs.T).T
225
+ return np.matmul(decomposition, rvs.T).T
229
226
 
230
- @staticmethod
231
- def cholesky_transform(rvs: np.array, matrix: np.array) -> np.ndarray:
227
+ def create_corr_returns(self, matrix: np.ndarray | pd.DataFrame) -> pd.Series | pd.DataFrame:
232
228
  """
233
- Perform Cholesky transformation on random variables.
229
+ This method can construct a basket of correlated asset paths using the
230
+ Cholesky decomposition method.
234
231
 
235
232
  Parameters
236
233
  ----------
237
- rvs : np.array
238
- Random variables to transform.
239
- matrix : np.array
240
- The matrix for Cholesky decomposition.
234
+ matrix : pd.DataFrame or np.array
235
+ The matrix applied in Cholesky decomposition.
241
236
 
242
237
  Returns
243
238
  -------
244
- np.ndarray
245
- Transformed random variables.
239
+ pd.Series or pd.DataFrame:
240
+ Data representing correlated log returns.
246
241
  """
247
- try:
248
- decomposition = np.linalg.cholesky(matrix)
242
+ self.seed # Regenerate seed
249
243
 
250
- except:
251
- # raise Warning('Covariance is not positive definite.')
252
- positive_definite_matrix = sth.nearest_positive_definite(matrix)
253
- decomposition = np.linalg.cholesky(positive_definite_matrix)
244
+ # Construct uncorrelated paths to convert into correlated paths
245
+ rvs = np.random.normal(
246
+ loc=0,
247
+ scale=np.sqrt(self.delta) * self.sigma,
248
+ size=(self.length + 1, self.num_paths)
249
+ )
250
+ rvs_matrix = np.matrix(rvs)
254
251
 
255
- # return (decomposition @ rvs.T).T
256
- return np.matmul(decomposition, rvs.T).T
252
+ correlated_matrix = self.cholesky_transform(rvs_matrix, matrix)
253
+
254
+ extracted_paths = [[] for _ in range(1, self.num_paths + 1)]
255
+ for j in range(0, len(correlated_matrix) * self.num_paths - self.num_paths, self.num_paths):
256
+ for i in range(self.num_paths):
257
+ extracted_paths[i].append(correlated_matrix.item(j + i))
258
+
259
+ output = np.array(extracted_paths).T
260
+ return self.to_pandas(output)
257
261
 
258
262
  # #### Converter #### #
259
263
 
@@ -277,7 +281,7 @@ class BaseSynthetic(ABC):
277
281
  def to_prices(
278
282
  self,
279
283
  log_returns: Iterable,
280
- start_value: float = 100.0
284
+ start_value: Optional[float] = 100.0
281
285
  ) -> np.ndarray:
282
286
  """
283
287
  This method converts a sequence of log returns into normal returns
@@ -303,7 +307,7 @@ class BaseSynthetic(ABC):
303
307
  # A sequence of prices starting with start_value
304
308
  return returns * start_value
305
309
 
306
- def to_pandas(self, output) -> pd.Series | pd.DataFrame:
310
+ def to_pandas(self, output: np.ndarray) -> pd.Series | pd.DataFrame:
307
311
  """
308
312
  Convert synthetic output to a pandas DataFrame or Series.
309
313