quantstats-pro 0.4.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. quantstats/__init__.py +163 -0
  2. quantstats/_compat.py +431 -0
  3. quantstats/_montecarlo.py +296 -0
  4. quantstats/_numpy_compat.py +289 -0
  5. quantstats/_plotting/__init__.py +0 -0
  6. quantstats/_plotting/core.py +2173 -0
  7. quantstats/_plotting/wrappers.py +2109 -0
  8. quantstats/_reporting/__init__.py +12 -0
  9. quantstats/_reporting/engine.py +37 -0
  10. quantstats/_reporting/sections.py +223 -0
  11. quantstats/alphadecay/__init__.py +25 -0
  12. quantstats/alphadecay/core.py +712 -0
  13. quantstats/alphadecay/plotting.py +206 -0
  14. quantstats/montecarlo/__init__.py +34 -0
  15. quantstats/montecarlo/analytics.py +291 -0
  16. quantstats/montecarlo/base.py +92 -0
  17. quantstats/montecarlo/core.py +175 -0
  18. quantstats/montecarlo/models/__init__.py +15 -0
  19. quantstats/montecarlo/models/bayesian.py +88 -0
  20. quantstats/montecarlo/models/block_bootstrap.py +108 -0
  21. quantstats/montecarlo/models/bootstrap.py +38 -0
  22. quantstats/montecarlo/models/garch.py +83 -0
  23. quantstats/montecarlo/models/gbm.py +44 -0
  24. quantstats/montecarlo/models/heston.py +103 -0
  25. quantstats/montecarlo/models/jump_diffusion.py +86 -0
  26. quantstats/montecarlo/models/shuffle.py +49 -0
  27. quantstats/montecarlo/models/trimmed.py +50 -0
  28. quantstats/montecarlo/plotting.py +324 -0
  29. quantstats/montecarlo/registry.py +34 -0
  30. quantstats/plots.py +27 -0
  31. quantstats/py.typed +0 -0
  32. quantstats/report.html +64 -0
  33. quantstats/report_alpha_decay.html +43 -0
  34. quantstats/report_montecarlo.html +62 -0
  35. quantstats/report_simple.html +58 -0
  36. quantstats/reports.py +3502 -0
  37. quantstats/stats.py +3321 -0
  38. quantstats/utils.py +1011 -0
  39. quantstats/version.py +1 -0
  40. quantstats_pro-0.4.1.dist-info/METADATA +509 -0
  41. quantstats_pro-0.4.1.dist-info/RECORD +43 -0
  42. quantstats_pro-0.4.1.dist-info/WHEEL +4 -0
  43. quantstats_pro-0.4.1.dist-info/licenses/LICENSE.txt +202 -0
@@ -0,0 +1,296 @@
1
+ #!/usr/bin/env python
2
+ #
3
+ # QuantStats: Portfolio analytics for quants
4
+ # https://github.com/ranaroussi/quantstats
5
+ #
6
+ # Copyright 2019-2025 Ran Aroussi
7
+ #
8
+ # Licensed under the Apache License, Version 2.0 (the "License");
9
+ # you may not use this file except in compliance with the License.
10
+ # You may obtain a copy of the License at
11
+ #
12
+ # http://www.apache.org/licenses/LICENSE-2.0
13
+ #
14
+ # Unless required by applicable law or agreed to in writing, software
15
+ # distributed under the License is distributed on an "AS IS" BASIS,
16
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
+ # See the License for the specific language governing permissions and
18
+ # limitations under the License.
19
+
20
+ """
21
+ Monte Carlo Simulation Module
22
+
23
+ This module provides Monte Carlo simulation functionality for portfolio
24
+ analysis. It allows users to generate multiple simulated return paths
25
+ by shuffling historical returns, enabling probability-based risk assessment.
26
+ """
27
+
28
+ from dataclasses import dataclass, field
29
+ from typing import Any
30
+
31
+ import numpy as np
32
+ import pandas as pd
33
+
34
+
35
+ @dataclass
36
+ class MonteCarloResult:
37
+ """
38
+ Container for Monte Carlo simulation results.
39
+
40
+ This class holds the results of a Monte Carlo simulation and provides
41
+ convenient methods for analyzing and visualizing the simulated paths.
42
+
43
+ Attributes
44
+ ----------
45
+ data : pd.DataFrame
46
+ Raw simulation paths (sims x periods) as cumulative returns
47
+ original : pd.Series
48
+ Original cumulative returns path
49
+ bust_threshold : float, optional
50
+ Drawdown threshold used for bust probability calculation
51
+ goal_threshold : float, optional
52
+ Return threshold used for goal probability calculation
53
+
54
+ Examples
55
+ --------
56
+ >>> import quantstats as qs
57
+ >>> returns = qs.utils.download_returns("SPY")
58
+ >>> mc = qs.stats.montecarlo(returns, sims=1000)
59
+ >>> print(mc.stats)
60
+ >>> mc.plot()
61
+ """
62
+
63
+ data: pd.DataFrame
64
+ original: pd.Series
65
+ bust_threshold: float | None = None
66
+ goal_threshold: float | None = None
67
+ _maxdd_cache: pd.Series | None = field(default=None, repr=False)
68
+
69
+ @property
70
+ def stats(self) -> dict[str, float]:
71
+ """
72
+ Terminal value statistics across all simulations.
73
+
74
+ Returns
75
+ -------
76
+ dict
77
+ Dictionary containing min, max, mean, median, std of terminal values
78
+ """
79
+ terminal = self.data.iloc[-1]
80
+ return {
81
+ "min": terminal.min(),
82
+ "max": terminal.max(),
83
+ "mean": terminal.mean(),
84
+ "median": terminal.median(),
85
+ "std": terminal.std(),
86
+ "percentile_5": terminal.quantile(0.05),
87
+ "percentile_25": terminal.quantile(0.25),
88
+ "percentile_75": terminal.quantile(0.75),
89
+ "percentile_95": terminal.quantile(0.95),
90
+ }
91
+
92
+ @property
93
+ def maxdd(self) -> dict[str, float]:
94
+ """
95
+ Maximum drawdown statistics across all simulations.
96
+
97
+ Returns
98
+ -------
99
+ dict
100
+ Dictionary containing min, max, mean, median of max drawdowns
101
+ """
102
+ if self._maxdd_cache is None:
103
+ # Calculate max drawdown for each simulation path
104
+ maxdd_values = []
105
+ for col in self.data.columns:
106
+ path = self.data[col]
107
+ # Calculate drawdown from cumulative returns
108
+ cumulative = path + 1 # Convert to growth factor
109
+ running_max = cumulative.cummax()
110
+ drawdown = (cumulative - running_max) / running_max
111
+ maxdd_values.append(drawdown.min())
112
+ object.__setattr__(self, "_maxdd_cache", pd.Series(maxdd_values))
113
+
114
+ dd = self._maxdd_cache
115
+ return {
116
+ "min": dd.min(), # Worst (most negative) drawdown
117
+ "max": dd.max(), # Best (least negative) drawdown
118
+ "mean": dd.mean(),
119
+ "median": dd.median(),
120
+ "std": dd.std(),
121
+ "percentile_5": dd.quantile(0.05),
122
+ "percentile_95": dd.quantile(0.95),
123
+ }
124
+
125
+ @property
126
+ def bust_probability(self) -> float | None:
127
+ """
128
+ Probability of exceeding the bust (drawdown) threshold.
129
+
130
+ Returns
131
+ -------
132
+ float or None
133
+ Probability of bust if threshold was set, None otherwise
134
+ """
135
+ if self.bust_threshold is None:
136
+ return None
137
+
138
+ if self._maxdd_cache is None:
139
+ # Trigger maxdd calculation
140
+ _ = self.maxdd
141
+
142
+ # Count simulations where max drawdown exceeds bust threshold
143
+ bust_count = (self._maxdd_cache <= self.bust_threshold).sum()
144
+ return bust_count / len(self._maxdd_cache)
145
+
146
+ @property
147
+ def goal_probability(self) -> float | None:
148
+ """
149
+ Probability of reaching the goal (return) threshold.
150
+
151
+ Returns
152
+ -------
153
+ float or None
154
+ Probability of reaching goal if threshold was set, None otherwise
155
+ """
156
+ if self.goal_threshold is None:
157
+ return None
158
+
159
+ terminal = self.data.iloc[-1]
160
+ goal_count = (terminal >= self.goal_threshold).sum()
161
+ return goal_count / len(terminal)
162
+
163
+ def percentile(self, p: float) -> pd.Series:
164
+ """
165
+ Get the p-th percentile path across all simulations.
166
+
167
+ Parameters
168
+ ----------
169
+ p : float
170
+ Percentile value between 0 and 100
171
+
172
+ Returns
173
+ -------
174
+ pd.Series
175
+ The p-th percentile path
176
+ """
177
+ return self.data.quantile(p / 100, axis=1)
178
+
179
+ def confidence_band(
180
+ self, level: float = 0.95
181
+ ) -> tuple[pd.Series, pd.Series]:
182
+ """
183
+ Get lower and upper bounds for a confidence interval.
184
+
185
+ Parameters
186
+ ----------
187
+ level : float, default 0.95
188
+ Confidence level (e.g., 0.95 for 95% confidence interval)
189
+
190
+ Returns
191
+ -------
192
+ tuple
193
+ (lower_bound, upper_bound) as pd.Series
194
+ """
195
+ alpha = (1 - level) / 2
196
+ lower = self.data.quantile(alpha, axis=1)
197
+ upper = self.data.quantile(1 - alpha, axis=1)
198
+ return lower, upper
199
+
200
+ def plot(self, **kwargs) -> Any:
201
+ """
202
+ Plot all simulation paths with the original path highlighted.
203
+
204
+ Parameters
205
+ ----------
206
+ **kwargs
207
+ Additional arguments passed to the plotting function
208
+
209
+ Returns
210
+ -------
211
+ matplotlib.figure.Figure
212
+ The generated figure
213
+ """
214
+ # Import here to avoid circular imports
215
+ from . import plots
216
+
217
+ return plots.montecarlo(self, **kwargs)
218
+
219
+
220
+ def run_montecarlo(
221
+ returns: pd.Series,
222
+ sims: int = 1000,
223
+ bust: float | None = None,
224
+ goal: float | None = None,
225
+ seed: int | None = None,
226
+ ) -> MonteCarloResult:
227
+ """
228
+ Run Monte Carlo simulation by shuffling returns.
229
+
230
+ This function creates multiple simulated return paths by randomly
231
+ shuffling the historical returns. This preserves the return distribution
232
+ while breaking any time-series dependencies.
233
+
234
+ Parameters
235
+ ----------
236
+ returns : pd.Series
237
+ Daily returns (not prices)
238
+ sims : int, default 1000
239
+ Number of simulations to run
240
+ bust : float, optional
241
+ Drawdown threshold for "bust" probability (e.g., -0.1 for -10%)
242
+ goal : float, optional
243
+ Return threshold for "goal" probability (e.g., 1.0 for +100%)
244
+ seed : int, optional
245
+ Random seed for reproducibility
246
+
247
+ Returns
248
+ -------
249
+ MonteCarloResult
250
+ Object containing simulation results with stats, maxdd, and plot methods
251
+
252
+ Examples
253
+ --------
254
+ >>> import quantstats as qs
255
+ >>> returns = pd.Series([0.01, -0.02, 0.03, -0.01, 0.02])
256
+ >>> mc = run_montecarlo(returns, sims=100, bust=-0.1, goal=0.5)
257
+ >>> print(mc.stats)
258
+ >>> print(f"Bust probability: {mc.bust_probability:.1%}")
259
+ """
260
+ # Initialize random number generator
261
+ rng = np.random.default_rng(seed)
262
+
263
+ # Get returns as numpy array for efficiency
264
+ returns_array = returns.dropna().values
265
+ n_periods = len(returns_array)
266
+
267
+ # Pre-allocate simulation array
268
+ sim_returns = np.empty((n_periods, sims))
269
+
270
+ # First column is original (unshuffled) returns
271
+ sim_returns[:, 0] = returns_array
272
+
273
+ # Generate shuffled paths
274
+ for i in range(1, sims):
275
+ sim_returns[:, i] = rng.permutation(returns_array)
276
+
277
+ # Calculate cumulative returns for all paths
278
+ # Using (1 + r).cumprod() - 1 formula
279
+ cumulative = np.cumprod(1 + sim_returns, axis=0) - 1
280
+
281
+ # Create DataFrame with simulation results
282
+ sim_df = pd.DataFrame(
283
+ cumulative,
284
+ index=range(n_periods),
285
+ columns=[f"sim_{i}" for i in range(sims)],
286
+ )
287
+
288
+ # Original cumulative returns
289
+ original = pd.Series(cumulative[:, 0], index=range(n_periods), name="original")
290
+
291
+ return MonteCarloResult(
292
+ data=sim_df,
293
+ original=original,
294
+ bust_threshold=bust,
295
+ goal_threshold=goal,
296
+ )
@@ -0,0 +1,289 @@
1
+ #!/usr/bin/env python
2
+ """
3
+ Numpy compatibility layer
4
+ Handles numpy version differences and deprecated functionality
5
+
6
+ This module provides a unified interface for working with different versions of numpy,
7
+ ensuring that quantstats functions work consistently across various numpy versions.
8
+ It handles deprecated functionality, version-specific changes, and provides fallback
9
+ mechanisms for functions that may not exist in older versions.
10
+ """
11
+
12
+ import warnings
13
+ from typing import Any
14
+
15
+ import numpy as np
16
+ from packaging import version
17
+
18
+ # Version detection - Parse numpy version string to enable version comparisons
19
+ NUMPY_VERSION = version.parse(np.__version__)
20
+
21
+ # Handle deprecated numpy functions
22
+ # In numpy 1.25.0+, np.product was deprecated in favor of np.prod
23
+ if version.parse("1.25.0") <= NUMPY_VERSION:
24
+ # Use np.prod instead of deprecated np.product for newer versions
25
+ product = np.prod
26
+ else:
27
+ # Use np.product if available, otherwise fallback to np.prod for older versions
28
+ product = getattr(np, "product", np.prod)
29
+
30
+
31
+ def safe_numpy_operation(data, operation: str):
32
+ """
33
+ Safe numpy operations with deprecation handling.
34
+
35
+ This function provides a unified interface for numpy operations that may
36
+ have been deprecated or changed behavior across different numpy versions.
37
+ It handles the transition from deprecated functions to their replacements.
38
+
39
+ Parameters
40
+ ----------
41
+ data : array_like
42
+ Input data to perform the operation on. Can be any array-like structure
43
+ that numpy can process (list, tuple, numpy array, etc.)
44
+ operation : str
45
+ The numpy operation to perform. Supported operations include 'product',
46
+ 'prod', and any other numpy function name that exists in the current version
47
+
48
+ Returns
49
+ -------
50
+ ndarray
51
+ Result of the numpy operation applied to the input data
52
+
53
+ Examples
54
+ --------
55
+ >>> safe_numpy_operation([1, 2, 3, 4], 'product') # Returns 24
56
+ >>> safe_numpy_operation([1, 2, 3, 4], 'sum') # Returns 10
57
+ """
58
+ # Handle the deprecated 'product' operation specifically
59
+ if operation == "product":
60
+ # Use our version-aware product function
61
+ return product(data)
62
+ elif operation == "prod":
63
+ # Use np.prod directly for 'prod' operation
64
+ return np.prod(data)
65
+ else:
66
+ # For all other operations, dynamically get the function from numpy
67
+ # This allows for flexible operation support across numpy versions
68
+ return getattr(np, operation)(data)
69
+
70
+
71
+ def safe_array_function(func_name: str, *args, **kwargs) -> Any:
72
+ """
73
+ Safe wrapper for numpy array functions.
74
+
75
+ This function provides a safe way to call numpy functions that may not exist
76
+ in all numpy versions or have been deprecated. It handles version-specific
77
+ function availability and provides meaningful error messages.
78
+
79
+ Parameters
80
+ ----------
81
+ func_name : str
82
+ Name of the numpy function to call (e.g., 'mean', 'std', 'product')
83
+ *args
84
+ Positional arguments to pass to the numpy function
85
+ **kwargs
86
+ Keyword arguments to pass to the numpy function
87
+
88
+ Returns
89
+ -------
90
+ Any
91
+ Result of the numpy function call. Return type depends on the specific
92
+ function being called and the input data.
93
+
94
+ Raises
95
+ ------
96
+ AttributeError
97
+ If the requested function doesn't exist in the current numpy version
98
+
99
+ Examples
100
+ --------
101
+ >>> safe_array_function('mean', [1, 2, 3, 4]) # Returns 2.5
102
+ >>> safe_array_function('product', [1, 2, 3, 4]) # Returns 24
103
+ """
104
+ # Handle deprecated functions with special cases
105
+ if func_name == "product":
106
+ # Use our version-aware product function
107
+ return product(*args, **kwargs)
108
+
109
+ # Handle functions that might not exist in older numpy versions
110
+ if hasattr(np, func_name):
111
+ # Function exists in current numpy version, call it normally
112
+ return getattr(np, func_name)(*args, **kwargs)
113
+ else:
114
+ # Function doesn't exist in current numpy version, raise informative error
115
+ raise AttributeError(
116
+ f"numpy has no attribute '{func_name}' in version {NUMPY_VERSION}"
117
+ )
118
+
119
+
120
+ def handle_numpy_warnings():
121
+ """
122
+ Context manager to handle numpy warnings appropriately.
123
+
124
+ This function returns a context manager that can be used to suppress
125
+ or handle numpy warnings in a controlled manner. Useful for managing
126
+ deprecation warnings and other numpy-specific warnings when working
127
+ with multiple numpy versions.
128
+
129
+ Returns
130
+ -------
131
+ warnings.catch_warnings
132
+ A context manager for handling numpy warnings
133
+
134
+ Examples
135
+ --------
136
+ >>> with handle_numpy_warnings():
137
+ ... # Code that might generate numpy warnings
138
+ ... result = np.some_deprecated_function()
139
+ """
140
+ # Return the warnings context manager for flexible warning handling
141
+ return warnings.catch_warnings()
142
+
143
+
144
+ def safe_percentile(data, percentile: float | list, **kwargs):
145
+ """
146
+ Safe percentile calculation.
147
+
148
+ This function provides a wrapper around np.percentile with consistent parameters.
149
+
150
+ Parameters
151
+ ----------
152
+ data : array_like
153
+ Input data to calculate percentiles from. Can be any array-like
154
+ structure that numpy can process
155
+ percentile : float or array_like
156
+ Percentile(s) to compute. Values should be between 0 and 100.
157
+ Can be a single value or an array of values
158
+ **kwargs
159
+ Additional arguments passed to np.percentile
160
+
161
+ Returns
162
+ -------
163
+ float or ndarray
164
+ The computed percentile(s). Returns float for single percentile,
165
+ ndarray for multiple percentiles
166
+
167
+ Examples
168
+ --------
169
+ >>> safe_percentile([1, 2, 3, 4, 5], 50) # Returns 3.0 (median)
170
+ >>> safe_percentile([1, 2, 3, 4, 5], [25, 75]) # Returns [2.0, 4.0]
171
+ """
172
+ # Numpy 1.24+ supports 'method' parameter for percentile calculation
173
+ return np.percentile(data, percentile, **kwargs)
174
+
175
+
176
+ def safe_nanpercentile(data, percentile: float | list, **kwargs):
177
+ """
178
+ Safe nanpercentile calculation that ignores NaN values.
179
+
180
+ This function provides a wrapper around np.nanpercentile with consistent parameters.
181
+
182
+ Parameters
183
+ ----------
184
+ data : array_like
185
+ Input data to calculate percentiles from. NaN values are ignored.
186
+ Can be any array-like structure that numpy can process
187
+ percentile : float or array_like
188
+ Percentile(s) to compute. Values should be between 0 and 100.
189
+ Can be a single value or an array of values
190
+ **kwargs
191
+ Additional arguments passed to np.nanpercentile
192
+
193
+ Returns
194
+ -------
195
+ float or ndarray
196
+ The computed percentile(s) ignoring NaN values. Returns float for
197
+ single percentile, ndarray for multiple percentiles
198
+
199
+ Examples
200
+ --------
201
+ >>> safe_nanpercentile([1, 2, np.nan, 4, 5], 50) # Returns 3.0
202
+ >>> safe_nanpercentile([1, np.nan, 3, 4, 5], [25, 75]) # Returns [2.0, 4.5]
203
+ """
204
+ # Numpy 1.24+ supports 'method' parameter for nanpercentile calculation
205
+ return np.nanpercentile(data, percentile, **kwargs)
206
+
207
+
208
+ def safe_quantile(data, quantile: float | list, **kwargs):
209
+ """
210
+ Safe quantile calculation.
211
+
212
+ This function provides a wrapper around np.quantile with consistent parameters.
213
+ Quantiles are similar to percentiles but use values between 0 and 1.
214
+
215
+ Parameters
216
+ ----------
217
+ data : array_like
218
+ Input data to calculate quantiles from. Can be any array-like
219
+ structure that numpy can process
220
+ quantile : float or array_like
221
+ Quantile(s) to compute. Values should be between 0 and 1.
222
+ Can be a single value or an array of values
223
+ **kwargs
224
+ Additional arguments passed to np.quantile
225
+
226
+ Returns
227
+ -------
228
+ float or ndarray
229
+ The computed quantile(s). Returns float for single quantile,
230
+ ndarray for multiple quantiles
231
+
232
+ Examples
233
+ --------
234
+ >>> safe_quantile([1, 2, 3, 4, 5], 0.5) # Returns 3.0 (median)
235
+ >>> safe_quantile([1, 2, 3, 4, 5], [0.25, 0.75]) # Returns [2.0, 4.0]
236
+ """
237
+ # Numpy 1.24+ supports 'method' parameter for quantile calculation
238
+ return np.quantile(data, quantile, **kwargs)
239
+
240
+
241
+ def safe_random_seed(seed: int | None):
242
+ """
243
+ Safe random seed setting for numpy.
244
+
245
+ This function provides a unified interface for setting random seeds.
246
+
247
+ Parameters
248
+ ----------
249
+ seed : int or None
250
+ Random seed value to set. If None, the random state is not modified.
251
+ Setting the same seed ensures reproducible random number sequences
252
+
253
+ Examples
254
+ --------
255
+ >>> safe_random_seed(42) # Sets seed for reproducible results
256
+ >>> safe_random_seed(None) # No seed set, random behavior continues
257
+ """
258
+ if seed is not None:
259
+ # Use the modern random number generator (numpy 1.17.0+)
260
+ np.random.default_rng(seed)
261
+
262
+
263
+ def safe_datetime64_unit(dt, unit: str):
264
+ """
265
+ Safe datetime64 unit conversion.
266
+
267
+ This function provides a safe way to convert numpy datetime64 objects
268
+ to different time units.
269
+
270
+ Parameters
271
+ ----------
272
+ dt : np.datetime64
273
+ Input datetime object to convert
274
+ unit : str
275
+ Target time unit (e.g., 'D' for days, 'H' for hours, 'M' for minutes,
276
+ 'S' for seconds, 'ms' for milliseconds)
277
+
278
+ Returns
279
+ -------
280
+ np.datetime64
281
+ Converted datetime object with the specified unit
282
+
283
+ Examples
284
+ --------
285
+ >>> dt = np.datetime64('2023-01-01T12:00:00')
286
+ >>> safe_datetime64_unit(dt, 'D') # Convert to day precision
287
+ >>> safe_datetime64_unit(dt, 'H') # Convert to hour precision
288
+ """
289
+ return dt.astype(f"datetime64[{unit}]")
File without changes