OPEN-SOURCE SCRIPT
KNN Adaptive Cycles

█ OVERVIEW
An adaptive Stochastic RSI whose lookback lengths are driven by the market's measured dominant cycle period, further refined in real time by a K-Nearest Neighbors machine learning layer. Rather than accepting a fixed RSI or Stochastic length, the indicator continuously measures the dominant cycle in price using two independent spectral methods, then uses KNN to anticipate where the cycle is heading and to condition the oscillator output against historical outcomes — so the indicator adapts to what the market is actually doing, not what a static setting assumes it should be.
█ CYCLE DETECTION
The indicator measures the dominant cycle period using two independent methods from the digital signal processing work of John Ehlers, who treated price as a waveform and applied engineering filters to extract its underlying structure.
Autocorrelation Periodogram
Computes Pearson correlation across lags from the minimum to maximum period range, identifying the lag at which price most strongly repeats. Returns a correlation coefficient used directly as a confidence score.
Goertzel / DFT Power Spectrum
A frequency-domain scan that computes spectral power at each candidate period and selects the one carrying the most energy. Independent of the autocorrelation method, giving two mathematically distinct perspectives on the same cycle.
Before measurement, price is conditioned with Ehlers' filter set: a Highpass filter to remove the trend component, a Super Smoother for anti-aliasing, and an optional Bandpass pre-filter to isolate the cycle band. In AC + DFT (Confirmed) mode the two estimates are cross-checked, with each method weighted by its agreement strength and the AC correlation coefficient before blending into a single confirmed period. Single-method modes run the selected method at full per-bar resolution.
█ KNN MACHINE LEARNING
Two independent KNN nearest-neighbor routines operate on top of the cycle and signal layers. Both use weighted Euclidean distance across feature vectors, a 1/distance-weighted outcome average across K neighbors, and ALMA smoothing on the output bias.
Period KNN
Searches history for bars whose cycle state most closely resembles the current bar — matching on current period, rate of change, stability streak, confidence score, and volatility regime. Observes what the period actually became Forward Bars later at each neighbor, then blends that prediction into the current period estimate before final smoothing. Helps the indicator anticipate cycle transitions rather than just react to them.
Signal KNN
Searches history for bars whose StochRSI context most closely resembles now — matching on K level, K−D histogram, K slope, volatility regime, OB/OS proximity, and D line. Observes the forward price outcome at each neighbor and blends the resulting bias into the K line before D smoothing, so D inherits the correction naturally.
█ FEATURES
Cycle detection
• Dual spectral cycle detection — AC and DFT run in parallel with a 0–100% confidence score reflecting method agreement
• Confidence-weighted period blending — each method weighted by agreement and correlation strength, smoothed into one adaptive period
• Single-method modes — Optional select Autocorrelation Only or DFT Only run for faster loading
• Optional Performance Throttle — cadence-limited spectral scans for the AC + DFT mode
KNN layer
• Period KNN — anticipates cycle transitions by learning from historical cycle states and their forward outcomes
• Signal KNN — conditions the K line against historically similar StochRSI contexts and their forward price outcomes
• Per-feature importance weights for both KNN routines — tunable to emphasize what matters most on a given instrument
• ALMA-smoothed bias output — configurable length, offset, and sigma
An adaptive Stochastic RSI whose lookback lengths are driven by the market's measured dominant cycle period, further refined in real time by a K-Nearest Neighbors machine learning layer. Rather than accepting a fixed RSI or Stochastic length, the indicator continuously measures the dominant cycle in price using two independent spectral methods, then uses KNN to anticipate where the cycle is heading and to condition the oscillator output against historical outcomes — so the indicator adapts to what the market is actually doing, not what a static setting assumes it should be.
█ CYCLE DETECTION
The indicator measures the dominant cycle period using two independent methods from the digital signal processing work of John Ehlers, who treated price as a waveform and applied engineering filters to extract its underlying structure.
Autocorrelation Periodogram
Computes Pearson correlation across lags from the minimum to maximum period range, identifying the lag at which price most strongly repeats. Returns a correlation coefficient used directly as a confidence score.
Goertzel / DFT Power Spectrum
A frequency-domain scan that computes spectral power at each candidate period and selects the one carrying the most energy. Independent of the autocorrelation method, giving two mathematically distinct perspectives on the same cycle.
Before measurement, price is conditioned with Ehlers' filter set: a Highpass filter to remove the trend component, a Super Smoother for anti-aliasing, and an optional Bandpass pre-filter to isolate the cycle band. In AC + DFT (Confirmed) mode the two estimates are cross-checked, with each method weighted by its agreement strength and the AC correlation coefficient before blending into a single confirmed period. Single-method modes run the selected method at full per-bar resolution.
█ KNN MACHINE LEARNING
Two independent KNN nearest-neighbor routines operate on top of the cycle and signal layers. Both use weighted Euclidean distance across feature vectors, a 1/distance-weighted outcome average across K neighbors, and ALMA smoothing on the output bias.
Period KNN
Searches history for bars whose cycle state most closely resembles the current bar — matching on current period, rate of change, stability streak, confidence score, and volatility regime. Observes what the period actually became Forward Bars later at each neighbor, then blends that prediction into the current period estimate before final smoothing. Helps the indicator anticipate cycle transitions rather than just react to them.
Signal KNN
Searches history for bars whose StochRSI context most closely resembles now — matching on K level, K−D histogram, K slope, volatility regime, OB/OS proximity, and D line. Observes the forward price outcome at each neighbor and blends the resulting bias into the K line before D smoothing, so D inherits the correction naturally.
█ FEATURES
Cycle detection
• Dual spectral cycle detection — AC and DFT run in parallel with a 0–100% confidence score reflecting method agreement
• Confidence-weighted period blending — each method weighted by agreement and correlation strength, smoothed into one adaptive period
• Single-method modes — Optional select Autocorrelation Only or DFT Only run for faster loading
• Optional Performance Throttle — cadence-limited spectral scans for the AC + DFT mode
KNN layer
• Period KNN — anticipates cycle transitions by learning from historical cycle states and their forward outcomes
• Signal KNN — conditions the K line against historically similar StochRSI contexts and their forward price outcomes
• Per-feature importance weights for both KNN routines — tunable to emphasize what matters most on a given instrument
• ALMA-smoothed bias output — configurable length, offset, and sigma
오픈 소스 스크립트
트레이딩뷰의 진정한 정신에 따라, 이 스크립트의 작성자는 이를 오픈소스로 공개하여 트레이더들이 기능을 검토하고 검증할 수 있도록 했습니다. 작성자에게 찬사를 보냅니다! 이 코드는 무료로 사용할 수 있지만, 코드를 재게시하는 경우 하우스 룰이 적용된다는 점을 기억하세요.
discord.gg/REapC6SGtz
b3artrades@gmail.com
b3artrades@gmail.com
면책사항
해당 정보와 게시물은 금융, 투자, 트레이딩 또는 기타 유형의 조언이나 권장 사항으로 간주되지 않으며, 트레이딩뷰에서 제공하거나 보증하는 것이 아닙니다. 자세한 내용은 이용 약관을 참조하세요.
오픈 소스 스크립트
트레이딩뷰의 진정한 정신에 따라, 이 스크립트의 작성자는 이를 오픈소스로 공개하여 트레이더들이 기능을 검토하고 검증할 수 있도록 했습니다. 작성자에게 찬사를 보냅니다! 이 코드는 무료로 사용할 수 있지만, 코드를 재게시하는 경우 하우스 룰이 적용된다는 점을 기억하세요.
discord.gg/REapC6SGtz
b3artrades@gmail.com
b3artrades@gmail.com
면책사항
해당 정보와 게시물은 금융, 투자, 트레이딩 또는 기타 유형의 조언이나 권장 사항으로 간주되지 않으며, 트레이딩뷰에서 제공하거나 보증하는 것이 아닙니다. 자세한 내용은 이용 약관을 참조하세요.