Indicator · Pine Script v4 · Own pane

Durbin Watson Test

by Anderson-ALGO· code credited to balipour

This indicator calculates the Durbin-Watson test statistic to measure serial autocorrelation in log returns over a user-defined lookback period.

View on GitHub

GitHub stars9on the repository
Pine versionv4older, still runs
Lines of code176
Settings3inputs
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

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

Durbin Watson Test Statistic.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("Durbin Watson Test [pig]", "BA🐷 DWT", false, format.inherit, precision=2, resolution = "")

//Background Color
bgcolor(#000000c0)

//Inputs
src = input(close,"===== Source =====",     input.source)
len = input(   30,"Lookback",               input.integer, minval = 6, step   = 2)
tk  = input(    1,"--- Line Thickness ---", input.integer, options=[1,2,3])

//Linear Regression: Runs an Regression on barindex and log returns
y = log(src/src[1]) //Log returns
x = bar_index
sumy  = sum(y,len)
sumx  = sum(x,len)
sumxy = sum(x*y,len)
sumx2 = sum(pow(x,2),len)
sumy2 = sum(pow(y,2),len)

//slope
B = ((len*sumxy) - sumx*sumy)/((len*sumx2) - pow(sumx,2))

//Intercept
a = ((sumy - B*sumx)/len)

//Linear Regression Function
Y = B*x + a

//Residual Function: Substract the prediction result generated from linear regression from the data
f(n) =>
    y[n] - (B*(x-n) + a)

//Sum of squared of the first difference error terms
d = array.new_float(0)
for i = 0 to len - 2
    array.push(d, pow(f(i+1) - f(i),2))

sumd = array.sum(d)

//Sum of squared of all error terms
e = array.new_float(0)
for i = 0 to len - 1
    array.push(e,pow(f(i),2))

sume = array.sum(e)

//Durbin Watson Stats, Value between 0 and 4. 
dw = sumd /sume

//Significance level based on N of observation. 0.05 significance Durbin Watson Table below
//Between Lower and Upper Threshold means no significant first order autocorrelation, outside threshold means significant first order autocorrelation
l = 0.0
if len == 6
    l := 0.61
if len == 7
    l := 0.70
if len == 8
    l := 0.76
if len == 9
    l := 0.82
if len == 10
    l := 0.88
if len == 11
    l := 0.93
if len == 12
    l := 0.97
if len == 13
    l := 1.01
if len == 14
    l := 1.05
if len == 15
    l := 1.08
if len == 16
    l := 1.10
if len == 17
    l := 1.13
if len == 18
    l := 1.16
if len == 19
    l := 1.18
if len == 20
    l := 1.20
if len == 21
    l := 1.22
if len == 22
    l := 1.24
if len == 23
    l := 1.26
if len == 24
    l := 1.27
if len == 25
    l := 1.29
if len == 26
    l := 1.30
if len == 27
    l := 1.32
if len == 28
    l := 1.33
if len == 29
    l := 1.34
if len == 30
    l := 1.35
if len == 31
    l := 1.36
if len == 32
    l := 1.37
if len == 33
    l := 1.38
if len == 34
    l := 1.39
if len == 35
    l := 1.40
if len == 36
    l := 1.41
if len == 37
    l := 1.42
if len == 38
    l := 1.43
if len == 39
    l := 1.43
if len == 40
    l := 1.44
if len > 40 and len <= 45
    l := 1.48
if len > 45 and len <= 50
    l := 1.50
if len > 50 and len <= 55
    l := 1.53
if len > 55 and len <= 60
    l := 1.55
if len > 60 and len <= 65
    l := 1.57
if len > 65 and len <= 70
    l := 1.58
if len > 70 and len <= 75
    l := 1.60
if len > 75 and len <= 80
    l := 1.61
if len > 80 and len <= 85
    l := 1.62
if len > 85 and len <= 90
    l := 1.63
if len > 90 and len <= 95
    l := 1.64
if len > 95 and len <= 100
    l := 1.65
if len > 100 and len <= 150
    l := 1.72
if len > 150 and len <= 200
    l := 1.76
if len > 200 and len <= 250
    l := 1.79
if len > 250 and len <= 300
    l := 1.80
if len > 300
    l := 1.82

//Upper Threshold eqauls to 4 - lower threshold due to symmetry
ut = 4 - l

//Colors
c = dw > 2 ? color.white : dw < 2 ? color.orange : na

bgcolor(dw > ut ? color.aqua: na,75)
bgcolor(dw < l  ? color.red : na,70)

//Plots
plot(dw, "DWS", color = c, transp=0, linewidth=tk, style = plot.style_stepline)

hline(2, "Mid",             color.gray, hline.style_solid) //Above 2 -autocorrelation, Below 2 +autocorrelation
plot(l,  "Lower threshold", color.fuchsia, trackprice = true, show_last = 1, style = plot.style_linebr)
plot(ut, "Upper threshold", color.lime,    trackprice = true, show_last = 1, style = plot.style_linebr)

Overview

Durbin Watson Test performs a linear regression of log returns against bar indices to extract residuals and computes the ratio of squared residual differences to total squared residuals. Plotted in a separate pane, the resulting value ranges from 0 to 4. Background shading highlights statistically significant positive or negative autocorrelation based on built-in significance thresholds. Key inputs allow adjusting the source price, lookback length, and line thickness.

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

Trend

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
Lookbackint30len
--- Line Thickness ---int1tk
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

Schaff Trend Cycle

by everget
948 stars

This indicator plots the Schaff Trend Cycle in a separate pane. It subtracts a slow exponential moving average from a fast one, applies a stochastic cycle twice, and smooths each result to form a 0–100 oscillator. Line color follows the slope, or the upper and

Indicator v4 Oscillators & momentumTrend
Updated 10 days ago · GPL-3.0 GitHub repository of Schaff Trend Cycle

This indicator plots a Supertrend-based trend-following setup in a separate pane and skips conditions it treats as a sideways market. A volatility range is built from an ATR value, with RMA, SMA, EMA, or WMA smoothing, or from a fixed point distance. Optional

Indicator v5 TrendVolatility & bands
Updated 1 year ago · MPL-2.0 GitHub repository of Trend Following Setup - Sideways Market Skipper

Beep Boop

by magic8bot
409 stars

This indicator calculates a modified MACD oscillator and signal line alongside a trend EMA filter, plotting the output as a stylized column histogram in a separate pane. Instead of plotting true MACD distance, it quantifies positive and negative histogram mome

Indicator v4 Oscillators & momentumTrend
Updated 3 years ago · MIT GitHub repository of Beep Boop

[RS]Standardized Trend Map

by ricardosantos79
261 stars

Standardized Trend Map calculates series momentum relative to active price range across 40 distinct lookback periods ranging from 2 to 80 bars on an exponential moving average source. Each standardized calculation rounds to an integer values of -1, 0, or 1 to

Indicator v4 TrendOscillators & momentum
Updated 4 years ago · None stated GitHub repository of [RS]Standardized Trend Map

ADX Histogram

by harryguiacorn
219 stars

This indicator calculates and displays the Average Directional Index (ADX) as a column histogram in a separate pane. It evaluates market trend strength by calculating directional movement metrics based on specified smoothing and DI length inputs. When the ADX

Indicator v5 TrendOscillators & momentum
Updated 1 year ago · None stated GitHub repository of ADX Histogram

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