pandas FutureWarning: Series.__setitem__ treating keys as labels
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.
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.
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. 😅
Ah, I see this is a different bug altogether.
Sure, welcome a PR!
Works! I'll look into the setitem patterns and put up a PR.
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.
Assumed fixed in https://github.com/kernc/backtesting.py/pull/1359. Thanks!