backtesting.py icon indicating copy to clipboard operation
backtesting.py copied to clipboard

pandas FutureWarning: Series.__setitem__ treating keys as labels

Open atharvajoshi01 opened this issue 7 months ago • 6 comments

Several places in the codebase use integer-based indexing on Series via __setitem__ (e.g., series[i] = value) instead of .iloc[i]. With recent pandas versions this triggers FutureWarnings and will break in pandas 3.0 when integer keys are always treated as labels.

This is the same class of bug that ta library fixed in their PSARIndicator (bukosabino/ta#361).

Spotted while reviewing PR #1346. Happy to put together a PR if you want — would just need to grep for __setitem__ patterns on Series objects and replace with .iloc[] where the intent is positional.

atharvajoshi01 avatar Apr 06 '26 08:04 atharvajoshi01

Dug into this a bit more. The main _equity tracking in backtesting.py uses np.tile which returns an ndarray, so the integer indexing there is fine. The warnings are more likely coming from the indicator/data wrapper classes where pandas Series objects get indexed by position with integer keys.

The fix is mechanical: replace series[i] = value with series.iloc[i] = value wherever the intent is positional. Same pattern as the ta library fix in bukosabino/ta#361. I can put up a PR if there's interest.

atharvajoshi01 avatar Apr 20 '26 01:04 atharvajoshi01

Note, this is how the CI is failing:

Traceback (most recent call last):
  File "/home/runner/work/backtesting.py/backtesting.py/backtesting/test/_test.py", line 960, in test_FractionalBacktest
    stats = ubtc_bt.run(fast=2, slow=3)
  File "/home/runner/work/backtesting.py/backtesting.py/backtesting/lib.py", line 557, in run
    indicator /= self._fractional_unit
ValueError: output array is read-only

Our errant use of __setitem__ sure is not obvious here. 😅

kernc avatar Apr 22 '26 03:04 kernc

Ah, I see this is a different bug altogether.

Sure, welcome a PR!

kernc avatar Apr 22 '26 03:04 kernc

Works! I'll look into the setitem patterns and put up a PR.

atharvajoshi01 avatar Apr 25 '26 20:04 atharvajoshi01

ran the test suite with -W default::FutureWarning on pandas 2.2 and didnt get any setitem warnings, so probably a pandas 3.x only thing. what version were you on when you originally hit it? want to scope before grepping.

atharvajoshi01 avatar Apr 29 '26 03:04 atharvajoshi01

Assumed fixed in https://github.com/kernc/backtesting.py/pull/1359. Thanks!

kernc avatar Jul 20 '26 12:07 kernc