Skip to content

Commit

Permalink
TYP: Fix mypy .991 errors
Browse files Browse the repository at this point in the history
  • Loading branch information
kernc committed Nov 27, 2022
1 parent a4016e5 commit 57e5251
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 30 deletions.
4 changes: 2 additions & 2 deletions backtesting/_plotting.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
try:
from bokeh.models import CustomJSTickFormatter
except ImportError: # Bokeh < 3.0
from bokeh.models import FuncTickFormatter as CustomJSTickFormatter
from bokeh.models import FuncTickFormatter as CustomJSTickFormatter # type: ignore
from bokeh.io import output_notebook, output_file, show
from bokeh.io.state import curstate
from bokeh.layouts import gridplot
Expand Down Expand Up @@ -88,7 +88,7 @@ def colorgen():
def lightness(color, lightness=.94):
rgb = np.array([color.r, color.g, color.b]) / 255
h, _, s = rgb_to_hls(*rgb)
rgb = np.array(hls_to_rgb(h, lightness, s)) * 255
rgb = np.array(hls_to_rgb(h, lightness, s)) * 255.
return RGB(*rgb)


Expand Down
2 changes: 1 addition & 1 deletion backtesting/_stats.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def compute_stats(
index=index)

if isinstance(trades, pd.DataFrame):
trades_df = trades
trades_df: pd.DataFrame = trades
else:
# Came straight from Backtest.run()
trades_df = pd.DataFrame({
Expand Down
49 changes: 26 additions & 23 deletions backtesting/backtesting.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,10 +196,10 @@ def __repr__(self): return '.9999'

def buy(self, *,
size: float = _FULL_EQUITY,
limit: float = None,
stop: float = None,
sl: float = None,
tp: float = None):
limit: Optional[float] = None,
stop: Optional[float] = None,
sl: Optional[float] = None,
tp: Optional[float] = None):
"""
Place a new long order. For explanation of parameters, see `Order` and its properties.
Expand All @@ -213,10 +213,10 @@ def buy(self, *,

def sell(self, *,
size: float = _FULL_EQUITY,
limit: float = None,
stop: float = None,
sl: float = None,
tp: float = None):
limit: Optional[float] = None,
stop: Optional[float] = None,
sl: Optional[float] = None,
tp: Optional[float] = None):
"""
Place a new short order. For explanation of parameters, see `Order` and its properties.
Expand Down Expand Up @@ -382,11 +382,11 @@ class Order:
"""
def __init__(self, broker: '_Broker',
size: float,
limit_price: float = None,
stop_price: float = None,
sl_price: float = None,
tp_price: float = None,
parent_trade: 'Trade' = None):
limit_price: Optional[float] = None,
stop_price: Optional[float] = None,
sl_price: Optional[float] = None,
tp_price: Optional[float] = None,
parent_trade: Optional['Trade'] = None):
self.__broker = broker
assert size != 0
self.__size = size
Expand Down Expand Up @@ -696,12 +696,12 @@ def __repr__(self):

def new_order(self,
size: float,
limit: float = None,
stop: float = None,
sl: float = None,
tp: float = None,
limit: Optional[float] = None,
stop: Optional[float] = None,
sl: Optional[float] = None,
tp: Optional[float] = None,
*,
trade: Trade = None):
trade: Optional[Trade] = None):
"""
Argument size indicates whether the order is long or short
"""
Expand Down Expand Up @@ -963,7 +963,8 @@ def _close_trade(self, trade: Trade, price: float, time_index: int):
self.closed_trades.append(trade._replace(exit_price=price, exit_bar=time_index))
self._cash += trade.pl

def _open_trade(self, price: float, size: int, sl: float, tp: float, time_index: int):
def _open_trade(self, price: float, size: int,
sl: Optional[float], tp: Optional[float], time_index: int):
trade = Trade(self, size, price, time_index)
self.trades.append(trade)
# Create SL/TP (bracket) orders.
Expand Down Expand Up @@ -1202,11 +1203,11 @@ def run(self, **kwargs) -> pd.Series:
def optimize(self, *,
maximize: Union[str, Callable[[pd.Series], float]] = 'SQN',
method: str = 'grid',
max_tries: Union[int, float] = None,
constraint: Callable[[dict], bool] = None,
max_tries: Optional[Union[int, float]] = None,
constraint: Optional[Callable[[dict], bool]] = None,
return_heatmap: bool = False,
return_optimization: bool = False,
random_state: int = None,
random_state: Optional[int] = None,
**kwargs) -> Union[pd.Series,
Tuple[pd.Series, pd.Series],
Tuple[pd.Series, pd.Series, dict]]:
Expand Down Expand Up @@ -1292,6 +1293,7 @@ def maximize(stats: pd.Series, _key=maximize):
raise TypeError('`maximize` must be str (a field of backtest.run() result '
'Series) or a function that accepts result Series '
'and returns a number; the higher the better')
assert callable(maximize), maximize

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

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

def _grid_size():
size = np.prod([len(_tuple(v)) for v in kwargs.values()])
size = int(np.prod([len(_tuple(v)) for v in kwargs.values()]))
if size < 10_000 and have_constraint:
size = sum(1 for p in product(*(zip(repeat(k), _tuple(v))
for k, v in kwargs.items()))
Expand Down
8 changes: 4 additions & 4 deletions backtesting/lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ def resample_apply(rule: str,
func: Optional[Callable[..., Sequence]],
series: Union[pd.Series, pd.DataFrame, _Array],
*args,
agg: Union[str, dict] = None,
agg: Optional[Union[str, dict]] = None,
**kwargs):
"""
Apply `func` (such as an indicator) to `series`, resampled to
Expand Down Expand Up @@ -322,14 +322,14 @@ def wrap_func(resampled, *args, **kwargs):
method='ffill').reindex(series.index)
return result

wrap_func.__name__ = func.__name__ # type: ignore
wrap_func.__name__ = func.__name__

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


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

def set_signal(self, entry_size: Sequence[float],
exit_portion: Sequence[float] = None,
exit_portion: Optional[Sequence[float]] = None,
*,
plot: bool = True):
"""
Expand Down

0 comments on commit 57e5251

Please sign in to comment.