OPEN-SOURCE SCRIPT
Fair Value Lead-Lag Model [BackQuant]

Fair Value Lead-Lag Model [BackQuant]
A cross-asset model that estimates where price "should" be relative to a chosen reference series, then tracks the deviation as a normalized oscillator. It helps you answer two questions: 1) is the asset rich or cheap vs its driver, and 2) is the driver leading or lagging price over the next N bars.
Concept in one paragraph
Many assets co-move with a macro or sector driver. Think BTC vs DXY, gold vs real yields, a stock vs its sector ETF. This tool builds a rolling fair value of the charted asset from a reference series and shows how far price is above or below that fair value in standard deviation units. You can shift the reference forward or backward to test who leads whom, then use the deviation and its bands to structure mean-reversion or trend-following ideas.
What the model does
Why this is useful
How to use it step by step
Reading the display
Parameter tips
Playbook examples
Caveats
Bottom line
This tool turns a loose cross-asset intuition into a quantified, visual fair value map. It gives you a consistent way to find rich or cheap conditions, time mean-reversion toward a statistically grounded target, and confirm or fade trends when the driver agrees.
A cross-asset model that estimates where price "should" be relative to a chosen reference series, then tracks the deviation as a normalized oscillator. It helps you answer two questions: 1) is the asset rich or cheap vs its driver, and 2) is the driver leading or lagging price over the next N bars.
Concept in one paragraph
Many assets co-move with a macro or sector driver. Think BTC vs DXY, gold vs real yields, a stock vs its sector ETF. This tool builds a rolling fair value of the charted asset from a reference series and shows how far price is above or below that fair value in standard deviation units. You can shift the reference forward or backward to test who leads whom, then use the deviation and its bands to structure mean-reversion or trend-following ideas.
What the model does
- Reference mapping: Pulls a reference symbol at a chosen timeframe, with an optional lead or lag in bars to test causality.
- Fair value engine: Converts the reference into a synthetic fair value of the chart using one of four methods:
Ratio: price/ref with a rolling average ratio. Good when the relationship is proportional.
Spread: price minus ref with a rolling average spread. Good when the relationship is additive.
Z-Score: normalizes both series, aligns on standardized units, then re-projects to price space. Good when scale drifts.
Beta-Adjusted: rolling regression style. Uses covariance and variance to compute beta, then builds a fair value = mean(price) + beta * (ref − mean(ref)).
- Deviation and bands: Computes a z-scored deviation of price vs fair value and plots sigma bands (±1, ±2, ±3) around the fair value line on the chart.
- Correlation context: Shows rolling correlation so you can judge if deviations are meaningful or just noise when co-movement is weak.
- Visuals:
- Fair value line on price chart with sigma envelopes.
- Deviation as a column oscillator and optional line.
- Threshold shading beyond user-set upper and lower levels.
- Summary table with reference, deviation, status, correlation, and method.
- Fair value line on price chart with sigma envelopes.
Why this is useful
- Mean reversion framework: When correlation is healthy and deviation stretches beyond your sigma threshold, probability favors reversion toward fair value. This is classic pairs logic adapted to a driver and a target.
- Trend confirmation: If price rides the fair value line and deviation stays modest while correlation is positive, it supports trend persistence. Pullbacks to negative deviation in an uptrend can be buyable.
- Lead-lag discovery: Shift the reference forward by +N bars. If correlation improves, the reference tends to lead. Shift backward for the reverse. Use the best setting for planning early entries or hedges.
- Regime detection: Large persistent deviations with falling correlation hint at regime change. The relationship you relied on may be breaking down, so reduce confidence or switch methods.
How to use it step by step
- Pick a sensible reference: Choose a macro, index, currency, or sector driver that logically explains the asset’s moves. Example: gold with DXY, a semiconductor stock with SOXX.
- Test lead-lag: Nudge Lead/Lag Periods to small positive values like +1 to +5 to see if the reference leads. If correlation improves, keep that offset. If correlation worsens, try a small negative value or zero.
- Select a method:
Start with Beta-Adjusted when the relationship is approximately linear with drift.
Use Ratio if the assets usually move in proportional terms.
Use Spread when they trade around a level difference.
Use Z-Score when scales wander or volatility regimes shift.
- Tune windows:
Rolling Window controls how quickly fair value adapts. Shorter equals faster but noisier.
Normalization Period controls how deviations are standardized. Longer equals stabler sigma sizing.
Correlation Length controls how co-movement is measured. Keep it near the fair value window.
- Trade the edges:
Mean reversion idea: Wait for deviation beyond your Upper or Lower Threshold with positive correlation. Fade back toward fair value. Exit at the fair value line or the next inner sigma band.
Trend idea: In an uptrend, buy pullbacks when deviation dips negative but correlation remains healthy. In a downtrend, sell bounces when deviation spikes positive.
- Read the table: Deviation shows how many sigmas you are from fair value. Status tells you overvalued or undervalued. Correlation color hints confidence. Method tells you the projection style used.
Reading the display
- Fair value line on price chart: the model’s estimate of where price should trade given the reference, updated each bar.
- Sigma bands around fair value: a quick sense of residual volatility. Reversions often target inner bands first.
- Deviation oscillator: above zero means rich vs fair value, below zero means cheap. Color bins intensify with distance.
- Correlation line (optional): scale is folded to match thresholds. Higher values increase trust in deviations.
Parameter tips
- Start with Rolling Window 20 to 30, Normalization Period 100, Correlation Length 50.
- Upper and Lower Threshold at ±2.0 are classic. Tighten to ±1.5 for more signals or widen to ±2.5 to focus on outliers.
- When correlation drifts below about 0.3, treat deviations with caution. Consider switching method or reference.
- If the fair value line whipsaws, increase Rolling Window or move to Beta-Adjusted which tends to be smoother.
Playbook examples
- Pairs-style reversion: Asset is +2.3 sigma rich vs reference, correlation 0.65, trend flat. Short the deviation back toward fair value. Cover near the fair value line or +1 sigma.
- Pro-trend pullback: Uptrend with correlation 0.7. Deviation dips to −1.2 sigma while price sits near the −1 sigma band. Buy the dip, target the fair value line, trail if the line is rising.
- Lead-lag timing: Reference leads by +3 bars with improved correlation. Use reference swings as early cues to anticipate deviation turns on the target.
Caveats
- The model assumes a stable relationship over the chosen windows. Structural breaks, policy shocks, and index rebalances can invalidate recent history.
- Correlation is descriptive, not causal. A strong correlation does not guarantee future convergence.
- Do not force trades when the reference has low liquidity or mismatched hours. Use a reference timeframe that captures real overlap.
Bottom line
This tool turns a loose cross-asset intuition into a quantified, visual fair value map. It gives you a consistent way to find rich or cheap conditions, time mean-reversion toward a statistically grounded target, and confirm or fade trends when the driver agrees.
Скрипт с открытым кодом
В истинном духе TradingView автор этого скрипта опубликовал его с открытым исходным кодом, чтобы трейдеры могли понять, как он работает, и проверить на практике. Вы можете воспользоваться им бесплатно, но повторное использование этого кода в публикации регулируется Правилами поведения.
Check out whop.com/signals-suite for Access to Invite Only Scripts!
Отказ от ответственности
Все виды контента, которые вы можете увидеть на TradingView, не являются финансовыми, инвестиционными, торговыми или любыми другими рекомендациями. Мы не предоставляем советы по покупке и продаже активов. Подробнее — в Условиях использования TradingView.
Скрипт с открытым кодом
В истинном духе TradingView автор этого скрипта опубликовал его с открытым исходным кодом, чтобы трейдеры могли понять, как он работает, и проверить на практике. Вы можете воспользоваться им бесплатно, но повторное использование этого кода в публикации регулируется Правилами поведения.
Check out whop.com/signals-suite for Access to Invite Only Scripts!
Отказ от ответственности
Все виды контента, которые вы можете увидеть на TradingView, не являются финансовыми, инвестиционными, торговыми или любыми другими рекомендациями. Мы не предоставляем советы по покупке и продаже активов. Подробнее — в Условиях использования TradingView.