OPEN-SOURCE SCRIPT

Z-Score line Daily/Weekly

692
# Z-Score Line Daily/Weekly

**A forward-projected linear regression z-score that measures how far current price has deviated from where its statistical trend *expects* it to be — turning regression residuals into a normalized mean-reversion oscillator.**

---

## What It Does

Z-Score Line computes a linear regression with a configurable forward offset, then measures the residual distance between current price and that projected regression line, normalized by the standard deviation of non-offset regression residuals. The result is a statistically grounded oscillator where readings beyond ±2σ represent historically rare deviations from the projected trend. A smoothed moving average overlay provides momentum context — rising MA confirms z-score direction, divergences flag potential reversals. The forward offset is the key differentiator: rather than measuring deviation from the *current* best-fit line (which always passes near recent price), it measures deviation from where the trend *was heading*, making it structurally better at identifying overshoot conditions.

---

## Theoretical Foundations

- **Linear regression residual analysis** — OLS residuals measure the component of price unexplained by the linear trend; standardizing by residual σ converts this to a z-score with known statistical properties under normality assumptions
- **Forward-projected regression (offset parameter)** — Projecting the regression line forward by `offset` bars creates a "where price should be" reference, rather than a retrospective best-fit; deviations from this projection identify trend exhaustion and overshoot
- **Z-score normalization** — Dividing residuals by their rolling standard deviation produces a unit-free oscillator where ±1σ, ±2σ, ±3σ levels carry standard probabilistic interpretation (68/95/99.7 under Gaussian assumptions — wider in practice for fat-tailed crypto returns)
- **Smoothed z-score as momentum filter** — The SMA of the z-score acts as a second-order trend confirmation, analogous to a signal line on MACD; slope direction separates impulsive moves from mean-reverting ones

---

## Signals

**Bullish:**
- Z-score crosses above zero → price has moved above its projected regression, trend bias shifting positive
- Z-score crosses below lower threshold (−4.7) → extreme negative overshoot, potential mean-reversion long entry
- Z-score MA turning green (rising) while z-score is positive → confirmed bullish momentum

**Bearish:**
- Z-score crosses below zero → price has fallen below its projected regression, trend bias shifting negative
- Z-score crosses above upper threshold (+5.1) → extreme positive overshoot, potential mean-reversion short entry or profit-taking
- Z-score MA turning red (falling) while z-score is negative → confirmed bearish momentum

**Neutral / Caution:**
- Z-score near zero with flat MA → price tracking projected regression, no actionable deviation
- Z-score and MA diverging (z-score rising, MA falling or vice versa) → signal conflict, reduce conviction

---

## Oscillator Pane Fields

| Plot | Description | Range |
|------|-------------|-------|
| **Z-Score** | Standardized residual from forward-projected linear regression (green = positive, red = negative) | Unbounded (typically ±6) |
| **Z-Score MA** | SMA of z-score (green when rising, red when falling) | Same scale as z-score |
| **Upper Line** | Static upper extreme threshold | +5.1 (default) |
| **Lower Line** | Static lower extreme threshold | −4.7 (default) |
| **Zero Line** | Trend-neutral reference | 0 |

---

## Key Inputs

| Input | Default | Guidance |
|-------|---------|----------|
| **Timeframe** | D | Daily is the primary design target. Weekly smooths signals for swing/position trading. Both apply to the regression computation — chart timeframe is independent. |
| **Linear Regression Length** | 21 | Lookback for OLS fit. 21 ≈ one trading month. Shorter (10–14) increases sensitivity to recent moves; longer (30–50) captures broader trend structure. Affects both the offset projection and residual σ. |
| **Linear Regression Offset** | 30 | Forward projection distance in bars. 30 bars on daily ≈ 1.5 months ahead. This is the core parameter — higher offset creates a more "stale" reference line, amplifying deviation signals. Reduce to 10–15 for faster mean-reversion signals; increase to 40–60 for identifying macro-scale overshoot. |
| **Z-Score MA Length** | 13 | SMA smoothing period for the momentum overlay. 13 ≈ half the regression length. Shorter (5–8) tracks z-score more closely; longer (21+) filters noise but lags direction changes. |

---

## Data Sources & request.security() Budget

| Symbol | Purpose | Calls |
|--------|---------|-------|
| Chart symbol (`close`) | All regression, residual, and z-score computations | 0 |

**Total request.security() usage: 0 of 40.** The indicator operates entirely on the current chart's close data with no external security calls, making it fully compatible as a companion pane alongside request.security()-heavy indicators. The Timeframe input uses TradingView's built-in `input.timeframe()` resolution override, not `request.security()`.

---

## Alerts

| Alert | Trigger | Use Case |
|-------|---------|----------|
| **Z-Score Crosses Above Zero** | `ta.crossover(zscore, 0)` | Trend bias flips positive — potential long entry or short exit |
| **Z-Score Crosses Below Zero** | `ta.crossunder(zscore, 0)` | Trend bias flips negative — potential short entry or long exit |
| **Z-Score Crosses Above Upper Line** | `ta.crossover(zscore, 5.1)` | Extreme positive overshoot — mean-reversion short or profit-taking zone |
| **Z-Score Crosses Below Lower Line** | `ta.crossunder(zscore, -4.7)` | Extreme negative overshoot — mean-reversion long or capitulation signal |

All alerts fire via `alertcondition()` (static presets). Alerts trigger on **bar close only** for the selected timeframe resolution — no intra-bar repainting.

---

## Important Notes

- **Anti-repainting:** All computations use `close` (confirmed bar data). The `ta.linreg()` offset parameter projects the regression line forward but does not use future data — it extrapolates the regression slope computed from the trailing `length` bars. No `request.security()` calls, no `barmerge.lookahead_on`, no future data references.
- **Offset interpretation:** The offset does *not* look ahead. It computes the regression from the most recent `length` bars, then evaluates where that line would be `offset` bars in the future. The residual measures current price vs. that extrapolated point. This means the z-score is structurally biased: when trends persist, the offset projection undershoots; when trends reverse, it overshoots. This is the intended behavior for mean-reversion detection.
- **Asymmetric thresholds:** The default upper (+5.1) and lower (−4.7) thresholds are asymmetric, reflecting empirical BTC behavior where downside deviations tend to be sharper but shorter-lived than upside overextensions. Calibrate these to your asset — use the v2 adaptive mode (percentile-based thresholds) for automatic adjustment.
- **Recommended timeframes:** Daily (primary), Weekly (swing). The 21-bar regression on daily captures ~1 month of structure. On 4H, the same 21-bar length captures only 3.5 days — reduce offset proportionally or switch to Weekly resolution via the Timeframe input.
- **Asset scope:** Designed for BTC and major crypto pairs. The z-score normalization assumes roughly stationary residual variance — works on any liquid asset with sufficient history (>50 bars minimum for regression warmup). Not calibrated for low-liquidity altcoins where gap behavior distorts regression fits.

Feragatname

Bilgiler ve yayınlar, TradingView tarafından sağlanan veya onaylanan finansal, yatırım, alım satım veya diğer türden tavsiye veya öneriler anlamına gelmez ve teşkil etmez. Kullanım Koşulları bölümünde daha fazlasını okuyun.