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

Pine Script求解指定时间占比对应的MACD对称区间阈值方法

Pine Script 反向求解MACD对称区间阈值实现方案

核心实现逻辑:你的需求本质是求MACD绝对值的对应百分位数值,当你要求60%的时间MACD落在[-x,x]区间时,x就是所有统计范围内MACD绝对值的第60百分位数,不需要循环试值,直接用百分位统计即可高效实现。

//@version=5
indicator("MACD对称区间阈值计算", overlay=false)

// 自定义输入参数
target_percent = input.float(title="目标区间占比", defval=60, minval=1, maxval=100, step=0.1, tooltip="MACD落在[-x,x]区间的时间占比")
calc_range = input.int(title="统计K线范围", defval=0, minval=0, tooltip="填0表示统计指标加载以来的所有K线,填正数表示统计最近N根K线")

// 计算自定义MACD值
a = ta.ema(close, 10) - ta.ema(close, 200)
abs_a = math.abs(a)

// 存储绝对值到数组做百分位计算
var array<float> abs_macd_arr = array.new_float()

if calc_range == 0
    // 全历史统计
    array.push(abs_macd_arr, abs_a)
else
    // 固定窗口统计
    array.push(abs_macd_arr, abs_a)
    if array.size(abs_macd_arr) > calc_range
        array.shift(abs_macd_arr)

// 计算对应阈值x
x = na
if array.size(abs_macd_arr) > 0
    array.sort(abs_macd_arr)
    // 计算对应百分位的索引位置
    idx = math.round(array.size(abs_macd_arr) * target_percent / 100) - 1
    idx := math.max(idx, 0)
    x := array.get(abs_macd_arr, idx)

// 绘图与结果输出
plot(a, "MACD线", color=color.blue)
hline(x, "上阈值", color=color.red, linestyle=hline.style_dashed)
hline(-x, "下阈值", color=color.red, linestyle=hline.style_dashed)
var table res_table = table.new(position.top_right, 2, 3, bg_color=color.new(color.white, 0), border_width=1)
table.cell(res_table, 0, 0, "目标占比")
table.cell(res_table, 1, 0, str.tostring(target_percent) + "%")
table.cell(res_table, 0, 1, "计算得到的x值")
table.cell(res_table, 1, 1, str.tostring(x, "###.####"))

// 验证逻辑:输出实际区间占比,验证计算准确性
frequency(source, boundary) =>
    var r_count = 0.0
    var total_count = 0.0
    total_count := total_count + 1
    if source <= boundary and source >= -boundary
        r_count := r_count + 1
    r_count / total_count * 100

if not na(x)
    actual_percent = frequency(a, x)
    table.cell(res_table, 0, 2, "实际区间占比")
    table.cell(res_table, 1, 2, str.tostring(actual_percent, "##.#") + "%")

注意事项

  • 若只需统计固定时间段的阈值,修改「统计K线范围」参数即可,填0默认统计所有加载的K线数据
  • K线样本量越大,计算得到的x值越准确,样本量较小时会存在小幅误差
  • 代码内置验证逻辑,右上角表格会输出实际区间占比,和目标占比误差基本在1%以内

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 12:45:03