OPEN-SOURCE SCRIPT

Savitzky-Golay Hampel Filter | AlphaNatt

302
Savitzky-Golay Hampel Filter | AlphaNatt

A revolutionary indicator combining NASA's satellite data processing algorithms with robust statistical outlier detection to create the most scientifically advanced trend filter available on TradingView.

"This is the same mathematics that processes signals from the Hubble Space Telescope and analyzes data from the Large Hadron Collider - now applied to financial markets."


━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

🚀 SCIENTIFIC PEDIGREE

Savitzky-Golay Filter Applications:
  • NASA: Satellite telemetry and space probe data processing
  • CERN: Particle physics data analysis at the LHC
  • Pharmaceutical: Chromatography and spectroscopy analysis
  • Astronomy: Processing signals from radio telescopes
  • Medical: ECG and EEG signal processing


Hampel Filter Usage:
  • Aerospace: Cleaning sensor data from aircraft and spacecraft
  • Manufacturing: Quality control in precision engineering
  • Seismology: Earthquake detection and analysis
  • Robotics: Sensor fusion and noise reduction


━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

🧬 THE MATHEMATICS

1. Savitzky-Golay Filter

The SG filter performs local polynomial regression on data points:
  • Fits a polynomial of degree n to a sliding window of data
  • Evaluates the polynomial at the center point
  • Preserves higher moments (peaks, valleys) unlike moving averages
  • Maintains derivative information for true momentum analysis
  • Originally published in Analytical Chemistry (1964)


Mathematical Properties:
  • Optimal smoothing in the least-squares sense
  • Preserves statistical moments up to polynomial order
  • Exact derivative calculation without additional lag
  • Superior frequency response vs traditional filters


2. Hampel Filter

A robust outlier detector based on Median Absolute Deviation (MAD):
  • Identifies outliers using robust statistics
  • Replaces spurious values with polynomial-fitted estimates
  • Resistant to up to 50% contaminated data
  • MAD is 1.4826 times more robust than standard deviation


Outlier Detection Formula:
|x - median| > k × 1.4826 × MAD


Where k is the threshold parameter (typically 3 for 99.7% confidence)

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

💎 WHY THIS IS SUPERIOR

vs Moving Averages:
  • Preserves peaks and valleys (critical for catching tops/bottoms)
  • No lag penalty for smoothness
  • Maintains derivative information
  • Polynomial fitting > simple averaging


vs Other Filters:
  • Outlier immunity (Hampel component)
  • Scientifically optimal smoothing
  • Preserves higher-order features
  • Used in billion-dollar research projects


Unique Advantages:
  • Feature Preservation: Maintains market structure while smoothing
  • Spike Immunity: Ignores false breakouts and stop hunts
  • Derivative Accuracy: True momentum without additional indicators
  • Scientific Validation: 60+ years of academic research


━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

⚙️ PARAMETER OPTIMIZATION

1. Polynomial Order (2-5)
  • 2 (Quadratic): Maximum smoothing, gentle curves
  • 3 (Cubic): Balanced smoothing and responsiveness (recommended)
  • 4-5 (Higher): More responsive, preserves more features


2. Window Size (7-51)
  • Must be odd number
  • Larger = smoother but more lag
  • Formula: 2×(desired smoothing period) + 1
  • Default 21 = analyzes 10 bars each side


3. Hampel Threshold (1.0-5.0)
  • 1.0: Aggressive outlier removal (68% confidence)
  • 2.0: Moderate outlier removal (95% confidence)
  • 3.0: Conservative outlier removal (99.7% confidence) (default)
  • 4.0+: Only extreme outliers removed


4. Final Smoothing (1-7)
  • Additional WMA smoothing after filtering
  • 1 = No additional smoothing
  • 3-5 = Recommended for most timeframes
  • 7 = Ultra-smooth for position trading


━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

📊 TRADING STRATEGIES

Signal Recognition:
  • Cyan Line: Bullish trend with positive derivative
  • Pink Line: Bearish trend with negative derivative
  • Color Change: Trend reversal with polynomial confirmation


1. Trend Following Strategy
  • Enter when price crosses above cyan filter
  • Exit when filter turns pink
  • Use filter as dynamic stop loss
  • Best in trending markets


2. Mean Reversion Strategy
  • Enter long when price touches filter from below in uptrend
  • Enter short when price touches filter from above in downtrend
  • Exit at opposite band or filter color change
  • Excellent for range-bound markets


3. Derivative Strategy (Advanced)
  • The SG filter preserves derivative information
  • Acceleration = second derivative > 0
  • Enter on positive first derivative + positive acceleration
  • Exit on negative second derivative (momentum slowing)


━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

📈 PERFORMANCE CHARACTERISTICS

Strengths:
  • Outlier Immunity: Ignores stop hunts and flash crashes
  • Feature Preservation: Catches tops/bottoms better than MAs
  • Smooth Output: Reduces whipsaws significantly
  • Scientific Basis: Not curve-fitted or optimized to markets


Considerations:
  • Slight lag in extreme volatility (all filters have this)
  • Requires odd window sizes (mathematical requirement)
  • More complex than simple moving averages
  • Best with liquid instruments


━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

🔬 SCIENTIFIC BACKGROUND

Savitzky-Golay Publication:
"Smoothing and Differentiation of Data by Simplified Least Squares Procedures"
- Abraham Savitzky & Marcel Golay
- Analytical Chemistry, Vol. 36, No. 8, 1964

Hampel Filter Origin:
"Robust Statistics: The Approach Based on Influence Functions"
- Frank Hampel et al., 1986
- Princeton University Press

These techniques have been validated in thousands of scientific papers and are standard tools in:
  • NASA's Jet Propulsion Laboratory
  • European Space Agency
  • CERN (Large Hadron Collider)
  • MIT Lincoln Laboratory
  • Max Planck Institutes


━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

💡 ADVANCED TIPS

  1. News Trading: Lower Hampel threshold before major events to catch spikes
  2. Scalping: Use Order=2 for maximum smoothness, Window=11 for responsiveness
  3. Position Trading: Increase Window to 31+ for long-term trends
  4. Combine with Volume: Strong trends need volume confirmation
  5. Multiple Timeframes: Use daily for trend, hourly for entry
  6. Watch the Derivative: Filter color changes when first derivative changes sign


━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

⚠️ IMPORTANT NOTICES

  • Not financial advice - educational purposes only
  • Past performance does not guarantee future results
  • Always use proper risk management
  • Test settings on your specific instrument and timeframe
  • No indicator is perfect - part of complete trading system


━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

🏆 CONCLUSION

The Savitzky-Golay Hampel Filter represents the pinnacle of scientific signal processing applied to financial markets. By combining polynomial regression with robust outlier detection, traders gain access to the same mathematical tools that:

  • Guide spacecraft to other planets
  • Detect gravitational waves from black holes
  • Analyze particle collisions at near light-speed
  • Process signals from deep space


This isn't just another indicator - it's rocket science for trading.

"When NASA needs to separate signal from noise in billion-dollar missions, they use these exact algorithms. Now you can too."


━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Developed by AlphaNatt

Version: 1.0
Release: 2025
Pine Script: v6

"Where Space Technology Meets Market Analysis"
Not financial advice. Always DYOR

면책사항

이 정보와 게시물은 TradingView에서 제공하거나 보증하는 금융, 투자, 거래 또는 기타 유형의 조언이나 권고 사항을 의미하거나 구성하지 않습니다. 자세한 내용은 이용 약관을 참고하세요.