You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PineScript策略回测显示‘无数据’逻辑异常求助

问题诊断与修复方案

核心问题分析

你的策略出现回测无数据、信号不触发的问题,主要由以下几个原因导致:

  1. request.security变量作用域错误
    计算720周期的RSI SMA时,你错误引用了外部的rsi变量,而非在目标时间框架内直接计算RSI。这种写法会导致跨周期数据同步异常,干扰信号判断逻辑。

  2. 初始资金与仓位不匹配
    初始资金仅设为1000,仓位占比5%即50单位。若交易标的价格较高(如加密货币、股票),50单位不足以覆盖最小交易单位,直接导致无法开仓,回测自然显示"无数据"。

  3. 信号逻辑冗余与计算模式问题
    重复编写交叉判断条件,且开启calc_on_every_tick=true会让策略在每笔tick上计算,容易引发信号重复触发或丢失,同时增大回测误差。

修正后的脚本

strategy('RSI Crossover Strategy', shorttitle='RSI Cross', 
         default_qty_type=strategy.percent_of_equity, 
         default_qty_value=5, 
         initial_capital=10000,  // 提高初始资金适配多数标的
         calc_on_every_tick=false,  // 关闭逐tick计算,避免信号混乱
         overlay=false)

// 输入参数
rsiLength = input(title='RSI Length', defval=14)
smaLength = input(title='SMA Length', defval=21)
maLength = input(title='200-Day MA Length', defval=200)

// 统一获取跨周期数据,避免作用域错误
[rsi_12h, sma_rsi_12h] = request.security(syminfo.tickerid, "720", 
     [ta.rsi(close, rsiLength), 
      ta.sma(ta.rsi(close, rsiLength), smaLength)])
// 单独获取日线200MA,保证数据对齐
ma_1d = request.security(syminfo.tickerid, "D", ta.sma(close, maLength))

// 绘图模块
plotColor = rsi_12h > sma_rsi_12h ? color.green : color.red
rsiPlot = plot(rsi_12h, color=plotColor, title='12h RSI')
smaPlot = plot(sma_rsi_12h, color=color.white, title='12h RSI SMA')
fill(rsiPlot, smaPlot, color=color.new(rsi_12h > sma_rsi_12h ? color.lime : color.red, 75))
hline(30, title='Oversold level')
hline(70, title='Overbought level')

// 定义信号变量,避免重复计算
longCondition = ta.crossover(rsi_12h, sma_rsi_12h) and rsi_12h < 44
closeLongCondition = ta.crossunder(rsi_12h, sma_rsi_12h) and rsi_12h > 55
shortCondition = ta.crossunder(rsi_12h, sma_rsi_12h) and rsi_12h > 50 and close < ma_1d
closeShortCondition = ta.crossover(rsi_12h, sma_rsi_12h) and rsi_12h < 45

// 策略执行逻辑
if (longCondition)
    strategy.entry("Long", strategy.long, comment="Long")

if (closeLongCondition)
    strategy.close("Long", comment="Close Long")

if (shortCondition)
    strategy.entry("Short", strategy.short, comment="Short")
   
if (closeShortCondition)
    strategy.close("Short", comment="Close Short")

修改说明

  1. 修复跨周期数据获取逻辑
    将12小时周期的RSI和RSI SMA放在同一个request.security调用中计算,确保在目标时间框架内使用本地数据,彻底解决变量作用域导致的同步问题。日线200MA单独获取,保证不同周期数据对齐。

  2. 调整资金与计算模式

    • 初始资金提高至10000,适配多数交易标的的最小单位要求;
    • 关闭逐tick计算,改为仅在K线闭合时触发策略逻辑,减少信号混乱与回测偏差。
  3. 优化代码可读性与逻辑

    • 为变量添加时间周期后缀(如rsi_12h),明确数据来源;
    • 统一定义信号变量,避免重复编写判断条件,降低维护成本。
  4. 细节优化

    • 移除不必要的color.new透明设置(color.new(plotColor, 0)等价于直接使用plotColor);
    • 添加overlay=false明确指标独立显示,避免与K线图混淆。

内容的提问来源于stack exchange,提问作者TDC Backtesting

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 08:25:14