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.
- quantstats/__init__.py +163 -0
- quantstats/_compat.py +431 -0
- quantstats/_montecarlo.py +296 -0
- quantstats/_numpy_compat.py +289 -0
- quantstats/_plotting/__init__.py +0 -0
- quantstats/_plotting/core.py +2173 -0
- quantstats/_plotting/wrappers.py +2109 -0
- quantstats/_reporting/__init__.py +12 -0
- quantstats/_reporting/engine.py +37 -0
- quantstats/_reporting/sections.py +223 -0
- quantstats/alphadecay/__init__.py +25 -0
- quantstats/alphadecay/core.py +712 -0
- quantstats/alphadecay/plotting.py +206 -0
- quantstats/montecarlo/__init__.py +34 -0
- quantstats/montecarlo/analytics.py +291 -0
- quantstats/montecarlo/base.py +92 -0
- quantstats/montecarlo/core.py +175 -0
- quantstats/montecarlo/models/__init__.py +15 -0
- quantstats/montecarlo/models/bayesian.py +88 -0
- quantstats/montecarlo/models/block_bootstrap.py +108 -0
- quantstats/montecarlo/models/bootstrap.py +38 -0
- quantstats/montecarlo/models/garch.py +83 -0
- quantstats/montecarlo/models/gbm.py +44 -0
- quantstats/montecarlo/models/heston.py +103 -0
- quantstats/montecarlo/models/jump_diffusion.py +86 -0
- quantstats/montecarlo/models/shuffle.py +49 -0
- quantstats/montecarlo/models/trimmed.py +50 -0
- quantstats/montecarlo/plotting.py +324 -0
- quantstats/montecarlo/registry.py +34 -0
- quantstats/plots.py +27 -0
- quantstats/py.typed +0 -0
- quantstats/report.html +64 -0
- quantstats/report_alpha_decay.html +43 -0
- quantstats/report_montecarlo.html +62 -0
- quantstats/report_simple.html +58 -0
- quantstats/reports.py +3502 -0
- quantstats/stats.py +3321 -0
- quantstats/utils.py +1011 -0
- quantstats/version.py +1 -0
- quantstats_pro-0.4.1.dist-info/METADATA +509 -0
- quantstats_pro-0.4.1.dist-info/RECORD +43 -0
- quantstats_pro-0.4.1.dist-info/WHEEL +4 -0
- quantstats_pro-0.4.1.dist-info/licenses/LICENSE.txt +202 -0
quantstats/utils.py
ADDED
|
@@ -0,0 +1,1011 @@
|
|
|
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
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
8
|
+
# you may not use this file except in compliance with the License.
|
|
9
|
+
# You may obtain a copy of the License at
|
|
10
|
+
#
|
|
11
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
12
|
+
# ˜
|
|
13
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
14
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
15
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
16
|
+
# See the License for the specific language governing permissions and
|
|
17
|
+
# limitations under the License.
|
|
18
|
+
|
|
19
|
+
import datetime as _dt
|
|
20
|
+
import inspect
|
|
21
|
+
import io as _io
|
|
22
|
+
import threading
|
|
23
|
+
|
|
24
|
+
import numpy as _np
|
|
25
|
+
import pandas as _pd
|
|
26
|
+
|
|
27
|
+
from ._compat import safe_concat, safe_yfinance_download
|
|
28
|
+
|
|
29
|
+
# Type alias for return data
|
|
30
|
+
Returns = _pd.Series | _pd.DataFrame
|
|
31
|
+
"""Type alias for returns data: can be a pandas Series or DataFrame."""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
# Custom exception classes for QuantStats
|
|
35
|
+
class QuantStatsError(Exception):
|
|
36
|
+
"""Base exception class for QuantStats"""
|
|
37
|
+
|
|
38
|
+
pass
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class DataValidationError(QuantStatsError):
|
|
42
|
+
"""Raised when input data validation fails"""
|
|
43
|
+
|
|
44
|
+
pass
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class CalculationError(QuantStatsError):
|
|
48
|
+
"""Raised when a calculation fails"""
|
|
49
|
+
|
|
50
|
+
pass
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class PlottingError(QuantStatsError):
|
|
54
|
+
"""Raised when plotting operations fail"""
|
|
55
|
+
|
|
56
|
+
pass
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class BenchmarkError(QuantStatsError):
|
|
60
|
+
"""Raised when benchmark data issues occur"""
|
|
61
|
+
|
|
62
|
+
pass
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def validate_input(data, allow_empty=False):
|
|
66
|
+
"""
|
|
67
|
+
Validate input data for QuantStats functions
|
|
68
|
+
|
|
69
|
+
Parameters
|
|
70
|
+
----------
|
|
71
|
+
data : pd.Series or pd.DataFrame
|
|
72
|
+
Input data to validate
|
|
73
|
+
allow_empty : bool, default False
|
|
74
|
+
Whether to allow empty datasets
|
|
75
|
+
|
|
76
|
+
Raises
|
|
77
|
+
------
|
|
78
|
+
DataValidationError
|
|
79
|
+
If data validation fails
|
|
80
|
+
"""
|
|
81
|
+
if data is None:
|
|
82
|
+
raise DataValidationError("Input data cannot be None")
|
|
83
|
+
|
|
84
|
+
if not isinstance(data, (_pd.Series, _pd.DataFrame)):
|
|
85
|
+
raise DataValidationError(
|
|
86
|
+
f"Input data must be pandas Series or DataFrame, got {type(data)}"
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
if not allow_empty and len(data) == 0:
|
|
90
|
+
raise DataValidationError("Input data cannot be empty")
|
|
91
|
+
|
|
92
|
+
if not allow_empty and data.dropna().empty:
|
|
93
|
+
raise DataValidationError("Input data contains only NaN values")
|
|
94
|
+
|
|
95
|
+
# Check for valid date index
|
|
96
|
+
if not isinstance(data.index, (_pd.DatetimeIndex, _pd.RangeIndex)):
|
|
97
|
+
try:
|
|
98
|
+
data.index = _pd.to_datetime(data.index)
|
|
99
|
+
except Exception:
|
|
100
|
+
raise DataValidationError(
|
|
101
|
+
"Input data must have a valid datetime index"
|
|
102
|
+
) from None
|
|
103
|
+
|
|
104
|
+
return True
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
# Cache for _prepare_returns function with thread safety
|
|
108
|
+
_PREPARE_RETURNS_CACHE = {}
|
|
109
|
+
_CACHE_MAX_SIZE = 100
|
|
110
|
+
_cache_lock = threading.Lock()
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _generate_cache_key(data, rf, nperiods):
|
|
114
|
+
"""
|
|
115
|
+
Generate a cache key for the _prepare_returns function
|
|
116
|
+
|
|
117
|
+
Parameters
|
|
118
|
+
----------
|
|
119
|
+
data : pd.Series or pd.DataFrame
|
|
120
|
+
Input data to generate hash from
|
|
121
|
+
rf : float
|
|
122
|
+
Risk-free rate parameter
|
|
123
|
+
nperiods : int
|
|
124
|
+
Number of periods parameter
|
|
125
|
+
|
|
126
|
+
Returns
|
|
127
|
+
-------
|
|
128
|
+
str or None
|
|
129
|
+
Cache key string or None if hashing fails
|
|
130
|
+
"""
|
|
131
|
+
try:
|
|
132
|
+
# Create a hash from the data. The type and column layout must be part
|
|
133
|
+
# of the key: a Series and a single-column DataFrame holding identical
|
|
134
|
+
# values produce the same row hashes, so without this they would share
|
|
135
|
+
# a cache entry and return the wrong type (bug: stat fns receiving a
|
|
136
|
+
# Series would get a DataFrame back).
|
|
137
|
+
if isinstance(data, _pd.Series):
|
|
138
|
+
data_hash = _pd.util.hash_pandas_object(data).sum()
|
|
139
|
+
kind = f"series[{data.name}]"
|
|
140
|
+
elif isinstance(data, _pd.DataFrame):
|
|
141
|
+
data_hash = _pd.util.hash_pandas_object(data).sum()
|
|
142
|
+
kind = f"frame{tuple(data.columns)}"
|
|
143
|
+
else:
|
|
144
|
+
data_hash = hash(str(data))
|
|
145
|
+
kind = "other"
|
|
146
|
+
|
|
147
|
+
# Include type/columns and parameters in the key
|
|
148
|
+
key = f"{kind}_{data_hash}_{rf}_{nperiods}"
|
|
149
|
+
return key
|
|
150
|
+
except (ValueError, TypeError, AttributeError, MemoryError):
|
|
151
|
+
# If hashing fails, return None to skip caching
|
|
152
|
+
return None
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _clear_cache_if_full():
|
|
156
|
+
"""
|
|
157
|
+
Clear cache if it exceeds maximum size
|
|
158
|
+
|
|
159
|
+
Uses a simple FIFO strategy, keeping the most recent half of entries
|
|
160
|
+
when cache size limit is exceeded.
|
|
161
|
+
"""
|
|
162
|
+
with _cache_lock:
|
|
163
|
+
if len(_PREPARE_RETURNS_CACHE) >= _CACHE_MAX_SIZE:
|
|
164
|
+
# Remove oldest entries (simple FIFO) - keep the most recent half
|
|
165
|
+
keys_to_remove = list(_PREPARE_RETURNS_CACHE.keys())[:-(_CACHE_MAX_SIZE // 2)]
|
|
166
|
+
for key in keys_to_remove:
|
|
167
|
+
del _PREPARE_RETURNS_CACHE[key]
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _mtd(df):
|
|
171
|
+
"""
|
|
172
|
+
Filter dataframe to month-to-date data
|
|
173
|
+
|
|
174
|
+
Parameters
|
|
175
|
+
----------
|
|
176
|
+
df : pd.DataFrame or pd.Series
|
|
177
|
+
Input data with datetime index
|
|
178
|
+
|
|
179
|
+
Returns
|
|
180
|
+
-------
|
|
181
|
+
pd.DataFrame or pd.Series
|
|
182
|
+
Filtered data from start of current month
|
|
183
|
+
"""
|
|
184
|
+
# Get first day of current month as string
|
|
185
|
+
return df[df.index >= _dt.datetime.now().strftime("%Y-%m-01")]
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _qtd(df):
|
|
189
|
+
"""
|
|
190
|
+
Filter dataframe to quarter-to-date data
|
|
191
|
+
|
|
192
|
+
Parameters
|
|
193
|
+
----------
|
|
194
|
+
df : pd.DataFrame or pd.Series
|
|
195
|
+
Input data with datetime index
|
|
196
|
+
|
|
197
|
+
Returns
|
|
198
|
+
-------
|
|
199
|
+
pd.DataFrame or pd.Series
|
|
200
|
+
Filtered data from start of current quarter
|
|
201
|
+
"""
|
|
202
|
+
date = _dt.datetime.now()
|
|
203
|
+
# Check which quarter we're in (Q1: Jan-Mar, Q2: Apr-Jun, Q3: Jul-Sep, Q4: Oct-Dec)
|
|
204
|
+
for q in [1, 4, 7, 10]: # First month of each quarter
|
|
205
|
+
if date.month <= q:
|
|
206
|
+
return df[df.index >= _dt.datetime(date.year, q, 1).strftime("%Y-%m-01")]
|
|
207
|
+
# Default to current month if no quarter match
|
|
208
|
+
return df[df.index >= date.strftime("%Y-%m-01")]
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _ytd(df):
|
|
212
|
+
"""
|
|
213
|
+
Filter dataframe to year-to-date data
|
|
214
|
+
|
|
215
|
+
Parameters
|
|
216
|
+
----------
|
|
217
|
+
df : pd.DataFrame or pd.Series
|
|
218
|
+
Input data with datetime index
|
|
219
|
+
|
|
220
|
+
Returns
|
|
221
|
+
-------
|
|
222
|
+
pd.DataFrame or pd.Series
|
|
223
|
+
Filtered data from start of current year
|
|
224
|
+
"""
|
|
225
|
+
# Get first day of current year as string
|
|
226
|
+
return df[df.index >= _dt.datetime.now().strftime("%Y-01-01")]
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _pandas_date(df, dates):
|
|
230
|
+
"""
|
|
231
|
+
Filter dataframe to specific dates
|
|
232
|
+
|
|
233
|
+
Parameters
|
|
234
|
+
----------
|
|
235
|
+
df : pd.DataFrame or pd.Series
|
|
236
|
+
Input data with datetime index
|
|
237
|
+
dates : list or single date
|
|
238
|
+
Date(s) to filter by
|
|
239
|
+
|
|
240
|
+
Returns
|
|
241
|
+
-------
|
|
242
|
+
pd.DataFrame or pd.Series
|
|
243
|
+
Filtered data for specified dates
|
|
244
|
+
"""
|
|
245
|
+
# Ensure dates is a list for consistent processing
|
|
246
|
+
if not isinstance(dates, list):
|
|
247
|
+
dates = [dates]
|
|
248
|
+
return df[df.index.isin(dates)]
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _pandas_current_month(df):
|
|
252
|
+
"""
|
|
253
|
+
Filter dataframe to current month's data
|
|
254
|
+
|
|
255
|
+
Parameters
|
|
256
|
+
----------
|
|
257
|
+
df : pd.DataFrame or pd.Series
|
|
258
|
+
Input data with datetime index
|
|
259
|
+
|
|
260
|
+
Returns
|
|
261
|
+
-------
|
|
262
|
+
pd.DataFrame or pd.Series
|
|
263
|
+
Filtered data for current month
|
|
264
|
+
"""
|
|
265
|
+
n = _dt.datetime.now()
|
|
266
|
+
# Create date range from first day of current month to now
|
|
267
|
+
daterange = _pd.date_range(_dt.date(n.year, n.month, 1), n)
|
|
268
|
+
return df[df.index.isin(daterange)]
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def multi_shift(df, shift=3):
|
|
272
|
+
"""Get last N rows relative to another row in pandas - optimized for memory usage"""
|
|
273
|
+
if isinstance(df, _pd.Series):
|
|
274
|
+
df = _pd.DataFrame(df)
|
|
275
|
+
|
|
276
|
+
# More memory-efficient approach using dictionary comprehension
|
|
277
|
+
# and direct column assignment
|
|
278
|
+
result = df.copy()
|
|
279
|
+
|
|
280
|
+
# Create lagged versions of the data
|
|
281
|
+
for i in range(1, shift):
|
|
282
|
+
shifted = df.shift(i)
|
|
283
|
+
# Rename columns to avoid conflicts
|
|
284
|
+
shifted.columns = [f"{col}{i}" for col in shifted.columns]
|
|
285
|
+
result = safe_concat([result, shifted], axis=1, sort=True)
|
|
286
|
+
|
|
287
|
+
return result
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def to_returns(prices: Returns, rf: float = 0.0) -> Returns:
|
|
291
|
+
"""
|
|
292
|
+
Calculate simple arithmetic returns from price series
|
|
293
|
+
|
|
294
|
+
Parameters
|
|
295
|
+
----------
|
|
296
|
+
prices : pd.Series or pd.DataFrame
|
|
297
|
+
Price data
|
|
298
|
+
rf : float, default 0.0
|
|
299
|
+
Risk-free rate
|
|
300
|
+
|
|
301
|
+
Returns
|
|
302
|
+
-------
|
|
303
|
+
pd.Series or pd.DataFrame
|
|
304
|
+
Simple arithmetic returns
|
|
305
|
+
"""
|
|
306
|
+
return _prepare_returns(prices, rf)
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def to_prices(returns: Returns, base: float = 1e5) -> Returns:
|
|
310
|
+
"""
|
|
311
|
+
Convert returns series to price data
|
|
312
|
+
|
|
313
|
+
Parameters
|
|
314
|
+
----------
|
|
315
|
+
returns : pd.Series or pd.DataFrame
|
|
316
|
+
Returns data
|
|
317
|
+
base : float, default 1e5
|
|
318
|
+
Starting base value for price series
|
|
319
|
+
|
|
320
|
+
Returns
|
|
321
|
+
-------
|
|
322
|
+
pd.Series or pd.DataFrame
|
|
323
|
+
Price data calculated from returns
|
|
324
|
+
"""
|
|
325
|
+
from . import stats as _stats # deferred import to avoid circular dependency
|
|
326
|
+
|
|
327
|
+
# Clean returns data by filling NaN and replacing infinite values
|
|
328
|
+
returns = returns.copy().fillna(0).replace([_np.inf, -_np.inf], float("NaN"))
|
|
329
|
+
|
|
330
|
+
# Convert returns to prices using compounded sum
|
|
331
|
+
return base + base * _stats.compsum(returns)
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def log_returns(returns: Returns, rf: float = 0.0, nperiods: int | None = None) -> Returns:
|
|
335
|
+
"""
|
|
336
|
+
Shorthand for to_log_returns function
|
|
337
|
+
|
|
338
|
+
Parameters
|
|
339
|
+
----------
|
|
340
|
+
returns : pd.Series or pd.DataFrame
|
|
341
|
+
Returns data
|
|
342
|
+
rf : float, default 0.0
|
|
343
|
+
Risk-free rate
|
|
344
|
+
nperiods : int, optional
|
|
345
|
+
Number of periods for risk-free rate conversion
|
|
346
|
+
|
|
347
|
+
Returns
|
|
348
|
+
-------
|
|
349
|
+
pd.Series or pd.DataFrame
|
|
350
|
+
Log returns
|
|
351
|
+
"""
|
|
352
|
+
return to_log_returns(returns, rf, nperiods)
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def to_log_returns(returns: Returns, rf: float = 0.0, nperiods: int | None = None) -> Returns:
|
|
356
|
+
"""
|
|
357
|
+
Convert returns series to log returns
|
|
358
|
+
|
|
359
|
+
Parameters
|
|
360
|
+
----------
|
|
361
|
+
returns : pd.Series or pd.DataFrame
|
|
362
|
+
Returns data
|
|
363
|
+
rf : float, default 0.0
|
|
364
|
+
Risk-free rate
|
|
365
|
+
nperiods : int, optional
|
|
366
|
+
Number of periods for risk-free rate conversion
|
|
367
|
+
|
|
368
|
+
Returns
|
|
369
|
+
-------
|
|
370
|
+
pd.Series or pd.DataFrame
|
|
371
|
+
Log returns calculated as ln(1 + returns)
|
|
372
|
+
"""
|
|
373
|
+
returns = _prepare_returns(returns, rf, nperiods)
|
|
374
|
+
try:
|
|
375
|
+
# Calculate log returns: ln(1 + returns)
|
|
376
|
+
return _np.log(returns + 1).replace([_np.inf, -_np.inf], float("NaN")) # type: ignore
|
|
377
|
+
except (ValueError, TypeError, AttributeError, OverflowError) as e:
|
|
378
|
+
from warnings import warn
|
|
379
|
+
warn(f"Error converting to log returns: {type(e).__name__}: {e}, returning 0.0", stacklevel=2)
|
|
380
|
+
return 0.0
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def exponential_stdev(returns, window=30, is_halflife=False):
|
|
384
|
+
"""
|
|
385
|
+
Calculate exponential weighted standard deviation (volatility) of returns
|
|
386
|
+
|
|
387
|
+
Parameters
|
|
388
|
+
----------
|
|
389
|
+
returns : pd.Series or pd.DataFrame
|
|
390
|
+
Returns data
|
|
391
|
+
window : int, default 30
|
|
392
|
+
Window size for exponential weighting
|
|
393
|
+
is_halflife : bool, default False
|
|
394
|
+
Whether window parameter represents halflife
|
|
395
|
+
|
|
396
|
+
Returns
|
|
397
|
+
-------
|
|
398
|
+
pd.Series or pd.DataFrame
|
|
399
|
+
Exponential weighted standard deviation
|
|
400
|
+
"""
|
|
401
|
+
returns = _prepare_returns(returns)
|
|
402
|
+
# Set halflife parameter based on is_halflife flag
|
|
403
|
+
halflife = window if is_halflife else None
|
|
404
|
+
return returns.ewm(
|
|
405
|
+
com=None, span=window, halflife=halflife, min_periods=window
|
|
406
|
+
).std()
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def rebase(prices: Returns, base: float = 100.0) -> Returns:
|
|
410
|
+
"""
|
|
411
|
+
Rebase all series to a given intial base.
|
|
412
|
+
This makes comparing/plotting different series together easier.
|
|
413
|
+
Args:
|
|
414
|
+
* prices: Expects a price series/dataframe
|
|
415
|
+
* base (number): starting value for all series.
|
|
416
|
+
"""
|
|
417
|
+
# Normalize prices to start at the base value
|
|
418
|
+
return prices.dropna() / prices.dropna().iloc[0] * base
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
def group_returns(returns: Returns, groupby, compounded: bool = False) -> Returns:
|
|
422
|
+
"""
|
|
423
|
+
Summarize returns by grouping criteria
|
|
424
|
+
|
|
425
|
+
Parameters
|
|
426
|
+
----------
|
|
427
|
+
returns : pd.Series or pd.DataFrame
|
|
428
|
+
Returns data
|
|
429
|
+
groupby : grouper object
|
|
430
|
+
Pandas groupby object or criteria
|
|
431
|
+
compounded : bool, default False
|
|
432
|
+
Whether to compound returns or use simple sum
|
|
433
|
+
|
|
434
|
+
Returns
|
|
435
|
+
-------
|
|
436
|
+
pd.Series or pd.DataFrame
|
|
437
|
+
Grouped returns
|
|
438
|
+
|
|
439
|
+
Examples
|
|
440
|
+
--------
|
|
441
|
+
group_returns(df, df.index.year)
|
|
442
|
+
group_returns(df, [df.index.year, df.index.month])
|
|
443
|
+
"""
|
|
444
|
+
if compounded:
|
|
445
|
+
from . import stats as _stats # deferred import to avoid circular dependency
|
|
446
|
+
|
|
447
|
+
# Use compounded returns calculation
|
|
448
|
+
return returns.groupby(groupby).apply(_stats.comp)
|
|
449
|
+
# Use simple sum for non-compounded returns
|
|
450
|
+
return returns.groupby(groupby).sum()
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def aggregate_returns(returns: Returns, period: str | None = None, compounded: bool = True) -> Returns:
|
|
454
|
+
"""
|
|
455
|
+
Aggregate returns based on specified time periods
|
|
456
|
+
|
|
457
|
+
Parameters
|
|
458
|
+
----------
|
|
459
|
+
returns : pd.Series or pd.DataFrame
|
|
460
|
+
Returns data
|
|
461
|
+
period : str, optional
|
|
462
|
+
Time period for aggregation ('month', 'quarter', 'year', etc.)
|
|
463
|
+
compounded : bool, default True
|
|
464
|
+
Whether to compound returns
|
|
465
|
+
|
|
466
|
+
Returns
|
|
467
|
+
-------
|
|
468
|
+
pd.Series or pd.DataFrame
|
|
469
|
+
Aggregated returns for specified period
|
|
470
|
+
"""
|
|
471
|
+
# Normalize timezone for consistency before aggregation
|
|
472
|
+
# Convert to UTC if timezone-aware, then make naive
|
|
473
|
+
if hasattr(returns.index, 'tz') and returns.index.tz is not None:
|
|
474
|
+
returns = returns.tz_convert('UTC').tz_localize(None)
|
|
475
|
+
|
|
476
|
+
# Return original data if no period specified or daily period
|
|
477
|
+
if period is None or "day" in period:
|
|
478
|
+
return returns
|
|
479
|
+
|
|
480
|
+
index = returns.index
|
|
481
|
+
|
|
482
|
+
# Group by month
|
|
483
|
+
if "month" in period:
|
|
484
|
+
return group_returns(returns, index.month, compounded=compounded)
|
|
485
|
+
|
|
486
|
+
# Group by quarter
|
|
487
|
+
if "quarter" in period:
|
|
488
|
+
return group_returns(returns, index.quarter, compounded=compounded)
|
|
489
|
+
|
|
490
|
+
# Group by year (multiple possible period strings)
|
|
491
|
+
if period == "YE" or any(x in period for x in ["year", "eoy", "yoy"]):
|
|
492
|
+
return group_returns(returns, index.year, compounded=compounded)
|
|
493
|
+
|
|
494
|
+
# Group by week
|
|
495
|
+
if "week" in period:
|
|
496
|
+
return group_returns(returns, index.week, compounded=compounded)
|
|
497
|
+
|
|
498
|
+
# End of week grouping
|
|
499
|
+
if "eow" in period or period == "W":
|
|
500
|
+
return group_returns(returns, [index.year, index.week], compounded=compounded)
|
|
501
|
+
|
|
502
|
+
# End of month grouping
|
|
503
|
+
if "eom" in period or period == "ME":
|
|
504
|
+
return group_returns(returns, [index.year, index.month], compounded=compounded)
|
|
505
|
+
|
|
506
|
+
# End of quarter grouping
|
|
507
|
+
if "eoq" in period or period == "QE":
|
|
508
|
+
return group_returns(
|
|
509
|
+
returns, [index.year, index.quarter], compounded=compounded
|
|
510
|
+
)
|
|
511
|
+
|
|
512
|
+
# Custom period grouping (non-string)
|
|
513
|
+
if not isinstance(period, str):
|
|
514
|
+
return group_returns(returns, period, compounded)
|
|
515
|
+
|
|
516
|
+
# Default: return original data
|
|
517
|
+
return returns
|
|
518
|
+
|
|
519
|
+
|
|
520
|
+
def to_excess_returns(returns: Returns, rf: float, nperiods: int | None = None) -> Returns:
|
|
521
|
+
"""
|
|
522
|
+
Calculates excess returns by subtracting
|
|
523
|
+
risk-free returns from total returns
|
|
524
|
+
|
|
525
|
+
Args:
|
|
526
|
+
* returns (Series, DataFrame): Returns
|
|
527
|
+
* rf (float, Series, DataFrame): Risk-Free rate(s)
|
|
528
|
+
* nperiods (int): Optional. If provided, will convert rf to different
|
|
529
|
+
frequency using deannualize
|
|
530
|
+
Returns:
|
|
531
|
+
* excess_returns (Series, DataFrame): Returns - rf
|
|
532
|
+
"""
|
|
533
|
+
# Convert integer rf to float for consistency
|
|
534
|
+
if isinstance(rf, int):
|
|
535
|
+
rf = float(rf)
|
|
536
|
+
|
|
537
|
+
# Align rf with returns index if rf is a series/dataframe
|
|
538
|
+
if not isinstance(rf, float):
|
|
539
|
+
rf = rf[rf.index.isin(returns.index)] # type: ignore
|
|
540
|
+
|
|
541
|
+
# Deannualize rf if nperiods is provided
|
|
542
|
+
if nperiods is not None:
|
|
543
|
+
# deannualize
|
|
544
|
+
rf = _np.power(1 + rf, 1.0 / nperiods) - 1.0
|
|
545
|
+
|
|
546
|
+
# Calculate excess returns
|
|
547
|
+
df = returns - rf
|
|
548
|
+
df = df.tz_localize(None)
|
|
549
|
+
return df
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
def _prepare_prices(data, base=1.0):
|
|
553
|
+
"""
|
|
554
|
+
Convert return data into prices and perform cleanup
|
|
555
|
+
|
|
556
|
+
Parameters
|
|
557
|
+
----------
|
|
558
|
+
data : pd.Series or pd.DataFrame
|
|
559
|
+
Input data (returns or prices)
|
|
560
|
+
base : float, default 1.0
|
|
561
|
+
Base value for price conversion
|
|
562
|
+
|
|
563
|
+
Returns
|
|
564
|
+
-------
|
|
565
|
+
pd.Series or pd.DataFrame
|
|
566
|
+
Cleaned price data
|
|
567
|
+
"""
|
|
568
|
+
data = data.copy()
|
|
569
|
+
if isinstance(data, _pd.DataFrame):
|
|
570
|
+
for col in data.columns:
|
|
571
|
+
# Cache dropna operation to avoid repeated computation
|
|
572
|
+
col_clean = data[col].dropna()
|
|
573
|
+
# Check if data looks like returns (negative values or values < 1)
|
|
574
|
+
if col_clean.min() <= 0 or col_clean.max() < 1:
|
|
575
|
+
data[col] = to_prices(data[col], base)
|
|
576
|
+
|
|
577
|
+
# Check if series looks like returns data
|
|
578
|
+
# elif data.min() < 0 and data.max() < 1:
|
|
579
|
+
elif data.min() < 0 or data.max() < 1:
|
|
580
|
+
data = to_prices(data, base)
|
|
581
|
+
|
|
582
|
+
# Clean data by filling NaN and replacing infinite values
|
|
583
|
+
if isinstance(data, (_pd.DataFrame, _pd.Series)):
|
|
584
|
+
data = data.fillna(0).replace([_np.inf, -_np.inf], float("NaN"))
|
|
585
|
+
|
|
586
|
+
# Normalize timezone information for consistency
|
|
587
|
+
# Convert to UTC if timezone-aware, then make naive
|
|
588
|
+
if hasattr(data.index, 'tz') and data.index.tz is not None:
|
|
589
|
+
data = data.tz_convert('UTC').tz_localize(None)
|
|
590
|
+
return data
|
|
591
|
+
|
|
592
|
+
|
|
593
|
+
def _prepare_returns(data, rf=0.0, nperiods=None):
|
|
594
|
+
"""
|
|
595
|
+
Convert price data into returns and perform cleanup
|
|
596
|
+
|
|
597
|
+
Parameters
|
|
598
|
+
----------
|
|
599
|
+
data : pd.Series or pd.DataFrame
|
|
600
|
+
Input data (prices or returns)
|
|
601
|
+
rf : float, default 0.0
|
|
602
|
+
Risk-free rate
|
|
603
|
+
nperiods : int, optional
|
|
604
|
+
Number of periods for risk-free rate conversion
|
|
605
|
+
|
|
606
|
+
Returns
|
|
607
|
+
-------
|
|
608
|
+
pd.Series or pd.DataFrame
|
|
609
|
+
Cleaned returns data
|
|
610
|
+
"""
|
|
611
|
+
# Try to get from cache first
|
|
612
|
+
cache_key = _generate_cache_key(data, rf, nperiods)
|
|
613
|
+
if cache_key:
|
|
614
|
+
with _cache_lock:
|
|
615
|
+
if cache_key in _PREPARE_RETURNS_CACHE:
|
|
616
|
+
return _PREPARE_RETURNS_CACHE[cache_key].copy()
|
|
617
|
+
|
|
618
|
+
data = data.copy()
|
|
619
|
+
# Get calling function name for conditional processing
|
|
620
|
+
function = inspect.stack()[1][3]
|
|
621
|
+
|
|
622
|
+
# Process DataFrame columns
|
|
623
|
+
if isinstance(data, _pd.DataFrame):
|
|
624
|
+
for col in data.columns:
|
|
625
|
+
# Cache dropna operation to avoid repeated computation
|
|
626
|
+
col_clean = data[col].dropna()
|
|
627
|
+
# Check if data looks like prices (positive values > 1)
|
|
628
|
+
if col_clean.min() >= 0 and col_clean.max() > 1:
|
|
629
|
+
data[col] = data[col].pct_change(fill_method=None)
|
|
630
|
+
# Process Series data
|
|
631
|
+
elif data.min() >= 0 and data.max() > 1:
|
|
632
|
+
data = data.pct_change(fill_method=None)
|
|
633
|
+
|
|
634
|
+
# cleanup data - replace infinite values with NaN
|
|
635
|
+
data = data.replace([_np.inf, -_np.inf], float("NaN"))
|
|
636
|
+
|
|
637
|
+
# Fill NaN values with 0 and replace infinite values
|
|
638
|
+
if isinstance(data, (_pd.DataFrame, _pd.Series)):
|
|
639
|
+
data = data.fillna(0).replace([_np.inf, -_np.inf], float("NaN"))
|
|
640
|
+
|
|
641
|
+
# Functions that don't need excess returns calculation
|
|
642
|
+
unnecessary_function_calls = [
|
|
643
|
+
"_prepare_benchmark",
|
|
644
|
+
"cagr",
|
|
645
|
+
"gain_to_pain_ratio",
|
|
646
|
+
"rolling_volatility",
|
|
647
|
+
]
|
|
648
|
+
|
|
649
|
+
# Calculate excess returns if rf > 0 and function needs it
|
|
650
|
+
if function not in unnecessary_function_calls and rf > 0:
|
|
651
|
+
result = to_excess_returns(data, rf, nperiods)
|
|
652
|
+
# Cache the result
|
|
653
|
+
if cache_key:
|
|
654
|
+
_clear_cache_if_full()
|
|
655
|
+
with _cache_lock:
|
|
656
|
+
_PREPARE_RETURNS_CACHE[cache_key] = result.copy()
|
|
657
|
+
return result
|
|
658
|
+
|
|
659
|
+
# Normalize timezone information for consistency
|
|
660
|
+
# Convert to UTC if timezone-aware, then make naive
|
|
661
|
+
if hasattr(data.index, 'tz') and data.index.tz is not None:
|
|
662
|
+
data = data.tz_convert('UTC').tz_localize(None)
|
|
663
|
+
|
|
664
|
+
# Cache the result
|
|
665
|
+
if cache_key:
|
|
666
|
+
_clear_cache_if_full()
|
|
667
|
+
with _cache_lock:
|
|
668
|
+
_PREPARE_RETURNS_CACHE[cache_key] = data.copy()
|
|
669
|
+
|
|
670
|
+
return data
|
|
671
|
+
|
|
672
|
+
|
|
673
|
+
def download_returns(ticker, period="max", proxy=None):
|
|
674
|
+
"""
|
|
675
|
+
Download returns data for a given ticker using yfinance
|
|
676
|
+
|
|
677
|
+
Parameters
|
|
678
|
+
----------
|
|
679
|
+
ticker : str
|
|
680
|
+
Stock ticker symbol
|
|
681
|
+
period : str or pd.DatetimeIndex, default "max"
|
|
682
|
+
Time period for data download
|
|
683
|
+
proxy : str, optional
|
|
684
|
+
Proxy server for download
|
|
685
|
+
|
|
686
|
+
Returns
|
|
687
|
+
-------
|
|
688
|
+
pd.Series
|
|
689
|
+
Daily returns data for the ticker
|
|
690
|
+
"""
|
|
691
|
+
# Set up parameters for yfinance download
|
|
692
|
+
params = {
|
|
693
|
+
"tickers": ticker,
|
|
694
|
+
"auto_adjust": True,
|
|
695
|
+
"multi_level_index": False,
|
|
696
|
+
"progress": False,
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
# Handle different period types
|
|
700
|
+
if isinstance(period, _pd.DatetimeIndex):
|
|
701
|
+
params["start"] = period[0]
|
|
702
|
+
else:
|
|
703
|
+
params["period"] = period
|
|
704
|
+
|
|
705
|
+
# Download data and calculate returns
|
|
706
|
+
df = safe_yfinance_download(proxy=proxy, **params)["Close"].pct_change(fill_method=None) # type: ignore
|
|
707
|
+
df = df.fillna(0).tz_localize(None)
|
|
708
|
+
return df
|
|
709
|
+
|
|
710
|
+
|
|
711
|
+
def _prepare_benchmark(benchmark=None, period="max", rf=0.0, prepare_returns=True):
|
|
712
|
+
"""
|
|
713
|
+
Fetch benchmark if ticker is provided, and pass through
|
|
714
|
+
_prepare_returns()
|
|
715
|
+
|
|
716
|
+
period can be options or (expected) _pd.DatetimeIndex range
|
|
717
|
+
"""
|
|
718
|
+
if benchmark is None:
|
|
719
|
+
return None
|
|
720
|
+
|
|
721
|
+
# Download benchmark data if ticker string provided
|
|
722
|
+
if isinstance(benchmark, str):
|
|
723
|
+
benchmark = download_returns(benchmark)
|
|
724
|
+
|
|
725
|
+
# Extract first column if DataFrame provided
|
|
726
|
+
elif isinstance(benchmark, _pd.DataFrame):
|
|
727
|
+
benchmark = benchmark[benchmark.columns[0]].copy()
|
|
728
|
+
|
|
729
|
+
# Align benchmark with strategy period if needed
|
|
730
|
+
if isinstance(period, _pd.DatetimeIndex) and set(period) != set(benchmark.index):
|
|
731
|
+
|
|
732
|
+
# Adjust Benchmark to Strategy frequency
|
|
733
|
+
benchmark_prices = to_prices(benchmark, base=1)
|
|
734
|
+
new_index = _pd.date_range(start=period[0], end=period[-1], freq="D")
|
|
735
|
+
benchmark = (
|
|
736
|
+
benchmark_prices.reindex(new_index, method="bfill")
|
|
737
|
+
.reindex(period)
|
|
738
|
+
.pct_change(fill_method=None)
|
|
739
|
+
.fillna(0)
|
|
740
|
+
)
|
|
741
|
+
benchmark = benchmark[benchmark.index.isin(period)]
|
|
742
|
+
|
|
743
|
+
# Normalize timezone information for consistent comparisons
|
|
744
|
+
# Convert to UTC if timezone-aware, then make naive
|
|
745
|
+
if hasattr(benchmark.index, 'tz') and benchmark.index.tz is not None:
|
|
746
|
+
benchmark = benchmark.tz_convert('UTC').tz_localize(None)
|
|
747
|
+
# If already timezone-naive, no action needed
|
|
748
|
+
|
|
749
|
+
# Prepare returns or return raw data
|
|
750
|
+
if prepare_returns:
|
|
751
|
+
return _prepare_returns(benchmark.dropna(), rf=rf)
|
|
752
|
+
return benchmark.dropna()
|
|
753
|
+
|
|
754
|
+
|
|
755
|
+
def _round_to_closest(val, res, decimals=None):
|
|
756
|
+
"""
|
|
757
|
+
Round value to closest resolution
|
|
758
|
+
|
|
759
|
+
Parameters
|
|
760
|
+
----------
|
|
761
|
+
val : float
|
|
762
|
+
Value to round
|
|
763
|
+
res : float
|
|
764
|
+
Resolution to round to
|
|
765
|
+
decimals : int, optional
|
|
766
|
+
Number of decimal places
|
|
767
|
+
|
|
768
|
+
Returns
|
|
769
|
+
-------
|
|
770
|
+
float
|
|
771
|
+
Rounded value
|
|
772
|
+
"""
|
|
773
|
+
# Auto-detect decimals from resolution if not provided
|
|
774
|
+
if decimals is None and "." in str(res):
|
|
775
|
+
decimals = len(str(res).split(".")[1])
|
|
776
|
+
return round(round(val / res) * res, decimals)
|
|
777
|
+
|
|
778
|
+
|
|
779
|
+
def _file_stream():
|
|
780
|
+
"""
|
|
781
|
+
Create and return a file stream object
|
|
782
|
+
|
|
783
|
+
Returns
|
|
784
|
+
-------
|
|
785
|
+
io.BytesIO
|
|
786
|
+
File stream object for handling bytes
|
|
787
|
+
"""
|
|
788
|
+
return _io.BytesIO()
|
|
789
|
+
|
|
790
|
+
|
|
791
|
+
def _in_notebook(matplotlib_inline=False):
|
|
792
|
+
"""
|
|
793
|
+
Identify current environment (notebook, terminal, etc.)
|
|
794
|
+
|
|
795
|
+
Parameters
|
|
796
|
+
----------
|
|
797
|
+
matplotlib_inline : bool, default False
|
|
798
|
+
Whether to enable matplotlib inline mode
|
|
799
|
+
|
|
800
|
+
Returns
|
|
801
|
+
-------
|
|
802
|
+
bool
|
|
803
|
+
True if running in Jupyter notebook, False otherwise
|
|
804
|
+
"""
|
|
805
|
+
try:
|
|
806
|
+
# Get IPython shell class name
|
|
807
|
+
shell = get_ipython().__class__.__name__ # type: ignore
|
|
808
|
+
if shell == "ZMQInteractiveShell":
|
|
809
|
+
# Jupyter notebook or qtconsole
|
|
810
|
+
if matplotlib_inline:
|
|
811
|
+
get_ipython().run_line_magic("matplotlib", "inline") # type: ignore
|
|
812
|
+
return True
|
|
813
|
+
if shell == "TerminalInteractiveShell":
|
|
814
|
+
# Terminal running IPython
|
|
815
|
+
return False
|
|
816
|
+
# Other type (?)
|
|
817
|
+
return False
|
|
818
|
+
except NameError:
|
|
819
|
+
# Probably standard Python interpreter
|
|
820
|
+
return False
|
|
821
|
+
|
|
822
|
+
|
|
823
|
+
def _count_consecutive(data):
|
|
824
|
+
"""
|
|
825
|
+
Count consecutive occurrences in data (like cumsum() with reset on zeroes)
|
|
826
|
+
|
|
827
|
+
Parameters
|
|
828
|
+
----------
|
|
829
|
+
data : pd.Series or pd.DataFrame
|
|
830
|
+
Input data to count consecutive occurrences
|
|
831
|
+
|
|
832
|
+
Returns
|
|
833
|
+
-------
|
|
834
|
+
pd.Series or pd.DataFrame
|
|
835
|
+
Data with consecutive counts
|
|
836
|
+
"""
|
|
837
|
+
|
|
838
|
+
def _count(data):
|
|
839
|
+
# Group by consecutive values and count occurrences
|
|
840
|
+
return data * (data.groupby((data != data.shift(1)).cumsum()).cumcount() + 1)
|
|
841
|
+
|
|
842
|
+
# Handle DataFrame by processing each column
|
|
843
|
+
if isinstance(data, _pd.DataFrame):
|
|
844
|
+
for col in data.columns:
|
|
845
|
+
data[col] = _count(data[col])
|
|
846
|
+
return data
|
|
847
|
+
return _count(data)
|
|
848
|
+
|
|
849
|
+
|
|
850
|
+
def _score_str(val):
|
|
851
|
+
"""
|
|
852
|
+
Format value string with appropriate sign (used in plots)
|
|
853
|
+
|
|
854
|
+
Parameters
|
|
855
|
+
----------
|
|
856
|
+
val : str or numeric
|
|
857
|
+
Value to format
|
|
858
|
+
|
|
859
|
+
Returns
|
|
860
|
+
-------
|
|
861
|
+
str
|
|
862
|
+
Formatted string with + or - sign
|
|
863
|
+
"""
|
|
864
|
+
# Add + sign for positive values, - is already included for negative
|
|
865
|
+
return ("" if "-" in val else "+") + str(val)
|
|
866
|
+
|
|
867
|
+
|
|
868
|
+
def make_index(
|
|
869
|
+
ticker_weights, rebalance="1ME", period="max", returns=None, match_dates=False
|
|
870
|
+
):
|
|
871
|
+
"""
|
|
872
|
+
Makes an index out of the given tickers and weights.
|
|
873
|
+
Optionally you can pass a dataframe with the returns.
|
|
874
|
+
If returns is not given it try to download them with yfinance
|
|
875
|
+
|
|
876
|
+
Args:
|
|
877
|
+
* ticker_weights (Dict): A python dict with tickers as keys
|
|
878
|
+
and weights as values
|
|
879
|
+
* rebalance: Pandas resample interval or None for never
|
|
880
|
+
* period: time period of the returns to be downloaded
|
|
881
|
+
* returns (Series, DataFrame): Optional. Returns If provided,
|
|
882
|
+
it will fist check if returns for the given ticker are in
|
|
883
|
+
this dataframe, if not it will try to download them with
|
|
884
|
+
yfinance
|
|
885
|
+
Returns:
|
|
886
|
+
* index_returns (Series, DataFrame): Returns for the index
|
|
887
|
+
"""
|
|
888
|
+
# Declare a returns variable
|
|
889
|
+
index = None
|
|
890
|
+
portfolio = {}
|
|
891
|
+
|
|
892
|
+
# Iterate over weights and get returns for each ticker
|
|
893
|
+
for ticker in ticker_weights:
|
|
894
|
+
if (returns is None) or (ticker not in returns.columns):
|
|
895
|
+
# Download the returns for this ticker, e.g. GOOG
|
|
896
|
+
ticker_returns = download_returns(ticker, period)
|
|
897
|
+
else:
|
|
898
|
+
ticker_returns = returns[ticker]
|
|
899
|
+
|
|
900
|
+
portfolio[ticker] = ticker_returns
|
|
901
|
+
|
|
902
|
+
# Create index members time-series
|
|
903
|
+
index = _pd.DataFrame(portfolio).dropna()
|
|
904
|
+
|
|
905
|
+
# Match dates to start from first non-zero date
|
|
906
|
+
if match_dates:
|
|
907
|
+
index = index[max(index.ne(0).idxmax()):]
|
|
908
|
+
|
|
909
|
+
# Handle case with no rebalancing
|
|
910
|
+
if rebalance is None:
|
|
911
|
+
# Apply weights directly to returns
|
|
912
|
+
for ticker, weight in ticker_weights.items():
|
|
913
|
+
index[ticker] = weight * index[ticker]
|
|
914
|
+
return index.sum(axis=1)
|
|
915
|
+
|
|
916
|
+
last_day = index.index[-1]
|
|
917
|
+
|
|
918
|
+
# Apply weights to each ticker's returns
|
|
919
|
+
# For a weighted portfolio, each day's portfolio return is sum of (weight * asset_return)
|
|
920
|
+
for ticker, weight in ticker_weights.items():
|
|
921
|
+
index[ticker] = weight * index[ticker]
|
|
922
|
+
|
|
923
|
+
# Calculate daily portfolio returns as sum of weighted asset returns
|
|
924
|
+
portfolio_returns = index.sum(axis=1)
|
|
925
|
+
|
|
926
|
+
# Remove rows where all values are NaN
|
|
927
|
+
portfolio_returns = portfolio_returns.dropna()
|
|
928
|
+
return portfolio_returns[portfolio_returns.index <= last_day]
|
|
929
|
+
|
|
930
|
+
|
|
931
|
+
def make_portfolio(returns, start_balance=1e5, mode="comp", round_to=None):
|
|
932
|
+
"""
|
|
933
|
+
Calculate compounded value of portfolio from returns
|
|
934
|
+
|
|
935
|
+
Parameters
|
|
936
|
+
----------
|
|
937
|
+
returns : pd.Series or pd.DataFrame
|
|
938
|
+
Returns data
|
|
939
|
+
start_balance : float, default 1e5
|
|
940
|
+
Starting portfolio balance
|
|
941
|
+
mode : str, default "comp"
|
|
942
|
+
Calculation mode ("comp", "cumsum", "sum", or other)
|
|
943
|
+
round_to : int, optional
|
|
944
|
+
Number of decimal places to round to
|
|
945
|
+
|
|
946
|
+
Returns
|
|
947
|
+
-------
|
|
948
|
+
pd.Series or pd.DataFrame
|
|
949
|
+
Portfolio values over time
|
|
950
|
+
"""
|
|
951
|
+
returns = _prepare_returns(returns)
|
|
952
|
+
|
|
953
|
+
# Calculate portfolio values based on mode
|
|
954
|
+
if mode.lower() in ["cumsum", "sum"]:
|
|
955
|
+
# Simple cumulative sum approach
|
|
956
|
+
p1 = start_balance + start_balance * returns.cumsum()
|
|
957
|
+
elif mode.lower() in ["compsum", "comp"]:
|
|
958
|
+
# Compounded returns approach
|
|
959
|
+
p1 = to_prices(returns, start_balance)
|
|
960
|
+
else:
|
|
961
|
+
# Fixed amount every day approach
|
|
962
|
+
comp_rev = (start_balance + start_balance * returns.shift(1)).fillna(
|
|
963
|
+
start_balance
|
|
964
|
+
) * returns
|
|
965
|
+
p1 = start_balance + comp_rev.cumsum()
|
|
966
|
+
|
|
967
|
+
# Add day before with starting balance
|
|
968
|
+
p0 = _pd.Series(data=start_balance, index=p1.index + _pd.Timedelta(days=-1))[:1]
|
|
969
|
+
|
|
970
|
+
# Combine starting balance with portfolio values
|
|
971
|
+
portfolio = safe_concat([p0, p1])
|
|
972
|
+
|
|
973
|
+
# Handle DataFrame case
|
|
974
|
+
if isinstance(returns, _pd.DataFrame):
|
|
975
|
+
portfolio.iloc[:1, :] = start_balance
|
|
976
|
+
portfolio.drop(columns=[0], inplace=True)
|
|
977
|
+
|
|
978
|
+
# Round if requested
|
|
979
|
+
if round_to:
|
|
980
|
+
portfolio = _np.round(portfolio, round_to)
|
|
981
|
+
|
|
982
|
+
return portfolio
|
|
983
|
+
|
|
984
|
+
|
|
985
|
+
def _flatten_dataframe(df, set_index=None):
|
|
986
|
+
"""
|
|
987
|
+
Flatten multi-index dataframe using CSV conversion method
|
|
988
|
+
|
|
989
|
+
Parameters
|
|
990
|
+
----------
|
|
991
|
+
df : pd.DataFrame
|
|
992
|
+
Multi-index dataframe to flatten
|
|
993
|
+
set_index : str, optional
|
|
994
|
+
Column to use as index after flattening
|
|
995
|
+
|
|
996
|
+
Returns
|
|
997
|
+
-------
|
|
998
|
+
pd.DataFrame
|
|
999
|
+
Flattened dataframe
|
|
1000
|
+
"""
|
|
1001
|
+
# Use string buffer to convert to CSV and back to flatten structure
|
|
1002
|
+
s_buf = _io.StringIO()
|
|
1003
|
+
df.to_csv(s_buf)
|
|
1004
|
+
s_buf.seek(0)
|
|
1005
|
+
|
|
1006
|
+
# Read back from CSV to get flattened structure
|
|
1007
|
+
df = _pd.read_csv(s_buf)
|
|
1008
|
+
if set_index is not None:
|
|
1009
|
+
df.set_index(set_index, inplace=True)
|
|
1010
|
+
|
|
1011
|
+
return df
|