2019-07-16 04:45:13 +00:00
|
|
|
"""
|
2019-07-23 15:51:24 +00:00
|
|
|
SharpeHyperOptLoss
|
2019-07-16 04:45:13 +00:00
|
|
|
|
2019-07-23 15:51:24 +00:00
|
|
|
This module defines the alternative HyperOptLoss class which can be used for
|
|
|
|
Hyperoptimization.
|
|
|
|
"""
|
2019-07-16 04:45:13 +00:00
|
|
|
from datetime import datetime
|
|
|
|
|
|
|
|
import numpy as np
|
2020-09-28 17:39:41 +00:00
|
|
|
from pandas import DataFrame
|
2019-07-16 04:45:13 +00:00
|
|
|
|
2019-07-17 05:14:27 +00:00
|
|
|
from freqtrade.optimize.hyperopt import IHyperOptLoss
|
2019-07-16 04:45:13 +00:00
|
|
|
|
|
|
|
|
|
|
|
class SharpeHyperOptLoss(IHyperOptLoss):
|
|
|
|
"""
|
2019-07-23 15:51:24 +00:00
|
|
|
Defines the loss function for hyperopt.
|
|
|
|
|
|
|
|
This implementation uses the Sharpe Ratio calculation.
|
2019-07-16 04:45:13 +00:00
|
|
|
"""
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def hyperopt_loss_function(results: DataFrame, trade_count: int,
|
|
|
|
min_date: datetime, max_date: datetime,
|
|
|
|
*args, **kwargs) -> float:
|
|
|
|
"""
|
2019-07-23 15:51:24 +00:00
|
|
|
Objective function, returns smaller number for more optimal results.
|
|
|
|
|
|
|
|
Uses Sharpe Ratio calculation.
|
2019-07-16 04:45:13 +00:00
|
|
|
"""
|
2021-01-23 12:02:48 +00:00
|
|
|
total_profit = results["profit_ratio"]
|
2019-07-16 04:45:13 +00:00
|
|
|
days_period = (max_date - min_date).days
|
|
|
|
|
|
|
|
# adding slippage of 0.1% per trade
|
|
|
|
total_profit = total_profit - 0.0005
|
2020-02-02 07:47:33 +00:00
|
|
|
expected_returns_mean = total_profit.sum() / days_period
|
|
|
|
up_stdev = np.std(total_profit)
|
2019-07-16 04:45:13 +00:00
|
|
|
|
2020-03-10 10:44:16 +00:00
|
|
|
if up_stdev != 0:
|
2020-02-02 07:47:33 +00:00
|
|
|
sharp_ratio = expected_returns_mean / up_stdev * np.sqrt(365)
|
2019-07-16 04:45:13 +00:00
|
|
|
else:
|
|
|
|
# Define high (negative) sharpe ratio to be clear that this is NOT optimal.
|
2019-08-08 20:10:51 +00:00
|
|
|
sharp_ratio = -20.
|
2019-07-16 04:45:13 +00:00
|
|
|
|
2020-02-02 07:47:33 +00:00
|
|
|
# print(expected_returns_mean, up_stdev, sharp_ratio)
|
2019-07-16 04:45:13 +00:00
|
|
|
return -sharp_ratio
|