1695 字
8 分钟

Freqtrade参数优化入门

什么是 Hyperopt?#

定义Hyperopt(超参数优化)是一种自动搜索算法,通过大量测试不同参数组合,找出使目标函数(如收益、Sharpe Ratio)最大化的参数。

工作原理#

1. 定义参数空间(例如:RSI 范围 20-40)
2. 生成随机参数组合
3. 用该组合回测策略
4. 记录结果(收益、Sharpe 等)
5. 根据结果调整搜索方向
6. 重复 2-5 步,直到找到最优参数

可视化流程

参数空间: RSI=[20,25,30,35,40]
Epoch 1: RSI=30 → 收益 +5%
Epoch 2: RSI=25 → 收益 +8% ✅ 更好
Epoch 3: RSI=22 → 收益 +12% ✅ 更好
Epoch 4: RSI=20 → 收益 +9%
Epoch 5: RSI=23 → 收益 +11%
...
Epoch 100: RSI=22 → 最优参数

Hyperopt vs 手动调参#

对比项手动调参Hyperopt
速度慢(每次手动改代码)快(自动化)
覆盖范围少(10-20 组)多(100-1000 组)
客观性受主观判断影响纯数据驱动
易用性简单需要学习
过拟合风险高(需警惕)

警告:过拟合陷阱#

⚠️ Hyperopt 容易导致过拟合

  • 在历史数据上找到”完美”参数
  • 但这些参数可能只适合历史数据
  • 未来表现可能很差

预防措施

  1. ✅ 使用样本外测试验证
  2. ✅ 限制优化的参数数量(≤ 5 个)
  3. ✅ 运行多次 Hyperopt,对比结果
  4. ✅ 优先优化影响大的参数

可优化的参数空间#

1. 买入信号参数#

示例:RSI 策略

class HyperOptStrategy(IStrategy):
# 定义参数空间
buy_rsi = IntParameter(20, 40, default=30, space='buy')
buy_rsi_enabled = CategoricalParameter([True, False], default=True, space='buy')
def populate_entry_trend(self, dataframe, metadata):
conditions = []
if self.buy_rsi_enabled.value:
conditions.append(dataframe['rsi'] < self.buy_rsi.value)
if conditions:
dataframe.loc[
reduce(lambda x, y: x & y, conditions),
'enter_long'] = 1
return dataframe

可优化参数

  • buy_rsi:RSI 阈值(20-40)
  • buy_rsi_enabled:是否启用该条件

2. 卖出信号参数#

sell_rsi = IntParameter(60, 80, default=70, space='sell')
sell_ema_short = IntParameter(5, 20, default=10, space='sell')
sell_ema_long = IntParameter(20, 50, default=30, space='sell')

3. ROI(止盈)参数#

def populate_roi_space(self):
return {
0: DecimalParameter(0.05, 0.20, default=0.10, space='roi'),
60: DecimalParameter(0.02, 0.10, default=0.05, space='roi'),
120: DecimalParameter(0.01, 0.05, default=0.02, space='roi'),
}

4. 止损参数#

stoploss = DecimalParameter(-0.15, -0.02, default=-0.05, space='stoploss')

5. 跟踪止损参数#

trailing_stop_positive = DecimalParameter(0.001, 0.05, default=0.01, space='trailing')
trailing_stop_positive_offset = DecimalParameter(0.01, 0.10, default=0.02, space='trailing')

参数类型#

参数类型说明示例
IntParameter整数参数RSI 周期(10-30)
DecimalParameter小数参数止损(-0.10 到 -0.02)
RealParameter实数参数同 DecimalParameter
CategoricalParameter分类参数[True, False] 或 [‘ema’, ‘sma’]

参数空间(Space)#

Freqtrade 将参数分为不同空间:

Space说明包含参数
buy买入信号参数RSI 阈值、EMA 周期等
sell卖出信号参数卖出条件参数
roiROI 止盈参数各时间点的止盈比例
stoploss止损参数固定止损百分比
trailing跟踪止损参数跟踪止损相关参数
protection保护机制参数冷却期、最大回撤等

优化指定空间

Terminal window
# 只优化买入参数
freqtrade hyperopt -c config.json --strategy MyStrategy --hyperopt-loss SharpeHyperOptLoss --spaces buy
# 优化买入和卖出参数
freqtrade hyperopt -c config.json --strategy MyStrategy --hyperopt-loss SharpeHyperOptLoss --spaces buy sell
# 优化所有参数
freqtrade hyperopt -c config.json --strategy MyStrategy --hyperopt-loss SharpeHyperOptLoss --spaces all

优化目标函数#

目标函数(Loss Function)#

Hyperopt 需要一个目标来评估参数的好坏。Freqtrade 提供多种内置目标函数:

1. SharpeHyperOptLoss(推荐)#

目标:最大化 Sharpe Ratio(风险调整后收益)

适用场景

  • ✅ 追求稳定收益
  • ✅ 注重风险控制
  • ✅ 长期交易

命令

Terminal window
freqtrade hyperopt \
-c config.json \
--strategy MyStrategy \
--hyperopt-loss SharpeHyperOptLoss \
--epochs 100

2. SortinoHyperOptLoss#

目标:最大化 Sortino Ratio(只考虑下行风险)

适用场景

  • ✅ 更关注下跌风险
  • ✅ 允许上涨波动

3. CalmarHyperOptLoss#

目标:最大化 Calmar Ratio(收益 / 最大回撤)

适用场景

  • ✅ 极度厌恶回撤
  • ✅ 追求平滑收益曲线

4. MaxDrawDownHyperOptLoss#

目标:最小化最大回撤

适用场景

  • ✅ 保守型投资者
  • ✅ 大资金账户

5. OnlyProfitHyperOptLoss#

目标:最大化总收益(不考虑风险)

适用场景

  • ⚠️ 激进型投资者
  • ⚠️ 容易导致过拟合
  • ⚠️ 不推荐新手使用

目标函数对比#

目标函数优化目标风险考虑适合人群推荐度
SharpeHyperOptLossSharpe Ratio大多数人⭐⭐⭐⭐⭐
SortinoHyperOptLossSortino Ratio中高进阶用户⭐⭐⭐⭐
CalmarHyperOptLossCalmar Ratio极高保守型⭐⭐⭐⭐
MaxDrawDownHyperOptLoss最小回撤极高保守型⭐⭐⭐
OnlyProfitHyperOptLoss总收益激进型⭐⭐

优化结果应用#

运行第一次 Hyperopt#

基础命令#

Terminal window
freqtrade hyperopt \
-c config.json \
--strategy Strategy001 \
--hyperopt-loss SharpeHyperOptLoss \
--spaces roi stoploss \
--epochs 100 \
--timerange 20250701-20250930

参数说明

  • --strategy:要优化的策略
  • --hyperopt-loss:目标函数
  • --spaces:要优化的参数空间
  • --epochs:运行次数(更多 = 更好的结果,但更耗时)
  • --timerange:优化的时间范围

运行过程#

2025-09-30 10:00:00 | INFO | Hyperopt | Starting Hyperopt...
2025-09-30 10:00:01 | INFO | Hyperopt | Epoch 1/100 - Current: 10.2%, Best: 10.2%
2025-09-30 10:00:03 | INFO | Hyperopt | Epoch 2/100 - Current: 8.5%, Best: 10.2%
2025-09-30 10:00:05 | INFO | Hyperopt | Epoch 3/100 - Current: 12.8%, Best: 12.8% ✅ New best
2025-09-30 10:00:07 | INFO | Hyperopt | Epoch 4/100 - Current: 9.3%, Best: 12.8%
...
2025-09-30 10:15:00 | INFO | Hyperopt | Epoch 100/100 - Current: 11.5%, Best: 15.2%
2025-09-30 10:15:01 | INFO | Hyperopt | Optimization complete!

查看优化结果#

结果文件#

优化结果保存在:

user_data/hyperopt_results/strategy_Strategy001_*.pkl

查看最佳结果#

Terminal window
# 查看最佳结果
freqtrade hyperopt-show --best -c config.json
# 列出所有最佳结果
freqtrade hyperopt-list -c config.json --best --min-trades 1
# 查看特定编号的结果
freqtrade hyperopt-show -n 1 -c config.json
# 列出所有结果
freqtrade hyperopt-list -c config.json
# 查看盈利的结果
freqtrade hyperopt-list -c config.json --profitable
# 导出为 CSV
freqtrade hyperopt-list -c config.json --export-csv results.csv

输出示例

Best result:
┏━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ Parameter ┃ Value ┃
┡━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━┩
│ buy_rsi │ 22 │
│ sell_rsi │ 72 │
│ roi_0 │ 0.15 │
│ roi_60 │ 0.08 │
│ roi_120 │ 0.03 │
│ stoploss │ -0.08 │
└───────────────────────────┴──────────────────────────┘
Result metrics:
┏━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ Metric ┃ Value ┃
┡━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━┩
│ Total profit │ 18.52% │
│ Avg profit per trade │ 1.42% │
│ Total trades │ 52 │
│ Win rate │ 84.6% │
│ Sharpe Ratio │ 3.45 │
│ Max drawdown │ 4.82% │
└─────────────────────────┴─────────────────────────┘

应用优化参数#

方法 1:导出参数到文件#

Terminal window
freqtrade hyperopt-show --best --print-json -c config.json > best_params

方法 2:手动复制参数#

将最佳参数复制到策略文件:

class Strategy001(IStrategy):
# 应用优化后的参数
buy_rsi = IntParameter(20, 40, default=22, space='buy', optimize=False) # 优化结果:22
sell_rsi = IntParameter(60, 80, default=72, space='sell', optimize=False) # 优化结果:72
minimal_roi = {
"0": 0.15, # 优化结果
"60": 0.08, # 优化结果
"120": 0.03 # 优化结果
}
stoploss = -0.08 # 优化结果

注意:设置 optimize=False 可防止再次优化该参数。

验证优化结果#

⚠️ 关键步骤:必须在样本外数据验证!

Terminal window
# 原始策略(优化前)- 先临时移除优化参数文件
mv user_data/strategies/Strategy001.json user_data/strategies/Strategy001.json.bak
freqtrade backtesting -c config.json --strategy Strategy001 --timerange 20250701-20250930
# 优化后的策略 - 恢复优化参数文件
mv user_data/strategies/Strategy001.json.bak user_data/strategies/Strategy001.json
freqtrade backtesting -c config.json --strategy Strategy001 --timerange 20250701-20250930

对比结果

原始策略(样本外):
收益:+8.5%
Sharpe:2.1
优化后策略(样本外):
收益:+12.3%(提升 45%!)✅
Sharpe:2.8(提升 33%!)✅
结论:优化有效!

警告信号

优化后策略(训练期):
收益:+25%
Sharpe:4.5
优化后策略(测试期):
收益:+3%(仅为训练期的 12%)❌
Sharpe:0.8(大幅下降)❌
结论:过拟合!不要使用优化参数!

支持与分享

如果这篇文章对你有帮助,欢迎分享给更多人或赞助支持!

赞助
Freqtrade参数优化入门
https://blog.smyb.fun/posts/aitrade/11_freqtrade参数优化入门/
作者
三木羽冰
发布于
2026-01-11
许可协议
CC BY-NC-SA 4.0
最后更新于 2026-01-11,距今已过 38 天

部分内容可能已过时

Profile Image of the Author
三木羽冰
嵌言片语
音乐
封面

音乐

暂未播放

0:00 0:00
暂无歌词
分类
标签
站点统计
文章
21
分类
3
标签
6
总字数
24,212
运行时长
0
最后活动
0 天前

目录