2021-09-22 01:04:23 +00:00
|
|
|
"""
|
|
|
|
CalmarHyperOptLoss
|
|
|
|
|
|
|
|
This module defines the alternative HyperOptLoss class which can be used for
|
|
|
|
Hyperoptimization.
|
|
|
|
"""
|
|
|
|
from datetime import datetime
|
2021-09-24 02:31:33 +00:00
|
|
|
from math import sqrt as msqrt
|
|
|
|
from typing import Any, Dict
|
|
|
|
|
|
|
|
from pandas import DataFrame
|
2021-09-22 01:04:23 +00:00
|
|
|
|
|
|
|
from freqtrade.data.btanalysis import calculate_max_drawdown
|
2021-09-22 14:18:17 +00:00
|
|
|
from freqtrade.optimize.hyperopt import IHyperOptLoss
|
2021-09-22 01:04:23 +00:00
|
|
|
|
|
|
|
|
|
|
|
class CalmarHyperOptLoss(IHyperOptLoss):
|
|
|
|
"""
|
|
|
|
Defines the loss function for hyperopt.
|
|
|
|
|
|
|
|
This implementation uses the Calmar Ratio calculation.
|
|
|
|
"""
|
|
|
|
|
|
|
|
@staticmethod
|
2021-09-24 02:31:33 +00:00
|
|
|
def hyperopt_loss_function(
|
|
|
|
results: DataFrame,
|
|
|
|
trade_count: int,
|
|
|
|
min_date: datetime,
|
|
|
|
max_date: datetime,
|
2021-09-27 22:32:49 +00:00
|
|
|
config: Dict,
|
|
|
|
processed: Dict[str, DataFrame],
|
2021-09-24 02:31:33 +00:00
|
|
|
backtest_stats: Dict[str, Any],
|
|
|
|
*args,
|
|
|
|
**kwargs
|
|
|
|
) -> float:
|
2021-09-22 01:04:23 +00:00
|
|
|
"""
|
|
|
|
Objective function, returns smaller number for more optimal results.
|
|
|
|
|
|
|
|
Uses Calmar Ratio calculation.
|
|
|
|
"""
|
2021-09-24 02:31:33 +00:00
|
|
|
total_profit = backtest_stats["profit_total"]
|
2021-09-22 01:04:23 +00:00
|
|
|
days_period = (max_date - min_date).days
|
|
|
|
|
|
|
|
# adding slippage of 0.1% per trade
|
|
|
|
total_profit = total_profit - 0.0005
|
2021-09-24 02:31:33 +00:00
|
|
|
expected_returns_mean = total_profit.sum() / days_period * 100
|
2021-09-22 01:04:23 +00:00
|
|
|
|
|
|
|
# calculate max drawdown
|
|
|
|
try:
|
2021-09-24 02:31:33 +00:00
|
|
|
_, _, _, high_val, low_val = calculate_max_drawdown(
|
|
|
|
results, value_col="profit_abs"
|
|
|
|
)
|
2021-09-22 01:25:17 +00:00
|
|
|
max_drawdown = (high_val - low_val) / high_val
|
2021-09-22 01:04:23 +00:00
|
|
|
except ValueError:
|
|
|
|
max_drawdown = 0
|
|
|
|
|
2021-10-25 05:45:10 +00:00
|
|
|
if max_drawdown != 0:
|
2021-09-24 02:31:33 +00:00
|
|
|
calmar_ratio = expected_returns_mean / max_drawdown * msqrt(365)
|
2021-09-22 01:04:23 +00:00
|
|
|
else:
|
2021-09-24 02:31:33 +00:00
|
|
|
# Define high (negative) calmar ratio to be clear that this is NOT optimal.
|
|
|
|
calmar_ratio = -20.0
|
2021-09-22 01:04:23 +00:00
|
|
|
|
2021-09-24 02:31:33 +00:00
|
|
|
# print(expected_returns_mean, max_drawdown, calmar_ratio)
|
2021-09-22 01:04:23 +00:00
|
|
|
return -calmar_ratio
|