OPEN-SOURCE SCRIPT
Updated Fourier series Model Of The Market

█ OVERVIEW
The Fourier Series Model of the Market (FSMM) decomposes price action into harmonic components using bandpass filtering, then reconstructs a composite wave weighted by rolling energy ratios. This approach isolates cyclical market behavior at multiple frequencies, emphasizing dominant cycles for cleaner signal generation. The energy-adaptive weighting is the key differentiator from simple harmonic summation: cycles that dominate current price action contribute more to the output.
Based on Fourier analysis principles applied to financial markets, the indicator extracts harmonics (fundamental, 2nd, 3rd, etc.) using second-order IIR bandpass filters, then weights each harmonic's contribution by its relative energy compared to adjacent harmonics. This energy-adaptive weighting naturally emphasizes the cycles that are most prominent in current market conditions.
█ CONCEPTS
Fourier Decomposition
Fourier analysis represents any periodic signal as a sum of sine waves at different frequencies. In market analysis, price action can be decomposed into a fundamental cycle (the base period) plus harmonics at integer multiples of that frequency (period/2, period/3, etc.). Each harmonic captures oscillations at a specific frequency band, and their sum reconstructs the original cyclical behavior.
Bandpass Filtering
Each harmonic is extracted using a second-order IIR (Infinite Impulse Response) bandpass filter tuned to that harmonic's frequency. The filter isolates price activity within a narrow frequency range while rejecting both higher-frequency noise and lower-frequency trend drift. Before filtering, the source is debiased via 2-bar momentum to remove DC offset, ensuring each bandpass operates around true zero.
Energy-Weighted Reconstruction
Rather than simply summing all harmonics equally, FSMM weights each harmonic by its rolling energy relative to the previous harmonic. The energy score combines the current harmonic value with its rate of change, so it reflects both amplitude and momentum. Higher harmonics that hold comparatively more energy therefore contribute more to the composite wave, while weaker harmonics fade out. This adaptive weighting allows the model to respond to changing market cyclicality.
Quadrature Component (Rate of Change)
The rate of change output represents the 90°-phase-shifted (quadrature) component of the wave. When the wave is at zero and rising, the rate of change is at maximum positive. This provides complementary information about cycle phase and can be used for timing entries relative to cycle position.
█ INTERPRETATION
Wave Output
The composite wave oscillates around zero, representing the sum of all extracted harmonic components weighted by energy:
• Above zero: Net bullish cyclical momentum across harmonics
• Below zero: Net bearish cyclical momentum across harmonics
• Zero crossings: Cycle phase transitions - potential reversal points
• Wave amplitude: Strength of cyclical behavior; larger swings indicate cleaner cycles
Rate of Change
The quadrature component (90° phase-shifted) provides cycle phase information:
• Maximum rate of change: Wave is near zero and accelerating - early cycle phase
• Zero rate of change: Wave is at peak or trough - cycle extremes
• Rate/Wave divergence: When wave makes new highs/lows but rate of change does not confirm (lower momentum), suggests cycle exhaustion or impending phase shift
Combined Analysis
• Wave crossing above zero with positive rate of change: Strong bullish cycle initiation
• Wave crossing below zero with negative rate of change: Strong bearish cycle initiation
• Wave at extreme with rate of change reversing: Potential cycle peak/trough
Threshold Bands
When enabled, threshold bands define statistically significant wave deviations:
• Breach above +threshold: Unusually strong bullish cyclical behavior
• Breach below -threshold: Unusually strong bearish cyclical behavior
• Return inside thresholds: Normalizing behavior, potential mean reversion ahead
Alert Conditions
Four built-in alerts trigger on bar close (no repainting):
• Above +Threshold: Strong bullish cycle behavior
• Below -Threshold: Strong bearish cycle behavior
• Above Zero: Bullish cycle phase shift
• Below Zero: Bearish cycle phase shift
█ SETTINGS & PARAMETER TUNING
Fourier Series Model
• Source: Price series to decompose into harmonic components.
• Period (6-100): Base period for the fundamental harmonic. Higher harmonics divide this period (harmonic 2 = period/2, harmonic 3 = period/3). Match to the dominant market cycle for best results. Default 20.
• Bandwidth (0.05-0.5): Bandpass filter selectivity. Lower values create narrower passbands that isolate harmonics more precisely but may miss slightly off-frequency cycles. Higher values capture broader ranges but reduce harmonic separation. Default 0.1 balances precision and robustness.
• Harmonics (1-20): Number of harmonic components to extract. More harmonics capture finer cyclical detail but increase computation. For most applications, 3-5 harmonics suffice. The fundamental alone (1 harmonic) functions as a simple bandpass filter.
Display Settings
• Wave Outputs: Toggle visibility and color of the composite Fourier wave.
• Rate of Change: Toggle visibility and color of the quadrature component (90° phase-shifted wave).
• Zero Line: Reference line for oscillator neutrality.
Diagnostics - Dynamic Thresholds
Optional significance bands that identify when wave readings indicate strong cyclical behavior:
• Dynamic Threshold: Toggle threshold bands and set colors.
• Threshold Mode: Select calculation method:
- MAD (Median Absolute Deviation): Robust, outlier-resistant measure using k * MAD where MAD ≈ 0.6745 * stdev.
- Standard Deviation: Volatility-sensitive, calculated as k * stdev of wave over the lookback period.
- Percentile Rank: Fixed probability bands using percentile of |wave| (90% means only 10% of values exceed threshold).
• Period (2-200): Lookback for threshold calculations. Default 50.
• Multiplier (k): Scaling for MAD/Standard Deviation modes. Default 1.5.
• Percentile (%) (0-100): For Percentile Rank mode only. Default 90%.
Parameter Interactions
• Shorter periods respond faster to cycle changes but may capture noise.
• Lower bandwidth + more harmonics = more precise decomposition but requires accurate period setting.
• Higher bandwidth is more forgiving of period mismatches.
• For strongly trending markets, restrict harmonics to 1-2 so the model tracks the dominant cycle with fewer higher-frequency components.
• For ranging/oscillating markets, more harmonics (4-6) capture complex cycles.
█ LIMITATIONS
Inherent Characteristics
• Period dependency: Effectiveness depends on correctly matching the Period parameter to actual market cycles. Use cycle measurement tools (autocorrelation, FFT, dominant cycle indicators) to identify appropriate periods.
• Stationarity assumption: The indicator assumes cycle frequencies remain relatively stable within the lookback window. Rapidly shifting dominant cycles (regime transitions) may produce inconsistent results until the buffer adapts.
• Filter lag: Despite bandpass design, some lag remains inherent to causal filtering. Higher harmonics have less lag but more noise sensitivity.
• Energy weighting artifacts: During regime changes when harmonic energy ratios shift rapidly, weighting may produce transient anomalies.
Market Conditions to Avoid
• Strong trending markets: Pure trends with no cyclicality produce weak, meandering signals. The indicator assumes cyclical market behavior.
• News events/gaps: Large discontinuities disrupt filter continuity. Requires 1-2 full periods to stabilize.
• Period mismatch: If the Period parameter doesn't match actual market cycles, harmonic extraction produces noise rather than signal.
Parameter Selection Pitfalls
• Too many harmonics: Beyond 5-6 harmonics, additional components often capture noise rather than meaningful cycles.
• Bandwidth too narrow: Very low bandwidth (< 0.05) requires extremely precise period matching; slight mismatches cause signal loss.
• Over-optimization: Perfect historical parameter fits typically fail forward. Use robust defaults across multiple instruments.
█ NOTES
Credits
This indicator applies Fourier analysis principles to financial market data, building on the extensive work of Dr. John F. Ehlers in applying digital signal processing to trading. The bandpass filter implementation and harmonic decomposition approach draw from DSP fundamentals as presented in Ehlers' publications.
For those interested in the underlying mathematics and DSP concepts:
• Ehlers, J.F. (2001). Rocket Science for Traders: Digital Signal Processing Applications. John Wiley & Sons.
• Ehlers, J.F. (2013). Cycle Analytics for Traders. John Wiley & Sons.
• Various TASC articles by John Ehlers on bandpass filters, cycle analysis, and harmonic decomposition.
by ♚e2e4
The Fourier Series Model of the Market (FSMM) decomposes price action into harmonic components using bandpass filtering, then reconstructs a composite wave weighted by rolling energy ratios. This approach isolates cyclical market behavior at multiple frequencies, emphasizing dominant cycles for cleaner signal generation. The energy-adaptive weighting is the key differentiator from simple harmonic summation: cycles that dominate current price action contribute more to the output.
Based on Fourier analysis principles applied to financial markets, the indicator extracts harmonics (fundamental, 2nd, 3rd, etc.) using second-order IIR bandpass filters, then weights each harmonic's contribution by its relative energy compared to adjacent harmonics. This energy-adaptive weighting naturally emphasizes the cycles that are most prominent in current market conditions.
█ CONCEPTS
Fourier Decomposition
Fourier analysis represents any periodic signal as a sum of sine waves at different frequencies. In market analysis, price action can be decomposed into a fundamental cycle (the base period) plus harmonics at integer multiples of that frequency (period/2, period/3, etc.). Each harmonic captures oscillations at a specific frequency band, and their sum reconstructs the original cyclical behavior.
Bandpass Filtering
Each harmonic is extracted using a second-order IIR (Infinite Impulse Response) bandpass filter tuned to that harmonic's frequency. The filter isolates price activity within a narrow frequency range while rejecting both higher-frequency noise and lower-frequency trend drift. Before filtering, the source is debiased via 2-bar momentum to remove DC offset, ensuring each bandpass operates around true zero.
Energy-Weighted Reconstruction
Rather than simply summing all harmonics equally, FSMM weights each harmonic by its rolling energy relative to the previous harmonic. The energy score combines the current harmonic value with its rate of change, so it reflects both amplitude and momentum. Higher harmonics that hold comparatively more energy therefore contribute more to the composite wave, while weaker harmonics fade out. This adaptive weighting allows the model to respond to changing market cyclicality.
Quadrature Component (Rate of Change)
The rate of change output represents the 90°-phase-shifted (quadrature) component of the wave. When the wave is at zero and rising, the rate of change is at maximum positive. This provides complementary information about cycle phase and can be used for timing entries relative to cycle position.
█ INTERPRETATION
Wave Output
The composite wave oscillates around zero, representing the sum of all extracted harmonic components weighted by energy:
• Above zero: Net bullish cyclical momentum across harmonics
• Below zero: Net bearish cyclical momentum across harmonics
• Zero crossings: Cycle phase transitions - potential reversal points
• Wave amplitude: Strength of cyclical behavior; larger swings indicate cleaner cycles
Rate of Change
The quadrature component (90° phase-shifted) provides cycle phase information:
• Maximum rate of change: Wave is near zero and accelerating - early cycle phase
• Zero rate of change: Wave is at peak or trough - cycle extremes
• Rate/Wave divergence: When wave makes new highs/lows but rate of change does not confirm (lower momentum), suggests cycle exhaustion or impending phase shift
Combined Analysis
• Wave crossing above zero with positive rate of change: Strong bullish cycle initiation
• Wave crossing below zero with negative rate of change: Strong bearish cycle initiation
• Wave at extreme with rate of change reversing: Potential cycle peak/trough
Threshold Bands
When enabled, threshold bands define statistically significant wave deviations:
• Breach above +threshold: Unusually strong bullish cyclical behavior
• Breach below -threshold: Unusually strong bearish cyclical behavior
• Return inside thresholds: Normalizing behavior, potential mean reversion ahead
Alert Conditions
Four built-in alerts trigger on bar close (no repainting):
• Above +Threshold: Strong bullish cycle behavior
• Below -Threshold: Strong bearish cycle behavior
• Above Zero: Bullish cycle phase shift
• Below Zero: Bearish cycle phase shift
█ SETTINGS & PARAMETER TUNING
Fourier Series Model
• Source: Price series to decompose into harmonic components.
• Period (6-100): Base period for the fundamental harmonic. Higher harmonics divide this period (harmonic 2 = period/2, harmonic 3 = period/3). Match to the dominant market cycle for best results. Default 20.
• Bandwidth (0.05-0.5): Bandpass filter selectivity. Lower values create narrower passbands that isolate harmonics more precisely but may miss slightly off-frequency cycles. Higher values capture broader ranges but reduce harmonic separation. Default 0.1 balances precision and robustness.
• Harmonics (1-20): Number of harmonic components to extract. More harmonics capture finer cyclical detail but increase computation. For most applications, 3-5 harmonics suffice. The fundamental alone (1 harmonic) functions as a simple bandpass filter.
Display Settings
• Wave Outputs: Toggle visibility and color of the composite Fourier wave.
• Rate of Change: Toggle visibility and color of the quadrature component (90° phase-shifted wave).
• Zero Line: Reference line for oscillator neutrality.
Diagnostics - Dynamic Thresholds
Optional significance bands that identify when wave readings indicate strong cyclical behavior:
• Dynamic Threshold: Toggle threshold bands and set colors.
• Threshold Mode: Select calculation method:
- MAD (Median Absolute Deviation): Robust, outlier-resistant measure using k * MAD where MAD ≈ 0.6745 * stdev.
- Standard Deviation: Volatility-sensitive, calculated as k * stdev of wave over the lookback period.
- Percentile Rank: Fixed probability bands using percentile of |wave| (90% means only 10% of values exceed threshold).
• Period (2-200): Lookback for threshold calculations. Default 50.
• Multiplier (k): Scaling for MAD/Standard Deviation modes. Default 1.5.
• Percentile (%) (0-100): For Percentile Rank mode only. Default 90%.
Parameter Interactions
• Shorter periods respond faster to cycle changes but may capture noise.
• Lower bandwidth + more harmonics = more precise decomposition but requires accurate period setting.
• Higher bandwidth is more forgiving of period mismatches.
• For strongly trending markets, restrict harmonics to 1-2 so the model tracks the dominant cycle with fewer higher-frequency components.
• For ranging/oscillating markets, more harmonics (4-6) capture complex cycles.
█ LIMITATIONS
Inherent Characteristics
• Period dependency: Effectiveness depends on correctly matching the Period parameter to actual market cycles. Use cycle measurement tools (autocorrelation, FFT, dominant cycle indicators) to identify appropriate periods.
• Stationarity assumption: The indicator assumes cycle frequencies remain relatively stable within the lookback window. Rapidly shifting dominant cycles (regime transitions) may produce inconsistent results until the buffer adapts.
• Filter lag: Despite bandpass design, some lag remains inherent to causal filtering. Higher harmonics have less lag but more noise sensitivity.
• Energy weighting artifacts: During regime changes when harmonic energy ratios shift rapidly, weighting may produce transient anomalies.
Market Conditions to Avoid
• Strong trending markets: Pure trends with no cyclicality produce weak, meandering signals. The indicator assumes cyclical market behavior.
• News events/gaps: Large discontinuities disrupt filter continuity. Requires 1-2 full periods to stabilize.
• Period mismatch: If the Period parameter doesn't match actual market cycles, harmonic extraction produces noise rather than signal.
Parameter Selection Pitfalls
• Too many harmonics: Beyond 5-6 harmonics, additional components often capture noise rather than meaningful cycles.
• Bandwidth too narrow: Very low bandwidth (< 0.05) requires extremely precise period matching; slight mismatches cause signal loss.
• Over-optimization: Perfect historical parameter fits typically fail forward. Use robust defaults across multiple instruments.
█ NOTES
Credits
This indicator applies Fourier analysis principles to financial market data, building on the extensive work of Dr. John F. Ehlers in applying digital signal processing to trading. The bandpass filter implementation and harmonic decomposition approach draw from DSP fundamentals as presented in Ehlers' publications.
For those interested in the underlying mathematics and DSP concepts:
• Ehlers, J.F. (2001). Rocket Science for Traders: Digital Signal Processing Applications. John Wiley & Sons.
• Ehlers, J.F. (2013). Cycle Analytics for Traders. John Wiley & Sons.
• Various TASC articles by John Ehlers on bandpass filters, cycle analysis, and harmonic decomposition.
by ♚e2e4
Release Notes
refactor: v6 update with Harmonic state management- Optimize loop performance
- Introduce Harmonic object for intra-state preservation
- Add threshold bands and alerts
Open-source script
In true TradingView spirit, the creator of this script has made it open-source, so that traders can review and verify its functionality. Kudos to the author! While you can use it for free, remember that republishing the code is subject to our House Rules.
Pisces swimming through the river
All their life against the stream
Searching for a hook to catch on
And see their sun beam
Then suffocate in painful tortures
On cutting tables of callous men
Under a knife of handsome butchers
Emeralds are ripped away
All their life against the stream
Searching for a hook to catch on
And see their sun beam
Then suffocate in painful tortures
On cutting tables of callous men
Under a knife of handsome butchers
Emeralds are ripped away
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.
Open-source script
In true TradingView spirit, the creator of this script has made it open-source, so that traders can review and verify its functionality. Kudos to the author! While you can use it for free, remember that republishing the code is subject to our House Rules.
Pisces swimming through the river
All their life against the stream
Searching for a hook to catch on
And see their sun beam
Then suffocate in painful tortures
On cutting tables of callous men
Under a knife of handsome butchers
Emeralds are ripped away
All their life against the stream
Searching for a hook to catch on
And see their sun beam
Then suffocate in painful tortures
On cutting tables of callous men
Under a knife of handsome butchers
Emeralds are ripped away
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.