Skip to content

Commit 6ac0a21

Browse files
committed
MNT: Replace flake8 with ruff
1 parent d47185f commit 6ac0a21

File tree

10 files changed

+74
-37
lines changed

10 files changed

+74
-37
lines changed

.github/workflows/ci.yml

+1-1
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ jobs:
3939
- run: pip install -U .[test]
4040

4141
- if: matrix.test-type == 'lint'
42-
run: flake8
42+
run: ruff backtesting
4343
- if: matrix.test-type == 'lint'
4444
run: mypy backtesting
4545
- if: matrix.test-type == 'lint'

backtesting/__init__.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -53,10 +53,10 @@
5353
# API Reference Documentation
5454
"""
5555
try:
56-
from ._version import version as __version__ # noqa: F401
56+
from ._version import version as __version__
5757
except ImportError:
5858
__version__ = '?.?.?' # Package not installed
5959

60-
from .backtesting import Backtest, Strategy # noqa: F401
6160
from . import lib # noqa: F401
6261
from ._plotting import set_bokeh_output # noqa: F401
62+
from .backtesting import Backtest, Strategy # noqa: F401

backtesting/_plotting.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -257,7 +257,7 @@ def plot(*, results: pd.Series,
257257
return this.labels[index] || "";
258258
''')
259259

260-
NBSP = '\N{NBSP}' * 4
260+
NBSP = '\N{NBSP}' * 4 # noqa: E999
261261
ohlc_extreme_values = df[['High', 'Low']].copy(deep=False)
262262
ohlc_tooltips = [
263263
('x, y', NBSP.join(('$index',

backtesting/_stats.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import List, TYPE_CHECKING, Union
1+
from typing import TYPE_CHECKING, List, Union
22

33
import numpy as np
44
import pandas as pd

backtesting/_util.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import warnings
2-
from typing import Dict, List, Optional, Sequence, Union, cast
32
from numbers import Number
3+
from typing import Dict, List, Optional, Sequence, Union, cast
44

55
import numpy as np
66
import pandas as pd

backtesting/backtesting.py

+10-10
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,11 @@
99
import os
1010
import sys
1111
import warnings
12-
from abc import abstractmethod, ABCMeta
12+
from abc import ABCMeta, abstractmethod
1313
from concurrent.futures import ProcessPoolExecutor, as_completed
1414
from copy import copy
1515
from functools import lru_cache, partial
16-
from itertools import repeat, product, chain, compress
16+
from itertools import chain, compress, product, repeat
1717
from math import copysign
1818
from numbers import Number
1919
from typing import Callable, Dict, List, Optional, Sequence, Tuple, Type, Union
@@ -29,7 +29,7 @@
2929
def _tqdm(seq, **_):
3030
return seq
3131

32-
from ._plotting import plot
32+
from ._plotting import plot # noqa: I001
3333
from ._stats import compute_stats
3434
from ._util import _as_str, _Indicator, _Data, try_
3535

@@ -75,7 +75,7 @@ def _check_params(self, params):
7575
setattr(self, k, v)
7676
return params
7777

78-
def I(self, # noqa: E741, E743
78+
def I(self, # noqa: E743
7979
func: Callable, *args,
8080
name=None, plot=True, overlay=None, color=None, scatter=False,
8181
**kwargs) -> np.ndarray:
@@ -126,7 +126,7 @@ def init():
126126
try:
127127
value = func(*args, **kwargs)
128128
except Exception as e:
129-
raise RuntimeError(f'Indicator "{name}" errored with exception: {e}')
129+
raise RuntimeError(f'Indicator "{name}" error') from e
130130

131131
if isinstance(value, pd.DataFrame):
132132
value = value.values.T
@@ -190,7 +190,7 @@ def next(self):
190190
super().next()
191191
"""
192192

193-
class __FULL_EQUITY(float):
193+
class __FULL_EQUITY(float): # noqa: N801
194194
def __repr__(self): return '.9999'
195195
_FULL_EQUITY = __FULL_EQUITY(1 - sys.float_info.epsilon)
196196

@@ -664,7 +664,7 @@ def __set_contingent(self, type, price):
664664
if order:
665665
order.cancel()
666666
if price:
667-
kwargs = dict(stop=price) if type == 'sl' else dict(limit=price)
667+
kwargs = {'stop': price} if type == 'sl' else {'limit': price}
668668
order = self.__broker.new_order(-self.size, trade=self, **kwargs)
669669
setattr(self, attr, order)
670670

@@ -1409,13 +1409,13 @@ def _optimize_skopt() -> Union[pd.Series,
14091409
Tuple[pd.Series, pd.Series, dict]]:
14101410
try:
14111411
from skopt import forest_minimize
1412-
from skopt.space import Integer, Real, Categorical
1413-
from skopt.utils import use_named_args
14141412
from skopt.callbacks import DeltaXStopper
14151413
from skopt.learning import ExtraTreesRegressor
1414+
from skopt.space import Categorical, Integer, Real
1415+
from skopt.utils import use_named_args
14161416
except ImportError:
14171417
raise ImportError("Need package 'scikit-optimize' for method='skopt'. "
1418-
"pip install scikit-optimize")
1418+
"pip install scikit-optimize") from None
14191419

14201420
nonlocal max_tries
14211421
max_tries = (200 if max_tries is None else

backtesting/lib.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -12,18 +12,18 @@
1212
"""
1313

1414
from collections import OrderedDict
15+
from inspect import currentframe
1516
from itertools import compress
1617
from numbers import Number
17-
from inspect import currentframe
18-
from typing import Sequence, Optional, Union, Callable
18+
from typing import Callable, Optional, Sequence, Union
1919

2020
import numpy as np
2121
import pandas as pd
2222

23-
from .backtesting import Strategy
2423
from ._plotting import plot_heatmaps as _plot_heatmaps
2524
from ._stats import compute_stats as _compute_stats
2625
from ._util import _Array, _as_str
26+
from .backtesting import Strategy
2727

2828
__pdoc__ = {}
2929

@@ -461,8 +461,8 @@ def set_atr_periods(self, periods: int = 100):
461461
Set the lookback period for computing ATR. The default value
462462
of 100 ensures a _stable_ ATR.
463463
"""
464-
h, l, c_prev = self.data.High, self.data.Low, pd.Series(self.data.Close).shift(1)
465-
tr = np.max([h - l, (c_prev - h).abs(), (c_prev - l).abs()], axis=0)
464+
hi, lo, c_prev = self.data.High, self.data.Low, pd.Series(self.data.Close).shift(1)
465+
tr = np.max([hi - lo, (c_prev - hi).abs(), (c_prev - lo).abs()], axis=0)
466466
atr = pd.Series(tr).rolling(periods).mean().bfill().values
467467
self.__atr = atr
468468

backtesting/test/_test.py

+15-15
Original file line numberDiff line numberDiff line change
@@ -18,21 +18,21 @@
1818

1919
from backtesting import Backtest, Strategy
2020
from backtesting._stats import compute_drawdown_duration_peaks
21+
from backtesting._util import _Array, _as_str, _Indicator, try_
2122
from backtesting.lib import (
2223
OHLCV_AGG,
24+
SignalStrategy,
25+
TrailingStrategy,
2326
barssince,
2427
compute_stats,
2528
cross,
2629
crossover,
27-
quantile,
28-
SignalStrategy,
29-
TrailingStrategy,
30-
resample_apply,
3130
plot_heatmaps,
31+
quantile,
3232
random_ohlc_data,
33+
resample_apply,
3334
)
34-
from backtesting.test import GOOG, EURUSD, SMA
35-
from backtesting._util import _Indicator, _as_str, _Array, try_
35+
from backtesting.test import EURUSD, GOOG, SMA
3636

3737
SHORT_DATA = GOOG.iloc[:20] # Short data for fast tests with no indicator lag
3838

@@ -146,7 +146,7 @@ def init(self):
146146

147147
assert float(self.data.Close) == self.data.Close[-1]
148148

149-
def next(self, FIVE_DAYS=pd.Timedelta('3 days')):
149+
def next(self, _FEW_DAYS=pd.Timedelta('3 days')): # noqa: N803
150150
assert self.equity >= 0
151151

152152
assert isinstance(self.sma, _Indicator)
@@ -193,7 +193,7 @@ def next(self, FIVE_DAYS=pd.Timedelta('3 days')):
193193
assert self.position.size < 0
194194

195195
trade = self.trades[0]
196-
if self.data.index[-1] - self.data.index[trade.entry_bar] > FIVE_DAYS:
196+
if self.data.index[-1] - self.data.index[trade.entry_bar] > _FEW_DAYS:
197197
assert not trade.is_long
198198
assert trade.is_short
199199
assert trade.size < 0
@@ -290,7 +290,7 @@ def almost_equal(a, b):
290290
except TypeError:
291291
return a == b
292292

293-
diff = {key: print(key) or value
293+
diff = {key: print(key) or value # noqa: T201
294294
for key, value in stats.filter(regex='^[^_]').items()
295295
if not almost_equal(value, expected[key])}
296296
self.assertDictEqual(diff, {})
@@ -510,7 +510,7 @@ def coroutine(self):
510510
class TestOptimize(TestCase):
511511
def test_optimize(self):
512512
bt = Backtest(GOOG.iloc[:100], SmaCross)
513-
OPT_PARAMS = dict(fast=range(2, 5, 2), slow=[2, 5, 7, 9])
513+
OPT_PARAMS = {'fast': range(2, 5, 2), 'slow': [2, 5, 7, 9]}
514514

515515
self.assertRaises(ValueError, bt.optimize)
516516
self.assertRaises(ValueError, bt.optimize, maximize='missing key', **OPT_PARAMS)
@@ -556,7 +556,7 @@ def test_method_skopt(self):
556556

557557
def test_max_tries(self):
558558
bt = Backtest(GOOG.iloc[:100], SmaCross)
559-
OPT_PARAMS = dict(fast=range(2, 10, 2), slow=[2, 5, 7, 9])
559+
OPT_PARAMS = {'fast': range(2, 10, 2), 'slow': [2, 5, 7, 9]}
560560
for method, max_tries, random_state in (('grid', 5, 0),
561561
('grid', .3, 0),
562562
('skopt', 7, 0),
@@ -589,7 +589,7 @@ def init(self):
589589

590590
def test_multiprocessing_windows_spawn(self):
591591
df = GOOG.iloc[:100]
592-
kw = dict(fast=[10])
592+
kw = {'fast': [10]}
593593

594594
stats1 = Backtest(df, SmaCross).optimize(**kw)
595595
with patch('multiprocessing.get_start_method', lambda **_: 'spawn'):
@@ -633,7 +633,7 @@ def test_params(self):
633633
bt = Backtest(GOOG.iloc[:100], SmaCross)
634634
bt.run()
635635
with _tempfile() as f:
636-
for p in dict(plot_volume=False,
636+
for p in dict(plot_volume=False, # noqa: C408
637637
plot_equity=False,
638638
plot_return=True,
639639
plot_pl=False,
@@ -722,8 +722,8 @@ def next(self):
722722
self.assertEqual(stats['Equity Final [$]'], 0)
723723
self.assertEqual(len(trades), 2)
724724
assert trades[['EntryTime', 'ExitTime']].equals(
725-
pd.DataFrame(dict(EntryTime=pd.to_datetime(['2006-11-01', '2008-11-14']),
726-
ExitTime=pd.to_datetime(['2007-10-31', '2009-09-21']))))
725+
pd.DataFrame({'EntryTime': pd.to_datetime(['2006-11-01', '2008-11-14']),
726+
'ExitTime': pd.to_datetime(['2007-10-31', '2009-09-21'])}))
727727
assert trades['PnL'].round().equals(pd.Series([23469., -34420.]))
728728

729729
with _tempfile() as f:

pyproject.toml

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
[tool.ruff]
2+
exclude = [
3+
'.git',
4+
'.eggs',
5+
'__pycache__',
6+
'doc/examples',
7+
]
8+
ignore = [
9+
'U006',
10+
'U007',
11+
'U009',
12+
'N802',
13+
'N806',
14+
'C901',
15+
'B008',
16+
'B011',
17+
]
18+
line-length = 100
19+
select = [
20+
'I',
21+
'E',
22+
'F',
23+
'W',
24+
'U',
25+
'N',
26+
'C',
27+
'B',
28+
'T',
29+
'M',
30+
'YTT',
31+
]
32+
33+
[tool.ruff.pep8-naming]
34+
ignore-names = [
35+
'l',
36+
'h',
37+
]

setup.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@
5050
'scikit-optimize',
5151
],
5252
'dev': [
53-
'flake8',
53+
'ruff',
5454
'coverage',
5555
'mypy',
5656
],

0 commit comments

Comments
 (0)