OPEN-SOURCE SCRIPT

Simplified Percentile Clustering

668
Simplified Percentile Clustering (SPC) is a clustering system for trend regime analysis.
Instead of relying on heavy iterative algorithms such as k-means, SPC takes a deterministic approach: it uses percentiles and running averages to form cluster centers directly from the data, producing smooth, interpretable market state segmentation that updates live with every bar.

Most clustering algorithms are designed for offline datasets, they require recomputation, multiple iterations, and fixed sample sizes.
SPC borrows from both statistical normalization and distance-based clustering theory, but simplifies them. Percentiles ensure that cluster centers are resistant to outliers, while the running mean provides a stable mid-point reference.
Unlike iterative methods, SPC’s centers evolve smoothly with time, ideal for charts that must update in real time without sudden reclassification noise.
SPC provides a simple yet powerful clustering heuristic that:
  • Runs continuously in a charting environment,
  • Remains interpretable and reproducible,
  • And allows traders to see how close the current market state is to transitioning between regimes.


Clustering by Percentiles

Traditional clustering methods find centers through iteration. SPC defines them deterministically using three simple statistics within a moving window:
  1. Lower percentile (p_low) → captures the lower basin of feature values.
  2. Upper percentile (p_high) → captures the upper basin.
  3. Mean (mid) → represents the central tendency.


From these, SPC computes stable “centers”:
Pine Script®
// K = 2 → two regimes (e.g., bullish / bearish) [k0, k1] = [avg(low_pct, mid), avg(high_pct, mid)] // K = 3 → adds a neutral zone [k0, k1, k2] = [avg(low_pct, mid), mid, avg(high_pct, mid)]


These centers move gradually with the market, forming live regime boundaries without ever needing convergence steps.
Snapshot
Two clusters capture directional bias; three clusters add a neutral ‘range’ state.

Multi-Feature Fusion

While SPC can cluster a single feature such as RSI, CCI, Fisher Transform, DMI, Z-Score, or the price-to-MA ratio (MAR), its real strength lies in feature fusion. Each feature adds a unique lens to the clustering system. By toggling features on or off, traders can test how each dimension contributes to the regime structure.
In “Clusters” mode, SPC measures how far the current bar is from each cluster center across all enabled features, averages these distances, and assigns the bar to the nearest combined center. This effectively creates a multi-dimensional regime map, where each feature contributes equally to defining the overall market state.

The fusion distance is computed as:
Pine Script®
dist := (rsi_d * on_off(use_rsi) + cci_d * on_off(use_cci) + fis_d * on_off(use_fis) + dmi_d * on_off(use_dmi) + zsc_d * on_off(use_zsc) + mar_d * on_off(use_mar)) / (on_off(use_rsi) + on_off(use_cci) + on_off(use_fis) + on_off(use_dmi) + on_off(use_zsc) + on_off(use_mar))


Because each feature can be standardized (Z-Score), the distances remain comparable across different scales.

Snapshot
Fusion mode combines multiple standardized features into a single smooth regime signal.

Visualizing Proximity - The Transition Gradient

Most indicators show binary or discrete conditions (e.g., bullish/bearish). SPC goes further, it quantifies how close the current value is to flipping into the next cluster.
It measures the distances to the two nearest cluster centers and interpolates between them:
Pine Script®
rel_pos = min_dist / (min_dist + second_min_dist) real_clust = cluster_val + (second_val - cluster_val) * rel_pos


This real_clust output forms a continuous line that moves smoothly between clusters:
  • Near 0.0 → firmly within the current regime
  • Around 0.5 → balanced between clusters (transition zone)
  • Near 1.0 → about to flip into the next regime


Snapshot
Smooth interpolation reveals when the market is close to a regime change.

How to Tune the Parameters
SPC includes intuitive parameters to adapt sensitivity and stability:
  • K Clusters (2–3): Defines the number of regimes. K = 2 for trend/range distinction, K = 3 for trend/neutral transitions.
  • Lookback: Determines the number of past bars used for percentile and mean calculations. Higher = smoother, more stable clusters. Lower = faster reaction to new trends.
  • Lower / Upper Percentiles: Define what counts as “low” and “high” states. Adjust to widen or tighten cluster ranges.


Snapshot
Shorter lookbacks react quickly to shifts; longer lookbacks smooth the clusters.

Visual Interpretation

In “Clusters” mode, SPC plots:
  • A colored histogram for each cluster (red, orange, green depending on K)
  • Horizontal guide lines separating cluster levels
  • Smooth proximity transitions between states


Each bar’s color also changes based on its assigned cluster, allowing quick recognition of when the market transitions between regimes.

Snapshot
Cluster bands visualize regime structure and transitions at a glance.

Practical Applications
  • Identify market regimes (bullish, neutral, bearish) in real time
  • Detect early transition phases before a trend flip occurs
  • Fuse multiple indicators into a single consistent signal
  • Engineer interpretable features for machine-learning research
  • Build adaptive filters or hybrid signals based on cluster proximity


Final Notes
Simplified Percentile Clustering (SPC) provides a balance between mathematical rigor and visual intuition. It replaces complex iterative algorithms with a clear, deterministic logic that any trader can understand, and yet retains the multidimensional insight of a fusion-based clustering system.
Use SPC to study how different indicators align, how regimes evolve, and how transitions emerge in real time. It’s not about predicting; it’s about seeing the structure of the market unfold.

Disclaimer
  • This indicator is intended for educational and analytical use.
  • It does not generate buy or sell signals.
  • Historical regime transitions are not indicative of future performance.
  • Always validate insights with independent analysis before making trading decisions.

Haftungsausschluss

Die Informationen und Veröffentlichungen sind nicht als Finanz-, Anlage-, Handels- oder andere Arten von Ratschlägen oder Empfehlungen gedacht, die von TradingView bereitgestellt oder gebilligt werden, und stellen diese nicht dar. Lesen Sie mehr in den Nutzungsbedingungen.