OPEN-SOURCE SCRIPT
Linear Regression Channels

This indicator dynamically identifies and plots the best-fit linear regression channels based on recent pivot points, optimizing for statistical strength across user-defined depths.
How It Works (Technical Methodology)
1. Pivot Point Detection
The indicator uses Pine Script's ta.pivothigh() and ta.pivotlow() functions with a configurable sensitivity length to detect swing highs and lows. All recent pivot indices are stored in an array (limited to avoid performance issues), providing potential starting points for regression calculations.
2. Multi-Depth Evaluation
Users input comma-separated "Pivot History Depths" (e.g., "5,20,50"). For each depth:
- The script evaluates regression fits starting from the most recent pivots, up to the specified depth count.
- It calculates linear regression statistics for each possible channel originating from those pivot bars backward to the current bar.
3. Linear Regression Calculation
For each candidate channel:
- Slope (m) and intercept (b) are computed using least-squares method.
- R-squared (R²) measures goodness of fit (how well price follows the trend line).
- Standard error of the estimate is calculated to quantify volatility around the regression line.
- A composite score = R² × log(length) prioritizes stronger fits on longer periods.
4. Best-Fit Selection and Validation
- Only channels with R² ≥ user-defined minimum (default 0.5) are considered valid.
- The channel with the highest score for each depth is selected and drawn.
- This ensures the most statistically significant and relevant channels are displayed, avoiding weak or short-term noise.
5. Channel Construction
- Mean Line: The regression trend line extended slightly into the future.
- Inner Channels: ± user-configurable standard deviation multiplier (default 2.0σ) around the mean.
- Outer Bands: ±1.5× the inner deviation for additional visual context.
- Filled areas between mean and inner channels for better visibility.
- Color: Green shades for upward slopes (bullish trend), red shades for downward slopes (bearish trend).
6. Dashboard and Statistics
- Optional table in the top-right corner displays for each depth:
- Depth value
- R² (colored green if >0.7, orange otherwise)
- Slope (Beta) – positive blue for uptrend, red for downtrend
- Current Z-Score: How many standard deviations the latest close is from the expected regression value (yellow if |Z| > 2)
How to Use
Regression channels help identify trending markets, potential mean reversion, and overextension.
- Upward Channels (Green): Price above the mean may indicate strength; pullbacks to the mean or lower band offer long opportunities. Overextension above upper band could signal exhaustion.
- Downward Channels (Red): Price below the mean may indicate weakness; rallies to the mean or upper band offer short opportunities. Overextension below lower band could signal capitulation.
- High R² (>0.7): Strong trending channel – trade in direction of slope.
- Low R²: Choppy/range-bound market – avoid trend-following trades.
- Z-Score: |Z| > 2 suggests price is statistically overextended from the trend (potential reversion setup).
- Multi-Depth: Smaller depths catch short-term trends; larger depths capture major trends. Use multiple for confluence across timeframes.
Combine with volume, support/resistance, or other indicators for confirmation.
Disclaimer
This indicator is a technical analysis tool and should be used in conjunction with other forms of analysis. Past performance does not guarantee future results. Always use proper risk management.
How It Works (Technical Methodology)
1. Pivot Point Detection
The indicator uses Pine Script's ta.pivothigh() and ta.pivotlow() functions with a configurable sensitivity length to detect swing highs and lows. All recent pivot indices are stored in an array (limited to avoid performance issues), providing potential starting points for regression calculations.
2. Multi-Depth Evaluation
Users input comma-separated "Pivot History Depths" (e.g., "5,20,50"). For each depth:
- The script evaluates regression fits starting from the most recent pivots, up to the specified depth count.
- It calculates linear regression statistics for each possible channel originating from those pivot bars backward to the current bar.
3. Linear Regression Calculation
For each candidate channel:
- Slope (m) and intercept (b) are computed using least-squares method.
- R-squared (R²) measures goodness of fit (how well price follows the trend line).
- Standard error of the estimate is calculated to quantify volatility around the regression line.
- A composite score = R² × log(length) prioritizes stronger fits on longer periods.
4. Best-Fit Selection and Validation
- Only channels with R² ≥ user-defined minimum (default 0.5) are considered valid.
- The channel with the highest score for each depth is selected and drawn.
- This ensures the most statistically significant and relevant channels are displayed, avoiding weak or short-term noise.
5. Channel Construction
- Mean Line: The regression trend line extended slightly into the future.
- Inner Channels: ± user-configurable standard deviation multiplier (default 2.0σ) around the mean.
- Outer Bands: ±1.5× the inner deviation for additional visual context.
- Filled areas between mean and inner channels for better visibility.
- Color: Green shades for upward slopes (bullish trend), red shades for downward slopes (bearish trend).
6. Dashboard and Statistics
- Optional table in the top-right corner displays for each depth:
- Depth value
- R² (colored green if >0.7, orange otherwise)
- Slope (Beta) – positive blue for uptrend, red for downtrend
- Current Z-Score: How many standard deviations the latest close is from the expected regression value (yellow if |Z| > 2)
How to Use
Regression channels help identify trending markets, potential mean reversion, and overextension.
- Upward Channels (Green): Price above the mean may indicate strength; pullbacks to the mean or lower band offer long opportunities. Overextension above upper band could signal exhaustion.
- Downward Channels (Red): Price below the mean may indicate weakness; rallies to the mean or upper band offer short opportunities. Overextension below lower band could signal capitulation.
- High R² (>0.7): Strong trending channel – trade in direction of slope.
- Low R²: Choppy/range-bound market – avoid trend-following trades.
- Z-Score: |Z| > 2 suggests price is statistically overextended from the trend (potential reversion setup).
- Multi-Depth: Smaller depths catch short-term trends; larger depths capture major trends. Use multiple for confluence across timeframes.
Combine with volume, support/resistance, or other indicators for confirmation.
Disclaimer
This indicator is a technical analysis tool and should be used in conjunction with other forms of analysis. Past performance does not guarantee future results. Always use proper risk management.
오픈 소스 스크립트
트레이딩뷰의 진정한 정신에 따라, 이 스크립트의 작성자는 이를 오픈소스로 공개하여 트레이더들이 기능을 검토하고 검증할 수 있도록 했습니다. 작성자에게 찬사를 보냅니다! 이 코드는 무료로 사용할 수 있지만, 코드를 재게시하는 경우 하우스 룰이 적용된다는 점을 기억하세요.
면책사항
해당 정보와 게시물은 금융, 투자, 트레이딩 또는 기타 유형의 조언이나 권장 사항으로 간주되지 않으며, 트레이딩뷰에서 제공하거나 보증하는 것이 아닙니다. 자세한 내용은 이용 약관을 참조하세요.
오픈 소스 스크립트
트레이딩뷰의 진정한 정신에 따라, 이 스크립트의 작성자는 이를 오픈소스로 공개하여 트레이더들이 기능을 검토하고 검증할 수 있도록 했습니다. 작성자에게 찬사를 보냅니다! 이 코드는 무료로 사용할 수 있지만, 코드를 재게시하는 경우 하우스 룰이 적용된다는 점을 기억하세요.
면책사항
해당 정보와 게시물은 금융, 투자, 트레이딩 또는 기타 유형의 조언이나 권장 사항으로 간주되지 않으며, 트레이딩뷰에서 제공하거나 보증하는 것이 아닙니다. 자세한 내용은 이용 약관을 참조하세요.