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

如何获取回测策略周期的首尾日期(非手动设置日期范围)?

自动获取回测首尾日期并格式化输出

在Pine Script里,要摆脱手动设置日期范围的限制,直接通过回测的K线数量自动识别首尾日期并输出成9/16/21 To 11/10/22这样的格式,可按以下方式实现:

核心思路

  • 用barstate.isfirst捕捉回测的第一根K线,记录其时间戳作为回测首日
  • 用barstate.islast捕捉回测的最后一根K线,记录其时间戳作为回测末日
  • 把时间戳转换成指定的短日期格式,再拼接成要求的字符串

完整代码

//@version=5
indicator("回测日期范围自动获取", overlay=true)

// 初始化变量存储首尾K线的时间戳
var float firstBarTime = na
var float lastBarTime = na

// 记录第一根K线的时间
if barstate.isfirst
    firstBarTime := time

// 记录最后一根K线的时间
if barstate.islast
    lastBarTime := time

// 格式化日期为短格式并拼接成目标字符串
backtestPeriod = str.format("{0} To {1}", str.tostring(firstBarTime, "MM/dd/yy"), str.tostring(lastBarTime, "MM/dd/yy"))

// 在图表上显示结果(仅最后一根K线时更新)
var label periodLabel = label.new(bar_index, high, "", yloc=yloc.abovebar, color=color.blue, textcolor=color.white)
if barstate.islast
    label.set_text(periodLabel, backtestPeriod)

代码说明

  • var修饰变量确保只初始化一次,不会随K线刷新重置
  • time返回K线的时间戳,通过str.tostring(time, "MM/dd/yy")转换为短日期格式
  • barstate.isfirst和barstate.islast是Pine Script内置的状态变量,精准定位回测的首尾节点
  • 最后用标签把日期范围显示在图表的最后一根K线上方,方便查看

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 21:10:15