Analogue Matcher | GainzAlgoAnalogue Matcher: Dual-Path Regression Projection
What It Is
The Analogue Matcher is a high-performance pattern recognition engine designed to find historical "price twins." Unlike standard fractals that look for raw shape similarity, this tool utilizes Linear Regression Analysis to identify periods in the past where market velocity (slope) and trend consistency ($R^2$) were near-identical to current conditions. It then projects those historical outcomes forward as "Ghost Candles," providing a probabilistic roadmap of where price might go.
How It Works
The indicator operates by scanning a user defined amount of lookback bars of history in real-time (Default 500).
• The Scan: It calculates the current regression slope over a user-defined window.
• The Match: It iterates through the lookback period to find the closest matches based on a strict Slope Tolerance .
• Dual-Path Intelligence: In "Dual Mode," the script identifies the single best Bullish outcome and the single best Bearish outcome simultaneously. This prevents "bias-blindness" by showing you the best-case scenarios for both directions.
Understanding Confidence & R2
The "Conf (R²)" column in your dashboard is the heart of the script's decision-making.
• Slope Similarity: Measures how closely the historical angle matches the current angle.
• R2 (Coefficient of Determination) : Measures the "cleanliness" of the trend. An R2 of 100.0 is a perfect straight line; 0.0 is pure noise.
• The Percentage: Our algorithm combines these two factors. A 90%+ Confidence rating means you have found a historical twin that moved at the same speed and with the same level of trend maturity as the current bar.
How to Use: A Risk Management Approach
This is not a "magic signal" generator—it is a Risk Management and Bias Tool .
• Identify Convergence: If both the Bullish and Bearish paths show high confidence (>80%) and both point in the same direction, you have high-probability confluence.
• Divergence Warning: If the Bullish path has 95% confidence but the Bearish path has only 10%, the historical precedent for a trend reversal is mathematically weak. Your bias in this case would lean bullish. Inverse if it’s flipped with a high bearish confidence and a low bullish confidence.
• Filtering Noise: Use the R2 percentage to ignore "messy" matches. If the confidence is below 50%, the analogue is likely too "noisy" to be used for a high-conviction trade entry.
• Single Mode for Speed: Switch to Single Mode on lower timeframes (1m, 5m) to find the absolute "Best Fit" twin for quick scalping targets.
Master the Engine: Key Inputs
To get the most out of the Analogue Matcher , it’s essential to understand the "knobs" you are turning. Tuning these correctly is the difference between finding a perfect twin and seeing random noise.
• Mode Selection (Single vs. Dual): Single Mode: Focuses the processing power on finding the absolute "Best Fit" regardless of direction. Ideal for high-speed scalping or very large lookbacks. Dual Mode: The full "Risk Management" suite. It forces the script to find both a Bullish and a Bearish path to show you the two most likely outcomes.
• Projection Window: This determines the size of the "Ghost." If set to 50, the script analyzes a 50-bar trend and projects a 50-bar future.
• Lookback Period: This is how far into the past the engine scans. While the script is optimized for performance, keeping this within a reasonable range (500–2000) ensures fast UI response.
• Slope Tolerance: This is your "Sensitivity" setting. Lower Values (0.001 - 0.004): Very strict. The script will only show matches that have a nearly identical angle of attack. Higher Values (>0.01): More lenient. Use this in highly volatile markets (like Crypto) where trends are aggressive and vary in steepness.
Examples
In this image, we can see BTCUSD on the daily. The confidence favours a bullish move, both Bearish and Bullish possible paths are plotted. Let’s see what happens.
The outcome was an initial bullish move though with a bit of a neutral tilt, as it ended relatively flat.
Now let us look at ES1!:
In this case, the indicator is showing 2 possible paths (Dual Mode), with a bullish tilt. Let’s see what happened next:
The move was indeed bullish, and volatility remained intact through the move.
Important Considerations
The indicators true strength stems from its ability to act as a risk management tool and compare the degree of “fit” of each respective path (i.e. bullish vs. bearish). If you are looking to take a bearish position on a ticker, but you see that the R2 skew slightly favours a move to the upside, you may want to hold off on pulling the short trigger until you have a skew that fits your bias.
While the paths are likely not going to be a perfect, identical match, the power comes from understanding the confidence skew of the bullish vs bearish path. This is your saving grace for managing risk in your positions.
Though the matches are not likely to be perfect, they are scaled to the ticker’s ATR and thus can be used to help you gauge potential entries, exits and positioning areas.
For example, if we look at SPY on the hourly timeframe:
We see we have a bearish skew. The bearish path has sizeable upside. We can use this forecasted range to identify potential entry/resistance areas like so:
Now let’s see how it plays out:
You can see that the key forecast areas provided actual levels for support and resistance!
Concluding Remarks
In a market driven by algorithmic repetition, the Analogue Matcher gives you the power to see the "scripts" the market has run before. By quantifying the similarity of price action through regression, traders can move away from "gut feelings" and toward data-driven forecasts.
Indicator

LOWESS Adaptive Envelope [BackQuant]LOWESS Adaptive Envelope
Overview
LOWESS Adaptive Envelope is a nonparametric trend-fit and volatility envelope tool built around LOWESS (Locally Weighted Scatterplot Smoothing). Instead of smoothing price with a fixed-form moving average, this indicator performs a rolling set of local weighted linear regressions across a chosen historical window and stitches those local fits into a single smooth curve that adapts to changing market structure.
On top of the fitted curve, the script builds an adaptive envelope whose width is driven by the local magnitude of the model’s residuals (how far price deviates from the fit). That means the envelope automatically expands when the market is noisy or trending aggressively, and contracts when price is stable or mean-reverting cleanly.
The output is a complete “structure map”:
A LOWESS fitted centerline (trend estimate).
Upper and lower adaptive bands derived from smoothed residual spread.
A filled region that changes color based on where price sits relative to the fit.
Optional extrapolation of the fit and envelope into the future using last slope, with widening uncertainty.
An info label showing fit quality (R²), position inside the envelope, and direction.
Where LOWESS comes from (and why it is different from moving averages)
LOWESS (also written LOESS) is a classic statistical smoothing technique used in exploratory data analysis and robust curve fitting. It became popular because it can approximate complex shapes without assuming a single global model. Instead of forcing the entire window to follow one equation (like a single linear regression or a single moving average kernel), LOWESS fits many small local regressions , each one tailored to its neighborhood.
Key distinction:
A moving average is a fixed smoother, it applies the same weighting rule everywhere, regardless of whether the market is trending, chopping, or accelerating.
LOWESS is a locally re-fitted model, it re-estimates slope and intercept at each point based on nearby data.
In price terms:
LOWESS is better at “hugging structure” when the market curves or transitions.
It can follow gradual regime shifts without the same lag profile as long-window MAs.
It does not assume the trend is constant across the whole lookback, it assumes trend can vary locally.
What the indicator is modeling
Think of the lookback window as a dataset of points:
x = bar index (0..length-1 inside the window)
y = price
For every point i inside that window, the indicator estimates the best local line:
y ≈ a + b * x
But it does this using only nearby points, and it weights them by distance from i. So the fitted value at i is a locally weighted regression prediction.
The final fitted curve is the collection of those predictions across i = 0..length-1.
Core mechanics: local weighted linear regression
1) Neighborhood size (bandwidth)
The “locality” is controlled by a bandwidth parameter. In this script:
h = max(bandwidth * length / 2, 2)
Interpretation:
h acts like a radius measured in bars inside the fitting window.
Lower bandwidth → smaller h → more local fit (more responsive, can track curvature, more sensitive to noise).
Higher bandwidth → larger h → more global fit (smoother, more stable, more lag in transitions).
So bandwidth controls the bias-variance tradeoff:
Small bandwidth: low bias, high variance.
Large bandwidth: higher bias, lower variance.
2) Tricube kernel weighting
LOWESS requires a weight function that decays smoothly with distance. This script uses the classic tricube kernel :
For each candidate point j around target i:
u = |i - j| / h
If u < 1:
- w = (1 - u³)³
If u ≥ 1:
- w = 0
Why tricube:
Weights go to zero smoothly at the boundary (no sharp cutoff artifacts).
Nearby points dominate the fit, distant points contribute little or nothing.
It is a standard LOWESS choice because it produces stable smooth curves.
3) Weighted least squares fit
For each i, the script accumulates weighted sums over j in the neighborhood:
sumW, sumWX, sumWY, sumWXX, sumWXY
These correspond to the normal equations for weighted linear regression. From those, it computes:
denom = sumW * sumWXX - sumWX²
a and b derived from sums (intercept and slope)
fitted = a + b * i
If denom is too small (numerical instability, insufficient variation), it falls back to the raw price at that i.
This entire process is repeated for every i in the window, which is why it is done only on the last bar (performance).
Why it fits inside the window rather than a single line
A single regression across 200 bars assumes one slope b explains the whole move. Markets rarely do that. LOWESS allows the slope to drift through time, which is exactly what “trend structure” actually does in real price.
Residuals: turning model error into volatility structure
Once the LOWESS fitted curve is computed, the script measures the residual at each point:
res = price - fitted
Residuals are the model’s error. In trading terms, residual magnitude is a proxy for:
Local noise level.
Deviations from trend structure (overextension/underextension).
Regime instability (trend is less “explanatory”).
The script takes absolute residuals:
absRes = |res |
This is important because envelope width should reflect spread size regardless of direction.
R²: fit quality and regime information
The indicator also computes R² over the window:
ssRes = Σ(res²)
ssTot = Σ((price - meanPrice)²)
R² = 1 - ssRes/ssTot
Interpretation:
Higher R² means the LOWESS fit explains more of the variation inside the window.
Lower R² means price is behaving in a way the smooth trend model cannot explain well (chop, shocks, irregular volatility).
In markets, R² can be read as “how trend-like vs how noisy” the recent environment is, but remember it depends on your chosen length and bandwidth.
Adaptive envelope construction (what makes it “adaptive”)
A normal envelope uses a constant width (like ±k*ATR or ±k*stdev). This script does something different: it estimates a local envelope width based on smoothed residual magnitude.
1) Smooth residual magnitude locally
It computes a residual averaging window:
rWin = max(3, int(h * 0.8))
So the residual smoothing window is linked to the LOWESS locality. If the fit is local, the envelope adapts locally. If the fit is global, the envelope adapts more slowly.
Then for each i:
envW = mean(absRes over ) * envMult
Interpretation:
The envelope width is proportional to how much price typically deviates from the fit around that region.
envMult is your “how many spreads” multiplier.
This creates an envelope that expands and contracts along the curve, not a single constant band.
2) Upper and lower envelopes
For each i:
upper = fitted + envW
lower = fitted - envW
This is a model-driven channel. It is not ATR-based directly, it is “error-based.” That makes it very effective at responding to the actual behavior of the market relative to the fitted structure.
How to interpret the envelope
The centerline is the best local structural estimate. The envelope is the expected deviation range around that structure.
Typical readings:
Price near centerline: balanced relative to structure.
Price riding upper band: strong bullish pressure, trend continuation or overextension depending on context.
Price riding lower band: strong bearish pressure, continuation or overextension.
Repeated band rejections: mean-reversion regime around the structural fit.
Envelope widening: instability rising, volatility expanding, structure less reliable.
Envelope tightening: compression, cleaner trend or coiling behavior.
Because the band width is based on residuals, widening often coincides with “trend breaks” and regime transitions, not just higher ATR.
Color logic and visual encoding
The envelope fill color is based on price relative to the most recent fitted value:
If close > fitted , bullish color.
Else bearish color.
So color is a regime/bias cue, not a volatility cue. The bands themselves are drawn with translucent versions of the same regime color, while the fit line is a subtle white.
The fill polygon is constructed by:
Walking forward through upper points.
Then walking backward through lower points.
So the shape is closed and can be filled cleanly using polyline fills.
Extrapolation: forward projection with widening uncertainty
This script can project the fitted line into future bars. This is not forecasting in a statistical sense, it is a deterministic extension based on the current slope.
How it extrapolates
It takes:
slope = fitted - fitted
lastFit = fitted
Then for i = 1..extrapBars:
futureFit = lastFit + slope * i
This is a linear continuation of the most recent fit direction. It is meant as a visual guide for “if the current local trend continues.”
Why the forward envelope widens
The script also grows the envelope slightly with each projected bar:
envGrow = lastEnv * 0.01
futureEnv = lastEnv + envGrow * i
This is a simple uncertainty widening mechanism. As you move further into the future, you should assume less confidence. The envelope expansion encodes that visually without claiming statistical rigor.
Info label: what it reports and how to read it
When enabled, the label shows:
1) Direction arrow
It computes a slope over the last few fitted points:
recentSlope = fitted - fitted (or closest valid index)
▲ if slope >= 0
▼ if slope < 0
This gives a slightly more stable direction read than one-bar slope.
2) R²
Displayed as R²: 0.xxx, representing how well the LOWESS curve explains window variation.
3) Envelope Position (Env Pos)
It measures where the current close sits inside the latest envelope:
0% = at lower band
50% = at centerline
100% = at upper band
This is extremely useful as a normalized “over/under extension” metric because it is scaled by the adaptive band width, not raw price units.
How to use it properly
Trend structure and regime filtering
Use the fit line as structural trend direction.
Use the fill color as quick bias context.
Use R² as a “trend quality” read: high R² tends to mean cleaner structure, low R² tends to mean chop or instability.
Mean reversion vs continuation
This tool can support both styles, but interpretation differs:
Mean reversion framing
If market repeatedly returns to the fit line, the fit is acting like value.
Upper band touches can be “overbought relative to structure.”
Lower band touches can be “oversold relative to structure.”
Envelope position becomes your normalized stretch gauge.
Trend continuation framing
In strong trends, price can ride a band rather than revert to centerline.
Band riding plus rising fit slope suggests persistence.
A sudden failure to hold the band plus falling R² can flag transition risk.
Breakdown/transition identification
Because the envelope width is residual-driven:
If price starts producing large residuals, the envelope expands.
That expansion is often a signature of regime change, not just volatility.
Combine expansion with slope flattening to identify trend exhaustion.
Parameter tuning (what each input really does)
Length
Defines how much historical data is used for the full fit. Larger length:
More stable curve.
More computational load.
Tends to represent macro structure.
Bandwidth
Controls locality:
Low bandwidth (0.10–0.25): more reactive, tracks curvature and micro-structure, more sensitive to noise.
Higher bandwidth (0.30–0.50+): smoother, more stable, more lag in fast turns.
Envelope Width (envMult)
Scales how wide the adaptive band is relative to the local residual spread:
Lower values create a tighter channel, more band interactions.
Higher values create a wider channel, fewer touches, better for regime filtering.
Extrapolation Bars
Purely visual. More bars gives a longer projected structure line and uncertainty region.
Limitations and correct expectations
LOWESS is powerful, but it is not a magic predictor.
LOWESS is descriptive, it fits what happened, then projects linearly if extrapolation is enabled.
In sudden shocks or gaps, the fit will update only after the new data is inside the window.
Very small bandwidth can overfit local noise, producing misleading curvature.
Very large bandwidth can underfit, behaving like a slow regression and missing turning points.
R² is window-dependent, a low value does not mean “bad indicator,” it often means “market is not smooth right now.”
Summary
LOWESS Adaptive Envelope applies locally weighted linear regression (LOWESS) with a tricube kernel to build a smooth, structure-following fitted price curve that adapts to regime changes without relying on a fixed moving-average form. It then converts the model’s local residual spread into a dynamic envelope that expands and contracts with real deviation behavior, provides fit quality via R², normalizes price position inside the band, and optionally extrapolates the latest structural slope forward with widening uncertainty. The result is a robust trend-structure and deviation framework that is equally useful for regime filtering, mean-reversion context, and trend persistence assessment. Indicator

Quant Stats: Alpha, Beta, R2Quant Stats Indicator for PulseWire: Alpha, Beta, and R-Squared
Overview
The Quant Stats Indicator is a professional-grade Pine Script tool designed for quantitative traders and hedge fund managers who need real-time analysis of stock or ETF performance against a benchmark using three fundamental CAPM metrics: Beta, R-Squared, and Alpha.
This indicator calculates three critical measurements that answer every quant trader's core questions: How volatile is this asset relative to my benchmark? How much of its performance is independent of the benchmark? And how much excess return am I achieving after adjusting for risk?
The Three Metrics Explained
Beta (β) measures systematic risk and volatility relative to your chosen benchmark. A Beta of 1.0 means the asset moves in lockstep with the benchmark. A Beta above 1.0 indicates higher volatility—if the market rises 10%, a Beta-1.5 asset should rise 15%. Conversely, a Beta below 1.0 indicates lower volatility, making it a defensive position. This metric helps you understand how much market exposure you're truly taking.
R-Squared (R²) quantifies what percentage of an asset's price movement can be explained by benchmark movements. An R² of 0.95 means 95% of the asset's moves are driven by the benchmark, leaving only 5% unexplained. Conversely, an R² of 0.2 means 80% of the asset's movement is independent of the benchmark. This distinction is crucial: high R² is desirable for passive index tracking but indicates weak alpha potential; low R² reveals genuine independent returns, exactly what active managers seek.
Alpha (α) reveals Jensen's Alpha—the excess risk-adjusted return after accounting for the return you "should" earn given your Beta exposure. A positive Alpha of 15% means you're outperforming the market by 15 percentage points after adjusting for systematic risk. This is the holy grail of stock picking: pure skill-driven excess return, not luck from market exposure.
How to Use It
Configure four key inputs: your benchmark ticker (default SPY, but use QQQ for tech-focused analysis or sector-specific ETFs), the lookback period in days, and the risk-free rate reflecting current Treasury yields. The lookback period is critical. Use 20 days for tactical trading to capture short-term sentiment and beta spikes; use 63 days for swing trading and quarterly rebalancing; use 252 days for structural asset allocation decisions.
The indicator plots Beta as a blue line, R-Squared as a red shaded background area, and Alpha as a green line in a sub-panel. Reference gridlines appear at Beta = 1.0 (market-equivalent volatility) and Alpha = 0.0 (breakeven performance), making interpretation intuitive.
Practical Applications
For swing traders monitoring a 63-day window, seek positions with low Beta (below 0.8) and positive Alpha—these are defensive winners. Avoid high Beta (above 1.2) with low R² unless you specifically want high-volatility speculation. Long/short hedge funds should use a 20-day lookback to detect regime changes: sudden Beta spikes often precede correlation breakdowns, while R² collapses signal rising idiosyncratic risk requiring immediate rebalancing.
For ETF portfolio construction, high R² (above 0.95) indicates index-tracking that doesn't justify active management fees. Low R² (below 0.3) combined with positive Alpha reveals genuine active management skill. The sweet spot is moderate Beta (0.5–0.8) with low R² and positive Alpha—a true diversifier that reduces portfolio volatility while generating independent returns.
Critical Interpretation Rules
A common mistake is assuming high R² is always desirable. It isn't. Passive index funds naturally have high R²; active managers should target low R² with high Alpha. Similarly, don't assume Alpha above 10% is sustainable—short-term Alpha (20–100 days) is inherently volatile and often represents temporary mispricings rather than repeatable skill. Always pair Beta analysis with R² interpretation; Beta alone ignores idiosyncratic risk, liquidity constraints, and tail risk.
Configuration Recommendations
Conservative investors should use SPY as benchmark with a 252-day lookback, targeting Alpha above 3% and Beta below 0.8. Growth-oriented portfolios might use QQQ with a 63-day lookback, targeting 8–12% Alpha and tolerating Beta up to 1.3. Hedge funds pursuing market-neutral strategies should use SPY with a 20-day lookback, set the risk-free rate to 2% (anticipating rate cuts), and target 15%+ Alpha while maintaining Beta below 0.3.
Important Limitations
The indicator is backward-looking; historical statistical relationships may not persist. Shorter lookback periods are noisier but more responsive; longer periods smooth noise but lag regime changes. Choosing the wrong benchmark completely invalidates analysis. Finally, the indicator doesn't account for tail risk or extreme market events where correlations spike unpredictably and Beta becomes unreliable.
Use this tool to separate signal from noise and identify true alpha generators. Apply it consistently, validate results against official fund factsheets, and monitor for 2–4 weeks before making significant portfolio decisions. Indicator

Indicator

Indicator

Indicator
