Cross-Asset Correlation & Cointegration Intelligence [NikaQuant]
**Cross-Asset Correlation & Cointegration Intelligence**
Track your chart symbol against up to six comparison symbols. The script
renders **three synchronized panels** that tell you, in plain numbers:
- How coupled the basket is **right now**
- Which pairs are genuinely tradeable (and the **expected mean-reversion time**)
- How much **gross exposure** you should carry given the current regime
## What It Does
- **Intelligence Dashboard** — per-symbol grid: correlation, beta, R²,
z-score, percentile, stability, lead/lag, spread z, quality score,
hedge size, stress-vs-normal correlation delta, signal verdict
- **N×N Correlation Matrix** — full 6×6 pairwise heatmap
- **Action Center** — regime timer, flip probability, risk-budget advisor,
top-5 ranked trades, top-3 cointegrated pair setups, trade playbook
## Why It Is Original
Unlike standard correlation heatmap scripts that display a single Pearson
value per pair, this script builds a composite intelligence layer across
**three independent axes** that no retail correlation indicator combines:
**1. Asymmetric (Conditional) Correlation**
Splits history into **normal-volatility** and **stress-volatility** regimes
using an ATR-median split on the base symbol, and reports the two
correlations side by side. This exposes the *"diversification fails when
you need it"* amplification that an averaged Pearson value hides — a
documented pattern in every crisis since 1998.
**2. Cointegration + Half-Life**
For all 15 unique pairs, runs an **Engle-Granger two-step** (log-regression
then AR(1) on the residual spread) to flag which spreads are genuinely
mean-reverting. Cointegrated pairs carry an **Ornstein-Uhlenbeck half-life**
t½ = −ln(2) / ln(1 + φ) — the expected mean-reversion time in bars.
*Correlation tells you direction; cointegration tells you whether the
spread will revert.*
**3. Regime Persistence + Flip Probability**
Tracks four states (Crisis / Coupled / Mixed / Decoupled) in a **4×4 Markov
transition counter**, stores per-regime dwell times, and converts them into
flip-probability estimates for the next 10 and 30 bars. You see not just
*"we are in X"* but *"X has lasted 47 bars, historical average is 62 bars,
probability of flip in 30 bars is 55%."*
## Composite Modules
- **Crisis Clock (0–100)** — composite of average absolute correlation,
cross-sectional dispersion collapse, and tail-dependence count
- **Market Brain** — union-find clustering on positive pairwise
correlations, auto-groups symbols that move as one
- **Dispersion Trade Detector** — fires when average correlation drops
>2σ while realized volatility rises
- **Hedge Desk** — converts OLS beta into a **dollar hedge notional**
given your base position size
- **Effective-N** — correlation-adjusted diversification count (six
symbols at ρ=1.0 gives effective N = 1)
- **Risk Budget Advisor** — regime + effective-N → suggested gross
exposure percentage
- **Setup Quality Score** — composite of |corr| × R² × stability,
adjusted for regime, clock, and break
- **Action List** — scans every symbol and every pair, scores each
candidate, ranks them, surfaces the top five with type, target, score,
direction, suggested size, rationale
## Per-Symbol Metrics
- Rolling Pearson correlation across **three lookbacks** (short, medium,
long) — three-block glyph reveals timeframe divergence
- **OLS beta** from log returns, **R²** as variance explained
- **Z-score** of current correlation vs its own 200-bar distribution
- **Percentile rank** of current correlation in its own history
- **Stability** from rolling stdev of the correlation itself
- **Optimal-lag scanner** across {−5, −3, −1, 0, +1, +3, +5} offsets
- **Spread z-score** of the price ratio for pairs signaling
- **Asymmetric Δ** = ρ_stress − ρ_normal (positive = hedge fails under stress)
## How To Use It
- **Scan the Quality column first.** Anything at or above 60 with a
TRACK++ or HEDGE++ signal is a high-confidence setup.
- **Cross-check AsymΔ.** Values above +0.3 mean that "hedge" is expected
to fail under stress — avoid relying on it in a crisis.
- **Use Hedge column values** as the dollar notional to short or long
against your base position to neutralize beta.
- **Read the matrix** like a portfolio risk report. Clusters of dark-green
tiles = diversification is breaking down. Red tiles = inverse pairs.
- **In the Action Center**, start at the Risk Budget line, then work
top-down through the Action List. Cointegrated pairs marked with a
check-mark prefix show expected mean-reversion time in bars.
**Recommended timeframes:** intraday or daily charts with at least 250
bars of history across all six symbols.
**Recommended markets:** anywhere the base asset has meaningful
relationships with a benchmark basket — equity indexes vs sector ETFs,
crypto majors vs index proxies, FX vs rates and commodities.
**Avoid using when:** fewer than three symbols resolve to valid data;
during the first 250 bars after chart load; or on a symbol with gapped
or illiquid history that creates artificial correlation jumps.
## Alerts
Regime Break · Dispersion Trade Setup · New Cointegrated Pair ·
High-Quality Setup · Imminent Regime Flip · Crisis Regime Entered ·
Asymmetric Correlation Amplification · Risk Budget Reduced · Clock
Stressed/Critical · Strong Positive/Negative Correlation Crossovers
## Key Settings
- **Comparison Symbols 1–6** — the basket (autocomplete from any TV ticker)
- **Medium-Term Correlation Period** (50) — primary correlation lookback
- **Short / Long Lookbacks** (20 / 200) — timeframe-divergence glyph
- **Historical Baseline** (200) — z-score, percentile, stability, regime
dwell times, and asymmetric-correlation ATR split
- **Strong Correlation** (0.70) — threshold for strong-signal eligibility
- **Regime-Break |Z|** (2.00) — flags correlations breaking their range
- **Pairs-Trade |Spread Z|** (2.00) — pairs-trade setup threshold
- **Min R² for Trust** (0.25), **Min Stability** (0.50) — quality gates
- **Cluster Threshold** (0.60) — Market Brain grouping
- **Crisis Clock** — Stressed (60), Critical (80) thresholds
- **Base Position Size** (10,000) — drives Hedge Desk and Action sizing
- **Min Action Quality** (60) — filters the Action List
- **Risk Budget per regime** — Crisis 50%, Coupled 75%, Mixed 90%,
Decoupled 100% (all user-tunable)
- **Display** — position each of three tables independently; Compact or
Pro column density; full palette customization
## Notes
**No repainting.** All correlations, betas, and regime computations use
confirmed bars only. Regime transition counters and dwell-time arrays
update only when a bar confirms.
**Data integrity.** Six external symbol requests are made with
non-forward-looking data fetches, well within TradingView's request limit.
**Methods.** Asymmetric correlation uses log returns with indicator
weights from an ATR-median volatility split on the base asset.
Cointegration is Engle-Granger two-step: log-regression residual, then
AR(1) test. A pair is flagged as cointegrated when the AR(1) coefficient
is sufficiently negative to indicate mean-reversion. Half-life uses the
standard Ornstein-Uhlenbeck solution t½ = −ln(2) / ln(1 + φ).
**Warm-up.** The first ~250 bars after chart load are a warm-up period.
Several metrics will display "—" until enough history accumulates.
**Originality.** All calculations, signal logic, clustering,
cointegration testing, and table rendering are original. No third-party
code is reused.
Pine Script® indicator






















