OPEN-SOURCE SCRIPT

Deviation based reversion with Stats

1 533
The "Deviation based reversion with Stats" indicator is designed to identify potential bullish and bearish trading signals based on price deviations from a linear regression line, with the flexibility to choose from multiple deviation measures for both bullish and bearish signals.

These measures include Median Absolute Deviation (MAD), Standard Deviation (SD), Average True Range (ATR), Z-Score, Interquartile Range (IQR) and Mean Absolute Deviation (Mean AD).

The indicator is supplemented by volume analysis and trend filtering to enhance signal reliability. The indicator plots buy and sell signals as arrows on the chart and provides a detailed statistical table to evaluate signal performance. It is highly customizable, allowing users to adjust parameters for bullish and bearish signals independently, including moving average types, lookback periods, volume thresholds, success/failure criteria, and the deviation measure used for signal generation.

The indicator works by:
Calculating Moving Averages: Uses various moving average types (e.g., SMA, EMA, T3, etc.) to establish a trend context for bullish and bearish signals.
Computing Price Deviation: Measures price deviation from a linear regression line, normalized by the user-selected deviation measure (e.g., MAD, SD, ATR), to identify significant price movements.
Incorporating Volume Analysis: Detects volume spikes relative to a moving average to confirm signal strength.
Applying Trend Filters: Optionally ensures signals align with the trend direction based on the slope of the moving average.
Implementing a Cooldown Period: Prevents signal clustering by enforcing a minimum number of bars between signals.
Tracking Performance Metrics: Monitors signal outcomes over a specified look-forward period, calculating metrics like success rate, failure rate, average price change, and more, displayed in a table.

Below is a detailed breakdown of the indicator’s components, including input variables, calculations in the stats table, descriptions of each deviation measure, and how to interpret the results.

Input Panel Definitions
The indicator provides separate input settings for bullish and bearish signals, moving average calculations, and now includes dropdown menus for selecting deviation measures. Each variable is grouped for clarity.

Bullish Signal Settings
Bullish Lookback Period (bull_length, default: 20):Defines the number of bars used to calculate the bullish moving average, linear regression line, and deviation measure.
Purpose: Determines the timeframe for assessing price trends and deviations for bullish signals.
Minval: 1 (ensures at least one bar is used).

Bullish Volume Avg Period (bull_volLength, default: 14):Specifies the lookback period for calculating the simple moving average (SMA) of volume to detect volume spikes.
Purpose: Compares current volume against historical volume to confirm bullish signal strength.
Minval: 1.

Bullish Deviation Multiplier (bull_madMult, default: 2.7):A multiplier applied to the selected deviation measure to set the threshold for detecting significant price deviations above the linear regression line.
Purpose: Determines how far the price must deviate (in units of the chosen deviation measure) to trigger a bullish signal.
Minval: 0.1, Step: 0.1.

Bullish Volume Spike Threshold (bull_volThreshold, default: 1.7):The minimum ratio of current volume to the volume SMA required to confirm a bullish signal.
Purpose: Ensures bullish signals are accompanied by significant trading volume.
Minval: 1.0, Step: 0.1.

Bullish Cooldown Period (Bars) (bull_cooldownBars, default: 10):The minimum number of bars that must pass before a new bullish signal can be generated.
Purpose: Prevents over-signaling during volatile periods.
Minval: 0.

Bullish Look-Forward Bars for Price Change (bull_lookForwardBars, default: 7):The number of bars after a bullish signal to evaluate price movement for performance metrics.
Purpose: Defines the timeframe for assessing success or failure thresholds.
Minval: 1.

Bullish Success Threshold (bull_successThreshold, default: 20.0):The minimum price change (in points or percentage) required to classify a bullish signal as successful.
Purpose: Sets the target for a successful trade outcome.
Minval: 0.1, Step: 0.1.

Bullish Failure Threshold (bull_failureThreshold, default: 20.0):The minimum adverse price change (in points or percentage) that classifies a bullish signal as a failure.
Purpose: Defines the loss threshold for a failed trade.
Minval: 0.1, Step: 0.1.

Bullish Success/Failure Threshold Type (bull_successThresholdType, default: "Points"):Specifies whether success and failure thresholds are measured in "Points" (absolute price change) or "Percent" (percentage change relative to the signal price).
Options: ["Percent", "Points"].
Purpose: Provides flexibility in defining success/failure criteria.

Bullish Conviction Arrow Color (bullish_conviction_color, default: Blue):The color used for plotting bullish signal arrows (triangle up) on the chart.
Purpose: Visual identification of bullish signals.

Enable Bullish Trend Filter (bull_trendFilter, default: true):A boolean that requires an uptrend (price above the bullish moving average and positive MA slope) for bullish signals.
Purpose: Filters out bullish signals in non-favorable trend conditions.

Bullish Deviation Measure (bull_deviation_type, default: "MAD"):A dropdown menu allowing users to select the deviation measure for bullish signals.
Options: ["MAD", "Standard Deviation", "ATR", "Z-Score", "IQR", "Theil-Sen", "Logarithmic", "Mean AD"].
Purpose: Customizes how price deviation from the linear regression line is measured, allowing tailored signal generation.

Bearish Signal Settings
The bearish settings mirror the bullish ones but are tailored for bearish signals (price decreases):
Bearish Lookback Period (bear_length, default: 8): Lookback for bearish moving average, linear regression, and deviation measure.
Bearish Volume Avg Period (bear_volLength, default: 14): Lookback for volume SMA.
Bearish Deviation Multiplier (bear_madMult, default: 2.0): Threshold for price deviation below the linear regression line.
Bearish Volume Spike Threshold (bear_volThreshold, default: 1.5): Minimum volume ratio for bearish signals.
Bearish Cooldown Period (Bars) (bear_cooldownBars, default: 10): Minimum bars between bearish signals.
Bearish Look-Forward Bars for Price Change (bear_lookForwardBars, default: 5): Evaluation period for bearish signal outcomes.
Bearish Success Threshold (bear_successThreshold, default: 20.0): Minimum price drop for a successful bearish signal.
Bearish Failure Threshold (bear_failureThreshold, default: 20.0): Minimum adverse price increase for a failed bearish signal.
Bearish Success/Failure Threshold Type (bear_successThresholdType, default: "Points"): Points or percentage for bearish thresholds.
Bearish Conviction Arrow Color (bearish_conviction_color, default: Purple): Color for bearish signal arrows (triangle down).
Enable Bearish Trend Filter (bear_trendFilter, default: true): Requires a downtrend for bearish signals.
Bearish Deviation Measure (bear_deviation_type, default: "MAD"): Dropdown menu to select the deviation measure for bearish signals, with the same options as bullish.

Bullish MA Settings
These configure the moving average for bullish trend filtering:
Bullish MA Type (bull_ma_type, default: "T3"):The type of moving average used for bullish signals.
Options: ["SMA", "EMA", "WMA", "RMA", "HMA", "DEMA", "TEMA", "VWMA", "ALMA", "TVMA", "T3", "ZLEMA", "KAMA"].
Purpose: Customizes the trend calculation method.

Bullish ALMA Offset (bull_alma_offset, default: 6), Bullish ALMA Sigma (bull_alma_sigma, default: 0.85), Bullish TVMA Length (bull_tvma_length, default: 3), Bullish T3 Factor (bull_t3_factor, default: 0.7), Bullish KAMA Fast EMA Length (bull_kama_fast_len, default: 2), Bullish KAMA Slow EMA Length (bull_kama_slow_len, default: 30): Parameters for specific moving average types.

Bearish MA Settings
These mirror the bullish MA settings for bearish signals:Bearish MA Type (bear_ma_type, default: "EMA"): Type of moving average for bearish signals.
Bearish ALMA Offset (bear_alma_offset, default: 6), Bearish ALMA Sigma (bear_alma_sigma, default: 0.85), Bearish TVMA Length (bear_tvma_length, default: 3), Bearish T3 Factor (bear_t3_factor, default: 0.7), Bearish KAMA Fast EMA Length (bear_kama_fast_len, default: 2), Bearish KAMA Slow EMA Length (bear_kama_slow_len, default: 30): Same as bullish counterparts.

Deviation Measures:
Description and How They Work
The indicator allows users to select from eight deviation measures to normalize the price deviation from the linear regression line (price - linreg) for bullish and bearish signals. Each measure quantifies price deviation differently, affecting signal frequency and strength. Below is a summary of each measure, its calculation, and how it works in the indicator.

Median Absolute Deviation (MAD):Description: Measures the median of absolute deviations from the median price, providing a robust estimate of variability less affected by outliers.
How It Works: Normalizes the price deviation from the linear regression line by MAD. A high positive value indicates a bullish deviation; a negative value indicates a bearish deviation. Signals trigger when the deviation exceeds bull_madMult or falls below -bear_madMult.
Use Case: Ideal for markets with non-normal price distributions or outliers, as it focuses on typical deviations.

Standard Deviation (SD):
Description: Measures the average distance of prices from their mean, emphasizing larger deviations due to squaring.
How It Works: Normalizes price deviation by SD, making signals sensitive to volatility. Suitable for markets with normal-like price distributions.
Use Case: Useful for volatility-based strategies but sensitive to extreme price movements.

Average True Range (ATR):
Description: Measures the average range of price movement (including gaps) to reflect volatility.
How It Works: Normalizes deviation by ATR, making signals adaptive to recent volatility. Signals trigger when the deviation exceeds the multiplier, reflecting significant moves relative to typical price ranges.
Use Case: Effective in trending or volatile markets where price ranges vary significantly.

Z-Score:
Description: Measures how many standard deviations the price is from its mean, providing a standardized deviation metric.
How It Works: Uses deviation from the mean (not linreg) to align with the standard Z-Score definition. Signals trigger based on the multiplier, indicating extreme price movements relative to historical volatility.
Use Case: Suitable for mean-reversion strategies or identifying overbought/oversold conditions.

Interquartile Range (IQR):
Description: Measures the range between the 25th and 75th percentiles of price data, capturing the middle 50% of the distribution.
How It Works: Normalizes deviation by IQR, focusing on the central data range and ignoring extremes. Signals trigger for significant deviations relative to this range.
Use Case: Robust for skewed data, useful for filtering out extreme price movements.

Mean Absolute Deviation (Mean AD):
Description: Measures the average absolute deviation of prices from their mean, providing a simpler alternative to SD.
How It Works: Normalizes deviation by Mean AD, offering a less outlier-sensitive measure than SD. Signals trigger for significant deviations.
Use Case: Suitable for stable markets where robustness is less critical than with MAD.

Calculations in the Stats Table
The stats table, displayed in the top-right corner of the chart, summarizes the performance of bullish and bearish signals. The metrics remain unchanged but now reflect the selected deviation measure’s impact on signal generation. Below are the metrics, their calculations, and derivations.
Bullish Metrics
Bullish Signals (bullSignalCount):Calculation: Increments by 1 each time a new bullish signal is triggered (newBullish = true).
Derivation: Triggered when price > linreg, bull_deviation > bull_madMult, bull_volScore > bull_volThreshold, isUptrend is true (if trend filter is enabled), and the cooldown period has passed.
Purpose: Counts the total number of bullish signals.

Bull Success Rate:
Calculation: (bullSuccessCount / bullSignalCount) * 100, rounded to 1 decimal place, displayed as a percentage. Returns "N/A" if bullSignalCount = 0.
Derivation: bullSuccessCount increments if the price change over bull_lookForwardBars meets or exceeds bull_successThreshold (in points or percent, based on bull_successThresholdType).
Purpose: Indicates the percentage of bullish signals achieving the success threshold.

Bull Failure Rate:
Calculation: (bullFailureCount / bullSignalCount) * 100, rounded to 1 decimal place, displayed as a percentage. Returns "N/A" if bullSignalCount = 0.
Derivation: bullFailureCount increments if the price change is less than or equal to -bull_failureThreshold.
Purpose: Shows the percentage of bullish signals resulting in significant losses.

Bull Avg Price Change:
Calculation: bullPriceChangeSum / bullSignalCount, rounded to 2 decimal places, displayed as a percentage. Returns "N/A" if bullSignalCount = 0.
Derivation: For each bullish signal, priceChange = (price - lastBullPrice) / lastBullPrice * 100 is calculated at the end of bull_lookForwardBars and added to bullPriceChangeSum.
Purpose: Measures the average percentage price change after bullish signals.

Bull Avg Bars to Success:
Calculation: bullBarsToSuccessSum / bullSuccessCount, rounded to 1 decimal place. Returns "N/A" if bullSuccessCount = 0.
Derivation: For successful bullish signals, the number of bars from the signal to when the success threshold is first met is added to bullBarsToSuccessSum.
Purpose: Indicates the average time (in bars) for successful bullish signals to reach the target.

Bull Avg MAE (Points):
Calculation: bullMAESum / bullSignalCount, rounded to 2 decimal places. Returns "N/A" if bullSignalCount = 0.
Derivation: Maximum Adverse Excursion (MAE) is the maximum price drop (lastBullPrice - low) during bull_lookForwardBars, summed in bullMAESum.
Purpose: Shows the average maximum drawdown in points.

Bull Avg MFE (Points):Calculation: bullMFESum / bullSignalCount, rounded to 2 decimal places. Returns "N/A" if bullSignalCount = 0.
Derivation: Maximum Favorable Excursion (MFE) is the maximum price gain (high - lastBullPrice) during bull_lookForwardBars, summed in bullMFESum.
Purpose: Indicates the average maximum profit potential in points.

Bull Win/Loss Ratio:
Calculation: bullSuccessCount / max(bullFailureCount, 1), rounded to 2 decimal places.
Derivation: Ratio of successful to failed bullish signals, with a minimum denominator of 1 to avoid division by zero.
Purpose: Measures the ratio of winning to losing signals.

Bull Avg Signal Strength:
Calculation: bullSignalStrengthSum / bullSignalCount, rounded to 2 decimal places. Returns "N/A" if bullSignalCount = 0.
Derivation: bullSignalStrengthSum accumulates the absolute value of the selected deviation measure (bull_deviation) at each bullish signal.
Purpose: Reflects the average magnitude of price deviation at signal points, varying by the chosen measure (e.g., MAD units, SD units, or logarithmic differences).

Bearish Metrics
These are analogous to bullish metrics but measure downward price movements:
Bearish Signals (bearSignalCount): Counts bearish signals (newBearish = true).
Bear Success Rate: (bearSuccessCount / bearSignalCount) * 100, where success is a price drop meeting bear_successThreshold.
Bear Failure Rate: (bearFailureCount / bearSignalCount) * 100, where failure is a price increase exceeding bear_failureThreshold.
Bear Avg Price Change: bearPriceChangeSum / bearSignalCount, where priceChange = (lastBearPrice - price) / lastBearPrice * 100.
Bear Avg Bars to Success: bearBarsToSuccessSum / bearSuccessCount.
Bear Avg MAE (Points): bearMAESum / bearSignalCount, where MAE is high - lastBearPrice.
Bear Avg MFE (Points): bearMFESum / bearSignalCount, where MFE is lastBearPrice - low.
Bear Win/Loss Ratio: bearSuccessCount / max(bearFailureCount, 1).
Bear Avg Signal Strength: bearSignalStrengthSum / bearSignalCount, using bear_deviation.

Combined Metric
Signal Frequency (per 100 bars):
Calculation: ((bullSignalCount + bearSignalCount) / bar_index) * 100, rounded to 2 decimal places. Returns "N/A" if bar_index = 0.
Derivation: Total signals divided by total bars, scaled to a per-100-bars rate.
Purpose: Indicates signal frequency relative to chart history.

How to Interpret the Stats Table
The stats table provides a comprehensive overview of the indicator’s performance, helping traders assess its effectiveness across different deviation measures. Here’s how to interpret each metric:

Bullish/Bearish Signals:
Interpretation: A high number of signals indicates frequent trading opportunities, but excessive signals may suggest over-signaling, especially if success rates are low. Compare with Signal Frequency to assess rarity.

Success Rate:
Interpretation: A higher success rate (e.g., >60%) suggests reliable signals. A low rate may require adjusting the deviation multiplier (bull_madMult, bear_madMult) or switching deviation measures.

Failure Rate:
Interpretation: A high failure rate (e.g., >50%) indicates frequent losses, suggesting the deviation measure or parameters may not suit the market. Consider stricter filters (e.g., trend filter or higher multiplier).

Average Price Change:
Interpretation: Positive values for bullish signals (or bearish for downward moves) indicate alignment with signal direction. Negative or low values suggest poor performance, possibly due to an unsuitable deviation measure.

Average Bars to Success:
Interpretation: A lower number (e.g., <3 bars) suits short-term traders; a higher number suits swing traders. Different deviation measures may affect this due to varying signal timing.

Average MAE (Points):
Interpretation: Represents average maximum drawdown. High MAE suggests higher risk, requiring wider stop-losses. Compare with Avg MFE for risk-reward assessment.

Average MFE (Points):Interpretation: Indicates average maximum profit potential. A high MFE relative to MAE suggests a favorable risk-reward ratio. Deviation measures like ATR may yield higher MFE in volatile markets.

Win/Loss Ratio:
Interpretation: A ratio >1 indicates more wins than losses. A ratio <1 suggests the deviation measure or parameters need adjustment.

Average Signal Strength:
Interpretation: Reflects the average deviation magnitude at signal points. Values vary by measure (e.g., Logarithmic Deviation yields smaller values, Z-Score yields larger ones). Higher values suggest stronger deviations, potentially increasing reliability.

Signal Frequency (per 100 bars):Interpretation: Low frequency (e.g., <5) indicates rare, potentially high-quality signals. High frequency suggests frequent signals, but check success/failure rates. Deviation measures like SD or Z-Score may produce fewer signals due to sensitivity to volatility.

How the Indicator Works
Moving Average Calculation:
The ma() function calculates the specified moving average (e.g., SMA, EMA, T3) for bullish (bull_sma) and bearish (bear_sma) signals using the respective input parameters.
Used for trend filtering and visualized with distinct colors.

Deviation and Oscillator:
Price Deviation: Calculated as price - linreg, where linreg is the linear regression line over bull_length (for bullish signals) or bear_length (for bearish signals).
Normalization: The deviation is normalized by the user-selected measure (bull_deviation_type or bear_deviation_type), producing bull_deviation or bear_deviation. This replaces the original madOsc.
Signal Trigger: Bullish signals occur when bull_deviation > bull_madMult; bearish signals occur when bear_deviation < -bear_madMult.

Signal Conditions:
Bullish Signal (newBullish):price > linreg (price above linear regression line).
bull_deviation > bull_madMult (significant upward deviation).
bull_volScore > bull_volThreshold (volume spike).
isUptrend is true (if trend filter enabled: price > bull_sma and bull_smaSlope > 0).
Cooldown period (bull_cooldownBars) has passed.

Bearish Signal (newBearish):price < linreg (price below linear regression line).
bear_deviation < -bear_madMult (significant downward deviation).
bear_volScore > bear_volThreshold (volume spike).
isDowntrend is true (if trend filter enabled: price < bear_sma and bear_smaSlope < 0).
Cooldown period (bear_cooldownBars) has passed.

Performance Tracking:
Tracks price, bar index, and deviation value at each signal.
Monitors price change, MAE, MFE, and success/failure over the look-forward period.
Aggregates metrics in the stats table.

Visualization:Bullish signals: Blue upward triangles below the bar with "Buy" label.
Bearish signals: Purple downward triangles above the bar with "Short" label.
Moving averages and median price (if plotted) are shown as stepped lines.

Practical Use and Interpretation
Trading Decisions:
Use bullish signals (blue triangles) for potential buy entries and bearish signals (purple triangles) for sell/short entries.
Evaluate signal reliability using the stats table, focusing on success rates, win/loss ratios, and MAE/MFE. Different deviation measures may yield varying performance.
Adjust bull_deviation_type and bear_deviation_type to test which measure best suits the asset (e.g., ATR for volatile markets, MAD for noisy data).

Risk Management:
Use Avg MAE to set stop-loss levels, accounting for drawdowns typical of the chosen deviation measure.
Compare Avg MFE with Avg MAE to assess risk-reward. Measures like ATR may show higher MFE in volatile conditions.
High Signal Frequency with low success rates may indicate overtrading; increase cooldownBars or deviation multipliers.

Parameter Tuning:
Adjust bull_madMult and bear_madMult based on the deviation measure:
MAD/IQR/Mean AD: 1–3.
SD/Z-Score: 1–2.
ATR: 1–3.

Experiment with bull_length and bear_length to match market speed (shorter for fast markets, longer for trending ones).
Test different ma_type settings to align with asset volatility.

Choosing Deviation Measures:
MAD/IQR: Use for robustness against outliers in noisy markets.
SD/Z-Score: Use for volatility-sensitive signals in normal-like markets.
ATR: Use for volatility-adjusted signals in trending markets.
Theil-Sen: Use for robust trend-based signals, though computationally intensive.
Logarithmic: Use for assets with exponential price growth (e.g., cryptocurrencies).
Mean AD: Use for simpler, less robust deviation measurement in stable markets.

Limitations:
The indicator may lag in fast-moving markets due to reliance on historical data.
Success/failure metrics depend on chosen thresholds and deviation measures, requiring backtesting.
Performance varies by asset, timeframe, and deviation measure; thorough testing is essential.

This enhanced indicator is a versatile tool for traders, combining customizable price deviation measures with volume and trend analysis. By selecting appropriate deviation measures and tuning parameters, traders can optimize the indicator for their strategy and market conditions.

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.