Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions backtesting/backtesting.py
Original file line number Diff line number Diff line change
Expand Up @@ -1224,10 +1224,10 @@ def __init__(self,
if (not isinstance(data.index, pd.DatetimeIndex) and
not isinstance(data.index, pd.RangeIndex) and
# Numeric index with most large numbers
(data.index.is_numeric() and
(pd.api.types.is_numeric_dtype(data.index) and
(data.index > pd.Timestamp('1975').timestamp()).mean() > .8)):
try:
data.index = pd.to_datetime(data.index, infer_datetime_format=True)
data.index = pd.to_datetime(data.index)
except ValueError:
pass

Expand Down
14 changes: 14 additions & 0 deletions backtesting/test/_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -1283,6 +1283,20 @@ def test_optimize_range_index(self):
res = bt.optimize(fast=range(2, 3), slow=range(4, 5))
self.assertGreater(res['# Trades'], 0)

def test_numeric_and_string_index(self):
# `Index.is_numeric()` and `to_datetime(infer_datetime_format=)` were
# removed in pandas 3.0, so any index that was neither a DatetimeIndex
# nor a RangeIndex made `Backtest()` raise.
data = GOOG.iloc[:100].copy()
data.index = pd.Index(data.index.values.astype('datetime64[ns]').astype('int64'))
bt = Backtest(data, SmaCross)
self.assertIsInstance(bt._data.index, pd.DatetimeIndex)
self.assertTrue(bt._data.index.equals(GOOG.index[:100]))

data.index = GOOG.index[:100].strftime('%Y-%m-%d')
with self.assertWarnsRegex(UserWarning, 'index is not datetime'):
Backtest(data, SmaCross)

def test_sl_tp_values_in_trades_df(self):
class S(_S):
def next(self):
Expand Down