Machine Learning PSAR [BOSWaves]Machine Learning PSAR - Adaptive Parabolic Stop and Reverse with K-Means Regime Detection and KNN Signal Validation
Overview
Machine Learning PSAR is a regime-aware trend reversal system that tracks directional price movement through an adaptive Parabolic SAR, where acceleration parameters dynamically adjust based on market regime classification and each reversal signal is validated against historically similar setups using a K-Nearest Neighbors scoring model.
Instead of relying on fixed acceleration factors or unfiltered SAR flips, trend state, parameter scaling, and signal confidence are determined through K-Means flip-frequency clustering, KNN outcome weighting, and Kalman-filtered output smoothing that maintains visual clarity without sacrificing reversal responsiveness.
This creates a SAR system that reflects actual market conditions rather than applying the same parameters regardless of context - tightening in trending environments where acceleration should build quickly, relaxing in choppy conditions where early flips are noise, and scoring every reversal against the historical record so confidence is quantified rather than assumed.
Price is therefore evaluated relative to a SAR that adapts to regime dynamics and historically validated reversal patterns rather than conventional fixed-parameter parabolic logic.
Conceptual Framework
Machine Learning PSAR is founded on the principle that meaningful reversal signals emerge when the SAR acceleration factor is calibrated to current market conditions, and when each flip is cross-referenced against similar historical flips to assess its probability of success.
Traditional PSAR implementations use fixed start, increment, and maximum AF values that ignore whether the market is trending or ranging. This framework replaces static acceleration logic with regime-driven parameter adaptation informed by flip frequency clustering, then layers a KNN validation pass on top to score each signal before it is presented.
Three core principles guide the design:
Acceleration factor behavior should adapt to the detected market regime, becoming more aggressive during trending conditions and more conservative during choppy ones.
Every SAR flip should be scored against historically similar setups so confidence is expressed as a quantified probability rather than a binary signal.
The displayed SAR line should be smooth enough for clean visual interpretation while remaining responsive enough that reversals are never delayed.
This shifts SAR analysis from a fixed-parameter trailing stop into an adaptive, regime-anchored reversal system with integrated signal confidence measurement.
Theoretical Foundation
The indicator combines classical Parabolic SAR logic, K-Means-inspired regime classification, K-Nearest Neighbors outcome scoring, exponential AF smoothing, and Kalman filter output processing.
Flip frequency over a configurable training period provides the feature for regime classification, with centroid distances determining whether the market is trending, neutral, or choppy. KNN validation uses a five-dimensional feature vector at each flip — prior trend duration, bars since last flip, AF at flip, flip frequency, and EP progress — to find the most similar historical flips and weight their outcomes by proximity. The Kalman filter then smooths the final SAR output while snapping to new values instantly on every reversal.
Four internal systems operate in tandem:
Adaptive PSAR Engine : Computes classical parabolic SAR with optional AF smoothing and minimum bars filter to suppress whipsaw flips.
K-Means Regime Classifier : Measures flip frequency relative to its historical range, assigns the current bar to the nearest of three regime centroids, and adjusts AF start, increment, and maximum accordingly.
KNN Signal Validator : On each flip, searches historical flips for the k most similar setups by Euclidean distance, computes an inverse-distance-weighted confidence score, and filters low-confidence signals from high-confidence alerts.
Kalman Smoothing Layer : Applies a recursive Kalman filter to the SAR output for display, balancing smoothness with responsiveness and resetting on every reversal so flips are never visually delayed.
This design allows reversal signals to reflect actual market behavior and historical precedent rather than reacting mechanically to fixed acceleration rules.
How It Works
Machine Learning PSAR evaluates price through a sequence of regime-aware and historically-validated processes:
PSAR Initialization : Classical parabolic SAR begins with base AF start value, tracking EP and advancing the stop in the trend direction.
AF Smoothing : Instead of stepping AF in discrete increments, exponential smoothing ramps it gradually toward the target, producing a more fluid SAR trajectory.
Minimum Bars Filter : Trend must persist for a configurable minimum number of bars before a flip is allowed, preventing immediate whipsaw reversals.
Flip Detection : Price crossing the SAR triggers a raw flip, resetting AF, capturing the new EP, and recording trend duration and context features.
Flip Frequency Measurement : Rolling count of flips over the training period, normalized to its historical range, provides the regime classification feature.
Regime Assignment : Flip frequency is compared against three percentile-anchored centroids; the nearest centroid determines whether the market is choppy, neutral, or trending.
Parameter Adaptation : Regime assignment scales AF start, increment, and maximum — reducing them in choppy conditions to slow the SAR, increasing them in trending conditions to accelerate it.
KNN Feature Construction : At each flip, a five-dimensional vector is built from current context and compared against all historical flips of the same direction within the lookback window.
Neighbor Scoring : The k closest historical flips by Euclidean distance are retrieved; each is weighted by inverse distance and its five-bar forward outcome determines a weighted success rate.
Confidence Assignment : Weighted success rate expressed as a 0–100% confidence score, with flips below the minimum threshold classified as low-confidence.
Kalman Filtering : SAR value is passed through a Kalman filter for display smoothing, with process and measurement noise configurable; filter snaps to new SAR position on every flip.
Confidence Fill : Fill opacity between SAR and price anchor reflects current confidence score — denser fill indicates higher conviction in the active trend.
Together, these elements form a continuously updating reversal framework anchored in regime awareness and historically validated signal quality.
Interpretation
Machine Learning PSAR should be interpreted as a confidence-weighted trend reversal system with regime-adaptive sensitivity:
Bullish State (Blue) : Established when price closes above the SAR after a validated bullish flip, with SAR acting as a dynamic trailing support level below price.
Bearish State (Red) : Established when price closes below the SAR after a validated bearish flip, with SAR acting as a dynamic trailing resistance level above price.
Confidence Fill : Gradient zone between SAR and price reflects KNN confidence — vivid, dense fill indicates high historical precedent for the current flip; faint fill indicates low confidence.
Confidence Score Labels : Percentage label at each flip displays the KNN confidence score. Green (70%+) indicates strong historical backing; orange (50–69%) indicates moderate backing; red (below 50%) indicates low historical support.
Regime Labels : Numbers displayed alongside the SAR indicate current market regime — 3 for trending, 2 for neutral, 1 for choppy — reflecting the K-Means classifier output in real time.
High-Confidence Flips : Flips meeting or exceeding the minimum confidence threshold trigger alerts and represent the primary actionable signals.
Low-Confidence Flips : Flips below the confidence threshold are still displayed but excluded from high-confidence alerts, flagging setups with weak historical precedent.
Regime classification, KNN confidence, and Kalman-smoothed SAR position together outweigh any isolated price movement against the stop.
Signal Logic & Visual Cues
Machine Learning PSAR presents two primary signal categories:
High-Confidence Flip : SAR reversal with KNN score at or above the minimum confidence threshold. These represent setups where historically similar conditions produced successful reversals at a statistically meaningful rate and form the basis for alert-driven systematic monitoring.
Low-Confidence Flip : SAR reversal with KNN score below the minimum confidence threshold. The signal is displayed for awareness but is not included in high-confidence alert conditions, reflecting limited historical precedent.
Regime labels provide continuous market context between flips, allowing real-time awareness of whether the K-Means system is operating in a trending, neutral, or choppy environment. Confidence fill intensity provides a passive, non-disruptive view of trend conviction without requiring active label reading.
Alert generation covers high-confidence bullish and bearish flips, separately triggerable 70%+ confidence signals, and regime transition events for systematic monitoring of market state changes.
Strategy Integration
Machine Learning PSAR fits within adaptive trend-following and signal-quality-filtered reversal approaches:
Confidence-Gated Entries : Enter reversals only on high-confidence flips, using the minimum confidence threshold as a quality gate that filters historically weak setups.
Regime-Aware Sizing : Increase position sizing during trending regime (label 3) where the K-Means system detects low flip frequency and sustained directional conviction.
Choppy Market Avoidance : Reduce or pause activity during choppy regime (label 1) where frequent flips indicate low directional conviction and elevated whipsaw risk.
SAR as Stop Placement : Use the Kalman-smoothed SAR as a trailing stop reference — exit longs when price closes below the bullish SAR, exit shorts when price closes above the bearish SAR.
Confidence Fill Monitoring : Use fill intensity as a passive conviction gauge — fading fill during an active trend may indicate the next flip is likely to be lower confidence.
Multi-Timeframe Regime Alignment : Apply higher-timeframe regime label as a directional filter, entering signals only when the regime aligns across timeframes.
Alert-Based Systematic Monitoring : Configure high-confidence and regime-change alerts for systematic notification without requiring active chart monitoring.
Technical Implementation Details
Core Engine : Classical Parabolic SAR with configurable base AF start, increment, and maximum, optional exponential AF smoothing, and minimum bars flip filter
Regime Model : Flip frequency normalized to training-period range with three percentile-anchored centroids (choppy, neutral, trending) and nearest-centroid assignment
KNN Validator : Five-dimensional feature vector with configurable k and lookback, inverse-distance weighting, and five-bar forward outcome labeling
Smoothing Layer : Kalman filter with configurable process and measurement noise, hard snap to SAR on every flip to preserve reversal timing
Visualization : Dual-plot SAR circles with confidence-opacity fill, percentage confidence labels, every-other-bar regime labels
Signal Logic : High/low confidence classification with configurable minimum threshold, raw flip detection decoupled from display
Performance Profile : Optimized for real-time execution across all timeframes with efficient array-based KNN search and FIFO distance sorting
Optimal Application Parameters
Timeframe Guidance:
1 - 5 min : Scalping with tighter AF values, shorter KNN lookback, and lower minimum confidence threshold
15 - 60 min : Intraday trend following with balanced regime sensitivity and moderate confidence filtering
4H - Daily : Swing and position trading with wider AF maximum, longer training period, and higher confidence threshold
Suggested Baseline Configuration:
Base AF Start : 0.02
Base AF Increment : 0.02
Base AF Maximum : 0.10
Training Data Period : 100
Choppy Regime Percentile : 0.75
Trending Regime Percentile : 0.25
K - Number of Neighbors : 8
Historical Lookback Period : 200
Minimum Confidence Filter : 15%
AF Smoothing Factor : 0.01
Kalman Process Noise : 0.015
Kalman Measurement Noise : 0.5
Minimum Bars Before Flip : 3
These suggested parameters should be used as a baseline; their effectiveness depends on the asset's volatility profile, trending characteristics, and preferred signal frequency, so fine-tuning is expected for optimal performance.
Parameter Calibration Notes
Use the following adjustments to refine behavior without altering the core logic:
Too many flips in ranging markets : Increase Minimum Bars Before Flip to require longer trend duration before a reversal is allowed, or increase Base AF Maximum to widen the SAR distance.
SAR too slow to reverse : Decrease Base AF Start and increase Base AF Increment so the acceleration factor builds more quickly during new trends.
Excessive low-confidence signals : Increase Minimum Confidence Filter to raise the threshold for high-confidence classification, focusing only on the strongest historical precedents.
KNN scores feel unstable : Increase K - Number of Neighbors to average over more historical examples, smoothing out per-flip score variance.
Regime changing too rapidly : Increase Training Data Period to smooth regime classification over a longer flip-frequency history.
Regime too slow to update : Decrease Training Data Period for more responsive regime detection that reacts faster to market character shifts.
SAR line too jumpy visually : Increase Kalman Measurement Noise for more aggressive smoothing, or decrease Kalman Process Noise to make the filter trust its own estimate more.
Kalman lagging reversals : Decrease Kalman Measurement Noise or increase Kalman Process Noise to make the filter more responsive to SAR changes between flips.
AF ramping too abruptly : Decrease AF Smoothing Factor toward 0.01 for a more gradual exponential ramp from start to target AF on each new trend.
Adjustments should be incremental and evaluated across multiple market sessions rather than isolated conditions.
Performance Characteristics
High Effectiveness:
Trending markets with sustained directional conviction where flip frequency remains low and regime classification stabilizes at label 3
Instruments with consistent volatility where ATR-normalized KNN features generalize well across historical flips
Momentum continuation strategies using SAR as a trailing stop with confidence-filtered entries at reversals
Systematic approaches benefiting from quantified signal confidence and regime-based parameter adaptation
Multi-timeframe frameworks where regime labels provide higher-timeframe directional context for lower-timeframe entries
Reduced Effectiveness:
Choppy, range-bound markets with high flip frequency causing frequent low-confidence signals and regime label 1 classification
Extremely thin historical data environments where the KNN lookback contains insufficient comparable flips for reliable scoring
News-driven or gapped markets where discrete price discontinuities bypass SAR logic and invalidate ATR-normalized tension features
Very low volatility instruments where ATR scaling compresses feature vectors and reduces KNN discriminative power
Consolidation phases where mean-reversion dominance causes repeated SAR whipsaws regardless of minimum bars filtering
Integration Guidelines
Confluence : Combine with BOSWaves volume analysis, structure detection, or supply and demand zone identification for multi-factor confirmation
SAR Respect : Honor the trailing SAR as the primary risk boundary — avoid holding positions against the active stop regardless of confidence score
Confidence Awareness : Treat confidence scores as probabilistic context, not certainty — high scores improve odds but do not guarantee outcome
Regime Discipline : Reduce activity during persistent choppy regime classification rather than fighting repeated low-confidence flips
Alert Utilization : Configure high-confidence and regime-change alerts to enable systematic monitoring without requiring active chart observation
Lookback Sufficiency : Ensure sufficient historical bars are loaded for the KNN lookback period before relying on confidence scores, particularly on shorter timeframes
Multi-Timeframe Alignment : Use higher timeframe regime label and trend direction as a filter for lower timeframe flip entries to ensure directional confluence
Disclaimer
Machine Learning PSAR is a professional-grade adaptive reversal and trend-following tool. It uses K-Means regime classification and KNN signal validation to adapt classical Parabolic SAR behavior to current market conditions but does not predict future price movements. Results depend on market conditions, volatility characteristics, parameter selection, and disciplined execution. BOSWaves recommends deploying this indicator within a broader analytical framework that incorporates price structure, volume context, and comprehensive risk management.
Indicador Pine Script®






















