Skip to content

Commit 74c16ea

Browse files
author
goblincomet
committed
BUG: Fix lib.resample_apply() on OHLC df input
1 parent 082eb7f commit 74c16ea

File tree

1 file changed

+13
-3
lines changed

1 file changed

+13
-3
lines changed

backtesting/lib.py

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,7 @@ def resample_apply(rule: str,
161161
func: Optional[Callable[..., Sequence]],
162162
series: Union[pd.Series, pd.DataFrame, _Array],
163163
*args,
164-
agg: str = 'last',
164+
agg: Union[str, dict] = None,
165165
**kwargs):
166166
"""
167167
Apply `func` (such as an indicator) to `series`, resampled to
@@ -185,8 +185,12 @@ def resample_apply(rule: str,
185185
has a datetime index.
186186
187187
`agg` is the aggregation function to use on resampled groups of data.
188-
Default value is `"last"`, which may be suitable for closing prices,
189-
but you might prefer another (e.g. 'max' for peaks, or similar).
188+
Valid values are anything accepted by `pandas/resample/.agg()`.
189+
Default value for dataframe input is `OHLCV_AGG` dictionary.
190+
Default value for series input is the appropriate entry from `OHLCV_AGG`
191+
if series has a matching name, or otherwise the value `"last"`,
192+
which is suitable for closing prices,
193+
but you might prefer another (e.g. `"max"` for peaks, or similar).
190194
191195
Finally, any `*args` and `**kwargs` that are not already eaten by
192196
implicit `backtesting.backtesting.Strategy.I` call
@@ -240,6 +244,12 @@ def func(x, *_, **__):
240244
'or a `Strategy.data.*` array'
241245
series = series.s
242246

247+
if agg is None:
248+
agg = OHLCV_AGG.get(getattr(series, 'name', None), 'last')
249+
if isinstance(series, pd.DataFrame):
250+
agg = {column: OHLCV_AGG.get(column, 'last')
251+
for column in series.columns}
252+
243253
resampled = series.resample(rule, label='right').agg(agg).dropna()
244254
resampled.name = _as_str(series) + '[' + rule + ']'
245255

0 commit comments

Comments
 (0)