From cfd8b068e7d8d82da0244d09c0fea86175685faf Mon Sep 17 00:00:00 2001 From: Stefano Ariestasia Date: Sat, 22 Jul 2023 11:25:53 +0900 Subject: [PATCH] add test for expectancy --- freqtrade/data/metrics.py | 4 ++-- tests/data/test_btanalysis.py | 10 ++++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/freqtrade/data/metrics.py b/freqtrade/data/metrics.py index cea88b88f..ea28b17ce 100644 --- a/freqtrade/data/metrics.py +++ b/freqtrade/data/metrics.py @@ -209,8 +209,8 @@ def calculate_expectancy(trades: pd.DataFrame) -> float: average_win = (profit_sum / nb_win_trades) if nb_win_trades > 0 else 0 average_loss = (loss_sum / nb_loss_trades) if nb_loss_trades > 0 else 0 - winrate = nb_win_trades / len(trades) - loserate = nb_loss_trades / len(trades) + winrate = (nb_win_trades / len(trades)) if len(trades) > 0 else 0 + loserate = (nb_loss_trades / len(trades)) if len(trades) > 0 else 0 expectancy = (winrate * average_win) - (loserate * average_loss) return expectancy diff --git a/tests/data/test_btanalysis.py b/tests/data/test_btanalysis.py index 83b0182d5..cbf3bcf10 100644 --- a/tests/data/test_btanalysis.py +++ b/tests/data/test_btanalysis.py @@ -338,6 +338,16 @@ def test_calculate_csum(testdatadir): with pytest.raises(ValueError, match='Trade dataframe empty.'): csum_min, csum_max = calculate_csum(DataFrame()) +def test_calculate_expectancy(testdatadir): + filename = testdatadir / "backtest_results/backtest-result.json" + bt_data = load_backtest_data(filename) + + expectancy = calculate_expectancy(DataFrame()) + assert expectancy == 0.0 + + expectancy = calculate_expectancy(bt_data) + assert isinstance(expectancy, float) + assert pytest.approx(expectancy) == 0.07151374226574791 def test_calculate_expectancy_ratio(testdatadir): filename = testdatadir / "backtest_results/backtest-result.json"