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
quantstats/__init__.py ADDED
@@ -0,0 +1,163 @@
1
+ #!/usr/bin/env python
2
+ #
3
+ # QuantStats Pro: Portfolio analytics for quants
4
+ # https://github.com/diegoalvarezmgl/quantstats-pro
5
+ # Original: https://github.com/ranaroussi/quantstats
6
+ #
7
+ # Copyright 2019-2025 Ran Aroussi
8
+ # Copyright 2025 Diego Alvarez
9
+ #
10
+ # Licensed under the Apache License, Version 2.0 (the "License");
11
+ # you may not use this file except in compliance with the License.
12
+ # You may obtain a copy of the License at
13
+ #
14
+ # http://www.apache.org/licenses/LICENSE-2.0
15
+ #
16
+ # Unless required by applicable law or agreed to in writing, software
17
+ # distributed under the License is distributed on an "AS IS" BASIS,
18
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ # See the License for the specific language governing permissions and
20
+ # limitations under the License.
21
+
22
+ from . import version
23
+
24
+ __version__ = version.version
25
+ __author__ = "Ran Aroussi"
26
+ __maintainer__ = "Diego Alvarez"
27
+
28
+ from . import plots, reports, stats, utils
29
+
30
+ __all__ = ["stats", "plots", "reports", "utils", "extend_pandas"]
31
+
32
+ # try automatic matplotlib inline
33
+ utils._in_notebook(matplotlib_inline=True)
34
+
35
+
36
+ def extend_pandas():
37
+ """
38
+ Extends pandas by exposing methods to be used like:
39
+ df.sharpe(), df.best('day'), ...
40
+ """
41
+ from pandas.core.base import PandasObject as _po # type: ignore[import]
42
+
43
+ _po.compsum = stats.compsum # type: ignore[attr-defined]
44
+ _po.comp = stats.comp # type: ignore[attr-defined]
45
+ _po.expected_return = stats.expected_return # type: ignore[attr-defined]
46
+ _po.geometric_mean = stats.geometric_mean # type: ignore[attr-defined]
47
+ _po.ghpr = stats.ghpr # type: ignore[attr-defined]
48
+ _po.outliers = stats.outliers # type: ignore[attr-defined]
49
+ _po.remove_outliers = stats.remove_outliers # type: ignore[attr-defined]
50
+ _po.best = stats.best # type: ignore[attr-defined]
51
+ _po.worst = stats.worst # type: ignore[attr-defined]
52
+ _po.consecutive_wins = stats.consecutive_wins # type: ignore[attr-defined]
53
+ _po.consecutive_losses = stats.consecutive_losses # type: ignore[attr-defined]
54
+ _po.exposure = stats.exposure # type: ignore[attr-defined]
55
+ _po.win_rate = stats.win_rate # type: ignore[attr-defined]
56
+ _po.avg_return = stats.avg_return # type: ignore[attr-defined]
57
+ _po.avg_win = stats.avg_win # type: ignore[attr-defined]
58
+ _po.avg_loss = stats.avg_loss # type: ignore[attr-defined]
59
+ _po.volatility = stats.volatility # type: ignore[attr-defined]
60
+ _po.rolling_volatility = stats.rolling_volatility # type: ignore[attr-defined]
61
+ _po.implied_volatility = stats.implied_volatility # type: ignore[attr-defined]
62
+ _po.sharpe = stats.sharpe # type: ignore[attr-defined]
63
+ _po.smart_sharpe = stats.smart_sharpe # type: ignore[attr-defined]
64
+ _po.rolling_sharpe = stats.rolling_sharpe # type: ignore[attr-defined]
65
+ _po.sortino = stats.sortino # type: ignore[attr-defined]
66
+ _po.smart_sortino = stats.smart_sortino # type: ignore[attr-defined]
67
+ _po.adjusted_sortino = stats.adjusted_sortino # type: ignore[attr-defined]
68
+ _po.rolling_sortino = stats.rolling_sortino # type: ignore[attr-defined]
69
+ _po.omega = stats.omega # type: ignore[attr-defined]
70
+ _po.cagr = stats.cagr # type: ignore[attr-defined]
71
+ _po.rar = stats.rar # type: ignore[attr-defined]
72
+ _po.skew = stats.skew # type: ignore[attr-defined]
73
+ _po.kurtosis = stats.kurtosis # type: ignore[attr-defined]
74
+ _po.calmar = stats.calmar # type: ignore[attr-defined]
75
+ _po.ulcer_index = stats.ulcer_index # type: ignore[attr-defined]
76
+ _po.ulcer_performance_index = stats.ulcer_performance_index # type: ignore[attr-defined]
77
+ _po.upi = stats.upi # type: ignore[attr-defined]
78
+ _po.serenity_index = stats.serenity_index # type: ignore[attr-defined]
79
+ _po.risk_of_ruin = stats.risk_of_ruin # type: ignore[attr-defined]
80
+ _po.ror = stats.ror # type: ignore[attr-defined]
81
+ _po.value_at_risk = stats.value_at_risk # type: ignore[attr-defined]
82
+ _po.var = stats.var # type: ignore[attr-defined]
83
+ _po.conditional_value_at_risk = stats.conditional_value_at_risk # type: ignore[attr-defined]
84
+ _po.cvar = stats.cvar # type: ignore[attr-defined]
85
+ _po.expected_shortfall = stats.expected_shortfall # type: ignore[attr-defined]
86
+ _po.tail_ratio = stats.tail_ratio # type: ignore[attr-defined]
87
+ _po.payoff_ratio = stats.payoff_ratio # type: ignore[attr-defined]
88
+ _po.win_loss_ratio = stats.win_loss_ratio # type: ignore[attr-defined]
89
+ _po.profit_ratio = stats.profit_ratio # type: ignore[attr-defined]
90
+ _po.profit_factor = stats.profit_factor # type: ignore[attr-defined]
91
+ _po.gain_to_pain_ratio = stats.gain_to_pain_ratio # type: ignore[attr-defined]
92
+ _po.cpc_index = stats.cpc_index # type: ignore[attr-defined]
93
+ _po.common_sense_ratio = stats.common_sense_ratio # type: ignore[attr-defined]
94
+ _po.outlier_win_ratio = stats.outlier_win_ratio # type: ignore[attr-defined]
95
+ _po.outlier_loss_ratio = stats.outlier_loss_ratio # type: ignore[attr-defined]
96
+ _po.recovery_factor = stats.recovery_factor # type: ignore[attr-defined]
97
+ _po.risk_return_ratio = stats.risk_return_ratio # type: ignore[attr-defined]
98
+ _po.max_drawdown = stats.max_drawdown # type: ignore[attr-defined]
99
+ _po.to_drawdown_series = stats.to_drawdown_series # type: ignore[attr-defined]
100
+ _po.kelly_criterion = stats.kelly_criterion # type: ignore[attr-defined]
101
+ _po.monthly_returns = stats.monthly_returns # type: ignore[attr-defined]
102
+ _po.pct_rank = stats.pct_rank # type: ignore[attr-defined]
103
+
104
+ _po.treynor_ratio = stats.treynor_ratio # type: ignore[attr-defined]
105
+ _po.probabilistic_sharpe_ratio = stats.probabilistic_sharpe_ratio # type: ignore[attr-defined]
106
+ _po.probabilistic_sortino_ratio = stats.probabilistic_sortino_ratio # type: ignore[attr-defined]
107
+ _po.probabilistic_adjusted_sortino_ratio = ( # type: ignore[attr-defined]
108
+ stats.probabilistic_adjusted_sortino_ratio
109
+ )
110
+
111
+ # Monte Carlo simulation
112
+ _po.montecarlo = stats.montecarlo # type: ignore[attr-defined]
113
+ _po.montecarlo_sharpe = stats.montecarlo_sharpe # type: ignore[attr-defined]
114
+ _po.montecarlo_drawdown = stats.montecarlo_drawdown # type: ignore[attr-defined]
115
+ _po.montecarlo_cagr = stats.montecarlo_cagr # type: ignore[attr-defined]
116
+
117
+ # methods from utils
118
+ _po.to_returns = utils.to_returns # type: ignore[attr-defined]
119
+ _po.to_prices = utils.to_prices # type: ignore[attr-defined]
120
+ _po.to_log_returns = utils.to_log_returns # type: ignore[attr-defined]
121
+ _po.log_returns = utils.log_returns # type: ignore[attr-defined]
122
+ _po.exponential_stdev = utils.exponential_stdev # type: ignore[attr-defined]
123
+ _po.rebase = utils.rebase # type: ignore[attr-defined]
124
+ _po.aggregate_returns = utils.aggregate_returns # type: ignore[attr-defined]
125
+ _po.to_excess_returns = utils.to_excess_returns # type: ignore[attr-defined]
126
+ _po.multi_shift = utils.multi_shift # type: ignore[attr-defined]
127
+ _po.curr_month = utils._pandas_current_month # type: ignore[attr-defined]
128
+ _po.date = utils._pandas_date # type: ignore[attr-defined]
129
+ _po.mtd = utils._mtd # type: ignore[attr-defined]
130
+ _po.qtd = utils._qtd # type: ignore[attr-defined]
131
+ _po.ytd = utils._ytd # type: ignore[attr-defined]
132
+
133
+ # methods that requires benchmark stats
134
+ _po.r_squared = stats.r_squared # type: ignore[attr-defined]
135
+ _po.r2 = stats.r2 # type: ignore[attr-defined]
136
+ _po.information_ratio = stats.information_ratio # type: ignore[attr-defined]
137
+ _po.greeks = stats.greeks # type: ignore[attr-defined]
138
+ _po.rolling_greeks = stats.rolling_greeks # type: ignore[attr-defined]
139
+ _po.compare = stats.compare # type: ignore[attr-defined]
140
+
141
+ # plotting methods
142
+ _po.plot_snapshot = plots.snapshot # type: ignore[attr-defined]
143
+ _po.plot_earnings = plots.earnings # type: ignore[attr-defined]
144
+ _po.plot_daily_returns = plots.daily_returns # type: ignore[attr-defined]
145
+ _po.plot_distribution = plots.distribution # type: ignore[attr-defined]
146
+ _po.plot_drawdown = plots.drawdown # type: ignore[attr-defined]
147
+ _po.plot_drawdowns_periods = plots.drawdowns_periods # type: ignore[attr-defined]
148
+ _po.plot_histogram = plots.histogram # type: ignore[attr-defined]
149
+ _po.plot_log_returns = plots.log_returns # type: ignore[attr-defined]
150
+ _po.plot_returns = plots.returns # type: ignore[attr-defined]
151
+ _po.plot_rolling_beta = plots.rolling_beta # type: ignore[attr-defined]
152
+ _po.plot_rolling_sharpe = plots.rolling_sharpe # type: ignore[attr-defined]
153
+ _po.plot_rolling_sortino = plots.rolling_sortino # type: ignore[attr-defined]
154
+ _po.plot_rolling_volatility = plots.rolling_volatility # type: ignore[attr-defined]
155
+ _po.plot_yearly_returns = plots.yearly_returns # type: ignore[attr-defined]
156
+ _po.plot_monthly_heatmap = plots.monthly_heatmap # type: ignore[attr-defined]
157
+ _po.plot_montecarlo = plots.montecarlo # type: ignore[attr-defined]
158
+ _po.plot_montecarlo_distribution = plots.montecarlo_distribution # type: ignore[attr-defined]
159
+
160
+ _po.metrics = reports.metrics # type: ignore[attr-defined]
161
+
162
+
163
+ # extend_pandas()
quantstats/_compat.py ADDED
@@ -0,0 +1,431 @@
1
+ #!/usr/bin/env python
2
+ """
3
+ Compatibility layer for pandas/numpy versions
4
+ Handles version differences and deprecated functionality
5
+
6
+ This module provides a unified interface for working with different versions of pandas
7
+ and numpy, ensuring that quantstats functions work consistently across various
8
+ dependency versions. It handles deprecated functionality and version-specific changes.
9
+ """
10
+
11
+ import warnings
12
+ from collections.abc import Callable
13
+
14
+ import numpy as np
15
+ import pandas as pd
16
+ import yfinance as yf
17
+ from packaging import version
18
+
19
+ # Version detection - Parse version strings to enable version comparisons
20
+ PANDAS_VERSION = version.parse(pd.__version__)
21
+ NUMPY_VERSION = version.parse(np.__version__)
22
+
23
+ # Frequency alias mapping for pandas compatibility
24
+ # Starting from pandas 2.2.0, frequency aliases changed to be more explicit
25
+ # M -> ME (Month End), Q -> QE (Quarter End), A/Y -> YE (Year End)
26
+ FREQUENCY_ALIASES = {
27
+ "M": "ME" if version.parse("2.2.0") <= PANDAS_VERSION else "M",
28
+ "Q": "QE" if version.parse("2.2.0") <= PANDAS_VERSION else "Q",
29
+ "A": "YE" if version.parse("2.2.0") <= PANDAS_VERSION else "A",
30
+ "Y": "YE" if version.parse("2.2.0") <= PANDAS_VERSION else "Y",
31
+ }
32
+
33
+
34
+ def get_frequency_alias(freq: str) -> str:
35
+ """
36
+ Get the correct frequency alias for current pandas version.
37
+
38
+ This function maps old frequency strings to their new equivalents in
39
+ pandas 2.2.0+, ensuring backward compatibility across pandas versions.
40
+
41
+ Parameters
42
+ ----------
43
+ freq : str
44
+ The frequency string (e.g., 'M', 'Q', 'A', 'Y')
45
+
46
+ Returns
47
+ -------
48
+ str
49
+ The appropriate frequency alias for the current pandas version
50
+
51
+ Examples
52
+ --------
53
+ >>> get_frequency_alias('M') # Returns 'ME' in pandas 2.2.0+, 'M' in older versions
54
+ >>> get_frequency_alias('D') # Returns 'D' (unchanged)
55
+ """
56
+ # Look up the frequency in our mapping, return original if not found
57
+ return FREQUENCY_ALIASES.get(freq, freq)
58
+
59
+
60
+ def normalize_timezone(data: pd.Series | pd.DataFrame) -> pd.Series | pd.DataFrame:
61
+ """
62
+ Normalize timezone information for consistent comparisons.
63
+
64
+ If data has timezone info, converts to UTC then removes timezone info.
65
+ This ensures all data can be compared regardless of original timezone.
66
+
67
+ Parameters
68
+ ----------
69
+ data : pd.Series or pd.DataFrame
70
+ Time series data with DatetimeIndex
71
+
72
+ Returns
73
+ -------
74
+ pd.Series or pd.DataFrame
75
+ Data with timezone-naive DatetimeIndex
76
+ """
77
+ if not isinstance(data.index, pd.DatetimeIndex):
78
+ return data
79
+
80
+ # If timezone aware, convert to UTC then make naive
81
+ if data.index.tz is not None:
82
+ result = data.copy()
83
+ result.index = result.index.tz_convert('UTC').tz_localize(None)
84
+ return result
85
+
86
+ # Already timezone naive, return as is
87
+ return data
88
+
89
+
90
+ def safe_resample(data: pd.Series | pd.DataFrame,
91
+ freq: str,
92
+ func_name: str | Callable | None = None,
93
+ **kwargs):
94
+ """
95
+ Safe resample operation that works with all pandas versions.
96
+
97
+ This function handles the resampling of time series data using the correct
98
+ frequency aliases and aggregation methods that are compatible across
99
+ different pandas versions. It also normalizes timezones to ensure
100
+ consistent comparisons.
101
+
102
+ Parameters
103
+ ----------
104
+ data : pd.Series or pd.DataFrame
105
+ The time series data to resample
106
+ freq : str
107
+ The frequency to resample to (e.g., 'M', 'Q', 'A', 'D')
108
+ func_name : str or callable, optional
109
+ The aggregation function to apply. Can be a string name like 'sum',
110
+ 'mean', 'std', etc., or a callable function
111
+ **kwargs
112
+ Additional arguments passed to the aggregation function
113
+
114
+ Returns
115
+ -------
116
+ pd.Series or pd.DataFrame
117
+ The resampled data with the specified frequency and aggregation,
118
+ with timezone normalized to UTC if present, or naive if not
119
+
120
+ Examples
121
+ --------
122
+ >>> safe_resample(data, 'M', 'sum') # Monthly sum aggregation
123
+ >>> safe_resample(data, 'Q', 'mean') # Quarterly mean aggregation
124
+ """
125
+ # Convert frequency to the appropriate alias for current pandas version
126
+ freq_alias = get_frequency_alias(freq)
127
+
128
+ # Create the resampler object using the correct frequency
129
+ resampler = data.resample(freq_alias)
130
+
131
+ # If no aggregation function specified, return the resampler object
132
+ if func_name is None:
133
+ return resampler
134
+
135
+ # Handle string function names with explicit method calls
136
+ # This approach avoids deprecation warnings and ensures compatibility
137
+ result = None
138
+ if isinstance(func_name, str):
139
+ # Map common aggregation functions to their pandas methods
140
+ if func_name == "sum":
141
+ result = resampler.sum(**kwargs)
142
+ elif func_name == "mean":
143
+ result = resampler.mean(**kwargs)
144
+ elif func_name == "std":
145
+ result = resampler.std(**kwargs)
146
+ elif func_name == "count":
147
+ result = resampler.count(**kwargs)
148
+ elif func_name == "min":
149
+ result = resampler.min(**kwargs)
150
+ elif func_name == "max":
151
+ result = resampler.max(**kwargs)
152
+ elif func_name == "first":
153
+ result = resampler.first(**kwargs)
154
+ elif func_name == "last":
155
+ result = resampler.last(**kwargs)
156
+ else:
157
+ # Try to find the method on the resampler object
158
+ if hasattr(resampler, func_name):
159
+ result = getattr(resampler, func_name)(**kwargs)
160
+ else:
161
+ # Fallback to apply for custom string functions
162
+ result = resampler.apply(func_name, **kwargs)
163
+ else:
164
+ # For callable functions, use apply method
165
+ # Suppress FutureWarning about callable usage - our use is intentional
166
+ with warnings.catch_warnings():
167
+ warnings.filterwarnings("ignore", category=FutureWarning,
168
+ message=".*callable.*")
169
+ result = resampler.apply(func_name, **kwargs)
170
+
171
+ # Normalize timezone to ensure consistent comparisons
172
+ return normalize_timezone(result)
173
+
174
+
175
+ def safe_concat(objs: list[pd.Series | pd.DataFrame],
176
+ axis: int = 0,
177
+ ignore_index: bool = False,
178
+ sort: bool = False,
179
+ **kwargs) -> pd.Series | pd.DataFrame:
180
+ """
181
+ Safe concatenation that handles pandas version differences.
182
+
183
+ This function provides a wrapper around pd.concat with consistent parameters.
184
+
185
+ Parameters
186
+ ----------
187
+ objs : list of pd.Series or pd.DataFrame
188
+ Objects to concatenate along the specified axis
189
+ axis : int, default 0
190
+ Axis to concatenate along. 0 for rows, 1 for columns
191
+ ignore_index : bool, default False
192
+ Whether to ignore the index and create a new default integer index
193
+ sort : bool, default False
194
+ Whether to sort the result
195
+ **kwargs
196
+ Additional arguments passed to pd.concat
197
+
198
+ Returns
199
+ -------
200
+ pd.Series or pd.DataFrame
201
+ The concatenated result
202
+
203
+ Examples
204
+ --------
205
+ >>> safe_concat([df1, df2]) # Concatenate along rows
206
+ >>> safe_concat([df1, df2], axis=1) # Concatenate along columns
207
+ """
208
+ # Perform the concatenation with sort parameter (available in pandas 2.0+)
209
+ return pd.concat(objs, axis=axis, ignore_index=ignore_index, sort=sort, **kwargs) # type: ignore[arg-type]
210
+
211
+
212
+ def safe_append(df: pd.DataFrame,
213
+ other: pd.DataFrame | pd.Series,
214
+ ignore_index: bool = False,
215
+ sort: bool = False) -> pd.DataFrame:
216
+ """
217
+ Safe append operation using pd.concat.
218
+
219
+ DataFrame.append() was removed in pandas 2.0.0. This function provides
220
+ a unified interface using pd.concat.
221
+
222
+ Parameters
223
+ ----------
224
+ df : pd.DataFrame
225
+ The DataFrame to append to (base DataFrame)
226
+ other : pd.DataFrame or pd.Series
227
+ The data to append to the base DataFrame
228
+ ignore_index : bool, default False
229
+ Whether to ignore the index and create a new default integer index
230
+ sort : bool, default False
231
+ Whether to sort the result by columns
232
+
233
+ Returns
234
+ -------
235
+ pd.DataFrame
236
+ The result of the append operation
237
+
238
+ Examples
239
+ --------
240
+ >>> safe_append(df, new_row) # Append a new row
241
+ >>> safe_append(df, other_df, ignore_index=True) # Append and reset index
242
+ """
243
+ # Use concat (append was removed in pandas 2.0)
244
+ result = safe_concat([df, other], ignore_index=ignore_index, sort=sort)
245
+ # Ensure we return a DataFrame
246
+ if isinstance(result, pd.DataFrame):
247
+ return result
248
+ elif isinstance(result, pd.Series):
249
+ return pd.DataFrame([result])
250
+ else:
251
+ return pd.DataFrame(result)
252
+
253
+
254
+ def safe_frequency_conversion(data: pd.Series | pd.DataFrame,
255
+ freq: str) -> pd.Series | pd.DataFrame:
256
+ """
257
+ Safe frequency conversion for time series data.
258
+
259
+ This function converts time series data to a specified frequency using
260
+ the most appropriate method available in the current pandas version.
261
+
262
+ Parameters
263
+ ----------
264
+ data : pd.Series or pd.DataFrame
265
+ Time series data with a datetime index
266
+ freq : str
267
+ Target frequency (e.g., 'D', 'M', 'Q', 'A')
268
+
269
+ Returns
270
+ -------
271
+ pd.Series or pd.DataFrame
272
+ Data with converted frequency
273
+
274
+ Examples
275
+ --------
276
+ >>> safe_frequency_conversion(data, 'M') # Convert to monthly frequency
277
+ >>> safe_frequency_conversion(data, 'D') # Convert to daily frequency
278
+ """
279
+ # Get the appropriate frequency alias for current pandas version
280
+ freq_alias = get_frequency_alias(freq)
281
+
282
+ # Handle different methods for frequency conversion
283
+ if hasattr(data, "asfreq"):
284
+ # Use asfreq if available (most direct method)
285
+ return data.asfreq(freq_alias)
286
+ else:
287
+ # Fallback to resampling with 'last' aggregation
288
+ # This preserves the last value in each period
289
+ return safe_resample(data, freq_alias, "last")
290
+
291
+
292
+ def handle_pandas_warnings():
293
+ """
294
+ Context manager to handle pandas warnings appropriately.
295
+
296
+ This function returns a context manager that can be used to suppress
297
+ or handle pandas warnings in a controlled manner. Useful for managing
298
+ deprecation warnings when working with multiple pandas versions.
299
+
300
+ Returns
301
+ -------
302
+ warnings.catch_warnings
303
+ A context manager for handling warnings
304
+
305
+ Examples
306
+ --------
307
+ >>> with handle_pandas_warnings():
308
+ ... # Code that might generate pandas warnings
309
+ ... pass
310
+ """
311
+ # Return the warnings context manager for flexible warning handling
312
+ return warnings.catch_warnings()
313
+
314
+
315
+ # Pandas accessor compatibility functions
316
+ def get_datetime_accessor(series: pd.Series):
317
+ """
318
+ Get datetime accessor for pandas Series.
319
+
320
+ This function provides a consistent interface for accessing datetime
321
+ properties of a pandas Series across different versions.
322
+
323
+ Parameters
324
+ ----------
325
+ series : pd.Series
326
+ The series with datetime data to get the accessor for
327
+
328
+ Returns
329
+ -------
330
+ pd.Series.dt
331
+ The datetime accessor for the series
332
+
333
+ Examples
334
+ --------
335
+ >>> dt_accessor = get_datetime_accessor(date_series)
336
+ >>> dt_accessor.year # Access year component
337
+ >>> dt_accessor.month # Access month component
338
+ """
339
+ # Return the datetime accessor - consistent across pandas versions
340
+ return series.dt
341
+
342
+
343
+ def get_string_accessor(series: pd.Series):
344
+ """
345
+ Get string accessor for pandas Series.
346
+
347
+ This function provides a consistent interface for accessing string
348
+ methods of a pandas Series across different versions.
349
+
350
+ Parameters
351
+ ----------
352
+ series : pd.Series
353
+ The series with string data to get the accessor for
354
+
355
+ Returns
356
+ -------
357
+ pd.Series.str
358
+ The string accessor for the series
359
+
360
+ Examples
361
+ --------
362
+ >>> str_accessor = get_string_accessor(string_series)
363
+ >>> str_accessor.lower() # Convert to lowercase
364
+ >>> str_accessor.contains('pattern') # Check for pattern
365
+ """
366
+ # Return the string accessor - consistent across pandas versions
367
+ return series.str
368
+
369
+
370
+ def safe_yfinance_download(tickers: str | list[str],
371
+ proxy: str | None = None,
372
+ **kwargs) -> pd.DataFrame:
373
+ """
374
+ Safe yfinance download that handles proxy configuration properly.
375
+
376
+ This function provides a wrapper around yfinance.download that handles
377
+ proxy configuration differences between yfinance versions. It ensures
378
+ compatibility with both old and new yfinance proxy configuration methods.
379
+
380
+ Parameters
381
+ ----------
382
+ tickers : str or list
383
+ Ticker symbols to download data for. Can be a single ticker string
384
+ or a list of ticker symbols
385
+ proxy : str, optional
386
+ Proxy configuration string (e.g., 'http://proxy.server:port')
387
+ Handled automatically based on yfinance version
388
+ **kwargs
389
+ Additional arguments passed to yfinance.download such as:
390
+ - start: Start date for data download
391
+ - end: End date for data download
392
+ - period: Period to download (e.g., '1y', '6mo')
393
+ - interval: Data interval (e.g., '1d', '1h')
394
+
395
+ Returns
396
+ -------
397
+ pd.DataFrame
398
+ Downloaded financial data with columns like Open, High, Low, Close, Volume
399
+
400
+ Examples
401
+ --------
402
+ >>> data = safe_yfinance_download('AAPL', start='2020-01-01', end='2021-01-01')
403
+ >>> data = safe_yfinance_download(['AAPL', 'MSFT'], period='1y')
404
+ """
405
+ # Handle proxy configuration based on yfinance version
406
+ if proxy is not None:
407
+ # Check if the new configuration method exists in yfinance
408
+ if hasattr(yf, "set_config"):
409
+ # New method: use set_config for global proxy configuration
410
+ # This approach is preferred in newer yfinance versions
411
+ yf.set_config(proxy=proxy)
412
+ # Remove proxy from kwargs to avoid duplicate parameter error
413
+ kwargs.pop("proxy", None)
414
+ else:
415
+ # Old method: pass proxy directly to download function
416
+ # This is for backward compatibility with older yfinance versions
417
+ kwargs["proxy"] = proxy
418
+
419
+ # Suppress yfinance warnings about deprecation and future changes
420
+ # This keeps the output clean while maintaining functionality
421
+ with warnings.catch_warnings():
422
+ warnings.filterwarnings("ignore", category=FutureWarning, module="yfinance")
423
+ # Download the data using yfinance with all provided parameters
424
+ result = yf.download(tickers, **kwargs)
425
+
426
+ # Handle case where yfinance returns None (network issues, invalid ticker, etc.)
427
+ if result is None:
428
+ # Return empty DataFrame with standard yfinance columns
429
+ return pd.DataFrame(columns=['Open', 'High', 'Low', 'Close', 'Volume', 'Adj Close'])
430
+
431
+ return result