From baefda80d19e3eaf14e2ec6a600dcb8c456a3ccf Mon Sep 17 00:00:00 2001 From: Matthias Date: Mon, 11 Apr 2022 18:02:02 +0200 Subject: [PATCH] Enable flake8 E226 rule --- freqtrade/configuration/PeriodicCache.py | 2 +- freqtrade/configuration/load_config.py | 2 +- freqtrade/exchange/exchange.py | 2 +- freqtrade/leverage/interest.py | 6 +-- freqtrade/misc.py | 2 +- freqtrade/optimize/hyperopt_tools.py | 10 ++--- freqtrade/persistence/models.py | 8 ++-- .../plugins/pairlist/VolatilityFilter.py | 2 +- freqtrade/rpc/telegram.py | 3 +- freqtrade/strategy/strategy_helper.py | 4 +- setup.cfg | 4 +- tests/exchange/test_exchange.py | 37 ++++++++++--------- tests/leverage/test_interest.py | 2 +- tests/optimize/test_optimize_reports.py | 2 +- tests/strategy/test_strategy_helpers.py | 2 +- tests/test_persistence.py | 8 ++-- 16 files changed, 50 insertions(+), 46 deletions(-) diff --git a/freqtrade/configuration/PeriodicCache.py b/freqtrade/configuration/PeriodicCache.py index 64fff668e..1a535440d 100644 --- a/freqtrade/configuration/PeriodicCache.py +++ b/freqtrade/configuration/PeriodicCache.py @@ -16,4 +16,4 @@ class PeriodicCache(TTLCache): return ts - offset # Init with smlight offset - super().__init__(maxsize=maxsize, ttl=ttl-1e-5, timer=local_timer, getsizeof=getsizeof) + super().__init__(maxsize=maxsize, ttl=ttl - 1e-5, timer=local_timer, getsizeof=getsizeof) diff --git a/freqtrade/configuration/load_config.py b/freqtrade/configuration/load_config.py index 4ef531c7a..3fcbd1f2f 100644 --- a/freqtrade/configuration/load_config.py +++ b/freqtrade/configuration/load_config.py @@ -31,7 +31,7 @@ def log_config_error_range(path: str, errmsg: str) -> str: offset = int(offsetlist[0]) text = Path(path).read_text() # Fetch an offset of 80 characters around the error line - subtext = text[offset-min(80, offset):offset+80] + subtext = text[offset - min(80, offset):offset + 80] segments = subtext.split('\n') if len(segments) > 3: # Remove first and last lines, to avoid odd truncations diff --git a/freqtrade/exchange/exchange.py b/freqtrade/exchange/exchange.py index 82505759a..af3e4c3eb 100644 --- a/freqtrade/exchange/exchange.py +++ b/freqtrade/exchange/exchange.py @@ -2177,7 +2177,7 @@ class Exchange: lev = tier['lev'] if tier_index < len(pair_tiers) - 1: - next_tier = pair_tiers[tier_index+1] + next_tier = pair_tiers[tier_index + 1] next_floor = next_tier['min'] / next_tier['lev'] if next_floor > stake_amount: # Next tier min too high for stake amount return min((tier['max'] / stake_amount), lev) diff --git a/freqtrade/leverage/interest.py b/freqtrade/leverage/interest.py index ff375b05e..367df5821 100644 --- a/freqtrade/leverage/interest.py +++ b/freqtrade/leverage/interest.py @@ -31,13 +31,13 @@ def interest( """ exchange_name = exchange_name.lower() if exchange_name == "binance": - return borrowed * rate * ceil(hours)/twenty_four + return borrowed * rate * ceil(hours) / twenty_four elif exchange_name == "kraken": # Rounded based on https://kraken-fees-calculator.github.io/ - return borrowed * rate * (one+ceil(hours/four)) + return borrowed * rate * (one + ceil(hours / four)) elif exchange_name == "ftx": # As Explained under #Interest rates section in # https://help.ftx.com/hc/en-us/articles/360053007671-Spot-Margin-Trading-Explainer - return borrowed * rate * ceil(hours)/twenty_four + return borrowed * rate * ceil(hours) / twenty_four else: raise OperationalException(f"Leverage not available on {exchange_name} with freqtrade") diff --git a/freqtrade/misc.py b/freqtrade/misc.py index acc7fc2e4..d5572ea0b 100644 --- a/freqtrade/misc.py +++ b/freqtrade/misc.py @@ -126,7 +126,7 @@ def format_ms_time(date: int) -> str: convert MS date to readable format. : epoch-string in ms """ - return datetime.fromtimestamp(date/1000.0).strftime('%Y-%m-%dT%H:%M:%S') + return datetime.fromtimestamp(date / 1000.0).strftime('%Y-%m-%dT%H:%M:%S') def deep_merge_dicts(source, destination, allow_null_overrides: bool = True): diff --git a/freqtrade/optimize/hyperopt_tools.py b/freqtrade/optimize/hyperopt_tools.py index 8c84f772a..8d3c3a266 100755 --- a/freqtrade/optimize/hyperopt_tools.py +++ b/freqtrade/optimize/hyperopt_tools.py @@ -390,8 +390,8 @@ class HyperoptTools(): lambda x: '{} {}'.format( round_coin_value(x['Total profit'], stake_currency, keep_trailing_zeros=True), f"({x['Profit']:,.2%})".rjust(10, ' ') - ).rjust(25+len(stake_currency)) - if x['Total profit'] != 0.0 else '--'.rjust(25+len(stake_currency)), + ).rjust(25 + len(stake_currency)) + if x['Total profit'] != 0.0 else '--'.rjust(25 + len(stake_currency)), axis=1 ) trials = trials.drop(columns=['Total profit']) @@ -399,11 +399,11 @@ class HyperoptTools(): if print_colorized: for i in range(len(trials)): if trials.loc[i]['is_profit']: - for j in range(len(trials.loc[i])-3): + for j in range(len(trials.loc[i]) - 3): trials.iat[i, j] = "{}{}{}".format(Fore.GREEN, str(trials.loc[i][j]), Fore.RESET) if trials.loc[i]['is_best'] and highlight_best: - for j in range(len(trials.loc[i])-3): + for j in range(len(trials.loc[i]) - 3): trials.iat[i, j] = "{}{}{}".format(Style.BRIGHT, str(trials.loc[i][j]), Style.RESET_ALL) @@ -459,7 +459,7 @@ class HyperoptTools(): 'loss', 'is_initial_point', 'is_best'] perc_multi = 100 - param_metrics = [("params_dict."+param) for param in results[0]['params_dict'].keys()] + param_metrics = [("params_dict." + param) for param in results[0]['params_dict'].keys()] trials = trials[base_metrics + param_metrics] base_columns = ['Best', 'Epoch', 'Trades', 'Avg profit', 'Median profit', 'Total profit', diff --git a/freqtrade/persistence/models.py b/freqtrade/persistence/models.py index 05de39caf..a9c07f12c 100644 --- a/freqtrade/persistence/models.py +++ b/freqtrade/persistence/models.py @@ -360,7 +360,7 @@ class LocalTrade(): if self.has_no_leverage: return 0.0 elif not self.is_short: - return (self.amount * self.open_rate) * ((self.leverage-1)/self.leverage) + return (self.amount * self.open_rate) * ((self.leverage - 1) / self.leverage) else: return self.amount @@ -747,7 +747,7 @@ class LocalTrade(): now = (self.close_date or datetime.now(timezone.utc)).replace(tzinfo=None) sec_per_hour = Decimal(3600) total_seconds = Decimal((now - open_date).total_seconds()) - hours = total_seconds/sec_per_hour or zero + hours = total_seconds / sec_per_hour or zero rate = Decimal(interest_rate or self.interest_rate) borrowed = Decimal(self.borrowed) @@ -861,9 +861,9 @@ class LocalTrade(): return 0.0 else: if self.is_short: - profit_ratio = (1 - (close_trade_value/self.open_trade_value)) * leverage + profit_ratio = (1 - (close_trade_value / self.open_trade_value)) * leverage else: - profit_ratio = ((close_trade_value/self.open_trade_value) - 1) * leverage + profit_ratio = ((close_trade_value / self.open_trade_value) - 1) * leverage return float(f"{profit_ratio:.8f}") diff --git a/freqtrade/plugins/pairlist/VolatilityFilter.py b/freqtrade/plugins/pairlist/VolatilityFilter.py index 7a355c291..6aa857c2c 100644 --- a/freqtrade/plugins/pairlist/VolatilityFilter.py +++ b/freqtrade/plugins/pairlist/VolatilityFilter.py @@ -107,7 +107,7 @@ class VolatilityFilter(IPairList): returns = (np.log(daily_candles.close / daily_candles.close.shift(-1))) returns.fillna(0, inplace=True) - volatility_series = returns.rolling(window=self._days).std()*np.sqrt(self._days) + volatility_series = returns.rolling(window=self._days).std() * np.sqrt(self._days) volatility_avg = volatility_series.mean() if self._min_volatility <= volatility_avg <= self._max_volatility: diff --git a/freqtrade/rpc/telegram.py b/freqtrade/rpc/telegram.py index b152b722c..5699b58aa 100644 --- a/freqtrade/rpc/telegram.py +++ b/freqtrade/rpc/telegram.py @@ -419,7 +419,8 @@ class Telegram(RPCHandler): if prev_avg_price: minus_on_entry = (cur_entry_average - prev_avg_price) / prev_avg_price - dur_entry = cur_entry_datetime - arrow.get(filled_orders[x-1]["order_filled_date"]) + dur_entry = cur_entry_datetime - arrow.get( + filled_orders[x - 1]["order_filled_date"]) days = dur_entry.days hours, remainder = divmod(dur_entry.seconds, 3600) minutes, seconds = divmod(remainder, 60) diff --git a/freqtrade/strategy/strategy_helper.py b/freqtrade/strategy/strategy_helper.py index f07c14e24..a36cb3dbb 100644 --- a/freqtrade/strategy/strategy_helper.py +++ b/freqtrade/strategy/strategy_helper.py @@ -93,9 +93,9 @@ def stoploss_from_open( return 1 if is_short is True: - stoploss = -1+((1-open_relative_stop)/(1-current_profit)) + stoploss = -1 + ((1 - open_relative_stop) / (1 - current_profit)) else: - stoploss = 1-((1+open_relative_stop)/(1+current_profit)) + stoploss = 1 - ((1 + open_relative_stop) / (1 + current_profit)) # negative stoploss values indicate the requested stop price is higher/lower # (long/short) than the current price diff --git a/setup.cfg b/setup.cfg index 6aaec9d73..f4a90bda7 100644 --- a/setup.cfg +++ b/setup.cfg @@ -39,7 +39,9 @@ console_scripts = freqtrade = freqtrade.main:main [flake8] -#ignore = +# Default from https://flake8.pycqa.org/en/latest/user/options.html#cmdoption-flake8-ignore +# minus E226 +ignore = E121,E123,E126,E24,E704,W503,W504 max-line-length = 100 max-complexity = 12 exclude = diff --git a/tests/exchange/test_exchange.py b/tests/exchange/test_exchange.py index f0417c4c5..cffeec5b3 100644 --- a/tests/exchange/test_exchange.py +++ b/tests/exchange/test_exchange.py @@ -382,11 +382,11 @@ def test__get_stake_amount_limit(mocker, default_conf) -> None: ) # min result = exchange.get_min_pair_stake_amount('ETH/BTC', 1, stoploss) - expected_result = 2 * (1+0.05) / (1-abs(stoploss)) + expected_result = 2 * (1 + 0.05) / (1 - abs(stoploss)) assert isclose(result, expected_result) # With Leverage result = exchange.get_min_pair_stake_amount('ETH/BTC', 1, stoploss, 3.0) - assert isclose(result, expected_result/3) + assert isclose(result, expected_result / 3) # max result = exchange.get_max_pair_stake_amount('ETH/BTC', 2) assert result == 10000 @@ -401,11 +401,11 @@ def test__get_stake_amount_limit(mocker, default_conf) -> None: PropertyMock(return_value=markets) ) result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, stoploss) - expected_result = 2 * 2 * (1+0.05) / (1-abs(stoploss)) + expected_result = 2 * 2 * (1 + 0.05) / (1 - abs(stoploss)) assert isclose(result, expected_result) # With Leverage result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, stoploss, 5.0) - assert isclose(result, expected_result/5) + assert isclose(result, expected_result / 5) # max result = exchange.get_max_pair_stake_amount('ETH/BTC', 2) assert result == 20000 @@ -420,11 +420,11 @@ def test__get_stake_amount_limit(mocker, default_conf) -> None: PropertyMock(return_value=markets) ) result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, stoploss) - expected_result = max(2, 2 * 2) * (1+0.05) / (1-abs(stoploss)) + expected_result = max(2, 2 * 2) * (1 + 0.05) / (1 - abs(stoploss)) assert isclose(result, expected_result) # With Leverage result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, stoploss, 10) - assert isclose(result, expected_result/10) + assert isclose(result, expected_result / 10) # min amount and cost are set (amount is minial) markets["ETH/BTC"]["limits"] = { @@ -436,11 +436,11 @@ def test__get_stake_amount_limit(mocker, default_conf) -> None: PropertyMock(return_value=markets) ) result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, stoploss) - expected_result = max(8, 2 * 2) * (1+0.05) / (1-abs(stoploss)) + expected_result = max(8, 2 * 2) * (1 + 0.05) / (1 - abs(stoploss)) assert isclose(result, expected_result) # With Leverage result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, stoploss, 7.0) - assert isclose(result, expected_result/7.0) + assert isclose(result, expected_result / 7.0) # Max result = exchange.get_max_pair_stake_amount('ETH/BTC', 2) assert result == 1000 @@ -450,7 +450,7 @@ def test__get_stake_amount_limit(mocker, default_conf) -> None: assert isclose(result, expected_result) # With Leverage result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, -0.4, 8.0) - assert isclose(result, expected_result/8.0) + assert isclose(result, expected_result / 8.0) # Max result = exchange.get_max_pair_stake_amount('ETH/BTC', 2) assert result == 1000 @@ -461,7 +461,7 @@ def test__get_stake_amount_limit(mocker, default_conf) -> None: assert isclose(result, expected_result) # With Leverage result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, -1, 12.0) - assert isclose(result, expected_result/12) + assert isclose(result, expected_result / 12) # Max result = exchange.get_max_pair_stake_amount('ETH/BTC', 2) assert result == 1000 @@ -489,7 +489,7 @@ def test__get_stake_amount_limit(mocker, default_conf) -> None: ) # With Leverage, Contract size 10 result = exchange.get_min_pair_stake_amount('ETH/BTC', 2, -1, 12.0) - assert isclose(result, (expected_result/12) * 10.0) + assert isclose(result, (expected_result / 12) * 10.0) # Max result = exchange.get_max_pair_stake_amount('ETH/BTC', 2) assert result == 10000 @@ -510,7 +510,7 @@ def test_get_min_pair_stake_amount_real_data(mocker, default_conf) -> None: PropertyMock(return_value=markets) ) result = exchange.get_min_pair_stake_amount('ETH/BTC', 0.020405, stoploss) - expected_result = max(0.0001, 0.001 * 0.020405) * (1+0.05) / (1-abs(stoploss)) + expected_result = max(0.0001, 0.001 * 0.020405) * (1 + 0.05) / (1 - abs(stoploss)) assert round(result, 8) == round(expected_result, 8) # Max result = exchange.get_max_pair_stake_amount('ETH/BTC', 2.0) @@ -518,12 +518,12 @@ def test_get_min_pair_stake_amount_real_data(mocker, default_conf) -> None: # Leverage result = exchange.get_min_pair_stake_amount('ETH/BTC', 0.020405, stoploss, 3.0) - assert round(result, 8) == round(expected_result/3, 8) + assert round(result, 8) == round(expected_result / 3, 8) # Contract_size markets["ETH/BTC"]["contractSize"] = 0.1 result = exchange.get_min_pair_stake_amount('ETH/BTC', 0.020405, stoploss, 3.0) - assert round(result, 8) == round((expected_result/3), 8) + assert round(result, 8) == round((expected_result / 3), 8) # Max result = exchange.get_max_pair_stake_amount('ETH/BTC', 12.0) @@ -2691,9 +2691,10 @@ async def test__async_get_trade_history_time(default_conf, mocker, caplog, excha # Monkey-patch async function exchange._api_async.fetch_trades = MagicMock(side_effect=mock_get_trade_hist) pair = 'ETH/BTC' - ret = await exchange._async_get_trade_history_time(pair, - since=fetch_trades_result[0]['timestamp'], - until=fetch_trades_result[-1]['timestamp']-1) + ret = await exchange._async_get_trade_history_time( + pair, + since=fetch_trades_result[0]['timestamp'], + until=fetch_trades_result[-1]['timestamp'] - 1) assert type(ret) is tuple assert ret[0] == pair assert type(ret[1]) is list @@ -2729,7 +2730,7 @@ async def test__async_get_trade_history_time_empty(default_conf, mocker, caplog, exchange._async_fetch_trades = MagicMock(side_effect=mock_get_trade_hist) pair = 'ETH/BTC' ret = await exchange._async_get_trade_history_time(pair, since=trades_history[0][0], - until=trades_history[-1][0]-1) + until=trades_history[-1][0] - 1) assert type(ret) is tuple assert ret[0] == pair assert type(ret[1]) is list diff --git a/tests/leverage/test_interest.py b/tests/leverage/test_interest.py index c7e787bdb..6b189ce50 100644 --- a/tests/leverage/test_interest.py +++ b/tests/leverage/test_interest.py @@ -6,7 +6,7 @@ import pytest from freqtrade.leverage import interest -ten_mins = Decimal(1/6) +ten_mins = Decimal(1 / 6) five_hours = Decimal(5.0) twentyfive_hours = Decimal(25.0) diff --git a/tests/optimize/test_optimize_reports.py b/tests/optimize/test_optimize_reports.py index ad9bcd978..d40fc1e2f 100644 --- a/tests/optimize/test_optimize_reports.py +++ b/tests/optimize/test_optimize_reports.py @@ -190,7 +190,7 @@ def test_store_backtest_stats(testdatadir, mocker): assert dump_mock.call_count == 3 assert isinstance(dump_mock.call_args_list[0][0][0], Path) - assert str(dump_mock.call_args_list[0][0][0]).startswith(str(testdatadir/'backtest-result')) + assert str(dump_mock.call_args_list[0][0][0]).startswith(str(testdatadir / 'backtest-result')) dump_mock.reset_mock() filename = testdatadir / 'testresult.json' diff --git a/tests/strategy/test_strategy_helpers.py b/tests/strategy/test_strategy_helpers.py index 205fb4dac..65fb9f6dc 100644 --- a/tests/strategy/test_strategy_helpers.py +++ b/tests/strategy/test_strategy_helpers.py @@ -164,7 +164,7 @@ def test_stoploss_from_absolute(): assert pytest.approx(stoploss_from_absolute(90, 100, True)) == 0 assert pytest.approx(stoploss_from_absolute(100, 100, True)) == 0 - assert pytest.approx(stoploss_from_absolute(110, 100, True)) == -(1 - (110/100)) + assert pytest.approx(stoploss_from_absolute(110, 100, True)) == -(1 - (110 / 100)) assert pytest.approx(stoploss_from_absolute(110, 100, True)) == 0.1 assert pytest.approx(stoploss_from_absolute(105, 100, True)) == 0.05 assert pytest.approx(stoploss_from_absolute(100, 0, True)) == 1 diff --git a/tests/test_persistence.py b/tests/test_persistence.py index ecac561f8..801e0e35f 100644 --- a/tests/test_persistence.py +++ b/tests/test_persistence.py @@ -119,7 +119,7 @@ def test_set_stop_loss_isolated_liq(fee): assert trade.stop_loss is None assert trade.initial_stop_loss is None - trade._set_stop_loss(0.1, (1.0/9.0)) + trade._set_stop_loss(0.1, (1.0 / 9.0)) assert trade.liquidation_price == 0.09 assert trade.stop_loss == 0.1 assert trade.initial_stop_loss == 0.1 @@ -160,7 +160,7 @@ def test_set_stop_loss_isolated_liq(fee): assert trade.stop_loss is None assert trade.initial_stop_loss is None - trade._set_stop_loss(0.08, (1.0/9.0)) + trade._set_stop_loss(0.08, (1.0 / 9.0)) assert trade.liquidation_price == 0.09 assert trade.stop_loss == 0.08 assert trade.initial_stop_loss == 0.08 @@ -171,13 +171,13 @@ def test_set_stop_loss_isolated_liq(fee): assert trade.initial_stop_loss == 0.08 trade.set_isolated_liq(0.07) - trade._set_stop_loss(0.1, (1.0/8.0)) + trade._set_stop_loss(0.1, (1.0 / 8.0)) assert trade.liquidation_price == 0.07 assert trade.stop_loss == 0.07 assert trade.initial_stop_loss == 0.08 # Stop doesn't move stop higher - trade._set_stop_loss(0.1, (1.0/9.0)) + trade._set_stop_loss(0.1, (1.0 / 9.0)) assert trade.liquidation_price == 0.07 assert trade.stop_loss == 0.07 assert trade.initial_stop_loss == 0.08