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

Pine Script array.get索引越界问题求解:获取最大回归线对应周期

解决Pine Script中回归线周期查找的数组越界问题

问题场景

想要遍历min_length到max_length的周期范围,计算每个周期的回归线值,最终找出对应回归线值最高的周期(例如最近15天回归线值最高则输出15),但运行代码时触发数组越界错误:

Error on bar 0: In 'array.get()' function. Index -1 is out of bounds, array size is 11.

错误指向代码最后一行max_len = array.get(indices, max_idx)。

错误根源

在图表第一根K线(Bar 0)时,ta.sma()、ta.stdev()、ta.correlation()这类需要历史数据的函数会返回na,导致计算出的regline也为na。此时array.max(regression)返回na,array.indexof(regression, max_val)找不到匹配值,返回-1,用-1作为索引调用array.get()就会触发越界错误。

修复方案

通过过滤无效值和边界判断解决问题,修改后的完整代码如下:

//@version=5
indicator("Max Regression Length Finder", overlay=true)
src = input.source(title="Source", defval=close)
min_length = input.int(10, "Min. length", minval=1)
max_length = input.int(20, "Max. length", minval=1)
step = input.int(1, "Step", minval=1)

regression = array.new_float()
indices = array.new_int()

for i = min_length to max_length by step
    length = i
    x = bar_index
    y = src
    // 确保有足够历史数据计算指标
    if bar_index >= length - 1
        x_ = ta.sma(x, length)
        y_ = ta.sma(y, length)
        mx = ta.stdev(x, length)
        my = ta.stdev(y, length)
        c = ta.correlation(x, y, length)
        // 避免除零错误
        if mx != 0
            slope = c * (my / mx)
            inter = y_ - slope * x_
            regline = x * slope + inter
            
            // 仅将有效回归线值存入数组
            if not na(regline)
                array.push(indices, i)
                array.push(regression, regline)

// 查找并存储最大回归线对应的周期
var int max_len = na
if array.size(regression) > 0
    max_val = array.max(regression)
    max_idx = array.indexof(regression, max_val)
    // 确保索引有效后再取值
    if max_idx != -1
        max_len = array.get(indices, max_idx)

// 在图表上标注结果
label.new(bar_index, high, str.tostring(max_len), color=color.green, textcolor=color.white)

核心修改说明

  • 历史数据判断:添加bar_index >= length - 1,确保当前K线有足够数据计算指定长度的指标,避免早期K线返回na。
  • 除零防护:添加mx != 0判断,防止斜率计算时触发除零错误。
  • 过滤无效值:通过not na(regline)只将有效的回归线值存入数组,保证数组内无na值。
  • 边界安全判断:添加array.size(regression) > 0和max_idx != -1,避免数组为空或找不到最大值时调用array.get()出错。
  • 保留有效值:用var声明max_len,保留历史计算的有效结果,避免早期无数据时返回na。

内容的提问来源于stack exchange,提问作者Julian JJ

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 02:49:53