如何在篩選器中計算波動率?

波動率衡量金融商品在指定時間段內的價格變化。價格範圍越廣,波動性就越大。價格區間越窄,波動性越低。

這是我們用於計算的波動率公式(每週、每月和每天):

//@version=4
study("volatility")fastSearchN(xs, x) => // xs - sorted, ascendingmax_bars_back(xs, 366)    left  = 0    right = min(bar_index,366)    mid = 0if xs < x        0elsefor i = 0 to 9            mid := ceil((left+right) / 2)if left == right                breakelse if xs[mid] < x                right := mid                continueelse if xs[mid] > x                left := mid                continueelsebreak        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 := 365if 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 編輯器將此腳本加到您的圖表中。圖表上將出現一個指標,圖表將顯示每種波動率的值。