OPEN-SOURCE SCRIPT

Granger Causality Flow Indicator

191
Granger Causality Flow Indicator (GC Flow)

█ OVERVIEW

The Granger Causality Flow Indicator (GC Flow) attempts to quantify the potential predictive relationship between two user-selected financial instruments (Symbol X and Symbol Y). In essence, it explores whether the past values of one series (e.g., Symbol X) can help explain the current value of another series (e.g., Symbol Y) better than Y's own past values alone.

This indicator provides a "Granger Causality Score" (GC Score) for both directions (X → Y and Y → X). A higher score suggests a stronger statistical linkage where one series may lead or influence the other. The indicator visualizes this "flow" of potential influence through background colors and on-chart text.

Important Note: "Granger Causality" does not imply true economic or fundamental causation. It is a statistical concept indicating predictive power or information flow. This implementation also involves simplifications (notably, using AR(1) models) due to the complexities of full Vector Autoregression (VAR) models in Pine Script®.

█ HOW IT WORKS

The indicator's methodology is based on comparing the performance of Autoregressive (AR) models:

1. Data Preprocessing:
  • Fetches historical close prices for two user-defined symbols (X and Y).
  • Optionally applies first-order differencing (`price - price[1]`) to the series. Differencing is a common technique to achieve a proxy for stationarity, which is an underlying assumption for Granger Causality tests. Non-stationary series can lead to spurious correlations.


2. Autoregressive (AR) Models (Simplified to AR(1)):
Due to Pine Script's current limitations for complex multivariate time series models, this indicator uses simplified AR(1) models (where the current value is predicted by its immediately preceding value).
  • Restricted Model (for Y → Y): Predicts the target series (e.g., Y) using only its own past value (Y[t-1]).
    [indent=1]`Y[t] = c_R + a_R * Y[t-1] + residuals_R`[/indent]
    The variance of `residuals_R` (Var_R) is calculated.
  • Unrestricted Model (Proxy for X → Y): To test if X Granger-causes Y, the indicator examines if the past values of X (X[t-1]) can explain the residuals from the restricted model of Y.
    [indent=1]`residuals_R[t] = c_UR' + b_UR * X[t-1] + residuals_UR`[/indent]
    The variance of these final `residuals_UR` (Var_UR) is calculated.

The same process is repeated to test if Y Granger-causes X.

3. Granger Causality (GC) Score Calculation:
The GC Score quantifies the improvement in prediction from adding the other series' past values. It's calculated as:
[indent=1]`GC Score = 1 - (Var_UR / Var_R)`[/indent]
  • A score closer to 1 suggests that the "causing" series significantly reduces the unexplained variance of the "target" series (i.e., Var_UR is much smaller than Var_R), indicating stronger Granger causality.
  • A score near 0 (or capped at 0 if Var_UR >= Var_R) suggests little to no improvement in prediction.
  • The score is calculated over a rolling `Calculation Window`.


Pine Script® Snippet (Conceptual GC Score Logic):
Pine Script®
// Conceptual representation of GC Score calculation // var_R: Variance of residuals when Y is predicted by Y[lag] // var_UR: Variance of residuals when Y's AR(1) residuals are predicted by X[lag] score = 0.0 if var_R > 1e-9 // Avoid division by zero score := 1.0 - (var_UR / var_R) score := score < 0 ? 0 : score // Ensure score is not negative


4. Determining Causal Flow:
The calculated GC Scores for X → Y and Y → X are compared against a user-defined `Significance Threshold for GC Score`.
  • If GC_X→Y > threshold AND GC_Y→X > threshold: Bidirectional flow.
  • If GC_X→Y > threshold only: X → Y flow.
  • If GC_Y→X > threshold only: Y → X flow.
  • Otherwise: No significant flow.


█ HOW TO USE IT

Interpreting the Visuals:
  • Background Color:Green: Indicates X → Y (Symbol 1 potentially leads Symbol 2).
    Orange: Indicates Y → X (Symbol 2 potentially leads Symbol 1).
    Blue: Indicates Bidirectional influence.
    Gray: No significant Granger causality detected based on the threshold.
  • Data Window Plots: The actual GC Scores for X → Y (blue) and Y → X (red) are plotted and visible in TradingView's Data Window. A dashed gray line shows your `Significance Threshold`.
  • On-Chart Table (Last Bar): Displays the currently detected causal direction text (e.g., "BTCUSDT → QQQ").


Potential Applications:
  • Intermarket Analysis: Explore potential lead-lag relationships between different asset classes (e.g., commodities and equities, bonds and currencies).
  • Pair Trading Components: Identify if one component of a potential pair tends to lead the other.
  • Confirmation Tool: Use alongside other analyses to see if a move in one asset might foreshadow a move in another.


Considerations:
  • Symbol Choice: Select symbols that have a plausible economic or market relationship.
  • Stationarity: Granger Causality tests ideally require stationary time series. The `Use Differencing` option is a simple proxy. True stationarity testing is complex. Non-stationary data can yield misleading results.
  • Lag Order (p): This indicator is fixed at p=1 due to Pine Script® limitations. In rigorous analysis, selecting the optimal lag order is crucial.
  • Calculation Window: Shorter windows are more responsive but may be noisier. Longer windows provide smoother scores but lag more.
  • Significance Threshold: Adjust this based on your desired sensitivity for detecting causal links. There's no universally "correct" threshold; it depends on the context and noise level of the series.


█ INPUTS
  • Symbol 1 (X): The first symbol in the analysis.
  • Symbol 2 (Y): The second symbol (considered the target when testing X → Y).
  • Use Differencing: If true, applies first-order differencing to both series as a proxy for stationarity.
  • Calculation Window (N): Lookback period for AR model coefficient estimation and variance calculations.
  • Lag Order (p): Currently fixed at 1. This defines the lag used (e.g., X[1], Y[1]) in the AR models.
  • Significance Threshold for GC Score: A value between 0.01 and 0.99. The calculated GC Score must exceed this to be considered significant.


█ VISUALIZATION
  • Background Color: Dynamically changes based on the detected Granger causal flow (Green for X → Y, Orange for Y → X, Blue for Bidirectional, Gray for None).
  • GC Scores (Data Window):Blue Plot: GC Score for X → Y.
    Red Plot: GC Score for Y → X.
  • Significance Threshold Line: A dashed gray horizontal line plotted at the level of your input threshold.
  • On-Chart Table: Displayed on the top-right (on the last bar), showing the current causal direction text.


█ ALERTS
The indicator can generate alerts for:
  • Emergence of X → Y causality.
  • Emergence of Y → X causality.
  • General change or cessation of a previously detected causal relationship.


█ IMPORTANT DISCLAIMERS & LIMITATIONS
  • Correlation vs. Causation: Granger causality measures predictive power, not true underlying economic causation. A strong GC Score doesn't prove one asset *causes* another to move, only that its past values improve predictions.
  • Stationarity Assumption: While differencing is offered, it's a simplified approach. Non-stationary data can lead to spurious (false) Granger causality detection.
  • Model Simplification (AR(1)): This script uses AR(1) models for simplicity. Real-world relationships can involve more complex dynamics and higher lag orders. The fixed lag of p=1 is a significant constraint.
  • Sensitivity to Parameters: Results can be sensitive to the chosen symbols, calculation window, differencing option, and significance threshold.
  • No Statistical Significance Testing (p-values): This indicator uses a direct threshold on the GC Score itself, not a formal statistical test (like an F-test producing p-values) typically found in econometric software.
  • Use this indicator as an exploratory tool within a broader analytical framework. Do not rely on it as a standalone basis for trading decisions.


█ CREDITS & LICENSE
  • Author: mastertop (Twitter: x.com/Top_Astray)
  • Version: 1.0 (Released: 2025-05-08)
  • This source code is subject to the terms of the Mozilla Public License 2.0 at mozilla.org/MPL/2.0/
  • © mastertop, 2025

Declinazione di responsabilità

Le informazioni ed i contenuti pubblicati non costituiscono in alcun modo una sollecitazione ad investire o ad operare nei mercati finanziari. Non sono inoltre fornite o supportate da TradingView. Maggiori dettagli nelle Condizioni d'uso.