1
0
mirror of https://github.com/Rikj000/MoniGoMani.git synced 2022-03-06 00:08:05 +03:00

♻ Refactor (Clarified parameter names, Optimized Imports, Fixed line lengths, Fixed typos, Parse types)

This commit is contained in:
Rik Helsen
2022-01-16 16:36:06 +01:00
parent fc5844c981
commit 6863ae14cf
5 changed files with 39 additions and 40 deletions

View File

@@ -22,7 +22,6 @@ import logging
import os
import sys
from datetime import datetime
from string import Template
import fire
import numpy as np # noqa
@@ -88,7 +87,7 @@ class MGMHurry:
def up(self): # pylint: disable=invalid-name
"""
The all in one command. Hurry up, turn it up!
The all-in-one command. Hurry up, turn it up!
"""
self.logger.info(Color.title('👉 The all in one command. Hurry up, turn it up!'))
@@ -226,7 +225,7 @@ class MGMHurry:
:param target_dir: (string, optional) Specify a target_dir to install Freqtrade. Defaults to os.getcwd().
:param branch: (string, optional) Checkout a specific branch. Defaults to 'develop'.
:param commit: (str) Checkout a specific commit. Defaults to latest supported by MoniGoMani,
:param commit: (str) Checkout a specific commit. Defaults to the latest supported by MoniGoMani,
but 'latest' can also be used.
:param install_ui: (bool) Install FreqUI. Defaults to True.
"""
@@ -324,13 +323,13 @@ class MGMHurry:
glob.glob(f'{self.basedir}/user_data/strategies/*.py'))
strategies_choices = []
for strat in strategies:
if strat != 'MasterMoniGoManiHyperStrategy':
strategies_choices.append({'name': strat, 'value': strat})
for strategy in strategies:
if strategy != 'MasterMoniGoManiHyperStrategy':
strategies_choices.append({'name': strategy, 'value': strategy})
if len(strategies_choices) == 0:
strat_dir = f'{self.basedir}/user_data/strategies/'
self.logger.error(Color.red(f'🤷 I could not find any strategy in {strat_dir}. '
strategy_directory = f'{self.basedir}/user_data/strategies/'
self.logger.error(Color.red(f'🤷 I could not find any strategy in {strategy_directory}. '
f'Did you install Freqtrade & MoniGoMani?'))
sys.exit(1)
@@ -493,11 +492,11 @@ class MGMHurry:
"""
Deletes stored HyperOpt config(s) from previous run(s)
:param strategy: (Optional, string) Name of the Strategy to cleanup, defaults to 'MoniGoManiHyperStrategy'
:param strategy: (Optional, string) Name of the Strategy to clean up, defaults to 'MoniGoManiHyperStrategy'
"""
self.logger.info(Color.title('👉 Cleanup'))
# Remove hyperopt files to cleanup
# Remove hyperopt files to clean up
cleaned_up = self.monigomani_config.cleanup_hyperopt_files(strategy)
message = f'🍺 Cleanup successful, {strategy} ready for a fresh HyperOpt Run...' if cleaned_up is True \
@@ -659,7 +658,7 @@ class MGMHurry:
:param strategy: (str, Optional): Hyper Opt strategy to use. Defaults to value in '.hurry'
:param loss: (str, Optional): Specify the HyperOptLoss which you want to use. Defaults to value in '.hurry'
:param spaces: (str, Optional): Spaces (space delimited) to optimize
for [default, all, buy, sell, roi, stoploss, etc]. Defaults to value in '.hurry'
for [default, all, buy, sell, roi, stoploss, etc.]. Defaults to value in '.hurry'
:param enable_protections: (bool, Optional): Add '--enable-protections' flag to HO-command. Defaults to True.
:param random_state: (int, Optional): Add '--random-state random_state' flag to HO-command. Defaults to None.
:param apply_best_results: (bool, Optional): Apply 'best' HO results direct after HO? Defaults to True.
@@ -717,7 +716,7 @@ class MGMHurry:
hyperopt_file_name = f'HyperOptResults-{output_file_name}'
output_file_path = f'{self.basedir}/user_data/hyperopt_results/{hyperopt_file_name}.log'
self.monigomani_cli.run_command(command=command, output_file_name=output_file_path,hyperopt=True)
self.monigomani_cli.run_command(command=command, output_file_name=output_file_path, hyperopt=True)
last_ho_results_path = f'{self.basedir}/user_data/hyperopt_results/.last_ho_results_table.log'
if os.stat(last_ho_results_path).st_size == 0:
@@ -838,7 +837,7 @@ class MGMHurry:
:param timerange: (string, Optional): The target timerange for backtesting. Defaults to timerange in '.hurry'.
:param strategy: (str, Optional): Strategy to use during BackTesting. Defaults to value in '.hurry'
:param enable_protections: (bool, Optional): Whether or not to enable protections. Defaults to True.
:param enable_protections: (bool, Optional): Whether to enable protections or not. Defaults to True.
:param plot_profits: (bool, Optional): Automatically plot visual profit graphs in '.html'. Defaults to True.
:param plot_stats: (bool, Optional): Automatically plot visual stats report in '.html'. Defaults to True.
:param output_file_name: (str, Optional) Custom filename for the BackTestResults '.log' file that will be stored
@@ -992,8 +991,10 @@ class MGMHurry:
starting_balance = backtest_results['strategy'][strategy]['starting_balance']
backtest_trades = pd.DataFrame(backtest_results['strategy'][strategy]['trades'])
backtest_trades['open_date'] = pd.to_datetime(backtest_trades['open_date'], utc=True, infer_datetime_format=True)
daily_returns = backtest_trades[['open_date', 'profit_abs']].groupby(pd.Grouper(key="open_date", freq='D')).sum('profit_abs')
backtest_trades['open_date'] = pd.to_datetime(
backtest_trades['open_date'], utc=True, infer_datetime_format=True)
daily_returns = backtest_trades[['open_date', 'profit_abs']].groupby(
pd.Grouper(key="open_date", freq='D')).sum('profit_abs')
daily_returns['balance'] = np.cumsum(daily_returns['profit_abs']) + starting_balance
dates = pd.date_range(daily_returns.index[0], daily_returns.index[-1], freq='D').tz_localize(None)
@@ -1001,7 +1002,8 @@ class MGMHurry:
daily_returns = pd.Series(daily_returns.balance).pct_change(1).values
returns_time_series = pd.Series(daily_returns, index=pd.to_datetime(list(dates)))
qs.reports.html(returns=returns_time_series, title=f'{strategy} {backtest_results_file}', output=output_file_path)
qs.reports.html(returns=returns_time_series, title=f'{strategy} {backtest_results_file}',
output=output_file_path)
MoniGoManiLogger(self.basedir).post_message(
username=self.monigomani_config.config['username'],
@@ -1052,7 +1054,7 @@ class MGMHurry:
:param output_file_name: (str, Optional) Custom filename for the CsvResults '.csv' file
that will be stored in the format: 'CsvResults-<output_file_name>.csv'.
Defaults to 'StrategyName + Current DateTime'.
:param fthypt: (str, Optional) '.fthypt' file to export results from.. If 'true' is passed,
:param fthypt: (str, Optional) '.fthypt' file to export results from. If 'true' is passed,
an interactive prompt will launch to pick an '.fthypt' file of choice. Defaults to latest
"""
@@ -1106,7 +1108,7 @@ class MGMHurry:
def __setup_telegram(self) -> bool:
"""
Questionnaire to setup Telegram Bot
Questionnaire to set up Telegram Bot
:return bool: False if no answers are given, True if all went ok.
"""

View File

@@ -51,7 +51,7 @@ class FreqtradeCli:
cli_logger The logger function of the MoniGoManiCli module.
monigomani_cli The MoniGoManiCli object.
monigomani_config The MoniGoManiConfig object.
_install_type The current install type of Freqtrade. Either 'source' or default 'docker'
_install_type The current installation type of Freqtrade. Either 'source' or default 'docker'
"""
basedir: str
freqtrade_binary: str
@@ -100,7 +100,7 @@ class FreqtradeCli:
"""
Return property install_type.
:return str: The install type. either source, docker or None.
:return str: The installation type. either source, docker or None.
"""
return self._install_type
@@ -119,7 +119,7 @@ class FreqtradeCli:
def installation_exists(self, silent: bool = False) -> bool:
"""
Return true if all is setup correctly.
Return true if all is set up correctly.
:param silent: (bool, Optional) Silently run method (without command line output)
:return bool: True if install_type is docker or Freqtrade is found. False otherwise.
@@ -161,7 +161,7 @@ class FreqtradeCli:
:param target_dir: (str) Specify a target_dir to install Freqtrade. Defaults to os.getcwd().
:param branch: (str) Checkout a specific branch. Defaults to 'develop'.
:param commit: (str) Checkout a specific commit. Defaults to latest supported by MoniGoMani,
:param commit: (str) Checkout a specific commit. Defaults to the latest supported by MoniGoMani,
but 'latest' can also be used.
:param install_ui: (bool) Install FreqUI. Defaults to True.
:return bool: True if setup completed without errors, else False.
@@ -207,7 +207,7 @@ class FreqtradeCli:
def copy_installation_files(self, temp_dirname: str, target_dir: str):
"""
Copy the installation files to the target directory. Also symlink the 'setup.exp' file.
Copy the installation files to the target directory. Also, symlink the 'setup.exp' file.
:param temp_dirname: (str) The source directory where installation files exist.
:param target_dir: (str) The target directory where the installation files should be copied to.
@@ -228,7 +228,7 @@ class FreqtradeCli:
def run_setup_installer(self, target_dir: str, install_ui: bool = True) -> bool:
"""
Run Freqtrade setup.sh --install through setup.exp + Install Freq-UI
Run Freqtrade setup.sh --install through 'setup.exp' + Install Freq-UI
:param target_dir: (str) The target directory where Freqtrade is installed.
:param install_ui: (bool) Install FreqUI. Defaults to True.

View File

@@ -62,7 +62,7 @@ class MoniGoManiCli(object):
Check if the MGM Hyper Strategy installation exists.
:param silent: (bool, Optional) Silently run method (without command line output)
:return success (bool): Whether or not the config and strategy files are found.
:return success (bool): Whether the config and strategy files are found or not.
"""
with yaspin(text='', color='cyan') as sp:
@@ -221,8 +221,7 @@ class MoniGoManiCli(object):
def fix_git_object_permissions(self, temp_dir_filepath: str) -> None:
"""
Fixes permissions of '.idx' and '.pack' files existing in
a temporary directory directory during the installation.
Fixes permissions of '.idx' and '.pack' files existing in a temporary directory during the installation.
:param temp_dir_filepath: (str) The path to the temporary directory for MoniGoMani or Freqtrade
"""
@@ -376,7 +375,7 @@ class MoniGoManiCli(object):
# Load the timerange from '.hurry' if none was provided
if timerange is not None:
split_timerange = timerange.split('-')
split_timerange = str(timerange).split('-')
else:
split_timerange = self.monigomani_config.config['timerange'].split('-')

View File

@@ -3,7 +3,7 @@
# --- ↑↓ Do not remove these libs ↑↓ -----------------------------------------------------------------------------------
"""MoniGoManiLogger is the module responsible for all logging related tasks.."""
"""MoniGoManiLogger is the module responsible for all logging related tasks..."""
# ___ ___ _ _____ ___ ___ _ _
# | \/ | (_)| __ \ | \/ | (_)| |

View File

@@ -25,8 +25,7 @@ from freqtrade.exchange import timeframe_to_prev_date
from freqtrade.misc import deep_merge_dicts, round_dict
from freqtrade.optimize.space import Categorical, Dimension, Integer, SKDecimal
from freqtrade.persistence import Trade
from freqtrade.strategy import (BooleanParameter, DecimalParameter, IntParameter, IStrategy,
merge_informative_pair, timeframe_to_minutes)
from freqtrade.strategy import DecimalParameter, IntParameter, IStrategy, merge_informative_pair, timeframe_to_minutes
logger = logging.getLogger(__name__)
@@ -1388,16 +1387,15 @@ class MasterMoniGoManiHyperStrategy(IStrategy, ABC):
"""
# Generates the utility attributes for the unclogger_spaces
for param_key in cls.mgm_unclogger_add_params:
parameter_name = '__' + param_key
param_config = cls.mgm_unclogger_add_params[param_key]
if isinstance(param_config, dict) is True:
param_config['threshold'] = (param_config['threshold'] if 'threshold' in param_config
else cls.search_threshold_weighted_signal_values)
for unclogger_key in cls.mgm_unclogger_params:
unclogger_config = cls.mgm_unclogger_params[unclogger_key]
if isinstance(unclogger_config, dict) is True:
unclogger_config['threshold'] = (unclogger_config['threshold'] if 'threshold' in unclogger_config
else cls.search_threshold_weighted_signal_values)
cls._init_vars(base_cls=base_cls, space='sell', parameter_name=parameter_name,
parameter_min_value=param_config['min'], parameter_max_value=param_config['max'],
parameter_threshold=param_config['threshold'],
cls._init_vars(base_cls=base_cls, space='sell', parameter_name=f'__{unclogger_key}',
parameter_min_value=unclogger_config['min'], parameter_max_value=unclogger_config['max'],
parameter_threshold=unclogger_config['threshold'],
precision=cls.precision, overrideable=False)
# Generate the utility attributes for the logic of the weighted_signal_spaces