Indicator · Pine Script v5 · Own pane

Factor Indicator: Correlation with Price Change

by jawauntb

This indicator measures a 20-bar rolling correlation between lagged changes in several price factors and the close change over the previous 10 bars.

View on GitHub

GitHub stars3on the repository
Pine versionv5runs as is
Lines of code147
Settings13inputs
LicenceGPL-3.0
Last update2 years ago22 May 2024

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

147 lines of Pine Script v5 from factor-correlation.pine, published under GPL-3.0. Keep the author's credit and licence lines when you reuse it.

factor-correlation.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © jawauntb

//@version=5
indicator(title="Factor Indicator: Correlation with Price Change in Next 10 Bars", shorttitle = 'FXI', overlay=false)

// Function to calculate correlation of an indicator with future price change
factorCorrelation(factor) =>
    pastFactorChange = factor[15] - factor[20] // Change in indicator over the first 5 bars of the past 20 bars
    futurePriceChange = close - close[10] // Net price change over the next 10 bars
    correlation = ta.correlation(pastFactorChange, futurePriceChange, 20) // 20-bar rolling correlation
    correlation

//13-30 EMA Calculation
short = ta.ema(close, 13)
long = ta.sma(close, 30)
crossoverFactor = short - long

// Skew Calculation
SkewLength = input(30)

deviation_max = 1.
deviation_min = 1.

alpha = 2.0/(1.0+SkewLength)

trueRange = math.max(math.max(high - low, math.abs(high - close[1])), math.abs(low - close[1]))/close[1]

deviation_max := alpha*(close > close[1] ? trueRange:0) + (1.0-alpha)*nz(deviation_max[1])
deviation_min := alpha*(close < close[1] ? trueRange:0) + (1.0-alpha)*nz(deviation_min[1])

skewValue = deviation_max/deviation_min


// Donchian Channel Calculation
length = input.int(20, minval=1)
lower = ta.lowest(length)
upper = ta.highest(length)
basis = (upper + lower) / 2.0

// Keltner Channel Calculation
lengthkc = input.int(20, minval=1)
mult = input(2.0, "Multiplier")
src = input(close, title="Source")
exp = input(true, "Use Exponential MA")
BandsStyle = input.string("Average True Range", options = ["Average True Range", "True Range", "Range"], title="Bands Style")
atrlength = input(10, "ATR Length")

esma(source, lengthk)=>
    s = ta.sma(source, lengthk)
    e = ta.ema(source, lengthk)
    exp ? e : s

kcma = esma(src, lengthkc)

// Inputs for VWAP settings
anchor = input.string(defval = "Session", title="Anchor Period",
 options=["Session", "Week", "Month", "Quarter", "Year", "Decade", "Century", "Earnings", "Dividends", "Splits"])

srcvw = input(close, title = "Source")

// Determine the start of a new period based on the selected anchor
isNewPeriod = switch anchor
    "Session"   => timeframe.change("D")
    "Week"      => timeframe.change("W")
    "Month"     => timeframe.change("M")
    "Quarter"   => timeframe.change("3M")
    "Year"      => timeframe.change("12M")
    "Decade"    => timeframe.change("12M") and year % 10 == 0
    "Century"   => timeframe.change("12M") and year % 100 == 0
    // Note: The earnings, dividends, and splits anchor types were ignored for simplicity.
    => false

float vwapValue = na

// Calculate the VWAP value
[_vwap, _, _] = ta.vwap(srcvw, isNewPeriod, 1)

vwapValue := _vwap
// Calculate the price relative to VWAP
priceRelativeToVWAP = close - vwapValue


// TWAP calculation
anchortw = input.timeframe(defval = "1D", title="Anchor Period")
srctw = input(title = "Source", defval = ohlc4)
offset = input(0, title="Offset")

twap(source, anchorChange) =>
    var prices = 0.0
    var count = 0

    if anchorChange
        prices := 0
        count := 0

    prices += src
    count += 1

    prices / count

twapValue = twap(srctw, timeframe.change(anchortw))

// Calculate the price's distance from the TWAP
priceRelativeToTwap = close - twapValue


// Correlation Calculation for the Donchian Channel's basis
correlationValueDonchian = factorCorrelation(basis)

// Correlation Calculation for the Skew
correlationValueSkew = factorCorrelation(skewValue)

// Correlation Calculation for the EMA
correlation1330EmaMaValue = factorCorrelation(crossoverFactor)

// Correlation Calculation for the Keltner Channel's MA
correlationValueKeltner = factorCorrelation(kcma)

// Correlation Calculation for the Price relative to VWAP
correlationValueVWAP = factorCorrelation(priceRelativeToVWAP)

correlationTWAP = factorCorrelation(priceRelativeToTwap)

// Plotting the Correlation of the EMA
histogramColor = correlation1330EmaMaValue >= 0 ? color.rgb(231, 228, 39) : color.rgb(154, 146, 0)
plot(correlation1330EmaMaValue, color=histogramColor, linewidth=1, title="EMA Cross Correlation")

// Plotting the Correlation of the Skew
histogramColorSkew = correlationValueSkew >= 0 ? color.rgb(4, 213, 255) : color.rgb(0, 87, 117)
plot(correlationValueSkew, color=histogramColorSkew, linewidth=1, title="Skew Correlation")

// Plotting the Correlation of the Donchian Channel's basis
histogramColorDonchian = correlationValueDonchian >= 0 ? color.rgb(38, 4, 230) : color.rgb(28, 18, 86)
plot(correlationValueDonchian, color=histogramColorDonchian, linewidth=1, title="Donchian Basis Correlation")

// Plotting the Correlation of the Keltner Channel's MA
histogramColorKeltner = correlationValueKeltner >= 0 ? color.rgb(251, 136, 3) : color.rgb(255, 136, 56)
plot(correlationValueKeltner, color=histogramColorKeltner, linewidth=1, title="Keltner MA Correlation")

// Plotting the Correlation of Price relative to VWAP
histogramColorVWAP = correlationValueVWAP >= 0 ? color.rgb(255, 154, 250) : color.rgb(240, 74, 240)
plot(correlationValueVWAP, color=histogramColorVWAP, linewidth=1, title="Price to VWAP Correlation")

// Plotting the Correlation of Price relative to TWAP
histogramColorTWAP = correlationValueVWAP >= 0 ? color.rgb(84, 255, 109) : color.rgb(27, 111, 30)
plot(correlationTWAP, color=histogramColorTWAP, linewidth=1, title="Price Relative to TWAP Correlation")

Overview

Factor Indicator: Correlation with Price Change is configured to draw in a separate pane. The factors include the gap between a 13-period EMA and a 30-period SMA, an up-versus-down true-range skew, the Donchian midpoint, and price distance from an anchored VWAP and TWAP. Settings change factor lengths, Keltner multiplier and band style, price sources, and VWAP or TWAP anchor periods. The excerpt ends before the skew correlation and any plot statements.

Details

Published by

jawauntb on GitHub

Type

Indicator, Pine Script v5

Draws

Separate pane below the chart

Category

Moving averages, Volatility & bands, Volume

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
SkewLengthint30SkewLength
lengthint20length
lengthkcint20lengthkc
Multiplierfloat2.0mult
Sourcesourceclosesrc
Use Exponential MAbooltrueexp
Bands StylestringAverage True RangeBandsStyle
ATR Lengthint10atrlength
Anchor PeriodstringSessionanchor
Sourcesourceclosesrcvw
Anchor Periodtimeframe1Danchortw
Sourcesourceohlc4srctw
Show all 13 settings
SettingTypeDefaultVariable
Offsetint0offset
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

PPO ATR Bands

by cryptorife
75 stars

PPO ATR Bands plots a percentage price oscillator in a separate pane. It compares a Hull average of typical price with a volume-weighted exponential average of Parabolic SAR, then scales three true-range bands around the slow average into matching oscillator l

Indicator v4 Oscillators & momentumMoving averages
Updated 3 years ago · GPL-3.0 GitHub repository of PPO ATR Bands

NFI v6

by koradiyakaushal
12 stars

This Pine v4 study ports early NostalgiaForInfinity V6 conditions onto the price chart. It computes two Bollinger setups, several EMAs and SMAs, RSI, MFI, a percent SMA spread labeled EWO, a 14-period choppiness value, and short and longer volume medians. Fixe

Indicator v4 Moving averagesVolatility & bands
Updated 5 years ago · MIT GitHub repository of NFI v6

This indicator plots On Balance Volume in a separate pane and can overlay a smoothing average of that series. By default it draws a 20-period SMA of OBV with Bollinger Bands set two standard deviations away, plus a fixed 10-period EMA of OBV. A fill between th

Indicator v6 VolumeVolatility & bands
Updated 5 months ago · None stated GitHub repository of On Balance Volume & Bolliner Bands

Koncord + MACD

by Following-BTC
5 stars

This indicator combines the Koncorde oscillator with a traditional Moving Average Convergence Divergence (MACD) indicator in a separate pane. It calculates Koncorde using a mixture of the Relative Strength Index (RSI), Money Flow Index (MFI), Bollinger Bands o

Indicator v5 Oscillators & momentumVolume
Updated 2 years ago · None stated GitHub repository of Koncord + MACD
4 stars

The Fakeout Filter indicator calculates a four-layer signal quality score ranging from 0 to 4 to evaluate trade setups. It assesses four conditions: volume expansion above a moving average multiple, alignment with a higher timeframe EMA trend, price move excee

Indicator v6 TrendVolume Repaints
Updated 2 months ago · MIT GitHub repository of Fakeout Filter [trugurpala]
3 stars

Buy Low Sell High Composite is a pane oscillator that normalizes RSI, a short-versus-long EMA difference, the MACD histogram, and the Money Flow Index onto a shared scale, then sums them into one composite. It plots that composite as a colored area, the MACD s

Indicator v5 Oscillators & momentumMoving averages
Updated 5 months ago · None stated GitHub repository of Buy Low Sell High Composite

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