为何Pine Script中weekofyear(time)以周二而非周一为周起始?
问题:Pine Script中交易周起始判断错误(周二而非周一)的修复
问题背景
我正在构建适配图表时间框架的OPEX标注指标,发现weekofyear(time)返回的交易周起始为周二,而非预期的周一。
现有OPEX标注逻辑(伪代码)
- 检查图表时间框架
- 若为月度框架,标注季度OPEX产品
- 若为周度框架,除上述操作外,在当周标注月度OPEX产品
- 若为日度框架,除上述操作外,在到期日标注日度及周度OPEX产品
- 若为日内框架,除上述操作外,在对应时段标注当周当日到期的OPEX产品
- 将当前K线与期权产品/OPEX时间列表比对并标注
问题代码分析
原代码尝试用weekofyear(time) != weekofyear(time[1])判断周起始,但结果不符合预期——原因是weekofyear的周起始规则依赖于交易所日历或时区设置,无法强制以周一为周起始。以下是原代码:
//@version=5 indicator('Start of Month/Week Label', overlay=true) // Check if the current bar is the first bar of the month is_monthStart = month(time) != month(time[1]) // Plot a label at the start of each month if is_monthStart label.new(x=bar_index, y=high, text="M: " + str.tostring(month(time)), style=label.style_label_down, color=color.green, textcolor=color.white) if timeframe.isdwm if timeframe.isdaily // Check if the current bar is the first bar of the week is_weekStart = weekofyear(time) != weekofyear(time[1]) // Plot a label at the start of each week if is_weekStart label.new(x=bar_index, y=high, yloc=yloc.belowbar, text="W: " + str.tostring(weekofyear(time)), style=label.style_label_up, color=color.green, textcolor=color.white)
修复方案
改用dayofweek函数直接锚定周一为周起始,同时结合周数对比确认是新一周的第一个K线,避免因交易所休市导致的偏移。核心逻辑:
- 用
dayofweek(time) == dayofweek.monday判断当前K线对应日期为周一 - 验证上一根K线的周数小于当前周数,避免跨年度的周一误判
完整修复代码
//@version=5 indicator('Start of Month/Week Label', overlay=true) // 月度起始判断 is_monthStart = month(time) != month(time[1]) if is_monthStart label.new(x=bar_index, y=high, text="M: " + str.tostring(month(time)), style=label.style_label_down, color=color.green, textcolor=color.white) // 周度起始判断(强制以周一为起始) if timeframe.isdaily // 判断当前bar是周一且属于新一周 is_weekStart = dayofweek(time) == dayofweek.monday and weekofyear(time) != weekofyear(time[1]) if is_weekStart label.new(x=bar_index, y=high, yloc=yloc.belowbar, text="W: " + str.tostring(weekofyear(time)), style=label.style_label_up, color=color.green, textcolor=color.white)
补充说明
如果需要完全忽略交易所休市(即使周一无K线,也要标注周一为周起始),可以手动计算周一的时间戳,通过匹配K线时间区间来完成标注。
内容的提问来源于stack exchange,提问作者phreshsprout
相关产品推荐
相关产品推荐

