stable/freqtrade/optimize/hyperopt_loss/hyperopt_loss_max_drawdown_...

47 lines
1.4 KiB
Python
Raw Normal View History

2022-04-10 15:53:47 +00:00
"""
MaxDrawDownRelativeHyperOptLoss
This module defines the alternative HyperOptLoss class which can be used for
Hyperoptimization.
"""
from pandas import DataFrame
2022-09-18 11:31:52 +00:00
from freqtrade.constants import Config
from freqtrade.data.metrics import calculate_underwater
2022-04-10 15:53:47 +00:00
from freqtrade.optimize.hyperopt import IHyperOptLoss
class MaxDrawDownRelativeHyperOptLoss(IHyperOptLoss):
"""
Defines the loss function for hyperopt.
This implementation optimizes for max draw down and profit
Less max drawdown more profit -> Lower return value
"""
@staticmethod
2022-09-18 11:31:52 +00:00
def hyperopt_loss_function(results: DataFrame, config: Config,
2022-04-10 15:53:47 +00:00
*args, **kwargs) -> float:
"""
Objective function.
Uses profit ratio weighted max_drawdown when drawdown is available.
Otherwise directly optimizes profit ratio.
"""
total_profit = results['profit_abs'].sum()
try:
2022-04-23 16:15:14 +00:00
drawdown_df = calculate_underwater(
results,
value_col='profit_abs',
starting_balance=config['dry_run_wallet']
2022-04-23 16:15:14 +00:00
)
2022-04-10 15:53:47 +00:00
max_drawdown = abs(min(drawdown_df['drawdown']))
relative_drawdown = max(drawdown_df['drawdown_relative'])
if max_drawdown == 0:
return -total_profit
return -total_profit / max_drawdown / relative_drawdown
except (Exception, ValueError):
return -total_profit