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

PineScript v5数组存储月度收益并表格展示异常问题咨询

问题分析与代码修正

原代码核心问题

  1. 数组与时间变量声明错误
    • 数组profits_jan未用var修饰,每根K线都会重新初始化,导致之前存储的数据全部丢失。
    • jan_0和jan_1用var声明,循环中仅会初始化一次,后续年份的时间判断会一直沿用2019年的1月区间,完全失效。
  2. 重复存储数据
    每根K线在1月期间都会执行array.push,导致数组中存入大量重复的收益率数据,array.get无法取到对应年份的正确值。
  3. 表格更新逻辑混乱
    每根K线都会重复设置表格单元格,且数组索引与年份的对应关系错误,导致表格展示异常。

修正后的代码

//@version=5
strategy("January Performance Tracker", overlay=true)

// 初始化数组存储每年1月收益率,var确保仅创建一次
var profits_jan = array.new_float()
// 初始化表格,var确保仅创建一次
var performance = table.new(position.top_right, 2, 6, title="January Returns")

// 写入表格表头
table.cell(performance, column=0, row=0, text="Year", text_color=color.white, bg_color=color.blue)
table.cell(performance, column=1, row=0, text="Return", text_color=color.white, bg_color=color.blue)

// 遍历2019-2023年
for int j = 0 to 4
    current_year = 2019 + j
    // 计算对应年份1月的起止时间,无需var,每次循环更新
    jan_start = timestamp(current_year, 1, 1)
    jan_end = timestamp(current_year, 1, 31)
    
    // 仅在当月最后一根K线记录收益率,避免重复存储
    if time == jan_end
        monthly_return = math.round(strategy.netprofit / strategy.initial_capital * 100, 2)
        array.push(profits_jan, monthly_return)
    
    // 写入年份到表格第一列
    table.cell(performance, column=0, row=1 + j, text=str.tostring(current_year), text_color=color.white)
    
    // 数组长度足够时,写入对应年份的收益率
    if array.size(profits_jan) > j
        table.cell(performance, column=1, row=1 + j, text=str.tostring(array.get(profits_jan, j)) + "%", text_color=color.white)

关键修改说明

  • 用var修饰数组和表格,确保数据与表格结构在整个回测周期内持续保留。
  • 移除时间变量的var修饰,每次循环计算对应年份的1月区间,保证时间判断准确。
  • 仅在当月最后一根K线记录收益率,避免同一月份重复存入数据。
  • 先写入年份列,再判断数组长度后写入收益率,避免索引越界问题。
  • 添加表头,让表格展示更清晰直观。

内容的提问来源于stack exchange,提问作者Fabio Rodriguez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 15:38:11