• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

freqtrade / freqtrade / 6181253459

08 Sep 2023 06:04AM UTC coverage: 94.614% (+0.06%) from 94.556%
6181253459

push

github-actions

web-flow
Merge pull request #9159 from stash86/fix-adjust

remove old codes when we only can do partial entries

2 of 2 new or added lines in 1 file covered. (100.0%)

19114 of 20202 relevant lines covered (94.61%)

0.95 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

94.64
/freqtrade/optimize/hyperopt_tools.py
1
import logging
1✔
2
from copy import deepcopy
1✔
3
from datetime import datetime, timezone
1✔
4
from pathlib import Path
1✔
5
from typing import Any, Dict, Iterator, List, Optional, Tuple
1✔
6

7
import numpy as np
1✔
8
import pandas as pd
1✔
9
import rapidjson
1✔
10
import tabulate
1✔
11
from colorama import Fore, Style
1✔
12
from pandas import isna, json_normalize
1✔
13

14
from freqtrade.constants import FTHYPT_FILEVERSION, Config
1✔
15
from freqtrade.enums import HyperoptState
1✔
16
from freqtrade.exceptions import OperationalException
1✔
17
from freqtrade.misc import deep_merge_dicts, round_coin_value, round_dict, safe_value_fallback2
1✔
18
from freqtrade.optimize.hyperopt_epoch_filters import hyperopt_filter_epochs
1✔
19
from freqtrade.optimize.optimize_reports import generate_wins_draws_losses
1✔
20

21

22
logger = logging.getLogger(__name__)
1✔
23

24
NON_OPT_PARAM_APPENDIX = "  # value loaded from strategy"
1✔
25

26
HYPER_PARAMS_FILE_FORMAT = rapidjson.NM_NATIVE | rapidjson.NM_NAN
1✔
27

28

29
def hyperopt_serializer(x):
1✔
30
    if isinstance(x, np.integer):
1✔
31
        return int(x)
1✔
32
    if isinstance(x, np.bool_):
1✔
33
        return bool(x)
1✔
34

35
    return str(x)
1✔
36

37

38
class HyperoptStateContainer:
1✔
39
    """ Singleton class to track state of hyperopt"""
40
    state: HyperoptState = HyperoptState.OPTIMIZE
1✔
41

42
    @classmethod
1✔
43
    def set_state(cls, value: HyperoptState):
1✔
44
        cls.state = value
1✔
45

46

47
class HyperoptTools:
1✔
48

49
    @staticmethod
1✔
50
    def get_strategy_filename(config: Config, strategy_name: str) -> Optional[Path]:
1✔
51
        """
52
        Get Strategy-location (filename) from strategy_name
53
        """
54
        from freqtrade.resolvers.strategy_resolver import StrategyResolver
1✔
55
        strategy_objs = StrategyResolver.search_all_objects(
1✔
56
            config, False, config.get('recursive_strategy_search', False))
57
        strategies = [s for s in strategy_objs if s['name'] == strategy_name]
1✔
58
        if strategies:
1✔
59
            strategy = strategies[0]
1✔
60

61
            return Path(strategy['location'])
1✔
62
        return None
1✔
63

64
    @staticmethod
1✔
65
    def export_params(params, strategy_name: str, filename: Path):
1✔
66
        """
67
        Generate files
68
        """
69
        final_params = deepcopy(params['params_not_optimized'])
1✔
70
        final_params = deep_merge_dicts(params['params_details'], final_params)
1✔
71
        final_params = {
1✔
72
            'strategy_name': strategy_name,
73
            'params': final_params,
74
            'ft_stratparam_v': 1,
75
            'export_time': datetime.now(timezone.utc),
76
        }
77
        logger.info(f"Dumping parameters to {filename}")
1✔
78
        with filename.open('w') as f:
1✔
79
            rapidjson.dump(final_params, f, indent=2,
1✔
80
                           default=hyperopt_serializer,
81
                           number_mode=HYPER_PARAMS_FILE_FORMAT
82
                           )
83

84
    @staticmethod
1✔
85
    def load_params(filename: Path) -> Dict:
1✔
86
        """
87
        Load parameters from file
88
        """
89
        with filename.open('r') as f:
×
90
            params = rapidjson.load(f, number_mode=HYPER_PARAMS_FILE_FORMAT)
×
91
        return params
×
92

93
    @staticmethod
1✔
94
    def try_export_params(config: Config, strategy_name: str, params: Dict):
1✔
95
        if params.get(FTHYPT_FILEVERSION, 1) >= 2 and not config.get('disableparamexport', False):
1✔
96
            # Export parameters ...
97
            fn = HyperoptTools.get_strategy_filename(config, strategy_name)
1✔
98
            if fn:
1✔
99
                HyperoptTools.export_params(params, strategy_name, fn.with_suffix('.json'))
1✔
100
            else:
101
                logger.warning("Strategy not found, not exporting parameter file.")
1✔
102

103
    @staticmethod
1✔
104
    def has_space(config: Config, space: str) -> bool:
1✔
105
        """
106
        Tell if the space value is contained in the configuration
107
        """
108
        # 'trailing' and 'protection spaces are not included in the 'default' set of spaces
109
        if space in ('trailing', 'protection', 'trades'):
1✔
110
            return any(s in config['spaces'] for s in [space, 'all'])
1✔
111
        else:
112
            return any(s in config['spaces'] for s in [space, 'all', 'default'])
1✔
113

114
    @staticmethod
1✔
115
    def _read_results(results_file: Path, batch_size: int = 10) -> Iterator[List[Any]]:
1✔
116
        """
117
        Stream hyperopt results from file
118
        """
119
        import rapidjson
1✔
120
        logger.info(f"Reading epochs from '{results_file}'")
1✔
121
        with results_file.open('r') as f:
1✔
122
            data = []
1✔
123
            for line in f:
1✔
124
                data += [rapidjson.loads(line)]
1✔
125
                if len(data) >= batch_size:
1✔
126
                    yield data
1✔
127
                    data = []
1✔
128
        yield data
1✔
129

130
    @staticmethod
1✔
131
    def _test_hyperopt_results_exist(results_file) -> bool:
1✔
132
        if results_file.is_file() and results_file.stat().st_size > 0:
1✔
133
            if results_file.suffix == '.pickle':
1✔
134
                raise OperationalException(
1✔
135
                    "Legacy hyperopt results are no longer supported."
136
                    "Please rerun hyperopt or use an older version to load this file."
137
                )
138
            return True
1✔
139
        else:
140
            # No file found.
141
            return False
1✔
142

143
    @staticmethod
1✔
144
    def load_filtered_results(results_file: Path, config: Config) -> Tuple[List, int]:
1✔
145
        filteroptions = {
1✔
146
            'only_best': config.get('hyperopt_list_best', False),
147
            'only_profitable': config.get('hyperopt_list_profitable', False),
148
            'filter_min_trades': config.get('hyperopt_list_min_trades', 0),
149
            'filter_max_trades': config.get('hyperopt_list_max_trades', 0),
150
            'filter_min_avg_time': config.get('hyperopt_list_min_avg_time'),
151
            'filter_max_avg_time': config.get('hyperopt_list_max_avg_time'),
152
            'filter_min_avg_profit': config.get('hyperopt_list_min_avg_profit'),
153
            'filter_max_avg_profit': config.get('hyperopt_list_max_avg_profit'),
154
            'filter_min_total_profit': config.get('hyperopt_list_min_total_profit'),
155
            'filter_max_total_profit': config.get('hyperopt_list_max_total_profit'),
156
            'filter_min_objective': config.get('hyperopt_list_min_objective'),
157
            'filter_max_objective': config.get('hyperopt_list_max_objective'),
158
        }
159
        if not HyperoptTools._test_hyperopt_results_exist(results_file):
1✔
160
            # No file found.
161
            logger.warning(f"Hyperopt file {results_file} not found.")
1✔
162
            return [], 0
1✔
163

164
        epochs = []
1✔
165
        total_epochs = 0
1✔
166
        for epochs_tmp in HyperoptTools._read_results(results_file):
1✔
167
            if total_epochs == 0 and epochs_tmp[0].get('is_best') is None:
1✔
168
                raise OperationalException(
×
169
                    "The file with HyperoptTools results is incompatible with this version "
170
                    "of Freqtrade and cannot be loaded.")
171
            total_epochs += len(epochs_tmp)
1✔
172
            epochs += hyperopt_filter_epochs(epochs_tmp, filteroptions, log=False)
1✔
173

174
        logger.info(f"Loaded {total_epochs} previous evaluations from disk.")
1✔
175

176
        # Final filter run ...
177
        epochs = hyperopt_filter_epochs(epochs, filteroptions, log=True)
1✔
178

179
        return epochs, total_epochs
1✔
180

181
    @staticmethod
1✔
182
    def show_epoch_details(results, total_epochs: int, print_json: bool,
1✔
183
                           no_header: bool = False, header_str: Optional[str] = None) -> None:
184
        """
185
        Display details of the hyperopt result
186
        """
187
        params = results.get('params_details', {})
1✔
188
        non_optimized = results.get('params_not_optimized', {})
1✔
189

190
        # Default header string
191
        if header_str is None:
1✔
192
            header_str = "Best result"
1✔
193

194
        if not no_header:
1✔
195
            explanation_str = HyperoptTools._format_explanation_string(results, total_epochs)
1✔
196
            print(f"\n{header_str}:\n\n{explanation_str}\n")
1✔
197

198
        if print_json:
1✔
199
            result_dict: Dict = {}
1✔
200
            for s in ['buy', 'sell', 'protection',
1✔
201
                      'roi', 'stoploss', 'trailing', 'max_open_trades']:
202
                HyperoptTools._params_update_for_json(result_dict, params, non_optimized, s)
1✔
203
            print(rapidjson.dumps(result_dict, default=str, number_mode=HYPER_PARAMS_FILE_FORMAT))
1✔
204

205
        else:
206
            HyperoptTools._params_pretty_print(params, 'buy', "Buy hyperspace params:",
1✔
207
                                               non_optimized)
208
            HyperoptTools._params_pretty_print(params, 'sell', "Sell hyperspace params:",
1✔
209
                                               non_optimized)
210
            HyperoptTools._params_pretty_print(params, 'protection',
1✔
211
                                               "Protection hyperspace params:", non_optimized)
212
            HyperoptTools._params_pretty_print(params, 'roi', "ROI table:", non_optimized)
1✔
213
            HyperoptTools._params_pretty_print(params, 'stoploss', "Stoploss:", non_optimized)
1✔
214
            HyperoptTools._params_pretty_print(params, 'trailing', "Trailing stop:", non_optimized)
1✔
215
            HyperoptTools._params_pretty_print(
1✔
216
                params, 'max_open_trades', "Max Open Trades:", non_optimized)
217

218
    @staticmethod
1✔
219
    def _params_update_for_json(result_dict, params, non_optimized, space: str) -> None:
1✔
220
        if (space in params) or (space in non_optimized):
1✔
221
            space_params = HyperoptTools._space_params(params, space)
1✔
222
            space_non_optimized = HyperoptTools._space_params(non_optimized, space)
1✔
223
            all_space_params = space_params
1✔
224

225
            # Merge non optimized params if there are any
226
            if len(space_non_optimized) > 0:
1✔
227
                all_space_params = {**space_params, **space_non_optimized}
1✔
228

229
            if space in ['buy', 'sell']:
1✔
230
                result_dict.setdefault('params', {}).update(all_space_params)
1✔
231
            elif space == 'roi':
1✔
232
                # Convert keys in min_roi dict to strings because
233
                # rapidjson cannot dump dicts with integer keys...
234
                result_dict['minimal_roi'] = {str(k): v for k, v in all_space_params.items()}
1✔
235
            else:  # 'stoploss', 'trailing'
236
                result_dict.update(all_space_params)
1✔
237

238
    @staticmethod
1✔
239
    def _params_pretty_print(params, space: str, header: str, non_optimized={}) -> None:
1✔
240
        if space in params or space in non_optimized:
1✔
241
            space_params = HyperoptTools._space_params(params, space, 5)
1✔
242
            no_params = HyperoptTools._space_params(non_optimized, space, 5)
1✔
243
            appendix = ''
1✔
244
            if not space_params and not no_params:
1✔
245
                # No parameters - don't print
246
                return
×
247
            if not space_params:
1✔
248
                # Not optimized parameters - append string
249
                appendix = NON_OPT_PARAM_APPENDIX
1✔
250

251
            result = f"\n# {header}\n"
1✔
252
            if space == "stoploss":
1✔
253
                stoploss = safe_value_fallback2(space_params, no_params, space, space)
1✔
254
                result += (f"stoploss = {stoploss}{appendix}")
1✔
255
            elif space == "max_open_trades":
1✔
256
                max_open_trades = safe_value_fallback2(space_params, no_params, space, space)
1✔
257
                result += (f"max_open_trades = {max_open_trades}{appendix}")
1✔
258
            elif space == "roi":
1✔
259
                result = result[:-1] + f'{appendix}\n'
1✔
260
                minimal_roi_result = rapidjson.dumps({
1✔
261
                    str(k): v for k, v in (space_params or no_params).items()
262
                }, default=str, indent=4, number_mode=rapidjson.NM_NATIVE)
263
                result += f"minimal_roi = {minimal_roi_result}"
1✔
264
            elif space == "trailing":
1✔
265
                for k, v in (space_params or no_params).items():
1✔
266
                    result += f"{k} = {v}{appendix}\n"
1✔
267

268
            else:
269
                # Buy / sell parameters
270

271
                result += f"{space}_params = {HyperoptTools._pprint_dict(space_params, no_params)}"
1✔
272

273
            result = result.replace("\n", "\n    ")
1✔
274
            print(result)
1✔
275

276
    @staticmethod
1✔
277
    def _space_params(params, space: str, r: Optional[int] = None) -> Dict:
1✔
278
        d = params.get(space)
1✔
279
        if d:
1✔
280
            # Round floats to `r` digits after the decimal point if requested
281
            return round_dict(d, r) if r else d
1✔
282
        return {}
1✔
283

284
    @staticmethod
1✔
285
    def _pprint_dict(params, non_optimized, indent: int = 4):
1✔
286
        """
287
        Pretty-print hyperopt results (based on 2 dicts - with add. comment)
288
        """
289
        p = params.copy()
1✔
290
        p.update(non_optimized)
1✔
291
        result = '{\n'
1✔
292

293
        for k, param in p.items():
1✔
294
            result += " " * indent + f'"{k}": '
1✔
295
            result += f'"{param}",' if isinstance(param, str) else f'{param},'
1✔
296
            if k in non_optimized:
1✔
297
                result += NON_OPT_PARAM_APPENDIX
1✔
298
            result += "\n"
1✔
299
        result += '}'
1✔
300
        return result
1✔
301

302
    @staticmethod
1✔
303
    def is_best_loss(results, current_best_loss: float) -> bool:
1✔
304
        return bool(results['loss'] < current_best_loss)
1✔
305

306
    @staticmethod
1✔
307
    def format_results_explanation_string(results_metrics: Dict, stake_currency: str) -> str:
1✔
308
        """
309
        Return the formatted results explanation in a string
310
        """
311
        return (f"{results_metrics['total_trades']:6d} trades. "
1✔
312
                f"{results_metrics['wins']}/{results_metrics['draws']}"
313
                f"/{results_metrics['losses']} Wins/Draws/Losses. "
314
                f"Avg profit {results_metrics['profit_mean']:7.2%}. "
315
                f"Median profit {results_metrics['profit_median']:7.2%}. "
316
                f"Total profit {results_metrics['profit_total_abs']:11.8f} {stake_currency} "
317
                f"({results_metrics['profit_total']:8.2%}). "
318
                f"Avg duration {results_metrics['holding_avg']} min."
319
                )
320

321
    @staticmethod
1✔
322
    def _format_explanation_string(results, total_epochs) -> str:
1✔
323
        return (("*" if results['is_initial_point'] else " ") +
1✔
324
                f"{results['current_epoch']:5d}/{total_epochs}: " +
325
                f"{results['results_explanation']} " +
326
                f"Objective: {results['loss']:.5f}")
327

328
    @staticmethod
1✔
329
    def prepare_trials_columns(trials: pd.DataFrame, has_drawdown: bool) -> pd.DataFrame:
1✔
330
        trials['Best'] = ''
1✔
331

332
        if 'results_metrics.winsdrawslosses' not in trials.columns:
1✔
333
            # Ensure compatibility with older versions of hyperopt results
334
            trials['results_metrics.winsdrawslosses'] = 'N/A'
1✔
335

336
        if not has_drawdown:
1✔
337
            # Ensure compatibility with older versions of hyperopt results
338
            trials['results_metrics.max_drawdown_account'] = None
1✔
339
        if 'is_random' not in trials.columns:
1✔
340
            trials['is_random'] = False
×
341

342
        # New mode, using backtest result for metrics
343
        trials['results_metrics.winsdrawslosses'] = trials.apply(
1✔
344
            lambda x: generate_wins_draws_losses(
345
                            x['results_metrics.wins'], x['results_metrics.draws'],
346
                            x['results_metrics.losses']
347
                      ), axis=1)
348

349
        trials = trials[['Best', 'current_epoch', 'results_metrics.total_trades',
1✔
350
                         'results_metrics.winsdrawslosses',
351
                         'results_metrics.profit_mean', 'results_metrics.profit_total_abs',
352
                         'results_metrics.profit_total', 'results_metrics.holding_avg',
353
                         'results_metrics.max_drawdown',
354
                         'results_metrics.max_drawdown_account', 'results_metrics.max_drawdown_abs',
355
                         'loss', 'is_initial_point', 'is_random', 'is_best']]
356

357
        trials.columns = [
1✔
358
            'Best', 'Epoch', 'Trades', ' Win  Draw  Loss  Win%', 'Avg profit',
359
            'Total profit', 'Profit', 'Avg duration', 'max_drawdown', 'max_drawdown_account',
360
            'max_drawdown_abs', 'Objective', 'is_initial_point', 'is_random', 'is_best'
361
            ]
362

363
        return trials
1✔
364

365
    @staticmethod
1✔
366
    def get_result_table(config: Config, results: list, total_epochs: int, highlight_best: bool,
1✔
367
                         print_colorized: bool, remove_header: int) -> str:
368
        """
369
        Log result table
370
        """
371
        if not results:
1✔
372
            return ''
×
373

374
        tabulate.PRESERVE_WHITESPACE = True
1✔
375
        trials = json_normalize(results, max_level=1)
1✔
376

377
        has_account_drawdown = 'results_metrics.max_drawdown_account' in trials.columns
1✔
378

379
        trials = HyperoptTools.prepare_trials_columns(trials, has_account_drawdown)
1✔
380

381
        trials['is_profit'] = False
1✔
382
        trials.loc[trials['is_initial_point'] | trials['is_random'], 'Best'] = '*     '
1✔
383
        trials.loc[trials['is_best'], 'Best'] = 'Best'
1✔
384
        trials.loc[
1✔
385
            (trials['is_initial_point'] | trials['is_random']) & trials['is_best'],
386
            'Best'] = '* Best'
387
        trials.loc[trials['Total profit'] > 0, 'is_profit'] = True
1✔
388
        trials['Trades'] = trials['Trades'].astype(str)
1✔
389
        # perc_multi = 1 if legacy_mode else 100
390
        trials['Epoch'] = trials['Epoch'].apply(
1✔
391
            lambda x: '{}/{}'.format(str(x).rjust(len(str(total_epochs)), ' '), total_epochs)
392
        )
393
        trials['Avg profit'] = trials['Avg profit'].apply(
1✔
394
            lambda x: f'{x:,.2%}'.rjust(7, ' ') if not isna(x) else "--".rjust(7, ' ')
395
        )
396
        trials['Avg duration'] = trials['Avg duration'].apply(
1✔
397
            lambda x: f'{x:,.1f} m'.rjust(7, ' ') if isinstance(x, float) else f"{x}"
398
                      if not isna(x) else "--".rjust(7, ' ')
399
        )
400
        trials['Objective'] = trials['Objective'].apply(
1✔
401
            lambda x: f'{x:,.5f}'.rjust(8, ' ') if x != 100000 else "N/A".rjust(8, ' ')
402
        )
403

404
        stake_currency = config['stake_currency']
1✔
405

406
        trials[f"Max Drawdown{' (Acct)' if has_account_drawdown else ''}"] = trials.apply(
1✔
407
            lambda x: "{} {}".format(
408
                round_coin_value(x['max_drawdown_abs'], stake_currency, keep_trailing_zeros=True),
409
                (f"({x['max_drawdown_account']:,.2%})"
410
                    if has_account_drawdown
411
                    else f"({x['max_drawdown']:,.2%})"
412
                 ).rjust(10, ' ')
413
            ).rjust(25 + len(stake_currency))
414
            if x['max_drawdown'] != 0.0 or x['max_drawdown_account'] != 0.0
415
            else '--'.rjust(25 + len(stake_currency)),
416
            axis=1
417
        )
418

419
        trials = trials.drop(columns=['max_drawdown_abs', 'max_drawdown', 'max_drawdown_account'])
1✔
420

421
        trials['Profit'] = trials.apply(
1✔
422
            lambda x: '{} {}'.format(
423
                round_coin_value(x['Total profit'], stake_currency, keep_trailing_zeros=True),
424
                f"({x['Profit']:,.2%})".rjust(10, ' ')
425
            ).rjust(25 + len(stake_currency))
426
            if x['Total profit'] != 0.0 else '--'.rjust(25 + len(stake_currency)),
427
            axis=1
428
        )
429
        trials = trials.drop(columns=['Total profit'])
1✔
430

431
        if print_colorized:
1✔
432
            for i in range(len(trials)):
1✔
433
                if trials.loc[i]['is_profit']:
1✔
434
                    for j in range(len(trials.loc[i]) - 3):
1✔
435
                        trials.iat[i, j] = f"{Fore.GREEN}{str(trials.loc[i][j])}{Fore.RESET}"
1✔
436
                if trials.loc[i]['is_best'] and highlight_best:
1✔
437
                    for j in range(len(trials.loc[i]) - 3):
1✔
438
                        trials.iat[i, j] = f"{Style.BRIGHT}{str(trials.loc[i][j])}{Style.RESET_ALL}"
1✔
439

440
        trials = trials.drop(columns=['is_initial_point', 'is_best', 'is_profit', 'is_random'])
1✔
441
        if remove_header > 0:
1✔
442
            table = tabulate.tabulate(
×
443
                trials.to_dict(orient='list'), tablefmt='orgtbl',
444
                headers='keys', stralign="right"
445
            )
446

447
            table = table.split("\n", remove_header)[remove_header]
×
448
        elif remove_header < 0:
1✔
449
            table = tabulate.tabulate(
1✔
450
                trials.to_dict(orient='list'), tablefmt='psql',
451
                headers='keys', stralign="right"
452
            )
453
            table = "\n".join(table.split("\n")[0:remove_header])
1✔
454
        else:
455
            table = tabulate.tabulate(
1✔
456
                trials.to_dict(orient='list'), tablefmt='psql',
457
                headers='keys', stralign="right"
458
            )
459
        return table
1✔
460

461
    @staticmethod
1✔
462
    def export_csv_file(config: Config, results: list, csv_file: str) -> None:
1✔
463
        """
464
        Log result to csv-file
465
        """
466
        if not results:
1✔
467
            return
×
468

469
        # Verification for overwrite
470
        if Path(csv_file).is_file():
1✔
471
            logger.error(f"CSV file already exists: {csv_file}")
×
472
            return
×
473

474
        try:
1✔
475
            Path(csv_file).open('w+').close()
1✔
476
        except OSError:
×
477
            logger.error(f"Failed to create CSV file: {csv_file}")
×
478
            return
×
479

480
        trials = json_normalize(results, max_level=1)
1✔
481
        trials['Best'] = ''
1✔
482
        trials['Stake currency'] = config['stake_currency']
1✔
483

484
        base_metrics = ['Best', 'current_epoch', 'results_metrics.total_trades',
1✔
485
                        'results_metrics.profit_mean', 'results_metrics.profit_median',
486
                        'results_metrics.profit_total', 'Stake currency',
487
                        'results_metrics.profit_total_abs', 'results_metrics.holding_avg',
488
                        'results_metrics.trade_count_long', 'results_metrics.trade_count_short',
489
                        'loss', 'is_initial_point', 'is_best']
490
        perc_multi = 100
1✔
491

492
        param_metrics = [("params_dict." + param) for param in results[0]['params_dict'].keys()]
1✔
493
        trials = trials[base_metrics + param_metrics]
1✔
494

495
        base_columns = ['Best', 'Epoch', 'Trades', 'Avg profit', 'Median profit', 'Total profit',
1✔
496
                        'Stake currency', 'Profit', 'Avg duration',
497
                        'Trade count long', 'Trade count short',
498
                        'Objective',
499
                        'is_initial_point', 'is_best']
500
        param_columns = list(results[0]['params_dict'].keys())
1✔
501
        trials.columns = base_columns + param_columns
1✔
502

503
        trials['is_profit'] = False
1✔
504
        trials.loc[trials['is_initial_point'], 'Best'] = '*'
1✔
505
        trials.loc[trials['is_best'], 'Best'] = 'Best'
1✔
506
        trials.loc[trials['is_initial_point'] & trials['is_best'], 'Best'] = '* Best'
1✔
507
        trials.loc[trials['Total profit'] > 0, 'is_profit'] = True
1✔
508
        trials['Epoch'] = trials['Epoch'].astype(str)
1✔
509
        trials['Trades'] = trials['Trades'].astype(str)
1✔
510
        trials['Median profit'] = trials['Median profit'] * perc_multi
1✔
511

512
        trials['Total profit'] = trials['Total profit'].apply(
1✔
513
            lambda x: f'{x:,.8f}' if x != 0.0 else ""
514
        )
515
        trials['Profit'] = trials['Profit'].apply(
1✔
516
            lambda x: f'{x:,.2f}' if not isna(x) else ""
517
        )
518
        trials['Avg profit'] = trials['Avg profit'].apply(
1✔
519
            lambda x: f'{x * perc_multi:,.2f}%' if not isna(x) else ""
520
        )
521
        trials['Objective'] = trials['Objective'].apply(
1✔
522
            lambda x: f'{x:,.5f}' if x != 100000 else ""
523
        )
524

525
        trials = trials.drop(columns=['is_initial_point', 'is_best', 'is_profit'])
1✔
526
        trials.to_csv(csv_file, index=False, header=True, mode='w', encoding='UTF-8')
1✔
527
        logger.info(f"CSV file created: {csv_file}")
1✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc