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

Pine Script如何获取上周开盘价与收盘价?

获取Pine Script中上周交易日的开盘/收盘价

你当前用request.security(syminfo.tickerid, "D", open[1])能拿到前一交易日数据,但要获取上周最后一个交易日(比如周三取上周五)的开收盘,直接固定偏移天数(比如[5])容易踩节假日的坑,更可靠的方式是通过周数判断或时间范围筛选来定位目标交易日,以下是两种实用方案:

方案1:基于周数精准定位(推荐)

通过ta.weekofyear判断日线bar所属周数,直接提取上周最后一个交易日的开收盘,自动处理跨年、节假日情况:

//@version=5
indicator("上周交易日数据", overlay=false)

// 计算上周的周数,处理跨年边界(当年第一周的上周为去年最后一周)
currentWeek = ta.weekofyear(time)
lastWeek = currentWeek - 1
if lastWeek == 0
    lastWeek := ta.weekofyear(timestamp(year(time)-1, 12, 31, 0, 0))

// 获取上周最后一个交易日的开盘价和收盘价
lastWeekOpen = request.security(syminfo.tickerid, "D", ta.valuewhen(ta.weekofyear(time) == lastWeek, open, 0))
lastWeekClose = request.security(syminfo.tickerid, "D", ta.valuewhen(ta.weekofyear(time) == lastWeek, close, 0))

// 输出结果
plot(lastWeekOpen, color=color.green, title="上周开盘价")
plot(lastWeekClose, color=color.red, title="上周收盘价")

方案2:按时间范围筛选

先计算上周的时间区间,再提取该区间内最后一个交易日的数据,逻辑更直观:

//@version=5
indicator("上周交易日数据", overlay=false)

// 获取当前周周一的起始时间(Pine Script中dayofweek=1为周日,2为周一)
currentWeekStart = timestamp(year(time), month(time), dayofmonth(time) - dayofweek(time) + 2, 0, 0)
// 上周的时间范围:上周周一0点到上周日23:59
lastWeekStart = currentWeekStart - 7 * 86400
lastWeekEnd = lastWeekStart + 6 * 86400 + 86399 // 加86399秒到当天23:59

// 提取上周时间范围内最后一个交易日的开收盘
lastWeekOpen = request.security(syminfo.tickerid, "D", ta.valuewhen(time >= lastWeekStart and time <= lastWeekEnd, open, 0))
lastWeekClose = request.security(syminfo.tickerid, "D", ta.valuewhen(time >= lastWeekStart and time <= lastWeekEnd, close, 0))

// 输出结果
plot(lastWeekOpen, color=color.green, title="上周开盘价")
plot(lastWeekClose, color=color.red, title="上周收盘价")

关键函数说明

  • request.security:跨周期调用数据,这里用来获取日线级别数据
  • ta.valuewhen(condition, value, index):返回满足condition的第index个value值,index=0代表最后一个满足条件的值
  • ta.weekofyear(time):返回时间对应的周数,方便区分不同周的bar

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 13:32:36