allow selecting hyperopt searchspace

This commit is contained in:
Janne Sinivirta 2018-02-09 20:59:06 +02:00
parent 12a19e400f
commit f14d6249e0
3 changed files with 50 additions and 14 deletions

View File

@ -280,6 +280,14 @@ def hyperopt_options(parser: argparse.ArgumentParser) -> None:
type=str, type=str,
dest='timerange', dest='timerange',
) )
parser.add_argument(
'-s', '--spaces',
help='Specify which parameters to hyperopt. Comma separate list. \
Allowed values: all, buy, sell, roi, stoploss. Default: $(default)s',
default='all',
type=str,
dest='spaces',
)
def parse_timerange(text): def parse_timerange(text):

View File

@ -312,8 +312,21 @@ def indicator_space() -> Dict[str, Any]:
} }
def hyperopt_space() -> Dict[str, Any]: def has_space(spaces, space):
return {**indicator_space(), **roi_space(), **stoploss_space()} if space in spaces or 'all' in spaces:
return True
return False
def hyperopt_space(selected_spaces: str) -> Dict[str, Any]:
spaces = {}
if has_space(selected_spaces, 'buy'):
spaces = {**spaces, **indicator_space()}
if has_space(selected_spaces, 'roi'):
spaces = {**spaces, **roi_space()}
if has_space(selected_spaces, 'stoploss'):
spaces = {**spaces, **stoploss_space()}
return spaces
def buy_strategy_generator(params: Dict[str, Any]) -> Callable: def buy_strategy_generator(params: Dict[str, Any]) -> Callable:
@ -393,15 +406,21 @@ def buy_strategy_generator(params: Dict[str, Any]) -> Callable:
def optimizer(params): def optimizer(params):
global _CURRENT_TRIES global _CURRENT_TRIES
strategy = Strategy()
if 'roi_t1' in params: if 'roi_t1' in params:
strategy = Strategy()
strategy.minimal_roi = generate_roi_table(params) strategy.minimal_roi = generate_roi_table(params)
backtesting.populate_buy_trend = buy_strategy_generator(params) if 'trigger' in params:
backtesting.populate_buy_trend = buy_strategy_generator(params)
if 'stoploss' in params:
stoploss = params['stoploss']
else:
stoploss = strategy.stoploss
results = backtest({'stake_amount': OPTIMIZE_CONFIG['stake_amount'], results = backtest({'stake_amount': OPTIMIZE_CONFIG['stake_amount'],
'processed': PROCESSED, 'processed': PROCESSED,
'stoploss': params['stoploss']}) 'stoploss': stoploss})
result_explanation = format_results(results) result_explanation = format_results(results)
total_profit = results.profit_percent.sum() total_profit = results.profit_percent.sum()
@ -475,7 +494,8 @@ def start(args):
data = optimize.load_data(args.datadir, pairs=pairs, data = optimize.load_data(args.datadir, pairs=pairs,
ticker_interval=strategy.ticker_interval, ticker_interval=strategy.ticker_interval,
timerange=timerange) timerange=timerange)
optimize.populate_indicators = populate_indicators if has_space(args.spaces, 'buy') or has_space(args.spaces, 'sell'):
optimize.populate_indicators = populate_indicators
PROCESSED = optimize.tickerdata_to_dataframe(data) PROCESSED = optimize.tickerdata_to_dataframe(data)
if args.mongodb: if args.mongodb:
@ -500,7 +520,7 @@ def start(args):
try: try:
best_parameters = fmin( best_parameters = fmin(
fn=optimizer, fn=optimizer,
space=hyperopt_space(), space=hyperopt_space(args.spaces),
algo=tpe.suggest, algo=tpe.suggest,
max_evals=TOTAL_TRIES, max_evals=TOTAL_TRIES,
trials=TRIALS trials=TRIALS
@ -517,7 +537,7 @@ def start(args):
# Improve best parameter logging display # Improve best parameter logging display
if best_parameters: if best_parameters:
best_parameters = space_eval( best_parameters = space_eval(
hyperopt_space(), hyperopt_space(args.spaces),
best_parameters best_parameters
) )

View File

@ -6,7 +6,7 @@ from unittest.mock import MagicMock
import pandas as pd import pandas as pd
from freqtrade.optimize.hyperopt import calculate_loss, TARGET_TRADES, EXPECTED_MAX_PROFIT, start, \ from freqtrade.optimize.hyperopt import calculate_loss, TARGET_TRADES, EXPECTED_MAX_PROFIT, start, \
log_results, save_trials, read_trials, generate_roi_table log_results, save_trials, read_trials, generate_roi_table, has_space
import freqtrade.optimize.hyperopt as hyperopt import freqtrade.optimize.hyperopt as hyperopt
@ -71,7 +71,7 @@ def test_start_calls_fmin(mocker):
mock_fmin = mocker.patch('freqtrade.optimize.hyperopt.fmin', return_value={}) mock_fmin = mocker.patch('freqtrade.optimize.hyperopt.fmin', return_value={})
args = mocker.Mock(epochs=1, config='config.json.example', mongodb=False, args = mocker.Mock(epochs=1, config='config.json.example', mongodb=False,
timerange=None) timerange=None, spaces='all')
start(args) start(args)
mock_fmin.assert_called_once() mock_fmin.assert_called_once()
@ -85,7 +85,7 @@ def test_start_uses_mongotrials(mocker):
mocker.patch('freqtrade.optimize.hyperopt.fmin', return_value={}) mocker.patch('freqtrade.optimize.hyperopt.fmin', return_value={})
args = mocker.Mock(epochs=1, config='config.json.example', mongodb=True, args = mocker.Mock(epochs=1, config='config.json.example', mongodb=True,
timerange=None) timerange=None, spaces='all')
start(args) start(args)
mock_mongotrials.assert_called_once() mock_mongotrials.assert_called_once()
@ -148,7 +148,7 @@ def test_fmin_best_results(mocker, caplog):
mocker.patch('freqtrade.optimize.hyperopt.fmin', return_value=fmin_result) mocker.patch('freqtrade.optimize.hyperopt.fmin', return_value=fmin_result)
args = mocker.Mock(epochs=1, config='config.json.example', args = mocker.Mock(epochs=1, config='config.json.example',
timerange=None) timerange=None, spaces='all')
start(args) start(args)
exists = [ exists = [
@ -172,7 +172,7 @@ def test_fmin_throw_value_error(mocker, caplog):
mocker.patch('freqtrade.optimize.hyperopt.fmin', side_effect=ValueError()) mocker.patch('freqtrade.optimize.hyperopt.fmin', side_effect=ValueError())
args = mocker.Mock(epochs=1, config='config.json.example', args = mocker.Mock(epochs=1, config='config.json.example',
timerange=None) timerange=None, spaces='all')
start(args) start(args)
exists = [ exists = [
@ -207,7 +207,8 @@ def test_resuming_previous_hyperopt_results_succeeds(mocker):
args = mocker.Mock(epochs=1, args = mocker.Mock(epochs=1,
config='config.json.example', config='config.json.example',
mongodb=False, mongodb=False,
timerange=None) timerange=None,
spaces='all')
start(args) start(args)
@ -279,3 +280,10 @@ def test_signal_handler(mocker):
mocker.patch('freqtrade.optimize.hyperopt.log_trials_result', m) mocker.patch('freqtrade.optimize.hyperopt.log_trials_result', m)
hyperopt.signal_handler(9, None) hyperopt.signal_handler(9, None)
assert m.call_count == 3 assert m.call_count == 3
def test_has_space():
assert has_space('buy,roi', 'roi')
assert has_space('buy,roi', 'buy')
assert not has_space('buy,roi', 'stoploss')
assert has_space('all', 'buy')