趋势计算方式改变成三段式
This commit is contained in:
parent
cd4a5b7518
commit
b02ac0ea97
@ -39,6 +39,14 @@ class FreqaiPrimer(IStrategy):
|
|||||||
TREND_BULLISH_THRESHOLD = 85
|
TREND_BULLISH_THRESHOLD = 85
|
||||||
TREND_BEARISH_THRESHOLD = 60
|
TREND_BEARISH_THRESHOLD = 60
|
||||||
|
|
||||||
|
# 新的加权趋势判定阈值(用于hyperopt优化)
|
||||||
|
TREND_FINAL_BULLISH_THRESHOLD = 70 # 上涨趋势最终阈值
|
||||||
|
TREND_FINAL_BEARISH_THRESHOLD = 30 # 下跌趋势最终阈值
|
||||||
|
|
||||||
|
# Hyperopt 可优化参数
|
||||||
|
trend_final_bullish_threshold = IntParameter(50, 90, default=87, space="buy", optimize=True, load=True)
|
||||||
|
trend_final_bearish_threshold = IntParameter(10, 50, default=53, space="buy", optimize=True, load=True)
|
||||||
|
|
||||||
# --- 🛠️ 固定配置参数 ---
|
# --- 🛠️ 固定配置参数 ---
|
||||||
stoploss = -0.15
|
stoploss = -0.15
|
||||||
timeframe = "3m"
|
timeframe = "3m"
|
||||||
@ -1022,11 +1030,11 @@ class FreqaiPrimer(IStrategy):
|
|||||||
|
|
||||||
def detect_trend_status(self, dataframe: DataFrame, metadata: dict) -> str:
|
def detect_trend_status(self, dataframe: DataFrame, metadata: dict) -> str:
|
||||||
"""
|
"""
|
||||||
基于最近20个周期的trend_score判断趋势状态
|
基于加权分段的trend_score判断趋势状态
|
||||||
规则:
|
规则:
|
||||||
- 最近20个周期中75%以上得分≥TREND_BULLISH_THRESHOLD,且最近10个周期中90%以上得分≥TREND_BULLISH_THRESHOLD → 上涨趋势
|
- 将最近20个trend_score分为3段:1-3(权重10),4-10(权重7),11-20(权重3)
|
||||||
- 最近20个周期中75%以上得分≤TREND_BEARISH_THRESHOLD,且最近10个周期中90%以上得分≤TREND_BEARISH_THRESHOLD → 下跌趋势
|
- 计算加权平均得分,映射到0-100区间
|
||||||
- 其他情况 → 震荡趋势
|
- 根据两个可优化的阈值判断趋势状态
|
||||||
"""
|
"""
|
||||||
pair = metadata.get('pair', 'Unknown')
|
pair = metadata.get('pair', 'Unknown')
|
||||||
|
|
||||||
@ -1047,26 +1055,45 @@ class FreqaiPrimer(IStrategy):
|
|||||||
else:
|
else:
|
||||||
trend_scores_20.append(50) # 默认值
|
trend_scores_20.append(50) # 默认值
|
||||||
|
|
||||||
# 最近10个周期
|
# 分段计算加权得分
|
||||||
trend_scores_10 = trend_scores_20[-10:]
|
# 第一段:最近1-3个周期 (索引-3到-1)
|
||||||
|
segment1 = trend_scores_20[-3:]
|
||||||
|
weighted_score1 = sum(score * 10 for score in segment1) / len(segment1)
|
||||||
|
|
||||||
# 计算满足条件的比例
|
# 第二段:4-10个周期 (索引-10到-4)
|
||||||
strong_bull_20 = sum(1 for score in trend_scores_20 if score >= self.TREND_BULLISH_THRESHOLD) / len(trend_scores_20)
|
segment2 = trend_scores_20[-10:-3]
|
||||||
strong_bull_10 = sum(1 for score in trend_scores_10 if score >= self.TREND_BULLISH_THRESHOLD) / len(trend_scores_10)
|
weighted_score2 = sum(score * 7 for score in segment2) / len(segment2)
|
||||||
|
|
||||||
strong_bear_20 = sum(1 for score in trend_scores_20 if score <= self.TREND_BEARISH_THRESHOLD) / len(trend_scores_20)
|
# 第三段:11-20个周期 (索引-20到-11)
|
||||||
strong_bear_10 = sum(1 for score in trend_scores_10 if score <= self.TREND_BEARISH_THRESHOLD) / len(trend_scores_10)
|
segment3 = trend_scores_20[-20:-10]
|
||||||
|
weighted_score3 = sum(score * 3 for score in segment3) / len(segment3)
|
||||||
|
|
||||||
# 判定趋势
|
# 计算最终加权得分
|
||||||
if strong_bull_20 >= 0.75 and strong_bull_10 >= 0.9:
|
final_weighted_score = (weighted_score1 + weighted_score2 + weighted_score3) / (10 + 7 + 3)
|
||||||
|
|
||||||
|
# 将得分映射到0-100区间(确保在合理范围内)
|
||||||
|
final_score = max(0, min(100, final_weighted_score))
|
||||||
|
|
||||||
|
# 使用hyperopt优化的阈值判断趋势状态
|
||||||
|
bullish_threshold = self.trend_final_bullish_threshold.value
|
||||||
|
bearish_threshold = self.trend_final_bearish_threshold.value
|
||||||
|
|
||||||
|
# 判定趋势状态
|
||||||
|
if final_score >= bullish_threshold:
|
||||||
trend_status = "bullish"
|
trend_status = "bullish"
|
||||||
logger.info(f"[{pair}] 🚀 检测到上涨趋势: 20周期强势比例={strong_bull_20:.1%}, 10周期强势比例={strong_bull_10:.1%}, 阈值={self.TREND_BULLISH_THRESHOLD}")
|
logger.info(f"[{pair}] 🚀 检测到上涨趋势: 最终加权得分={final_score:.2f}, 阈值≥{bullish_threshold}")
|
||||||
elif strong_bear_20 >= 0.75 and strong_bear_10 >= 0.9:
|
elif final_score <= bearish_threshold:
|
||||||
trend_status = "bearish"
|
trend_status = "bearish"
|
||||||
logger.info(f"[{pair}] 📉 检测到下跌趋势: 20周期弱势比例={strong_bear_20:.1%}, 10周期弱势比例={strong_bear_10:.1%}, 阈值={self.TREND_BEARISH_THRESHOLD}")
|
logger.info(f"[{pair}] 📉 检测到下跌趋势: 最终加权得分={final_score:.2f}, 阈值≤{bearish_threshold}")
|
||||||
else:
|
else:
|
||||||
trend_status = "ranging"
|
trend_status = "ranging"
|
||||||
logger.info(f"[{pair}] ⚖️ 检测到震荡趋势: 20周期强势比例={strong_bull_20:.1%}, 弱势比例={strong_bear_20:.1%}, 阈值={self.TREND_BULLISH_THRESHOLD}/{self.TREND_BEARISH_THRESHOLD}")
|
logger.info(f"[{pair}] ⚖️ 检测到震荡趋势: 最终加权得分={final_score:.2f}, 阈值范围({bearish_threshold}, {bullish_threshold})")
|
||||||
|
|
||||||
|
# 输出分段详细信息用于调试
|
||||||
|
logger.debug(f"[{pair}] 趋势分析详情 - "
|
||||||
|
f"第一段(1-3,权重10): {[f'{s:.1f}' for s in segment1]}, "
|
||||||
|
f"第二段(4-10,权重7): {[f'{s:.1f}' for s in segment2]}, "
|
||||||
|
f"第三段(11-20,权重3): {[f'{s:.1f}' for s in segment3]}")
|
||||||
|
|
||||||
return trend_status
|
return trend_status
|
||||||
|
|
||||||
|
|||||||
106
hyperopt_config_example.py
Normal file
106
hyperopt_config_example.py
Normal file
@ -0,0 +1,106 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
Hyperopt 配置示例,用于优化新的趋势判定参数
|
||||||
|
|
||||||
|
使用方法:
|
||||||
|
1. 将此文件保存为 hyperopt_trend_params.py
|
||||||
|
2. 运行: freqtrade hyperopt --config config.json --strategy freqaiprimer --hyperopt hyperopt_trend_params
|
||||||
|
"""
|
||||||
|
|
||||||
|
from freqtrade.optimize.hyperopt_interface import IHyperOpt
|
||||||
|
from typing import Dict, Any
|
||||||
|
import logging
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
class TrendParamsHyperopt(IHyperOpt):
|
||||||
|
"""
|
||||||
|
优化趋势判定参数的 Hyperopt 类
|
||||||
|
"""
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def generate_roi_table(params: Dict) -> Dict[int, float]:
|
||||||
|
"""生成ROI表格"""
|
||||||
|
return {
|
||||||
|
0: params['roi_p1'] + params['roi_p2'] + params['roi_p3'],
|
||||||
|
params['roi_t3']: params['roi_p1'] + params['roi_p2'],
|
||||||
|
params['roi_t3'] + params['roi_t2']: params['roi_p1'],
|
||||||
|
params['roi_t3'] + params['roi_t2'] + params['roi_t1']: 0,
|
||||||
|
}
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def roi_space():
|
||||||
|
"""ROI参数空间"""
|
||||||
|
return {
|
||||||
|
'roi_p1': [0.01, 0.08],
|
||||||
|
'roi_p2': [0.01, 0.08],
|
||||||
|
'roi_p3': [0.01, 0.08],
|
||||||
|
'roi_t1': [10, 120],
|
||||||
|
'roi_t2': [10, 60],
|
||||||
|
'roi_t3': [10, 60],
|
||||||
|
}
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def stoploss_space():
|
||||||
|
"""止损参数空间"""
|
||||||
|
return {
|
||||||
|
'stoploss': [-0.5, -0.05],
|
||||||
|
}
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def trailing_space():
|
||||||
|
"""追踪止损参数空间"""
|
||||||
|
return {
|
||||||
|
'trailing_stop': [True, False],
|
||||||
|
'trailing_stop_positive': [0.005, 0.05],
|
||||||
|
'trailing_stop_positive_offset_p1': [0.005, 0.05],
|
||||||
|
'trailing_only_offset_is_reached': [True, False],
|
||||||
|
}
|
||||||
|
|
||||||
|
def buy_params_space(self):
|
||||||
|
"""买入参数空间,包含新的趋势判定阈值"""
|
||||||
|
return {
|
||||||
|
# 原有参数
|
||||||
|
'buy_threshold': [-0.05, -0.001],
|
||||||
|
'volume_z_score_min': [0.1, 2.0],
|
||||||
|
'rsi_max': [20, 60],
|
||||||
|
|
||||||
|
# 新的趋势判定阈值
|
||||||
|
'trend_final_bullish_threshold': [50, 90], # 上涨趋势阈值
|
||||||
|
'trend_final_bearish_threshold': [10, 50], # 下跌趋势阈值
|
||||||
|
}
|
||||||
|
|
||||||
|
def sell_params_space(self):
|
||||||
|
"""卖出参数空间"""
|
||||||
|
return {
|
||||||
|
'sell_threshold': [0.001, 0.08],
|
||||||
|
'rsi_min': [60, 90],
|
||||||
|
'stochrsi_max': [60, 95],
|
||||||
|
}
|
||||||
|
|
||||||
|
def generate_estimator(self, dimensions: list, **kwargs) -> Any:
|
||||||
|
"""生成优化器"""
|
||||||
|
from skopt import Optimizer
|
||||||
|
from skopt.space import Real, Integer
|
||||||
|
|
||||||
|
# 定义参数空间
|
||||||
|
space = [
|
||||||
|
Real(-0.5, -0.05, name='stoploss'),
|
||||||
|
Real(0.001, 0.08, name='sell_threshold'),
|
||||||
|
Real(-0.05, -0.001, name='buy_threshold'),
|
||||||
|
Real(0.1, 2.0, name='volume_z_score_min'),
|
||||||
|
Integer(20, 60, name='rsi_max'),
|
||||||
|
Integer(60, 90, name='rsi_min'),
|
||||||
|
Integer(60, 95, name='stochrsi_max'),
|
||||||
|
Integer(50, 90, name='trend_final_bullish_threshold'),
|
||||||
|
Integer(10, 50, name='trend_final_bearish_threshold'),
|
||||||
|
]
|
||||||
|
|
||||||
|
return Optimizer(space, base_estimator='ET', acq_func='EI', n_initial_points=10)
|
||||||
|
|
||||||
|
# 使用示例配置
|
||||||
|
if __name__ == "__main__":
|
||||||
|
print("趋势参数优化配置已加载")
|
||||||
|
print("支持的优化参数:")
|
||||||
|
print("- trend_final_bullish_threshold: 50-90")
|
||||||
|
print("- trend_final_bearish_threshold: 10-50")
|
||||||
Loading…
x
Reference in New Issue
Block a user