如何获取每月最后一个周四收盘价并计算标准差(含节假日规则)
实现每月最后一个周四收盘价的标准差计算(Pine Script)
核心逻辑说明
- 先计算日历上每月的最后一个周四日期
- 若该周四为非交易日,直接取前一个交易日(周三)的收盘价,不向后取周五
- 收集所有符合条件的收盘价,计算其标准差
完整代码实现
//@version=5 indicator("每月最后一个周四收盘价标准差", overlay=false) // 获取日历上每月最后一个周四的日期 getLastThursdayOfMonth(year, month) => // 先拿到当月最后一天的日期 lastDayOfMonth = dayofmonth(time.new(year, month + 1, 1) - 1) // 计算当月最后一天是星期几 lastDayWeekday = dayofweek(time.new(year, month, lastDayOfMonth)) // 从月末往前推,找到最近的周四 offsetDays = (lastDayWeekday - dayofweek.thursday + 7) % 7 lastThursday = lastDayOfMonth - offsetDays time.new(year, month, lastThursday) // 跟踪当前年月和对应的最后一个周四日期 currentYear = year(time) currentMonth = month(time) lastThursdayDate = getLastThursdayOfMonth(currentYear, currentMonth) // 变量初始化:标记是否已找到当月目标日期、存储目标收盘价、存储历史目标价数组 var bool isTargetFound = false var float monthlyTargetClose = na var array<float> targetCloseHistory = array.new_float() // 每月初重置标记 if ta.change(currentMonth) isTargetFound := false lastThursdayDate := getLastThursdayOfMonth(currentYear, currentMonth) // 匹配目标日期并获取收盘价 if time >= lastThursdayDate and not isTargetFound // 周四是交易日,直接取当天收盘价 if not na(close) monthlyTargetClose := close // 周四休市,取前一天(周三)的收盘价 else monthlyTargetClose := close[1] isTargetFound := true // 将当月目标价存入历史数组 array.push(targetCloseHistory, monthlyTargetClose) // 计算标准差(至少需要2个数据点才有效) stdResult = array.size(targetCloseHistory) >= 2 ? ta.stdev(array.to_array(targetCloseHistory), array.size(targetCloseHistory)) : na // 可视化输出 plot(stdResult, color=color.new(color.blue, 0), linewidth=2, title="目标价标准差") // 右上角显示最新目标收盘价 var resultTable = table.new(position.top_right, 2, 1, bgcolor=color.gray, border_width=1) table.cell(resultTable, 0, 0, "最新目标收盘价:", text_color=color.white) table.cell(resultTable, 1, 0, str.tostring(monthlyTargetClose, "#.####"), text_color=color.yellow)
代码关键部分解释
getLastThursdayOfMonth函数:通过当月最后一天倒推,精准定位日历上的最后一个周四,避免手动计算每个月的日期偏差。- 交易日判断:直接通过
na(close)判断当天是否为交易日,若周四休市则取前一根K线(周三)的收盘价,严格符合需求。 - 历史数据存储:用数组累计每月的目标收盘价,确保标准差计算基于完整的历史样本。
内容的提问来源于stack exchange,提问作者Avi Singh
相关产品推荐
相关产品推荐

