OPEN-SOURCE SCRIPT

Stationarity Test: Dickey-Fuller & KPSS [Pinescriptlabs]


πŸ“Š 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.
snapshot

πŸ” 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.
snapshot

**πŸ“‰ 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 πŸ”„πŸ“Š**
snapshot

**πŸ“Š 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.
snapshot
β€’ **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.
snapshot

πŸ” 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.
snapshot

πŸ“‰ 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 πŸ”„πŸ“Š
snapshot

πŸ“Š 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.
snapshot

β€’ 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.

Disclaimer