如何在筛选器中计算波动率?

波动率衡量金融商品在指定时间段内的价格变化。价格范围越广,波动性就越大。价格区间越窄,波动性越低。

这是我们用于计算的波动率公式(每周、每月和每天):

//@version=4
study("volatility")

fastSearchN(xs, x) => // xs - sorted, ascending
    max_bars_back(xs, 366) 
   left  = 0 
   right = min(bar_index,366)
   mid = 0
   if xs < x
        0    else
        for i = 0 to 9
            mid := ceil((left+right) / 2)
            if left == right
                break
            else if xs[mid] < x 
               right := mid
                continue
            else if xs[mid] > x
                left := mid
                continue
            else
                break
        mid
 
month1 = 30
month_ago = timenow - 1000*60*60*24*month1 month_ago_this_bar = time - 1000*60*60*24*month1 countOfBars1MonthAgo = fastSearchN(time, month_ago)
countOfBars1MonthAgoThisBar = fastSearchN(time, month_ago_this_bar)
 week1 = 7

week_ago = timenow - 1000*60*60*24*week1 week_ago_this_bar = time - 1000*60*60*24*week1 countOfBarsWeekAgo = fastSearchN(time, week_ago)
countOfBarsWeekAgoThisBar = fastSearchN(time, week_ago_this_bar)

// volatility
volatility(bb) =>
    bb2 = bb
    if bar_index == 0
        bb2 := 365
    if bb2 == 0
        na
    else
        s = sum((high-low)/abs(low) * 100 / bb2, bb2)
        if bb == 0
            na
        else
            s
 
plot(volatility(countOfBarsWeekAgoThisBar), title="Volatility.W")
plot(volatility(countOfBars1MonthAgoThisBar),title="Volatility.M")
plot(tr(true)*100/abs(low), title="Volatility.D")
Java

注意:由于时间的原因,此脚本的历史值和实时值不同,请参阅 https://www.tradingview.com/pine-script-docs/en/v4/essential/Indicator_repainting.html

对于视觉显示,您可以使用图表的每日时间范围通过 Pine 编辑器将此脚本加到您的图表中。图表上将出现一个指标,图表将显示每种波动率的值。