Linear Regression [Anchored, Band, Signals]OVERVIEW
This indicator is a statistical analysis tool that plots linear regression channels alongside dynamic deviation bands. It aims to provide a flexible framework for observing price distribution and momentum quality without making predictive claims.
ORIGINALITY
This indicator provides advanced options for linear regression-based analysis.
📌 Allows setting the calculation window length based on a fixed bar count or an anchored timeframe.
📌 Draws regression channels in either linear or logarithmic scales.
📌 Identifies historical highest and lowest limits in addition to standard deviation levels.
📌 Displays the non-repainting history of the channel via the "Historical Plots" option.
📌 Calculates Pearson's R (correlation strength) and the Theta (θ) angle (the slope of the channel).
📌 Generates Long and Short signals using two distinct filters and four different channel strategies.
📌 Generates alerts based on signals.
📌 Includes dynamic visualization options. Also displays the precise values of the calculated metrics in the Data Window.
WHAT IS LINEAR REGRESSION?
Linear regression is an analytical method used to calculate a dependent variable based on independent variables when a cause-and-effect relationship exists between them. In this context, the dependent variable is the price, and the independent variable is the time or bar_index. It aims to model the potential behavior of price action based on this relationship. A regression channel is calculated based on the sample deviation and its multiples. Consequently, it is widely utilized to determine dynamic support and resistance levels.
REPAINTING AND THE SOLUTION
Repainting can be briefly defined as the alteration of past data values in subsequent bars. Because a standard regression channel is recalculated by shifting the array with every new bar, drawings based purely on line functions inherently repaint. However, this indicator overcomes the repainting issue through its "Historical Plots" feature. This option allows users to dynamically observe the true historical states of the channel levels. The signal mechanics of the indicator are also built strictly upon this non-repainting framework to ensure execution integrity.
APPLICATIONS
The data provided by this tool can be applied in various observational contexts. When prices stretch significantly toward the outer deviation bands, it highlights mathematical extremes that traders often view as potential mean-reversion zones. Conversely, when the price breaks outside the primary boundaries with a high Theta angle, it signals a statistically significant momentum shift. By utilizing the built-in Pearson's R correlation, observers can quantitatively filter out sideways, low-momentum periods (choppy markets) and focus solely on established directional trends.
HOW TO USE
Begin by defining the calculation scope in the settings, choosing either a fixed bar count or an anchored timeframe (e.g., Daily, Weekly). Select the appropriate scale (Linear or Logarithmic) to match your chart. Toggle the visibility of the central regression line and deviation bands (Upper, Lower, Optional, Highest, Lowest) as needed. In the "Signals" section, you can select a specific channel strategy and apply minimum thresholds for Pearson's correlation and the Theta angle. Enable the "Bands (Historical Plots)" option to visually audit the past states of the channel without current-bar distortion.
MECHANICS
At its core, the script utilizes the least-squares method to compute the slope and intercept of the price data. To keep the code modular and efficient, the architecture relies on several user-defined functions (e.g., f_calc_dynamic for historical rolling arrays, f_calc_slope_current for real-time line states, and f_scale_converter for logarithmic adjustments).
SIGNALS & EXECUTION LOGIC
It is important to note that the signal structure built here is a highly subjective approach to linear regression trading. In this sense, the current methodology is merely a "search for an answer" rather than a definitive solution. It aims to provide users with as flexible and customizable a workspace as possible.
Filters:
This indicator utilizes a state-machine (dir) to prevent consecutive redundant signals and to manage immediate directional reversals. All entry conditions can be independently gated by two optional mathematical filters: Pearson's R (minimum correlation strength) and Theta (θ) (minimum slope angle).
Channel Strategies:
The script features 5 distinct channel strategy options with specific entry and exit conditions:
1. None (Pure Trend)
• Logic: Ignores channel bands entirely and relies purely on trend momentum.
• Entry: Triggered when the mathematical Theta (θ) angle crosses the user-defined threshold
• Exit: Triggered when the Theta angle crosses the 0 line, indicating a trend exhaustion or directional shift.
2. Deviation | Break-Out
• Logic: Uses the current, dynamically calculated upper and lower standard deviation bands to catch momentum breakouts.
• Entry: Triggered when the close price crosses over the upper band (Long) or under the lower band (Short).
• Exit (Fakeout Protection): Triggered when the close price crosses back inside the respective entry band. This acts as a trailing stop to cut losses early during false breakouts.
3. Deviation | Mean Reversion
• Logic: Uses the current dynamic deviation bands to anticipate a price rebound towards the mean.
• Entry: Triggered when the close price crosses over the lower band (Long) or under the upper band (Short). Upon entry, a volatility-adjusted hard stop is dynamically recorded (Entry Band ± 1 Standard Deviation).
• Exit: Triggers either as a Take-Profit when the price wick (high for Longs, low for Shorts) hits the central Regression Line, OR as a Stop-Loss if the price breaches the recorded hard stop to prevent infinite drawdowns.
4. Highest & Lowest | Break-Out
• Logic: Uses 1-bar delayed ( ) highest and lowest recorded deviation lines to provide stable, non-repainting levels for breakout confirmation.
• Entry: Triggered when the close price crosses over the historical highest line (Long) or under the historical lowest line (Short).
• Exit (Fakeout Protection): Triggered when the close price crosses back inside the respective entry line.
5. Highest & Lowest | Mean Reversion
• Logic: Uses the stable 1-bar delayed highest and lowest lines to trade rebounds.
• Entry: Triggered when the close price crosses over the lowest line (Long) or under the highest line (Short). Similar to Option 3, a hard stop is recorded at the exact moment of entry.
• Exit: Triggers as a Take-Profit upon a wick touch to the central Regression Line, OR as a Stop-Loss upon breaching the recorded hard stop.
DISCLAIMER
This indicator is strictly a statistical observation tool, not a predictive financial model. Linear regression mathematically describes past price action; it does not forecast future movements. The mathematical filters and deviation bands provided are subjective interpretations of market data and should only be used as supplementary components within a broader, independent risk management framework.
Pine Script®指標






















