OPEN-SOURCE SCRIPT

Stationarity Test: Dickey-Fuller & KPSS [Pinescriptlabs]

Theo PINE_LABS

📊 Kwiatkowski-Phillips-Schmidt-Shin Model Indicator & Dickey-Fuller Test 📈

This algorithm performs two statistical tests on the price spread between two selected instruments: the first from the current chart and the second determined in the settings. The purpose is to determine if their relationship is stationary. It then uses this information to generate **visual signals** based on how far the current relationship deviates from its historical average.

⚙️ Key Components:

• 🧪 ADF Test (Augmented Dickey-Fuller):** Checks if the spread between the two instruments is stationary.

• 🔬 KPSS Test (Kwiatkowski-Phillips-Schmidt-Shin):** Another test for stationarity, complementing the ADF test.

• 📏 Z-Score Calculation:** Measures how many standard deviations the current spread is from its historical mean.

• 📊 Dynamic Threshold:** Adjusts the trading signal threshold based on recent market volatility.
ảnh chụp nhanh

🔍 What the Values Mean:

The indicator displays several key values in a table:

• 📈 ADF Stationarity:** Shows "Stationary" or "Non-Stationary" based on the ADF test result.

• 📉 KPSS Stationarity:** Shows "Stationary" or "Non-Stationary" based on the KPSS test result.

• 📏 Current Z-Score:** The current Z-score of the spread.

• 🔗 Hedge Ratio:** The relationship coefficient between the two instruments.

• 🌐 Market State:** Describes the current market condition based on the Z-score.



📊 How to Interpret the Chart:

• The main chart displays the Z-score of the spread over time.

• The green and red lines represent the upper and lower thresholds for trading signals.

• The area between the **Z-score** and the thresholds is filled when a trading signal is active.

• Additional charts show the **statistics of the ADF and KPSS tests** and their critical values.
ảnh chụp nhanh

**📉 Practical Example: NVIDIA Corporation (NVDA)**

Looking at the chart for **NVIDIA Corporation (NVDA)**, we can see how the indicator applies in a real case:

1. **Main Chart (Top):**
• Shows the **historical price** of NVIDIA on a weekly scale.
• A general **uptrend** is observed with periods of consolidation.

2. **KPSS & ADF Indicator (Bottom):**
• The lower chart shows the KPSS & ADF Model indicator applied to NVIDIA.
• The **green line** represents the Z-score of the spread.
• The **green shaded areas** indicate periods where the Z-score exceeded the thresholds, generating trading signals.

3. **📋 Current Values in the Table:**
• **ADF Stationarity:** Non-Stationary
• **KPSS Stationarity:** Non-Stationary
• **Current Z-Score:** 3.45
• **Hedge Ratio:** -164.8557
• **Market State:** Moderate Volatility

4. **🔍 Interpretation:**
• A Z-score of **3.45** suggests that NVIDIA’s price is significantly above its historical average relative to **EURUSD**.
• Both the **ADF** and **KPSS** tests indicate **non-stationarity**, suggesting **caution** when using mean reversion signals at this moment.
• The market state "Moderate Volatility" indicates noticeable deviation, but not extreme.

---

**💡 Usage:**

• **When Both Tests Show Stationarity:**

• **🔼 If Z-score > Upper Threshold:** Consider **buying the first instrument** and **selling the second**.

• **🔽 If Z-score < Lower Threshold:** Consider **selling the first instrument** and **buying the second**.

• **When Either Test Shows Non-Stationarity:**

• Wait for the relationship to become **stationary** before trading.

• **Market State:**

• Use this information to evaluate **general market conditions** and adjust your trading strategy accordingly.

**Mirror Comparison of the Same as Symbol 2 🔄📊**
ảnh chụp nhanh

**📊 Table Values:**

• **Extreme Volatility Threshold:** This value is displayed when the **Z-score** exceeds **100%**, indicating **extreme deviation**. It signals a potential **trading opportunity**, as the spread has reached unusually high or low levels, suggesting a **reversion or correction** in the market.
ảnh chụp nhanh
• **Mean Reversion Threshold:** Appears when the **Z-score** begins returning towards the mean after a period of **high or extreme volatility**. It indicates that the spread between the assets is returning to normal levels, suggesting a phase of **stabilization**.

• **Neutral Zone:** Displayed when the **Z-score** is near **zero**, signaling that the spread between assets is within expected limits. This indicates a **balanced market** with no significant volatility or clear trading opportunities.

• **Low Volatility Threshold:** Appears when the **Z-score** is below **70%** of the dynamic threshold, reflecting a period of **low volatility** and market stability, indicating fewer trading opportunities.

Español:

📊 Indicador del Modelo Kwiatkowski-Phillips-Schmidt-Shin & Prueba de Dickey-Fuller 📈

Este algoritmo realiza dos pruebas estadísticas sobre la diferencia de precios (spread) entre dos instrumentos seleccionados: el primero en el gráfico actual y el segundo determinado en la configuración. El objetivo es determinar si su relación es estacionaria. Luego utiliza esta información para generar señales visuales basadas en cuánto se desvía la relación actual de su promedio histórico.

⚙️ Componentes Clave:

• 🧪 Prueba ADF (Dickey-Fuller Aumentada): Verifica si el spread entre los dos instrumentos es estacionario.

• 🔬 Prueba KPSS (Kwiatkowski-Phillips-Schmidt-Shin): Otra prueba para la estacionariedad, complementando la prueba ADF.

• 📏 Cálculo del Z-Score: Mide cuántas desviaciones estándar se encuentra el spread actual de su media histórica.

• 📊 Umbral Dinámico: Ajusta el umbral de la señal de trading en función de la volatilidad reciente del mercado.
ảnh chụp nhanh

🔍 Qué Significan los Valores:

El indicador muestra varios valores clave en una tabla:

• 📈 Estacionariedad ADF: Muestra "Estacionario" o "No Estacionario" basado en el resultado de la prueba ADF.

• 📉 Estacionariedad KPSS: Muestra "Estacionario" o "No Estacionario" basado en el resultado de la prueba KPSS.

• 📏 Z-Score Actual: El Z-score actual del spread.

• 🔗 Ratio de Cobertura: El coeficiente de relación entre los dos instrumentos.

• 🌐 Estado del Mercado: Describe la condición actual del mercado basado en el Z-score.

📊 Cómo Interpretar el Gráfico:

• El gráfico principal muestra el Z-score del spread a lo largo del tiempo.

• Las líneas verdes y rojas representan los umbrales superior e inferior para las señales de trading.

• El área entre el Z-score y los umbrales se llena cuando una señal de trading está activa.

• Los gráficos adicionales muestran las estadísticas de las pruebas ADF y KPSS y sus valores críticos.
ảnh chụp nhanh

📉 Ejemplo Práctico: NVIDIA Corporation (NVDA)

Observando el gráfico para NVIDIA Corporation (NVDA), podemos ver cómo se aplica el indicador en un caso real:

Gráfico Principal (Superior): • Muestra el precio histórico de NVIDIA en escala semanal. • Se observa una tendencia alcista general con períodos de consolidación.

Indicador KPSS & ADF (Inferior): • El gráfico inferior muestra el indicador Modelo KPSS & ADF aplicado a NVIDIA. • La línea verde representa el Z-score del spread. • Las áreas sombreadas en verde indican períodos donde el Z-score superó los umbrales, generando señales de trading.

📋 Valores Actuales en la Tabla: • Estacionariedad ADF: No Estacionario • Estacionariedad KPSS: No Estacionario • Z-Score Actual: 3.45 • Ratio de Cobertura: -164.8557 • Estado del Mercado: Volatilidad Moderada

🔍 Interpretación: • Un Z-score de 3.45 sugiere que el precio de NVIDIA está significativamente por encima de su promedio histórico en relación con EURUSD. • Tanto la prueba ADF como la KPSS indican no estacionariedad, lo que sugiere precaución al usar señales de reversión a la media en este momento. • El estado del mercado "Volatilidad Moderada" indica una desviación notable, pero no extrema.

💡 Uso:

• Cuando Ambas Pruebas Muestran Estacionariedad:

• 🔼 Si Z-score > Umbral Superior: Considera comprar el primer instrumento y vender el segundo.

• 🔽 Si Z-score < Umbral Inferior: Considera vender el primer instrumento y comprar el segundo.

• Cuando Alguna Prueba Muestra No Estacionariedad:

• Espera a que la relación se vuelva estacionaria antes de operar.

• Estado del Mercado:

• Usa esta información para evaluar las condiciones generales del mercado y ajustar tu estrategia de trading en consecuencia.

Comparativo en Espejo del Mismo Como Símbolo 2 🔄📊
ảnh chụp nhanh

📊 Valores de la Tabla:

• Umbral de Volatilidad Extrema: Este valor se muestra cuando el Z-score supera el 100%, indicando desviación extrema. Señala una posible oportunidad de trading, ya que el spread entre los activos ha alcanzado niveles inusualmente altos o bajos, lo que podría indicar una reversión o corrección en el mercado.
ảnh chụp nhanh

• Umbral de Reversión a la Media: Aparece cuando el Z-score comienza a volver hacia la media tras un período de alta o extrema volatilidad. Indica que el spread entre los activos está regresando a niveles normales, sugiriendo una fase de estabilización.

• Zona Neutral: Se muestra cuando el Z-score está cerca de cero, señalando que el spread entre activos está dentro de lo esperado. Esto indica un mercado equilibrado con ninguna volatilidad significativa ni oportunidades claras de trading.

• Umbral de Baja Volatilidad: Aparece cuando el Z-score está por debajo del 70% del umbral dinámico, reflejando un período de baja volatilidad y estabilidad del mercado, indicando menos oportunidades de trading.
regressionsstatistics
PINE_LABS
Get Access to Pinescriptlabs Indicators pinescriptlabs.com/

Mã nguồn mở

Theo tinh thần TradingView thực sự, tác giả của tập lệnh này đã xuất bản dưới dạng nguồn mở để các nhà giao dịch có thể hiểu và xác minh. Chúc mừng tác giả! Bạn có thể sử dụng miễn phí. Tuy nhiên, bạn cần sử dụng lại mã này theo Quy tắc nội bộ. Bạn có thể yêu thích nó để sử dụng nó trên biểu đồ.

Bạn muốn sử dụng tập lệnh này trên biểu đồ?

Thông báo miễn trừ trách nhiệm