2021-10-06 07:54:27 +00:00
|
|
|
"""
|
|
|
|
MaxDrawDownHyperOptLoss
|
|
|
|
|
|
|
|
This module defines the alternative HyperOptLoss class which can be used for
|
|
|
|
Hyperoptimization.
|
|
|
|
"""
|
|
|
|
from datetime import datetime
|
|
|
|
|
|
|
|
from pandas import DataFrame
|
|
|
|
|
2022-04-30 12:47:27 +00:00
|
|
|
from freqtrade.data.metrics import calculate_max_drawdown
|
2021-10-06 08:16:05 +00:00
|
|
|
from freqtrade.optimize.hyperopt import IHyperOptLoss
|
|
|
|
|
2021-10-06 07:54:27 +00:00
|
|
|
|
|
|
|
class MaxDrawDownHyperOptLoss(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
|
|
|
|
def hyperopt_loss_function(results: DataFrame, trade_count: int,
|
|
|
|
min_date: datetime, max_date: datetime,
|
|
|
|
*args, **kwargs) -> float:
|
|
|
|
|
|
|
|
"""
|
|
|
|
Objective function.
|
|
|
|
|
|
|
|
Uses profit ratio weighted max_drawdown when drawdown is available.
|
|
|
|
Otherwise directly optimizes profit ratio.
|
|
|
|
"""
|
2021-10-07 02:37:07 +00:00
|
|
|
total_profit = results['profit_abs'].sum()
|
2021-10-06 07:54:27 +00:00
|
|
|
try:
|
2021-10-07 02:37:07 +00:00
|
|
|
max_drawdown = calculate_max_drawdown(results, value_col='profit_abs')
|
2021-10-06 07:54:27 +00:00
|
|
|
except ValueError:
|
|
|
|
# No losing trade, therefore no drawdown.
|
|
|
|
return -total_profit
|
2021-10-09 01:06:23 +00:00
|
|
|
return -total_profit / max_drawdown[0]
|