kernc / backtesting.py

:mag_right: :chart_with_upwards_trend: :snake: :moneybag: Backtest trading strategies in Python.
https://kernc.github.io/backtesting.py/
GNU Affero General Public License v3.0
5.04k stars 986 forks source link

The get_loc() method of the Index class in pandas does not have a method argument. #1098

Open chekh opened 6 months ago

chekh commented 6 months ago

Expected Behavior

Executing Backtest.plot() raise an exception in backtesting._plotting module in function def _group_trades(column).

new_bar_idx = new_index.get_loc(mean_time, method='nearest')
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Index.get_loc() got an unexpected keyword argument 'method'

The get_loc() method of the Index class in pandas does not have a method argument.

Original code which is rising exception:


    def _group_trades(column):
        def f(s, new_index=pd.Index(df.index.view(int)), bars=trades[column]):
            if s.size:
                # Via int64 because on pandas recently broken datetime
                mean_time = int(bars.loc[s.index].view(int).mean())
                new_bar_idx = new_index.get_loc(mean_time, method='nearest')
                return new_bar_idx
        return f

As a solution the following code snippet may be applied:


    def _group_trades(column):
        def f(s, new_index=pd.Index(df.index.view(int)), bars=trades[column]):
            if s.size:
                # Via int64 because on pandas recently broken datetime
                mean_time = int(bars.loc[s.index].view(int).mean())

                new_bar_idx = new_index.searchsorted(mean_time, side='left')

                return new_bar_idx
        return f

Additional info

craquinterogo commented 5 months ago

For some reason the version when installed by pip doesn't work, but installing by using "pip install -e " works perfectly.

RaccoonTrading commented 5 months ago

Patch works great thx !

oliver-zehentleitner commented 3 weeks ago

Here is a fork in which the error does not occur. It was solved by locking old versions in the dependencies. The aim was to create a stable version. We will subsequently migrate to newer versions.

https://github.com/LUCIT-Systems-and-Development/lucit-backtesting

vladiscripts commented 1 week ago

It would be better to update, instead of being locked into an unsupported version of Pandas.

https://pandas.pydata.org/docs/whatsnew/v1.4.0.html#other-deprecations :

Deprecated method argument in Index.get_loc(), use index.get_indexer([label], method=...) instead.

oliver-zehentleitner commented 4 days ago

Of course you're right!

My goal was to have a working version. I wasn't sure whether further side effects would occur if we updated bokeh in the dependencies. with the old version we were on the safe side.

But we will update the code accordingly, here is the current project list: https://github.com/orgs/LUCIT-Systems-and-Development/projects/2/views/1