More lint fixes (#198)

* autopep fixes

* remove unused imports

* fix plot_dataframe.py lint warnings

* make pep8 error fails the build

* two more line breakings

* matplotlib.use() must be called before pyplot import
This commit is contained in:
Janne Sinivirta 2017-12-18 18:36:00 +02:00 committed by Michael Egger
parent 1a556198b2
commit c8fb6c4661
9 changed files with 26 additions and 27 deletions

View File

@ -25,8 +25,9 @@ jobs:
- script: - script:
- cp config.json.example config.json - cp config.json.example config.json
- python freqtrade/main.py hyperopt -e 5 - python freqtrade/main.py hyperopt -e 5
- script: flake8 freqtrade
after_success: after_success:
- flake8 freqtrade && coveralls - coveralls
notifications: notifications:
slack: slack:
secure: bKLXmOrx8e2aPZl7W8DA5BdPAXWGpI5UzST33oc1G/thegXcDVmHBTJrBs4sZak6bgAclQQrdZIsRd2eFYzHLalJEaw6pk7hoAw8SvLnZO0ZurWboz7qg2+aZZXfK4eKl/VUe4sM9M4e/qxjkK+yWG7Marg69c4v1ypF7ezUi1fPYILYw8u0paaiX0N5UX8XNlXy+PBlga2MxDjUY70MuajSZhPsY2pDUvYnMY1D/7XN3cFW0g+3O8zXjF0IF4q1Z/1ASQe+eYjKwPQacE+O8KDD+ZJYoTOFBAPllrtpO1jnOPFjNGf3JIbVMZw4bFjIL0mSQaiSUaUErbU3sFZ5Or79rF93XZ81V7uEZ55vD8KMfR2CB1cQJcZcj0v50BxLo0InkFqa0Y8Nra3sbpV4fV5Oe8pDmomPJrNFJnX6ULQhQ1gTCe0M5beKgVms5SITEpt4/Y0CmLUr6iHDT0CUiyMIRWAXdIgbGh1jfaWOMksybeRevlgDsIsNBjXmYI1Sw2ZZR2Eo2u4R6zyfyjOMLwYJ3vgq9IrACv2w5nmf0+oguMWHf6iWi2hiOqhlAN1W74+3HsYQcqnuM3LGOmuCnPprV1oGBqkPXjIFGpy21gNx4vHfO1noLUyJnMnlu2L7SSuN1CdLsnjJ1hVjpJjPfqB4nn8g12x87TqM1bOm+3Q= secure: bKLXmOrx8e2aPZl7W8DA5BdPAXWGpI5UzST33oc1G/thegXcDVmHBTJrBs4sZak6bgAclQQrdZIsRd2eFYzHLalJEaw6pk7hoAw8SvLnZO0ZurWboz7qg2+aZZXfK4eKl/VUe4sM9M4e/qxjkK+yWG7Marg69c4v1ypF7ezUi1fPYILYw8u0paaiX0N5UX8XNlXy+PBlga2MxDjUY70MuajSZhPsY2pDUvYnMY1D/7XN3cFW0g+3O8zXjF0IF4q1Z/1ASQe+eYjKwPQacE+O8KDD+ZJYoTOFBAPllrtpO1jnOPFjNGf3JIbVMZw4bFjIL0mSQaiSUaUErbU3sFZ5Or79rF93XZ81V7uEZ55vD8KMfR2CB1cQJcZcj0v50BxLo0InkFqa0Y8Nra3sbpV4fV5Oe8pDmomPJrNFJnX6ULQhQ1gTCe0M5beKgVms5SITEpt4/Y0CmLUr6iHDT0CUiyMIRWAXdIgbGh1jfaWOMksybeRevlgDsIsNBjXmYI1Sw2ZZR2Eo2u4R6zyfyjOMLwYJ3vgq9IrACv2w5nmf0+oguMWHf6iWi2hiOqhlAN1W74+3HsYQcqnuM3LGOmuCnPprV1oGBqkPXjIFGpy21gNx4vHfO1noLUyJnMnlu2L7SSuN1CdLsnjJ1hVjpJjPfqB4nn8g12x87TqM1bOm+3Q=

View File

@ -168,8 +168,8 @@ def build_subcommands(parser: argparse.ArgumentParser) -> None:
) )
backtesting_cmd.add_argument( backtesting_cmd.add_argument(
'-r', '--refresh-pairs-cached', '-r', '--refresh-pairs-cached',
help='refresh the pairs files in tests/testdata with the latest data from Bittrex. Use it if you want to \ help='refresh the pairs files in tests/testdata with the latest data from Bittrex. \
run your backtesting with up-to-date data.', Use it if you want to run your backtesting with up-to-date data.',
action='store_true', action='store_true',
dest='refresh_pairs', dest='refresh_pairs',
) )

View File

@ -13,7 +13,8 @@ from freqtrade.analyze import populate_indicators, parse_ticker_dataframe
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
def load_data(pairs: List[str], ticker_interval: int = 5, refresh_pairs: Optional[bool] = False) -> Dict[str, List]: def load_data(pairs: List[str], ticker_interval: int = 5,
refresh_pairs: Optional[bool] = False) -> Dict[str, List]:
""" """
Loads ticker history data for the given parameters Loads ticker history data for the given parameters
:param ticker_interval: ticker interval in minutes :param ticker_interval: ticker interval in minutes
@ -61,10 +62,10 @@ def download_pairs(pairs: List[str]) -> bool:
"""For each pairs passed in parameters, download 1 and 5 ticker intervals""" """For each pairs passed in parameters, download 1 and 5 ticker intervals"""
for pair in pairs: for pair in pairs:
try: try:
for interval in [1,5]: for interval in [1, 5]:
download_backtesting_testdata(pair=pair, interval=interval) download_backtesting_testdata(pair=pair, interval=interval)
except BaseException: except BaseException:
logger.info('Impossible to download the pair: "{pair}", Interval: {interval} min'.format( logger.info('Failed to download the pair: "{pair}", Interval: {interval} min'.format(
pair=pair, pair=pair,
interval=interval, interval=interval,
)) ))
@ -103,7 +104,7 @@ def download_backtesting_testdata(pair: str, interval: int = 5) -> bool:
logger.debug("Current Start: None") logger.debug("Current Start: None")
logger.debug("Current End: None") logger.debug("Current End: None")
new_data = get_ticker_history(pair = pair, tick_interval = int(interval)) new_data = get_ticker_history(pair=pair, tick_interval=int(interval))
for row in new_data: for row in new_data:
if row not in data: if row not in data:
data.append(row) data.append(row)

View File

@ -140,7 +140,8 @@ def start(args):
data[pair] = exchange.get_ticker_history(pair, args.ticker_interval) data[pair] = exchange.get_ticker_history(pair, args.ticker_interval)
else: else:
logger.info('Using local backtesting data (using whitelist in given config) ...') logger.info('Using local backtesting data (using whitelist in given config) ...')
data = load_data(pairs=pairs, ticker_interval=args.ticker_interval, refresh_pairs=args.refresh_pairs) data = load_data(pairs=pairs, ticker_interval=args.ticker_interval,
refresh_pairs=args.refresh_pairs)
logger.info('Using stake_currency: %s ...', config['stake_currency']) logger.info('Using stake_currency: %s ...', config['stake_currency'])
logger.info('Using stake_amount: %s ...', config['stake_amount']) logger.info('Using stake_amount: %s ...', config['stake_amount'])

View File

@ -150,7 +150,7 @@ def optimizer(params):
'total_tries': TOTAL_TRIES, 'total_tries': TOTAL_TRIES,
'result': result, 'result': result,
'results': results 'results': results
} }
# logger.info('{:5d}/{}: {}'.format(_CURRENT_TRIES, TOTAL_TRIES, result)) # logger.info('{:5d}/{}: {}'.format(_CURRENT_TRIES, TOTAL_TRIES, result))
log_results(result_data) log_results(result_data)
@ -169,7 +169,7 @@ def format_results(results: DataFrame):
results.profit.mean() * 100.0, results.profit.mean() * 100.0,
results.profit.sum(), results.profit.sum(),
results.duration.mean() * 5, results.duration.mean() * 5,
) )
def buy_strategy_generator(params): def buy_strategy_generator(params):
@ -232,7 +232,8 @@ def start(args):
logger.info('Using config: %s ...', args.config) logger.info('Using config: %s ...', args.config)
config = load_config(args.config) config = load_config(args.config)
pairs = config['exchange']['pair_whitelist'] pairs = config['exchange']['pair_whitelist']
PROCESSED = optimize.preprocess(optimize.load_data(pairs=pairs, ticker_interval=args.ticker_interval)) PROCESSED = optimize.preprocess(optimize.load_data(
pairs=pairs, ticker_interval=args.ticker_interval))
if args.mongodb: if args.mongodb:
logger.info('Using mongodb ...') logger.info('Using mongodb ...')

View File

@ -232,11 +232,11 @@ def _daily(bot: Bot, update: Update) -> None:
for day in range(0, timescale): for day in range(0, timescale):
# need to query between day+1 and day-1 # need to query between day+1 and day-1
nextdate = date.fromordinal(today-day+1) nextdate = date.fromordinal(today - day + 1)
prevdate = date.fromordinal(today-day-1) prevdate = date.fromordinal(today - day - 1)
trades = Trade.query.filter(between(Trade.close_date, prevdate, nextdate)).all() trades = Trade.query.filter(between(Trade.close_date, prevdate, nextdate)).all()
curdayprofit = sum(trade.close_profit * trade.stake_amount for trade in trades) curdayprofit = sum(trade.close_profit * trade.stake_amount for trade in trades)
profit_days[date.fromordinal(today-day)] = format(curdayprofit, '.8f') profit_days[date.fromordinal(today - day)] = format(curdayprofit, '.8f')
stats = [[key, str(value) + ' BTC'] for key, value in profit_days.items()] stats = [[key, str(value) + ' BTC'] for key, value in profit_days.items()]
stats = tabulate(stats, headers=['Day', 'Profit'], tablefmt='simple') stats = tabulate(stats, headers=['Day', 'Profit'], tablefmt='simple')

View File

@ -128,7 +128,7 @@ def limit_sell_order():
@pytest.fixture @pytest.fixture
def ticker_history(): def ticker_history():
return [ return [
{ {
"O": 8.794e-05, "O": 8.794e-05,
"H": 8.948e-05, "H": 8.948e-05,
"L": 8.794e-05, "L": 8.794e-05,
@ -137,7 +137,7 @@ def ticker_history():
"T": "2017-11-26T08:50:00", "T": "2017-11-26T08:50:00",
"BV": 0.0877869 "BV": 0.0877869
}, },
{ {
"O": 8.88e-05, "O": 8.88e-05,
"H": 8.942e-05, "H": 8.942e-05,
"L": 8.88e-05, "L": 8.88e-05,
@ -146,7 +146,7 @@ def ticker_history():
"T": "2017-11-26T08:55:00", "T": "2017-11-26T08:55:00",
"BV": 0.05874751 "BV": 0.05874751
}, },
{ {
"O": 8.891e-05, "O": 8.891e-05,
"H": 8.893e-05, "H": 8.893e-05,
"L": 8.875e-05, "L": 8.875e-05,

View File

@ -1,15 +1,11 @@
# pragma pylint: disable=missing-docstring,W0212 # pragma pylint: disable=missing-docstring,W0212
from unittest.mock import MagicMock
from freqtrade import exchange, optimize from freqtrade import exchange, optimize
from freqtrade.exchange import Bittrex from freqtrade.exchange import Bittrex
from freqtrade.optimize.backtesting import backtest from freqtrade.optimize.backtesting import backtest
from freqtrade.optimize.__init__ import testdata_path, download_pairs, download_backtesting_testdata from freqtrade.optimize.__init__ import testdata_path, download_pairs, download_backtesting_testdata
import os import os
import pytest
def test_backtest(default_conf, mocker): def test_backtest(default_conf, mocker):
mocker.patch.dict('freqtrade.main._CONF', default_conf) mocker.patch.dict('freqtrade.main._CONF', default_conf)
@ -30,6 +26,7 @@ def test_1min_ticker_interval(default_conf, mocker):
results = backtest(default_conf, optimize.preprocess(data), 1, True) results = backtest(default_conf, optimize.preprocess(data), 1, True)
assert len(results) > 0 assert len(results) > 0
def test_backtest_with_new_pair(default_conf, ticker_history, mocker): def test_backtest_with_new_pair(default_conf, ticker_history, mocker):
mocker.patch('freqtrade.optimize.get_ticker_history', return_value=ticker_history) mocker.patch('freqtrade.optimize.get_ticker_history', return_value=ticker_history)
mocker.patch.dict('freqtrade.main._CONF', default_conf) mocker.patch.dict('freqtrade.main._CONF', default_conf)
@ -59,7 +56,7 @@ def test_download_pairs(default_conf, ticker_history, mocker):
file2_1 = 'freqtrade/tests/testdata/BTC_CFI-1.json' file2_1 = 'freqtrade/tests/testdata/BTC_CFI-1.json'
file2_5 = 'freqtrade/tests/testdata/BTC_CFI-5.json' file2_5 = 'freqtrade/tests/testdata/BTC_CFI-5.json'
assert download_pairs(pairs = ['BTC-MEME', 'BTC-CFI']) is True assert download_pairs(pairs=['BTC-MEME', 'BTC-CFI']) is True
assert os.path.isfile(file1_1) is True assert os.path.isfile(file1_1) is True
assert os.path.isfile(file1_5) is True assert os.path.isfile(file1_5) is True
@ -87,7 +84,7 @@ def test_download_backtesting_testdata(default_conf, ticker_history, mocker):
# Download a 1 min ticker file # Download a 1 min ticker file
file1 = 'freqtrade/tests/testdata/BTC_XEL-1.json' file1 = 'freqtrade/tests/testdata/BTC_XEL-1.json'
download_backtesting_testdata(pair = "BTC-XEL", interval = 1) download_backtesting_testdata(pair="BTC-XEL", interval=1)
assert os.path.isfile(file1) is True assert os.path.isfile(file1) is True
if os.path.isfile(file1): if os.path.isfile(file1):
@ -95,7 +92,7 @@ def test_download_backtesting_testdata(default_conf, ticker_history, mocker):
# Download a 5 min ticker file # Download a 5 min ticker file
file2 = 'freqtrade/tests/testdata/BTC_STORJ-5.json' file2 = 'freqtrade/tests/testdata/BTC_STORJ-5.json'
download_backtesting_testdata(pair = "BTC-STORJ", interval = 5) download_backtesting_testdata(pair="BTC-STORJ", interval=5)
assert os.path.isfile(file2) is True assert os.path.isfile(file2) is True
if os.path.isfile(file2): if os.path.isfile(file2):

View File

@ -3,7 +3,6 @@
import matplotlib # Install PYQT5 manually if you want to test this helper function import matplotlib # Install PYQT5 manually if you want to test this helper function
matplotlib.use("Qt5Agg") matplotlib.use("Qt5Agg")
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
from freqtrade import exchange, analyze from freqtrade import exchange, analyze
@ -52,4 +51,3 @@ def plot_analyzed_dataframe(pair: str) -> None:
if __name__ == '__main__': if __name__ == '__main__':
plot_analyzed_dataframe('BTC_ETH') plot_analyzed_dataframe('BTC_ETH')