OPEN-SOURCE SCRIPT
已更新 LAZARUS - Critical Transition EWS

LAZARUS ⚡ Critical Transition EWS
An Early Warning System (EWS) for detecting critical regime transitions, bifurcations, and market crashes before they fully materialize. LAZARUS monitors statistical signatures of "critical slowing down" — rising autocorrelation, variance inflation, spectral reddening, and rising skew/kurtosis — to flag when a market is approaching a tipping point.
What It Does
LAZARUS synthesizes five statistical moments into a composite z-scored Early Warning Signal (EWS). It detects when a market transitions from a stable equilibrium to a critical state where small perturbations can trigger large regime shifts. The indicator operates in three distinct states with hysteresis to prevent flickering:
The Five Statistical Pillars
Key Features
Inputs & Parameters
Core Detection
Component Weights
Signal Logic
Visualization
How to Read It
Signal Types & Alerts
Practical Usage Guidelines
Regime Change Anticipation
Risk Management
Asset-Specific Calibration
Important Notes
An Early Warning System (EWS) for detecting critical regime transitions, bifurcations, and market crashes before they fully materialize. LAZARUS monitors statistical signatures of "critical slowing down" — rising autocorrelation, variance inflation, spectral reddening, and rising skew/kurtosis — to flag when a market is approaching a tipping point.
What It Does
LAZARUS synthesizes five statistical moments into a composite z-scored Early Warning Signal (EWS). It detects when a market transitions from a stable equilibrium to a critical state where small perturbations can trigger large regime shifts. The indicator operates in three distinct states with hysteresis to prevent flickering:
- Normal (Cool Blue): Market operates within statistical equilibrium. No critical transition imminent.
- Warning (Warm Orange): Early signatures of critical slowing down detected. Volatility rising, autocorrelation increasing, distribution tails fattening. Elevated probability of regime change.
- Critical (Hot Red): Multiple statistical indicators simultaneously exceed critical thresholds. System is at or near bifurcation point. High probability of abrupt trend change, breakout, or crash.
The Five Statistical Pillars
- AR(1) Autocorrelation: First-order autocorrelation of the series. Increases as systems approach critical transitions (critical slowing down causes greater memory of previous states). Detects rising persistence in price action.
- Log-Variance: Rolling window variance of returns. Flickering and variance inflation are classic precursors to regime shifts. Captures sudden volatility clustering before visible price breakdowns.
- Absolute Skewness: Measures distributional asymmetry. Rising |skew| indicates one-sided risk building (positive or negative tail risk accumulation). Reflects underlying order flow imbalance.
- Spectral Reddening: Ratio of low-pass to high-pass variance. As critical transitions approach, low-frequency components dominate (spectral power shifts to "redder" regimes), indicating slower recovery from perturbations.
- Excess Kurtosis: "Tailedness" of the return distribution. Rising kurtosis indicates increasing probability of extreme events (leptokurtosis) beyond what normal distributions predict.
Key Features
- Dual-Window Architecture: Uses a short rolling window (W, default 50) to calculate current moments, and a long reference window (R, default 250) to establish baseline statistics. All components are z-scored against historical norms for genuine anomaly detection.
- Hysteresis State Machine: Implements exit thresholds (thWarn - hyst, thCrit - hyst) below entry thresholds to prevent rapid state flickering. Once Critical, the system maintains that state until EWS drops significantly below the entry threshold.
- Trend Bias Context: Displays directional bias (▲ uptrend / ▼ downtrend) based on price versus long-term EMA. Critical signals in the direction of the prevailing trend suggest acceleration; against the trend suggest reversal/collapse.
- Flexible Pre-Processing: Choose between log returns (standard), first differences (linear trends), or HP-filtered (business cycle extraction) depending on asset characteristics.
- Composite Histogram: Visual representation of EWS intensity with gradient coloring from cool (stable) to hot (critical).
- Transition Resolution Alerts: Unique "↯ Transition" signal fires when exiting Critical state, indicating the bifurcation has resolved (either completed its move or reversed).
Inputs & Parameters
Core Detection
- Source: Input price series (default close).
- Rolling window (short): 20–500 (default 50). Window for calculating current AR(1), variance, skew, kurtosis. Shorter = more responsive but noisier.
- Reference window (long): 100–2000 (default 250). Baseline for z-score normalization. Must be significantly longer than rolling window.
- Pre-processing: Select data transformation — log returns (standard for finance), first difference (raw deltas), or HP-filtered (cycle extraction).
Component Weights
- AR(1) weight: Contribution of autocorrelation to composite EWS.
- Variance weight: Contribution of log-variance.
- |Skew| weight: Contribution of absolute skewness.
- Spectral-red weight: Contribution of spectral reddening (low/high freq ratio).
- Kurtosis weight: Contribution of excess kurtosis.
Signal Logic
- Warning threshold (z): Z-score level to trigger Warning state (default 1.5σ).
- Critical threshold (z): Z-score level to trigger Critical state (default 2.5σ).
- Hysteresis band: Buffer below thresholds required to exit a state (default 0.3σ). Prevents rapid Normal→Warning→Normal flickering around threshold boundaries.
Visualization
- Show sub-components: Toggle visibility of individual z-scored components (z AR(1), z logVar, etc.).
- Gradient background: Toggle dynamic background coloring that intensifies with EWS heat.
- Diagnostic table: Toggle floating information panel showing current state, EWS value, component breakdowns, and trend bias.
- Composite histogram: Toggle column histogram visualization behind the main line.
- Event labels: Toggle on-chart labels for Critical entry ("⚡ CRITICAL") and Transition exit ("↯ TRANSITION").
How to Read It
- EWS Composite Line: The main oscillator plotted as a thick colored line. Values are z-scores (standard deviations from long-term mean). Above 0 = elevated statistical anomalies; below 0 = subdued/stabile.
- Color Gradient: Transitions from Cool Blue (EWS ≈ 0) through Warm Orange (approaching Warning) to Hot Red (Critical). The gradient uses the ratio EWS/thCrit to determine heat intensity.
- State Transitions:
- Enter Warning: EWS crosses above thWarn (1.5) from below.
- Enter Critical: EWS crosses above thCrit (2.5) OR crosses from Warning above thCrit.
- Exit Critical: EWS drops below (thCrit - hyst) = 2.2.
- Exit Warning: EWS drops below (thWarn - hyst) = 1.2.
- Trend Bias Indicator: Shown in diagnostic table as ▲ (uptrend) or ▼ (downtrend) based on price relative to long-term EMA. Contextualizes whether critical signals suggest trend acceleration or imminent reversal.
- Sub-Component Lines: Thin semi-transparent lines showing individual z-scores. Divergences between components (e.g., variance rising while AR(1) flat) indicate specific types of regime stress.
Signal Types & Alerts
- ⚠ Warning (Alert): Early-warning threshold crossed. Regime instability rising. First indication that system dynamics are shifting. Consider reducing position size or tightening stops.
- ⚡ Critical (Alert + Label): All EWS indicators elevated simultaneously. Phase transition imminent or underway. High conviction for significant move. Label appears below bar in red.
- ↯ Transition (Alert + Label): Exiting Critical state. The bifurcation has resolved — either the move completed, the system settled into a new regime, or the crisis passed without materializing. Label appears above bar in ice blue.
- State Persistence Counter: Internal counter tracks consecutive bars in current state. Longer duration in Critical increases probability of sustained regime change vs. temporary spike.
Practical Usage Guidelines
Regime Change Anticipation
- Enter Warning state: Reduce leverage, tighten stop-losses, prepare for volatility expansion. Do not yet assume direction (could be crash or explosive breakout).
- Enter Critical state: Consider directional positions in the direction of trend bias (▲ = long volatility/breakout continuation, ▼ = short/reversal). Or exit all positions if uncertainty is unacceptable.
- Exit Critical state (Transition signal): Reassess the new regime. If price moved significantly during Critical phase, this may mark the end of the move (take profit). If price did not move, it may indicate a "false alarm" or aborted transition.
Risk Management
- Use Critical signals as automatic trading halts for mean-reversion strategies (critical transitions destroy MR edge).
- Use Warning signals to reduce Kelly criterion / position sizing by 50% or more.
- Combine with trend-following systems: LAZARUS Critical + Trend Bias ▲ = high-conviction long continuation. LAZARUS Critical + Trend Bias ▼ = imminent collapse signal.
Asset-Specific Calibration
- High-volatility crypto: Lower thresholds (Warn 1.2, Crit 2.0) to catch earlier signals in naturally noisy data.
- Low-volatility forex/indices: Raise thresholds (Warn 1.8, Crit 3.0) to avoid false positives from normal market drift.
- First-difference mode: Use for non-stationary series with strong linear trends (certain commodities).
- HP-filtered mode: Use for removing business cycle effects in equity indices when looking for crashes specific to short-term dynamics.
Important Notes
- Critical Slowing Down Theory: This indicator is grounded in dynamical systems theory. As systems approach bifurcation points (tipping points), they exhibit slower recovery from perturbations, causing increased autocorrelation and variance, and shifting spectral power to lower frequencies. LAZARUS detects these pre-cursor patterns statistically.
- Z-Score Calculation: All components are normalized against the long reference window (R), not the short window. This means the indicator asks: "Are current statistical properties anomalous compared to the last 250 bars?" rather than "Are they high in absolute terms?"
- Hysteresis Necessity: Without the hysteresis band (default 0.3σ), markets hovering near 1.5σ would flicker between Normal and Warning every tick, creating alert spam. The state machine requires EWS to drop 0.3σ below the entry threshold to exit, ensuring stable state classification.
- Log Variance Guard: Variance calculations use max(variance, 1e-12) to prevent log(0) errors in flat markets. If 10+ consecutive bars have identical prices, variance floor prevents crash.
- AR(1) Interpretation: In efficient markets, AR(1) ≈ 0 (no serial correlation). As AR(1) rises toward 1.0, the market "remembers" its previous moves increasingly — a mathematical signature of approaching criticality (slowing down).
- Spectral Reddening Mechanics: The script separates the signal into low-pass (EMA-smoothed) and high-pass (residual) components. As critical transitions approach, the low-pass component captures increasingly more variance relative to high-pass, indicating the system is dominated by slow-moving forces rather than fast noise.
- No Repainting: Uses confirmed close prices and barstate-based calculations. The "bars in state" counter tracks historical persistence accurately.
發行說明
Made Bidirectional發行說明
Fixed Labels發行說明
optimized logic to improve accuracy 開源腳本
秉持TradingView一貫精神,這個腳本的創作者將其設為開源,以便交易者檢視並驗證其功能。向作者致敬!您可以免費使用此腳本,但請注意,重新發佈代碼需遵守我們的社群規範。
免責聲明
這些資訊和出版物並非旨在提供,也不構成TradingView提供或認可的任何形式的財務、投資、交易或其他類型的建議或推薦。請閱讀使用條款以了解更多資訊。
開源腳本
秉持TradingView一貫精神,這個腳本的創作者將其設為開源,以便交易者檢視並驗證其功能。向作者致敬!您可以免費使用此腳本,但請注意,重新發佈代碼需遵守我們的社群規範。
免責聲明
這些資訊和出版物並非旨在提供,也不構成TradingView提供或認可的任何形式的財務、投資、交易或其他類型的建議或推薦。請閱讀使用條款以了解更多資訊。