fix redis 问题

This commit is contained in:
zhangkun9038@dingtalk.com 2025-08-15 01:16:17 +08:00
parent 3dff6c61f7
commit a899a82532
2 changed files with 52 additions and 26 deletions

View File

@ -1072,7 +1072,6 @@ class FreqaiPrimer(IStrategy):
获取趋势得分优先从 Redis 缓存中读取如果缓存未命中则计算并存储到 Redis
"""
# 创建 Redis 客户端
if not hasattr(self, 'redis_client') and self.redis_url:
try:
@ -1082,8 +1081,10 @@ class FreqaiPrimer(IStrategy):
logger.error(f"❌ 初始化 Redis 客户端失败: {e}")
raise
# 生成缓存键
cache_key = f"trend_score:{pair}:{timeframe}:{timestamp}"
# 生成缓存键,使用新的命名格式
strategy_name = "freqaiprimer"
timeframes_str = "3m-15m-1h" # 固定的多时间框架组合
cache_key = f"{strategy_name}|trend_score|{pair.replace('/', '-')}|{timeframes_str}|{timestamp}"
logger.debug(f"[{pair}] 生成 Redis 缓存键:{cache_key} (时间戳: {timestamp})")
# 尝试从 Redis 获取趋势得分
@ -1102,9 +1103,6 @@ class FreqaiPrimer(IStrategy):
# 缓存未命中,计算趋势得分
logger.info(f"[{pair}] Redis 缓存未命中,开始计算趋势得分 (时间戳: {timestamp})")
# 缓存未命中,计算趋势得分
logger.info(f"[{pair}] Redis 缓存未命中,开始计算趋势得分")
trend_score = self.get_market_trend(dataframe=dataframe, metadata=metadata)
logger.info(f"[{pair}] 成功计算趋势得分: {trend_score:.2f}")
@ -1138,37 +1136,65 @@ class FreqaiPrimer(IStrategy):
# 计算最近20个周期的trend_score
trend_scores_20 = []
# 获取dataframe的实际索引长度
total_length = len(dataframe)
for i in range(-20, 0):
# 获取历史数据片段
hist_df = dataframe.iloc[:i+1] if i != -1 else dataframe
# 确保索引在有效范围内
if abs(i) > total_length:
logger.warning(f"[{pair}] 索引 {i} 超出数据范围,使用默认趋势得分 50")
trend_scores_20.append(50)
continue
# 确保索引是 DatetimeIndex 类型
if not isinstance(hist_df.index, pd.DatetimeIndex):
try:
hist_df.index = pd.to_datetime(hist_df.index)
logger.debug(f"[{pair}] 成功将索引转换为 DatetimeIndex")
except Exception as e:
logger.error(f"[{pair}] 无法将索引转换为 DatetimeIndex: {e}")
hist_df = pd.DataFrame() # 如果转换失败,设置为空 DataFrame
# 检查 hist_df 是否为空
if len(hist_df) == 0:
# 获取历史数据片段 - 使用正确的切片方式
end_idx = i + 1 if i != -1 else None
hist_df = dataframe.iloc[:end_idx]
if hist_df.empty:
logger.warning(f"[{pair}] 历史数据片段为空,使用默认趋势得分 50")
trend_scores_20.append(50) # 默认值
trend_scores_20.append(50)
continue
# 获取时间戳并记录日志
# 获取时间戳 - 使用更可靠的方式
try:
timestamp = int(hist_df.index[-1].timestamp())
logger.debug(f"[{pair}] 生成时间戳:{timestamp}, 时间:{hist_df.index[-1]}")
# 获取最后一个时间点的索引
last_idx = hist_df.index[-1]
# 如果是DatetimeIndex直接获取timestamp
if isinstance(last_idx, pd.Timestamp):
timestamp = int(last_idx.timestamp())
elif hasattr(last_idx, 'timestamp'):
# 其他有timestamp属性的类型
timestamp = int(last_idx.timestamp())
else:
# 如果是数值索引,使用时间戳作为标识
timestamp = int(pd.Timestamp.now().timestamp()) + i
logger.debug(f"[{pair}] 成功生成时间戳:{timestamp}, 对应时间:{last_idx}")
except Exception as e:
logger.error(f"[{pair}] 无法生成时间戳: {e}")
timestamp = 0 # 如果生成失败,使用默认时间戳 0
# 使用当前时间戳加上偏移量作为后备方案
timestamp = int(pd.Timestamp.now().timestamp()) + i
logger.warning(f"[{pair}] 使用后备时间戳:{timestamp}")
# 使用新的 get_trend_score_with_cache 方法替代直接调用 get_market_trend
score = self.get_trend_score_with_cache(pair=pair, timeframe=self.timeframe, timestamp=timestamp, dataframe=hist_df, metadata=metadata)
# 使用新的 get_trend_score_with_cache 方法
score = self.get_trend_score_with_cache(
pair=pair,
timeframe=self.timeframe,
timestamp=timestamp,
dataframe=hist_df,
metadata=metadata
)
trend_scores_20.append(score)
# 验证结果数量
if len(trend_scores_20) < 20:
logger.warning(f"[{pair}] 只获取到 {len(trend_scores_20)} 个趋势得分需要20个")
# 用默认值填充缺失的得分
while len(trend_scores_20) < 20:
trend_scores_20.append(50)
# 分段计算加权得分
# 第一段最近1-3个周期 (索引-3到-1)
segment1 = trend_scores_20[-3:]

BIN
venv.tar.gz Normal file

Binary file not shown.