DEV Community

Cover image for Chapter 5: How to Optimize Strategy Parameters? Freqtrade Hyperopt Quick Start
itrade icu
itrade icu

Posted on • Originally published at itrade.icu

Chapter 5: How to Optimize Strategy Parameters? Freqtrade Hyperopt Quick Start

πŸ“˜ Chapter 5: How to Optimize Strategy Parameters? Freqtrade Hyperopt Quick Start

In strategy development, besides building the buy and sell logic, parameter settings often determine the final return-to-risk ratio.

Freqtrade provides a powerful hyperopt feature for automatically searching for the optimal parameter combinations, greatly accelerating the strategy iteration speed.


🧠 1. What is Hyperopt? What is it suitable for?

Hyperopt is an automatic parameter optimization tool that can:

  • Help you find the best threshold for RSI?
  • Test which stop-profit/stop-loss level is optimal?
  • Automatically run multiple parameter combinations β†’ Compare results β†’ Find the best configuration

βœ… Suitable for the following scenarios:

  • Strategies with multiple numerical parameters (e.g., RSI, MACD, Bollinger Band width, stop-loss ratio)
  • Want to find the best combination in a specific historical period
  • Don't want to manually tune parameters


πŸš€ Want to learn quantitative trading?

πŸ‘‰ Click to visit: https://www.itrade.icu

Here you can find Freqtrade basics tutorials, strategy practice, indicator analysis, and other rich content to help you master quantitative trading skills effortlessly!


πŸš€ 2. Basic Commands and Parameter Explanation

freqtrade hyperopt \
  --config user_data/config.json \
  --strategy MyStrategy \
  --hyperopt-loss SharpeHyperOptLoss \
  --timerange 20230101-20230701 \
  --epochs 100
Enter fullscreen mode Exit fullscreen mode
Parameter Meaning
--config Config file path
--strategy Strategy class name to optimize
--hyperopt-loss Optimization objective function (see below)
--timerange Backtest time range
--epochs Number of iterations, more = more precise but more time-consuming
--spaces Which parameter spaces to optimize (default: buy, sell)

🎯 3. Common Optimization Objectives (Hyperopt Loss Functions)

Different objective functions represent different optimization directions. Common ones include:

Function Name Meaning Suitable Scenarios
SharpeHyperOptLoss Optimize Sharpe Ratio Balance of return and volatility
SortinoHyperOptLoss Optimize Sortino Ratio Focus on downside risk
ProfitHyperOptLoss Maximize total profit Aggressive return-driven strategies
CalmarHyperOptLoss Return / Max Drawdown ratio Risk control preference
TrailingBuyHyperOptLoss Specifically for trailing buy strategies

🧩 4. How to Define Hyperparameters?

Use the @parameter decorator in the strategy class, for example:

from freqtrade.strategy import IStrategy, IntParameter, DecimalParameter

class MyStrategy(IStrategy):
    rsi_period = IntParameter(10, 30, default=14, space="buy")
    stoploss_value = DecimalParameter(-0.10, -0.01, default=-0.05, space="sell")
Enter fullscreen mode Exit fullscreen mode

Freqtrade will automatically search for the best combination within the specified range.

⚠️ 5. Common Hyperopt Pitfalls (Must Avoid)

❗ Overfitting Historical Data

Backtest period too short or single sample may lead to strategies that only perform well in specific market conditions but poorly in live trading.

Suggestions:

  • Use longer time periods, such as more than 6 months
  • Run Hyperopt multiple times β†’ Check if parameters converge
  • Reserve some data for forward testing

❗ Objective Function Bias

Choosing unreasonable optimization objectives (e.g., only optimizing profit) while ignoring risk can lead to extreme strategies.

Suggestions:

  • Generally use Sharpe or Sortino as the first choice
  • If risk tolerance is low, recommend CalmarHyperOptLoss

❗ Search Space Too Large / Parameter Conflicts

Too many parameter combinations will greatly extend search time and may even cause conflicts.

Suggestions:

  • Keep the number of parameters between 3-6
  • Use effective ranges as much as possible, e.g., RSI doesn't need to search from 1-100

πŸ› οΈ 6. Running Example (Including Docker)

Strategy file:

from freqtrade.strategy.interface import IStrategy
from pandas import DataFrame
from freqtrade.strategy import IntParameter, DecimalParameter
import talib.abstract as ta

class MySimpleStrategy(IStrategy):
    # Backtest default timeframe
    timeframe = '15m'

    # Parameter spaces allowed (for hyperopt optimization)
    rsi_buy = IntParameter(10, 50, default=30, space="buy")
    stoploss_value = DecimalParameter(-0.1, -0.01, default=-0.05, space="sell")

    # Default stoploss (for dry-run or live trading)
    stoploss = -0.05

    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        # Add RSI indicator
        dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14)
        return dataframe

    def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        # Buy when RSI is below specified threshold
        dataframe.loc[
            (dataframe['rsi'] < self.rsi_buy.value),
            'buy'
        ] = 1
        return dataframe

    def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        # No explicit sell signal (exit via take-profit/stop-loss)
        dataframe['sell'] = 0
        return dataframe
Enter fullscreen mode Exit fullscreen mode

Local run:

freqtrade hyperopt \
  --config user_data/config.json \
  --strategy MySimpleStrategy \
  --hyperopt-loss SharpeHyperOptLoss \
  --timerange 20230101-20230630 \
  --epochs 100
Enter fullscreen mode Exit fullscreen mode

Docker run:

docker compose run --rm freqtrade hyperopt \
  --config /quants/freqtrade/user_data/config.json \
  --strategy MyStrategy \
  --hyperopt-loss SharpeHyperOptLoss \
  --timerange 20230101-20230630
Enter fullscreen mode Exit fullscreen mode

🎯 Current Strategy Tunable Parameters

Parameter Name Type Description
rsi_buy IntParameter(10, 50) Adjust RSI buy threshold
stoploss_value DecimalParameter(-0.1, -0.01) Control stop-loss ratio

πŸ“Œ Tips

  1. To optimize a parameter, must use .value to get the actual value
  2. space="buy", space="sell" controls the parameter range for hyperopt
  3. default=... is your manually set default value
  4. Before optimization, it's recommended to run backtesting first to confirm the strategy logic is working properly

πŸ“Š 7. Hyperopt Supported Evaluation Metrics

You can view all available Loss functions in freqtrade/optimize/losses.py. Common metrics include:

Metric Name Description
Sharpe Ratio Annualized return / Annualized volatility
Sortino Ratio Annualized return / Annualized downside volatility
Calmar Ratio Annualized return / Maximum drawdown
Total Profit Total profit
Drawdown Maximum drawdown
Avg Trade Duration Average trade duration

You can also customize evaluation functions to extend optimization objectives that best suit your needs.

βœ… 8. Recommended Practice Workflow

1. Use new-strategy to write strategy and define parameters
2. Run backtesting to initially verify strategy rationality
3. Use hyperopt for automatic parameter tuning
4. Replace optimal parameters into the strategy
5. Run backtest again for verification
6. Visualize analysis results β†’ Decide whether to go live
Enter fullscreen mode Exit fullscreen mode

πŸ“Œ Summary

Freqtrade's Hyperopt system provides strong support for strategy parameter tuning, but the premise is that you can reasonably set the parameter space, objective function, and data period.

The most important thing is not finding the "highest profit" parameters, but finding configurations that are stable, risk-resistant, and have strong generalization ability!

Top comments (0)