Indicator · Pine Script v4 · Own pane

Variance Ratio Test

by Anderson-ALGO· code credited to balipour

This indicator calculates the Variance Ratio Test statistic to evaluate random walk behavior across multiple sampling periods.

View on GitHub

GitHub stars9on the repository
Pine versionv4older, still runs
Lines of code106
Settings16inputs
LicenceNone statedfile: MPL-2.0
Last update5 years ago30 Nov 2020

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

106 lines of Pine Script v4 from Pine/Pine Wizards/Balipur/Variance Ratio Test.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

Variance Ratio Test.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © balipour

//@version=4
study("Variance Ratio Test [pig]", "BA🐷 VRT", false, format.inherit, precision=3, resolution = "")

//Backgorund Color
bgcolor(#000000c0)

//Inputs
src = input(close, "===== Source =====", input.source)
t   = input(   32, "Lookback",                    input.integer,  minval = 6, step = 2)
k   = input(    2, "Single VRT Sampling Period",  input.integer,  minval = 2, step = 2)
cl  = input( "5%", "Critical Value",              input.string,   options = ["10%", "5%", "2.5%", "1%"])
mv  = input(true,  "-------- Show Multiple Variance Ratio Stats --------",input.bool)
v1  = input(true,  "Show VRT1",input.bool)
k1  = input(2,"  VRT1 Sampling Period",input.integer,minval = 2,step = 2)
v2 = input(true,  "Show VRT2",input.bool)
k2  = input(4,"  VRT2 Sampling Period",input.integer,minval = 2,step = 2)
v3  = input(true,  "Show VRT3",input.bool)
k3  = input(8,"  VRT3 Sampling Period",input.integer, minval = 2,step = 2)
v4  = input(true,  "Show VRT4",input.bool)
k4  = input(16,"  VRT4 Sampling Period",input.integer,minval = 2,step = 2)
v5  = input(false, "Show VRT5",input.bool)
k5  = input(32,"  VRT5 Sampling Period",input.integer,minval = 2,step = 2)
lT  = input(1, "--- Line Thickness ---",input.integer,options=[1,2,3])

//log return one period
x = log(src/src[1])

//mean
mean = sma(x,t)

//Variance for one period
s1 = array.new_float(0)
for i = 0 to t - 1
    array.push(s1, pow(x[i]-mean,2))
v = array.sum(s1)/(t-1)

//Variance for k period
Vk(k)=>
    //log return k period
    xk = log(src/src[k])
    
    //Variance
    s2 = array.new_float(0)
    for i = 0 to t - 1 - k
        array.push(s2,pow(xk[i]-mean*k,2))

    //m the Unbiased Estimator scaling factor
    m = k * (t - k + 1) * (1 - (k/t)) 
    
    //Scale the K period Variance with m
    vk = array.sum(s2)/m


//Variance Ratio Function
VR(k)=>
    //(Homoscedasiticity assumption) Standard Deviation of variance ratio test
    phi = (2 * (k - 1)* (2*k - 1)) / (3*k*t)
    
    //Variance Ratio (Higher Period Variance / Lower Period Variance)
    vr = (Vk(k)/v)
    
    //Test Stats Z score (Divide SD of VR from VR)
    z = (vr - 1) / sqrt(phi)

//Multiple Variance Ratio Z Score
vr  = not mv ? VR(k) : na //Manual enter Period Z Score
vr1 = v1 and mv?VR(k1):na
vr2 = v2 and mv?VR(k2):na
vr3 = v3 and mv?VR(k3):na
vr4 = v4 and mv?VR(k4):na
vr5 = v5 and mv?VR(k5):na  

//Critical Values For Z score
float V = na
if (cl == "10%")
    V := 1.644853
if (cl == "5%")
    V := 1.959964
if (cl == "2.5%")
    V := 2.241403
if (cl == "1%")
    V := 2.575829

//Colors
c(z) =>
    z > 0 ? color.aqua : color.red

//Background Signals 
bgcolor(not mv and vr >  V  ? color.aqua   : na,75)
bgcolor(not mv and vr < -V  ? color.fuchsia: na,70)

//Plots
plot(vr,  "VRT",   c(vr), style = plot.style_columns)
plot(vr1, "VRT1",  c(vr1),linewidth=lT)
plot(vr2, "VRT2",  c(vr2),linewidth=lT)
plot(vr3, "VRT3",  c(vr3),linewidth=lT)
plot(vr4, "VRT4",  c(vr4),linewidth=lT)
plot(vr5, "VRT5",  c(vr5),linewidth=lT)

hline(0, "Mid", color.white, hline.style_dotted)

plot( V,  "Critical Value", color.yellow,trackprice = true, show_last = 1, style = plot.style_linebr)
plot(-V,  "Critival Value", color.yellow,trackprice = true, show_last = 1, style = plot.style_linebr)

Overview

Variance Ratio Test computes log returns, base period variance over a specified lookback window, and scaled multi-period variances to determine test Z-scores. The indicator plots single or multiple sampling period lines in a separate pane against configurable critical value bounds representing statistical significance levels. Users can customize the lookback length, sampling intervals, critical thresholds, and visual line options.

Details

Published by

Anderson-ALGO on GitHub

Code credit

balipour, as written in the script's header

Type

Indicator, Pine Script v4

Draws

Separate pane below the chart

Category

Volatility & bands, Mean reversion

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
===== Source =====sourceclosesrc
Lookbackint32t
Single VRT Sampling Periodint2k
Critical Valuestring5%cl
-------- Show Multiple Variance Ratio Stats --------booltruemv
Show VRT1booltruev1
  VRT1 Sampling Periodint2k1
Show VRT2booltruev2
  VRT2 Sampling Periodint4k2
Show VRT3booltruev3
  VRT3 Sampling Periodint8k3
Show VRT4booltruev4
Show all 16 settings
SettingTypeDefaultVariable
  VRT4 Sampling Periodint16k4
Show VRT5boolfalsev5
  VRT5 Sampling Periodint32k5
--- Line Thickness ---int1lT
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

261 stars

This indicator calculates standardized z-scores of price data across four different lookback periods (6, 14, 26, and 100). Standardizing data subtracts the moving average from the price and divides by the standard deviation. It applies a Double Exponential Mov

Indicator v5 Mean reversionVolatility & bands
114 stars

This indicator implements a dual-direction variation of the Williams Vix Fix oscillator in a separate pane. It normalizes price data using min-max scaling to compute both upward and downward synthetic volatility metrics across two selectable calculation modes

Indicator v4 Volatility & bandsMean reversion
Updated 1 year ago · None stated GitHub repository of Combo Williams Vix Fix (Twin)
99 stars

The Mean Squared Error indicator calculates the mean of squared differences between a source series and its EMA, averaged via a rolling buffer acting as SMA. This error metric plots as a filled red area on a separate pane, while the EMA overlays as a yellow li

Indicator v6 Volatility & bandsMean reversion
Updated 4 weeks ago · Apache-2.0 GitHub repository of Mean Squared Error (MSE)

This indicator classifies market behavior into momentum, mean-reversion, noise, or mixed regimes. It fuses four statistical predictability sensors—Variance Ratio across multiple horizons, return autocorrelation, Hurst exponent approximation, and fractal effici

Indicator v6 TrendMean reversion
Updated yesterday · MIT GitHub repository of Predictability Regime Index [WavesUnchained]

This indicator builds a channel from a Hull moving average of the source and an ATR scaled by a band multiplier, then normalizes price inside that channel into a 0 to 100 oscillator. It smooths the result with a weighted moving average and plots the line in a

Indicator v6 Mean reversionVolatility & bands
Updated 3 months ago · None stated GitHub repository of Radiant Mean Reversion Channels [Pineify]

This indicator plots trade entry and exit signals on the price chart by combining Bollinger Bands with optional filter conditions. It calculates standard Bollinger Bands along with RSI, Aroon, and moving average filters. Reversal signals trigger when price bre

Indicator v4 Volatility & bandsOscillators & momentum
Updated 2 months ago · None stated GitHub repository of Bollinger Bands Winner IND [Alorse]

More indicators

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers