Editors' picks
OPEN-SOURCE SCRIPT
Updated

Multi-Anchored Linear Regression Channels [TANHEF]

8 091
Overview:

The 'Multi-Anchored Linear Regression Channels [TANHEF]' plots multiple dynamic regression channels (or bands) with unique selectable calculation types for both regression and deviation. It leverages a variety of techniques, customizable anchor sources to determine regression lengths, and user-defined criteria to highlight potential opportunities.

Before getting started, it's worth exploring all sections, but make sure to review the Setup & Configuration section in particular. It covers key parameters like anchor type, regression length, bias, and signal criteria—essential for aligning the tool with your trading strategy.

Key Features:

⯁ Multi-Regression Capability:
  • Plot up to three distinct regression channels and/or bands simultaneously, each with customizable anchor types to define their length.

snapshot
⯁ Regression & Deviation Methods:
  • Regressions Types:
    • Standard: Uses ordinary least squares to compute a simple linear trend by averaging the data and deriving a slope and endpoints over the lookback period.
    • Ridge: Introduces L2 regularization to stabilize the slope by penalizing large coefficients, which helps mitigate multicollinearity in the data.
    • Lasso: Uses L1 regularization through soft-thresholding to shrink less important coefficients, yielding a simpler model that highlights key trends.
    • Elastic Net: Combines L1 and L2 penalties to balance coefficient shrinkage and selection, producing a robust weighted slope that handles redundant predictors.
    • Huber: Implements the Huber loss with iteratively reweighted least squares (IRLS) and EMA-style weights to reduce the impact of outliers while estimating the slope.
    • Least Absolute Deviations (LAD): Reduces absolute errors using iteratively reweighted least squares (IRLS), yielding a slope less sensitive to outliers than squared-error methods.
    • Bayesian Linear: Merges prior beliefs with weighted data through Bayesian updating, balancing the prior slope with data evidence to derive a probabilistic trend.

  • Deviation Types:
    • Regressive Linear (Reverse): In reverse order (recent to oldest), compute weighted squared differences between the data and a line defined by a starting value and slope.
    • Progressive Linear (Forward): In forward order (oldest to recent), compute weighted squared differences between the data and a line defined by a starting value and slope.
    • Balanced Linear: In forward order (oldest to newest), compute regression, then pair to source data in reverse order (newest to oldest) to compute weighted squared differences.
    • Mean Absolute: Compute weighted absolute differences between each data point and its regression line value, then aggregate them to yield an average deviation.
    • Median Absolute: Determine the weighted median of the absolute differences between each data point and its regression line value to capture the central tendency of deviations.
    • Percent: Compute deviation as a percentage of a base value by multiplying that base by the specified percentage, yielding symmetric positive and negative deviations.
    • Fitted: Compare a regression line with high and low series values by computing weighted differences to determine the maximum upward and downward deviations.
    • Average True Range: Iteratively compute the weighted average of absolute differences between the data and its regression line to yield an ATR-style deviation measure.

  • Bias:
    • Bias: Applies EMA or inverse-EMA style weighting to both Regression and/or Deviation, emphasizing either recent or older data.

snapshot
⯁ Customizable Regression Length via Anchors:
  • Anchor Types:
    • Fixed: Length.
    • Bar-Based: Bar Highest/Lowest, Volume Highest/Lowest, Spread Highest/Lowest.
    • Correlation: R Zero, R Highest, R Lowest, R Absolute.
    • Slope: Slope Zero, Slope Highest, Slope Lowest, Slope Absolute.
    • Indicator-Based: Indicators Highest/Lowest (ADX, ATR, BBW, CCI, MACD, RSI, Stoch).
    • Time-Based: Time (Day, Week, Month, Quarter, Year, Decade, Custom).
    • Session-Based: Session (Tokyo, London, New York, Sydney, Custom).
    • Event-Based: Earnings, Dividends, Splits.
    • External: Input Source Highest/Lowest.

  • Length Selection:
    • Maximum: The highest allowed regression length (also fixed value of “Length” anchor).
    • Minimum: The shortest allowed length, ensuring enough bars for a valid regression.
    • Step: The sampling interval (e.g., 1 checks every bar, 2 checks every other bar, etc.). Increasing the step reduces the loading time, most applicable to “Slope” and “R” anchors.

  • Adaptive lookback:
    • Adaptive Lookback: Enable to display regression regardless of too few historical bars.

snapshot
⯁ Selecting Bias:
  • Bias applies separately to regression and deviation.
  • Positive values emphasize recent data (EMA-style), negative invert, and near-zero maintains balance. (e.g., a length 100, bias +1 gives the newest price ~7× more weight than the oldest).
  • It's best to apply bias to both (regression and deviation) or just the deviation. Biasing only regression may distort deviation visually, while biasing both keeps their relationship intuitive. Using bias only for deviation scales it without altering regression, offering unique analysis.

snapshot
⯁ Scale Awareness:
  • Supports linear and logarithmic price scaling, the regression and deviations adjust accordingly.

snapshot
⯁ Signal Generation & Alerts:
  • Customizable entry/exit signals and alerts, detailed in the dedicated section below.

⯁ Visual Enhancements & Real-World Examples:
  • Optional on-chart table display summarizing regression input criteria (display type, anchor type, source, regression type, regression bias, deviation type, deviation bias, deviation multiplier) and key calculated metrics (regression length, slope, Pearson’s R, percentage position within deviations, etc.) for quick reference.


Understanding R (Pearson Correlation Coefficient):

Pearson’s R gauges data alignment to a straight-line trend within the regression length:
  • Range: R varies between –1 and +1.
  • R = +1 → Perfect positive correlation (strong uptrend).
  • R = 0 → No linear relationship detected.
  • R = –1 → Perfect negative correlation (strong downtrend).

This script uses Pearson’s R as an anchor, adjusting regression length to target specific R traits. Strong R (±1) follows the regression channel, while weak R (0) shows inconsistency.
snapshot

Understanding the Slope:

The slope is the direction and rate at which the regression line rises or falls per bar:
  • Positive Slope (>0): Uptrend – Steeper means faster increase.
  • Negative Slope (<0): Downtrend – Steeper means sharper drop.
  • Zero or Near-Zero Slope: Sideways – Indicating range-bound conditions.

This script uses highest and lowest slope as an anchor, where extremes highlight strong moves and trend lines, while values near zero indicate sideways action and possible support/resistance.
snapshot

█ Setup & Configuration:

Whether you’re new to this script or want to quickly adjust all critical parameters, the panel below shows the main settings available. You can customize everything from the anchor type and maximum length to the bias, signal conditions, and more.
  1. Scale (select Log Scale for logarithmic, otherwise linear scale).
  2. Display (regression channel and/or bands).
  3. Anchor (how regression length is determined).
  4. Length (control bars analyzed):
    • Max – Upper limit.
    • Min – Prevents regression from becoming too short.
    • Step – Controls scanning precision; increasing Step reduces load time.
  5. Regression:
    • Type – Calculation method.
    • Bias – EMA-style emphasis (>0=new bars weighted more; <0=old bars weighted more).
  6. Deviation:
    • Type – Calculation method.
    • Bias – EMA-style emphasis (>0=new bars weighted more; <0=old bars weighted more).
    • Multiplier - Adjusts Upper and Lower Deviation.
  7. Signal Criteria:
    • % (Price vs Deviation) – (0% = lower deviation, 50% = regression, 100% = upper deviation).
    • R – (0 = no correlation, ±1 = perfect correlation; >0 = +slope, <0 = -slope).
  8. Table (analyze table of input settings, calculated results, and signal criteria).
  9. Adaptive Lookback (display regression while too few historical bars).
  10. Multiple Regressions (steps 2 to 7 apply to #1, #2, and #3 regressions).

snapshot

Signal Generation & Alerts:

The script offers customizable entry and exit signals with flexible criteria and visual cues (background color, dots, or triangles). Alerts can also be triggered for these opportunities.
  • Percent Direction Criteria:
    (0% = lower deviation, 50% = regression line, 100% = upper deviation)
    • Above %: Triggers if price is above a specified percent of the deviation channel.
    • Below %: Triggers if price is below a specified percent of the deviation channel.
    • (Blank): Ignores the percent‐based condition.

  • Pearson's R (Correlation) Direction Criteria:
    (0 = no correlation, ±1 = perfect correlation; >0 = positive slope, <0 = negative slope)
    • Above R / Below R: Compares the correlation to a threshold.
    • Above│R│ / Below│R│: Uses absolute correlation to focus on strength, ignoring direction.
    • Zero to R: Checks if R is in the 0-to-threshold range.
    • (Blank): Ignores correlation-based conditions.

snapshot

User Tips & Best Practices:
  • Choose an anchor type that suits your strategy, “Bar Highest/Lowest” automatically spots commonly used regression zones, while “│R│ Highest” targets strong linear trends.
  • Consider enabling or disabling the Adaptive Lookback feature to ensure you always have a plotted regression if your chart doesn’t meet the maximum-length requirement.
  • Use a small Step size (1) unless relying on R-correlation or slope-based anchors as the are time-consuming to calculate. Larger steps speed up calculations but reduce precision.
  • Fine-tune settings such as lookback periods, regression bias, and deviation multipliers, or trend strength. Small adjustments can significantly affect how channels and signals behave.
  • To reduce loading time, show only channels (not bands) and disable signals, this limits calculations to the last bar and supports more extreme criteria.
  • Use the table display to monitor anchor type, calculated length, slope, R value, and percent location at a glance—especially if you have multiple regressions visible simultaneously.


Conclusion:

With its blend of advanced regression techniques, flexible deviation options, and a wide range of anchor types, this indicator offers a highly adaptable linear regression channeling system. Whether you're anchoring to time, price extremes, correlation, slope, or external events, the tool can be shaped to fit a variety of strategies. Combined with customizable signals and alerts, it may help highlight areas of confluence and support a more structured approach to identifying potential opportunities.
Release Notes
- Anchor can now be set to regression source (highest/lowest).
- Improved regression plotting for sources with different data availability dates than chart.
- Table now includes Avgerage Absolute R, and count of occurrences above/below regression.
- Minor changes.
Release Notes
- Fixed calculation of percent value (price vs deviation) on log scale.

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.