Anchored Regression Oracle [JOAT]Anchored Regression Oracle
Introduction
Linear regression is one of the most powerful tools in statistical analysis, yet its application in most trading indicators is limited to a fixed rolling window applied to closing prices — a single-dimensional view of a multi-dimensional problem. The Anchored Regression Oracle extends classical Ordinary Least Squares regression in four distinct ways: it supports both logarithmic and linear price scaling, it offers multiple anchor modes (fixed bar count or calendar-period anchoring), it computes a full set of deviation, Fibonacci, and extreme projection levels above and below the regression line, and it incorporates the Pearson R correlation coefficient and theta angle as real-time quality metrics that control signal eligibility.
The fundamental insight motivating the log/linear duality is that financial prices grow multiplicatively, not additively. A $10 move from $100 is a 10% change; a $10 move from $1000 is a 1% change. Fitting a straight line through raw prices on a linear scale treats these as equivalent. Fitting through log-transformed prices treats them as proportionally equivalent — and for equities, cryptocurrencies, and other compounding instruments, the log-space regression is often the more meaningful representation of trend. The indicator handles both cases transparently, transforming all calculation into log space when selected and back-transforming all output levels to price space for display.
The calendar anchoring system adds a dimension that pure bar-count indicators cannot provide: the ability to reset and recalculate the regression window at the start of each new trading day, week, month, or other period — automatically. This makes the regression channel contextually anchored to the current period's price action rather than an arbitrary historical bar count, without any manual intervention.
Core Concepts
1. Manual OLS Linear Regression
The indicator implements the full Ordinary Least Squares regression formula manually rather than using Pine Script's built-in ta.linreg(). This is a deliberate choice: the manual implementation supports both logarithmic transformation and expanding anchor windows, neither of which the built-in function accommodates. The calculation accumulates bar-level sums across the current window to derive the exact OLS slope and intercept.
slope = (n * sumXY - sumX * sumY) / (n * sumXX - sumX * sumX)
intercept = (sumY - slope * sumX) / n
lrValue = intercept + slope * n
Where n is the current window size, sumXY is the sum of bar-index times price products, sumXX is the sum of squared bar indices, and sumX and sumY are the simple sums of indices and prices respectively. In log mode, all price values entering the sums are first transformed via math.log(), and all output levels are back-transformed via math.exp() before rendering on the chart.
2. Pearson R Correlation Coefficient
After computing slope and intercept, the Pearson R coefficient is derived from the same accumulated sums. R measures the linearity of the relationship between bar index and price — essentially, how well the regression line fits the actual price path. Values near 1.0 or -1.0 indicate strong linear trends where the regression line is a reliable representation. Values near 0 indicate that price is moving chaotically relative to a linear model.
dxt = sumXX - sumX * sumX / n
dyt = sumYY - sumY * sumY / n
pearsonR = (sumXY - sumX * sumY / n) / math.sqrt(dxt * dyt)
The dashboard displays Pearson R with color coding: teal for |R| ≥ 0.8 (strong fit), orange for |R| ≥ 0.5 (moderate fit), red for |R| below 0.5 (weak fit). When the Pearson filter is enabled, only readings with |R| above the user threshold are eligible for signal generation — preventing trades on regression lines that do not actually describe the price behavior.
3. Theta Angle
The slope of the regression line is an abstract mathematical quantity that is not intuitively interpretable. Converting it to a theta angle using the arctangent function produces a human-readable degree value: a steeply rising trend shows a large positive angle, a flat trend shows near-zero degrees, and a declining trend shows a negative angle. The minimum theta filter allows users to exclude signals from very shallow trends — requiring a minimum degree of directional conviction before entries are considered.
theta = math.atan(-slope) * 180 / math.pi
Note that the negative sign before slope accounts for the inversion between mathematical y-axis convention (upward) and screen y-axis convention (downward in most chart implementations), ensuring the displayed angle intuitively matches the visual slope direction on the chart.
4. Window Modes: Rolling vs. Anchored
The "Bar" mode uses a fixed rolling window of N bars — the regression line covers exactly the last N candles regardless of calendar position. All period-based modes ("Minute", "Hour", "Day", "Week", "Month") use an expanding anchor: a bar counter resets to zero each time a new period begins (detected via timeframe.change()), and the regression window expands from that anchor point through the current bar. This means on day anchoring, the regression always describes the current day's price action from the first bar to now — expanding as the day progresses and resetting at the start of each new day.
var int windowBars = 0
periodChanged = timeframe.change(targetTF)
windowBars := periodChanged ? 1 : windowBars + 1
effectiveLen = windowMode == "Bar" ? barLen : windowBars
5. Deviation and Fibonacci Projection Levels
Six lines are drawn on the chart, all updated on barstate.islast to avoid performance overhead. The center line is the regression line itself. The upper and lower deviation lines are offset by user-configurable standard deviation multiples. A Fibonacci level is plotted at 1.618 standard deviations. Historical high and low lines track the maximum deviation point actually reached by price above and below the regression line over the window — providing empirical rather than statistical bounds.
f_lvl(base, std, mult) =>
logMode ? math.exp(math.log(base) + std * mult) : base + std * mult
upperDev = f_lvl(lrValue, stdDev, upperMult)
lowerDev = f_lvl(lrValue, stdDev, lowerMult)
fibLevel = f_lvl(lrValue, stdDev, 1.618)
In log mode, the offset is applied additively in log space (equivalent to multiplicative scaling in price space), ensuring the deviation levels remain proportionally consistent with the log-scale price representation.
6. Five Signal Modes
The signal system offers five distinct behavioral modes. "None" disables signals entirely. "Deviation|Breakout" fires when price crosses above the upper deviation (long) or below the lower deviation (short). "Deviation|MeanReversion" fires when price crosses back inside the deviation bands after an excursion outside. "Extreme|Breakout" uses the historical high and low deviation lines as the reference. "Extreme|MeanReversion" fires when price returns inside the historical extremes. "Theta-Only" generates signals based solely on the theta angle crossing the minimum threshold, regardless of price position relative to deviation levels.
Features
Full Manual OLS Regression: Complete Ordinary Least Squares implementation supporting both log and linear price scaling without any ta.linreg() dependency.
Log/Linear Scale Toggle: Log mode transforms all prices via math.log before regression and back-transforms all output levels, producing proportionally correct channels for compounding instruments.
Multiple Window Modes: Fixed bar count or calendar-anchored expanding windows (Minute, Hour, Day, Week, Month) that reset automatically on period transitions.
Pearson R Coefficient: Real-time correlation quality metric with color-coded dashboard display and optional signal eligibility filter.
Theta Angle: Human-readable trend angle from arctangent of slope with optional minimum threshold signal filter.
Six Regression Lines: Center regression line, upper and lower user-configured deviation bands, 1.618 Fibonacci level, and historical high/low deviation extremes.
Five Signal Modes: Deviation breakout, deviation mean-reversion, extreme breakout, extreme mean-reversion, and theta-only — covering different trading philosophies.
Historical Ghost Plots: Non-repainting semi-transparent historical regression and deviation plots for visual context of prior channel positions.
Efficient Line Updates: All six lines are updated on barstate.islast only, maintaining performance even on long chart histories.
Seven-Row Dashboard: Pearson R (color-coded), theta with sign, direction, signal mode, window type, standard deviation, and window size.
Four Alert Conditions: Long entry, short entry, long exit, short exit — all gated by optional Pearson and theta filters.
Input Parameters
Regression Settings:
Window Mode: Bar, Minute, Hour, Day, Week, or Month (default: Day)
Bar Length: Fixed window size when mode is "Bar" (default: 100)
Target Timeframe: Calendar period string used in timeframe.change() for anchored modes (default: "D")
Log Mode: Enable logarithmic price transformation (default: false)
Deviation Settings:
Upper Deviation Multiplier: Standard deviation multiple for upper channel boundary (default: 2.0)
Lower Deviation Multiplier: Standard deviation multiple for lower channel boundary (default: 2.0)
Show Fibonacci Level: Toggle the 1.618 StdDev Fibonacci projection line (default: true)
Show Historical Extremes: Toggle the historical high/low deviation lines (default: true)
Signal Settings:
Signal Mode: None, Deviation|Breakout, Deviation|MeanReversion, Extreme|Breakout, Extreme|MeanReversion, Theta-Only (default: Deviation|Breakout)
Minimum Theta: Minimum absolute angle in degrees required for signal eligibility (default: 5)
Pearson Filter: Enable Pearson R minimum threshold (default: false)
Min Pearson R: Minimum |R| required when filter is active (default: 0.7)
Display Settings:
Show Historical Plots: Toggle ghost regression and deviation plots (default: true)
Historical Alpha: Transparency level for historical plots (default: 75)
Show Dashboard: Toggle the seven-row information table (default: true)
How to Use This Indicator
Step 1: Select the Appropriate Window Mode
Start by choosing the window mode that matches your analytical context. For intraday trading, Day anchoring is most natural — it resets the regression at the start of each session, showing how the current day's price action trends from the open. For swing trading, Week or Month anchoring provides a broader structural perspective. Bar mode is appropriate when you want consistent lookback regardless of calendar, for example in crypto markets that trade continuously without session boundaries.
Step 2: Evaluate Regression Quality Before Trusting Signals
Check the Pearson R value in the dashboard before interpreting any signal. A strong R (teal, ≥ 0.8) means price has been moving in a well-defined linear trend — the regression line is descriptively accurate and signals from it carry more weight. A weak R (red, < 0.5) means price has been choppy and non-linear; the regression line is fitting noise, and deviation-based signals will be unreliable. If the Pearson filter is enabled, signals will simply not fire when R is below threshold, automating this quality check.
Step 3: Choose a Signal Mode Matching Your Strategy
Breakout modes are suited for momentum strategies — they enter when price is moving away from the regression mean with statistical force. Mean-reversion modes are suited for range-expansion strategies — they enter when price returns inside the channel after an excursion, betting on a return to mean. The Extreme modes use the actual historical high/low deviations rather than the fixed multiplier, making them adaptive to the specific price behavior observed in the current window.
Step 4: Apply Theta and Pearson Filters for Quality Control
Enable the minimum theta filter to avoid trading very shallow trends. A trend angled at 3 degrees has minimal directional conviction — the regression line is nearly horizontal, and any deviation signals from it may be as much noise as signal. Setting a minimum of 10-15 degrees for active entries ensures you are trading genuine directional moves rather than sideways grinding. Combine this with the Pearson filter for the highest-quality signal subset.
Indicator Limitations
Linear regression assumes the relationship between time and price is fundamentally linear during the window. In strongly trending markets this is approximately true; in markets with curves, accelerating trends, or parabolic moves, the linear model will systematically underfit the actual trajectory.
The OLS calculation accumulates sums over the entire window on every bar. On very long bar counts or in expanding anchor modes late in a long session, this can affect script execution time, particularly when combined with other indicators on the same chart.
Calendar anchoring uses timeframe.change() which is resolution-dependent. If the chart timeframe is coarser than the anchor period (e.g., viewing a weekly chart with day anchoring), the anchor period may not transition as expected.
Pearson R measures linear correlation specifically. A price series that follows a consistent curve will produce a lower R than one that follows a straight line, even if the curve describes a very orderly trend. In log mode, this issue is partially mitigated for exponentially trending instruments.
Historical ghost plots are informational only and represent completed regression windows. They do not update after their respective periods close.
In log mode, the volatility measure used for deviation computation is the standard deviation of log-transformed prices, which is equivalent to a percentage standard deviation. For very short windows, this measure can be highly sensitive to individual bar outliers.
Signals on the current (incomplete) bar are not displayed, as all signal conditions require barstate.isconfirmed to prevent look-ahead.
Originality Statement
The Anchored Regression Oracle is a substantially original analytical tool that addresses specific limitations of existing regression-based indicators on TradingView.
The manual OLS implementation (computing slope, intercept, and Pearson R from accumulated sums without ta.linreg()) enables the log-space calculation that built-in functions do not support — allowing mathematically correct regression channels for compounding assets.
The calendar-anchored expanding window system (using timeframe.change() to reset a bar counter and grow the regression window from a fixed calendar point) is an original approach to making regression contextually meaningful for session-based or period-based analysis.
Computing and displaying the theta angle (arctangent of slope in degrees) as a real-time trend steepness metric, with a configurable minimum threshold that gates signal eligibility, is an original signal quality framework not found in standard regression channel indicators.
The five-mode signal system — providing breakout and mean-reversion variants for both statistical deviation levels and empirical historical extremes, plus a theta-only mode — covers a range of trading philosophies from a single indicator, rather than requiring separate indicators for each approach.
The combination of log/linear duality, calendar anchoring, Pearson quality gating, theta filtering, Fibonacci projection at 1.618 StdDev, and historical ghost plots in a single indicator represents an integration of features not available in any single existing TradingView regression tool.
Disclaimer
The Anchored Regression Oracle is provided for educational and informational purposes only. It is a technical analysis tool and does not constitute financial advice. Statistical measures such as Pearson R and regression slope describe historical relationships and do not predict future price behavior. All trading involves risk of loss. Users are solely responsible for their own trading decisions. Please consider your individual risk tolerance and consult a licensed financial professional before engaging in any trading activity.
-Made with passion by officialjackofalltrades
Indicador Pine Script®






















