π 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.
π 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.
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 ππ**
**π 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. β’ **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.
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.
π 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 ππ
π 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.
β’ 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.
"Access our premium algorithms π»! Invite us for a beer at buymeacoffee.com/pinescriptlabs, then add your TradingView username in the 'Say something nice' section and send us a private message."
In true TradingView spirit, the author of this script has published it open-source, so traders can understand and verify it. Cheers to the author! You may use it for free, but reuse of this code in publication is governed by House rules. You can favorite it to use it on a chart.
"Access our premium algorithms π»! Invite us for a beer at buymeacoffee.com/pinescriptlabs, then add your TradingView username in the 'Say something nice' section and send us a private message."
Also on:
Disclaimer
The information and publications are not meant to be, and do not constitute, financial, investment, trading, or other types of advice or recommendations supplied or endorsed by TradingView. Read more in the Terms of Use.