Skip to content

Commit 57e5251

Browse files
committed
TYP: Fix mypy .991 errors
1 parent a4016e5 commit 57e5251

File tree

4 files changed

+33
-30
lines changed

4 files changed

+33
-30
lines changed

backtesting/_plotting.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@
3131
try:
3232
from bokeh.models import CustomJSTickFormatter
3333
except ImportError: # Bokeh < 3.0
34-
from bokeh.models import FuncTickFormatter as CustomJSTickFormatter
34+
from bokeh.models import FuncTickFormatter as CustomJSTickFormatter # type: ignore
3535
from bokeh.io import output_notebook, output_file, show
3636
from bokeh.io.state import curstate
3737
from bokeh.layouts import gridplot
@@ -88,7 +88,7 @@ def colorgen():
8888
def lightness(color, lightness=.94):
8989
rgb = np.array([color.r, color.g, color.b]) / 255
9090
h, _, s = rgb_to_hls(*rgb)
91-
rgb = np.array(hls_to_rgb(h, lightness, s)) * 255
91+
rgb = np.array(hls_to_rgb(h, lightness, s)) * 255.
9292
return RGB(*rgb)
9393

9494

backtesting/_stats.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ def compute_stats(
5252
index=index)
5353

5454
if isinstance(trades, pd.DataFrame):
55-
trades_df = trades
55+
trades_df: pd.DataFrame = trades
5656
else:
5757
# Came straight from Backtest.run()
5858
trades_df = pd.DataFrame({

backtesting/backtesting.py

+26-23
Original file line numberDiff line numberDiff line change
@@ -196,10 +196,10 @@ def __repr__(self): return '.9999'
196196

197197
def buy(self, *,
198198
size: float = _FULL_EQUITY,
199-
limit: float = None,
200-
stop: float = None,
201-
sl: float = None,
202-
tp: float = None):
199+
limit: Optional[float] = None,
200+
stop: Optional[float] = None,
201+
sl: Optional[float] = None,
202+
tp: Optional[float] = None):
203203
"""
204204
Place a new long order. For explanation of parameters, see `Order` and its properties.
205205
@@ -213,10 +213,10 @@ def buy(self, *,
213213

214214
def sell(self, *,
215215
size: float = _FULL_EQUITY,
216-
limit: float = None,
217-
stop: float = None,
218-
sl: float = None,
219-
tp: float = None):
216+
limit: Optional[float] = None,
217+
stop: Optional[float] = None,
218+
sl: Optional[float] = None,
219+
tp: Optional[float] = None):
220220
"""
221221
Place a new short order. For explanation of parameters, see `Order` and its properties.
222222
@@ -382,11 +382,11 @@ class Order:
382382
"""
383383
def __init__(self, broker: '_Broker',
384384
size: float,
385-
limit_price: float = None,
386-
stop_price: float = None,
387-
sl_price: float = None,
388-
tp_price: float = None,
389-
parent_trade: 'Trade' = None):
385+
limit_price: Optional[float] = None,
386+
stop_price: Optional[float] = None,
387+
sl_price: Optional[float] = None,
388+
tp_price: Optional[float] = None,
389+
parent_trade: Optional['Trade'] = None):
390390
self.__broker = broker
391391
assert size != 0
392392
self.__size = size
@@ -696,12 +696,12 @@ def __repr__(self):
696696

697697
def new_order(self,
698698
size: float,
699-
limit: float = None,
700-
stop: float = None,
701-
sl: float = None,
702-
tp: float = None,
699+
limit: Optional[float] = None,
700+
stop: Optional[float] = None,
701+
sl: Optional[float] = None,
702+
tp: Optional[float] = None,
703703
*,
704-
trade: Trade = None):
704+
trade: Optional[Trade] = None):
705705
"""
706706
Argument size indicates whether the order is long or short
707707
"""
@@ -963,7 +963,8 @@ def _close_trade(self, trade: Trade, price: float, time_index: int):
963963
self.closed_trades.append(trade._replace(exit_price=price, exit_bar=time_index))
964964
self._cash += trade.pl
965965

966-
def _open_trade(self, price: float, size: int, sl: float, tp: float, time_index: int):
966+
def _open_trade(self, price: float, size: int,
967+
sl: Optional[float], tp: Optional[float], time_index: int):
967968
trade = Trade(self, size, price, time_index)
968969
self.trades.append(trade)
969970
# Create SL/TP (bracket) orders.
@@ -1202,11 +1203,11 @@ def run(self, **kwargs) -> pd.Series:
12021203
def optimize(self, *,
12031204
maximize: Union[str, Callable[[pd.Series], float]] = 'SQN',
12041205
method: str = 'grid',
1205-
max_tries: Union[int, float] = None,
1206-
constraint: Callable[[dict], bool] = None,
1206+
max_tries: Optional[Union[int, float]] = None,
1207+
constraint: Optional[Callable[[dict], bool]] = None,
12071208
return_heatmap: bool = False,
12081209
return_optimization: bool = False,
1209-
random_state: int = None,
1210+
random_state: Optional[int] = None,
12101211
**kwargs) -> Union[pd.Series,
12111212
Tuple[pd.Series, pd.Series],
12121213
Tuple[pd.Series, pd.Series, dict]]:
@@ -1292,6 +1293,7 @@ def maximize(stats: pd.Series, _key=maximize):
12921293
raise TypeError('`maximize` must be str (a field of backtest.run() result '
12931294
'Series) or a function that accepts result Series '
12941295
'and returns a number; the higher the better')
1296+
assert callable(maximize), maximize
12951297

12961298
have_constraint = bool(constraint)
12971299
if constraint is None:
@@ -1303,6 +1305,7 @@ def constraint(_):
13031305
raise TypeError("`constraint` must be a function that accepts a dict "
13041306
"of strategy parameters and returns a bool whether "
13051307
"the combination of parameters is admissible or not")
1308+
assert callable(constraint), constraint
13061309

13071310
if return_optimization and method != 'skopt':
13081311
raise ValueError("return_optimization=True only valid if method='skopt'")
@@ -1320,7 +1323,7 @@ def __getattr__(self, item):
13201323
return self[item]
13211324

13221325
def _grid_size():
1323-
size = np.prod([len(_tuple(v)) for v in kwargs.values()])
1326+
size = int(np.prod([len(_tuple(v)) for v in kwargs.values()]))
13241327
if size < 10_000 and have_constraint:
13251328
size = sum(1 for p in product(*(zip(repeat(k), _tuple(v))
13261329
for k, v in kwargs.items()))

backtesting/lib.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -202,7 +202,7 @@ def resample_apply(rule: str,
202202
func: Optional[Callable[..., Sequence]],
203203
series: Union[pd.Series, pd.DataFrame, _Array],
204204
*args,
205-
agg: Union[str, dict] = None,
205+
agg: Optional[Union[str, dict]] = None,
206206
**kwargs):
207207
"""
208208
Apply `func` (such as an indicator) to `series`, resampled to
@@ -322,14 +322,14 @@ def wrap_func(resampled, *args, **kwargs):
322322
method='ffill').reindex(series.index)
323323
return result
324324

325-
wrap_func.__name__ = func.__name__ # type: ignore
325+
wrap_func.__name__ = func.__name__
326326

327327
array = strategy_I(wrap_func, resampled, *args, **kwargs)
328328
return array
329329

330330

331331
def random_ohlc_data(example_data: pd.DataFrame, *,
332-
frac=1., random_state: int = None) -> pd.DataFrame:
332+
frac=1., random_state: Optional[int] = None) -> pd.DataFrame:
333333
"""
334334
OHLC data generator. The generated OHLC data has basic
335335
[descriptive statistics](https://en.wikipedia.org/wiki/Descriptive_statistics)
@@ -391,7 +391,7 @@ def init(self):
391391
__exit_signal = (False,)
392392

393393
def set_signal(self, entry_size: Sequence[float],
394-
exit_portion: Sequence[float] = None,
394+
exit_portion: Optional[Sequence[float]] = None,
395395
*,
396396
plot: bool = True):
397397
"""

0 commit comments

Comments
 (0)