OPEN-SOURCE SCRIPT
RSI Distribution [Kodexius]

RSI Distribution is a statistics driven visualization companion for the classic RSI oscillator. In addition to plotting RSI itself, it continuously builds a rolling sample of recent RSI values and projects their distribution as a forward drawn histogram, so you can see where RSI has spent most of its time over the selected lookback window.
The indicator is designed to add context to oscillator readings. Instead of only treating RSI as a single point estimate that is either “high” or “low”, you can evaluate the current RSI level relative to its own recent history. This makes it easier to recognize when the market is operating inside a familiar regime, and when RSI is pushing into rarer tail conditions that tend to appear during momentum bursts, exhaustion, or volatility expansion.
To complement the histogram, the script can optionally overlay a Gaussian curve fitted to the sample mean and standard deviation. It also runs a Jarque Bera normality check, based on skewness and excess kurtosis, and surfaces the result both visually and in a compact dashboard. On the oscillator panel itself, RSI is presented with a clean gradient line and standard overbought and oversold references, with fills that become more visible when RSI meaningfully extends beyond key thresholds.

🔹 Features
1. Distribution Histogram of Recent RSI Values
The script stores the last N RSI values in an internal sample and uses that rolling window to compute a frequency distribution across a user selected number of bins. The histogram is drawn into the future by a configurable width in bars, which keeps it readable and prevents it from colliding with the active RSI plot. The result is a compact visual summary of where RSI clusters most often, whether it is spending more time near the center, or shifting toward higher or lower regimes.
2. Gaussian Overlay for Shape Intuition
If enabled, a fitted bell curve is drawn on top of the histogram using the sample mean and standard deviation. This overlay is not intended as a direct trading signal. Its purpose is to provide a fast visual comparator between the empirical RSI distribution and a theoretical normal shape. When the histogram diverges strongly from the curve, you can quickly spot skew, heavy tails, or regime changes that often occur when market structure or volatility conditions shift.
3. Jarque Bera Normality Check With Clear PASS/FAIL Feedback
The script computes skewness and excess kurtosis from the RSI sample, then forms the Jarque Bera statistic and compares it to a fixed 95% critical value. When the distribution is closer to normal under this test, the status is marked as PASS, otherwise it is marked as FAIL. This result is displayed in the dashboard and can also influence the histogram styling, giving immediate feedback about whether the recent RSI behavior resembles a bell shaped distribution or a more distorted, regime driven profile.

Jarque Bera is a goodness of fit test that evaluates whether a dataset looks consistent with a normal distribution by checking two shape properties: skewness (asymmetry) and kurtosis (tail heaviness, expressed here as excess kurtosis where a perfect normal has 0). Under the null hypothesis of normality, skewness should be near 0 and excess kurtosis should be near 0. The test combines deviations in both into a single statistic, which is then compared to a chi square threshold. A PASS in this script means the sample does not show strong evidence against normality at the chosen threshold, while a FAIL means the sample is meaningfully skewed, heavy tailed, or both. In practical trading terms, a FAIL often suggests RSI is behaving in a regime where extremes and asymmetry are more common, which is typical during strong trends, volatility expansions, or one sided market pressure. It is still a statistical diagnostic, not a prediction tool, and results can vary with lookback length and market conditions.
4. Integrated Stats Dashboard
A compact table in the top right summarizes key distribution moments and the normality result: Mean, StdDev, Skewness, Kurtosis, and the JB statistic with PASS/FAIL text. Skewness is color coded by sign to quickly distinguish right skew (more time at higher RSI) versus left skew (more time at lower RSI), which can be helpful when diagnosing trend bias and momentum persistence.

5. RSI Visual Quality and Context Zones
RSI is plotted with a gradient color scheme and standard overbought and oversold reference lines. The overbought and oversold areas are filled with a smart gradient so visual emphasis increases when RSI meaningfully extends beyond the 70 and 30 regions, improving readability without overwhelming the panel.
🔹 Calculations
This section summarizes the main calculations and transformations used internally.
1. RSI Series
RSI is computed from the selected source and length using the standard RSI function:
Pine Script®
2. Rolling Sample Collection
A float array stores recent RSI values. Each bar appends the newest RSI, and if the array exceeds the configured lookback, the oldest value is removed. Conceptually:
Pine Script®
This maintains a fixed size window that represents the most recent RSI behavior.
3. Mean, Variance, and Standard Deviation
The script computes the sample mean across the array. Variance is computed as sample variance using (n - 1) in the denominator, and standard deviation is the square root of that variance. These values serve both the dashboard display and the Gaussian overlay parameters.
4. Skewness and Excess Kurtosis
Skewness is calculated from the standardized third central moment with a small sample correction. Kurtosis is computed as excess kurtosis (kurtosis minus 3), so the normal baseline is 0. These two metrics summarize asymmetry and tail heaviness, which are the core ingredients for the Jarque Bera statistic.
5. Jarque Bera Statistic and Decision Rule
Using skewness S and excess kurtosis K, the Jarque Bera statistic is computed as:
Pine Script®
Normality is flagged using a fixed critical value:
Pine Script®
This produces a simple PASS/FAIL classification suitable for fast chart interpretation.
6. Histogram Binning and Scaling
The RSI domain is treated as 0 to 100 and divided into a configurable number of bins. Bin size is:
Pine Script®
Each RSI sample maps to a bin index via floor(rsi / bin_size), with clamping to ensure the index stays within valid bounds. The script counts occurrences per bin, tracks the maximum frequency, and normalizes each bar height by freq/max_freq so the histogram remains visually stable and comparable as the window updates.
7. Gaussian Curve Overlay (Optional)
The Gaussian overlay uses the normal probability density function with mu as the sample mean and sigma as the sample standard deviation:
Pine Script®
For drawing, the script samples x across the histogram width, evaluates the PDF, and normalizes it relative to its peak so the curve fits within the same visual height scale as the histogram.
The indicator is designed to add context to oscillator readings. Instead of only treating RSI as a single point estimate that is either “high” or “low”, you can evaluate the current RSI level relative to its own recent history. This makes it easier to recognize when the market is operating inside a familiar regime, and when RSI is pushing into rarer tail conditions that tend to appear during momentum bursts, exhaustion, or volatility expansion.
To complement the histogram, the script can optionally overlay a Gaussian curve fitted to the sample mean and standard deviation. It also runs a Jarque Bera normality check, based on skewness and excess kurtosis, and surfaces the result both visually and in a compact dashboard. On the oscillator panel itself, RSI is presented with a clean gradient line and standard overbought and oversold references, with fills that become more visible when RSI meaningfully extends beyond key thresholds.
🔹 Features
1. Distribution Histogram of Recent RSI Values
The script stores the last N RSI values in an internal sample and uses that rolling window to compute a frequency distribution across a user selected number of bins. The histogram is drawn into the future by a configurable width in bars, which keeps it readable and prevents it from colliding with the active RSI plot. The result is a compact visual summary of where RSI clusters most often, whether it is spending more time near the center, or shifting toward higher or lower regimes.
2. Gaussian Overlay for Shape Intuition
If enabled, a fitted bell curve is drawn on top of the histogram using the sample mean and standard deviation. This overlay is not intended as a direct trading signal. Its purpose is to provide a fast visual comparator between the empirical RSI distribution and a theoretical normal shape. When the histogram diverges strongly from the curve, you can quickly spot skew, heavy tails, or regime changes that often occur when market structure or volatility conditions shift.
3. Jarque Bera Normality Check With Clear PASS/FAIL Feedback
The script computes skewness and excess kurtosis from the RSI sample, then forms the Jarque Bera statistic and compares it to a fixed 95% critical value. When the distribution is closer to normal under this test, the status is marked as PASS, otherwise it is marked as FAIL. This result is displayed in the dashboard and can also influence the histogram styling, giving immediate feedback about whether the recent RSI behavior resembles a bell shaped distribution or a more distorted, regime driven profile.
Jarque Bera is a goodness of fit test that evaluates whether a dataset looks consistent with a normal distribution by checking two shape properties: skewness (asymmetry) and kurtosis (tail heaviness, expressed here as excess kurtosis where a perfect normal has 0). Under the null hypothesis of normality, skewness should be near 0 and excess kurtosis should be near 0. The test combines deviations in both into a single statistic, which is then compared to a chi square threshold. A PASS in this script means the sample does not show strong evidence against normality at the chosen threshold, while a FAIL means the sample is meaningfully skewed, heavy tailed, or both. In practical trading terms, a FAIL often suggests RSI is behaving in a regime where extremes and asymmetry are more common, which is typical during strong trends, volatility expansions, or one sided market pressure. It is still a statistical diagnostic, not a prediction tool, and results can vary with lookback length and market conditions.
4. Integrated Stats Dashboard
A compact table in the top right summarizes key distribution moments and the normality result: Mean, StdDev, Skewness, Kurtosis, and the JB statistic with PASS/FAIL text. Skewness is color coded by sign to quickly distinguish right skew (more time at higher RSI) versus left skew (more time at lower RSI), which can be helpful when diagnosing trend bias and momentum persistence.
5. RSI Visual Quality and Context Zones
RSI is plotted with a gradient color scheme and standard overbought and oversold reference lines. The overbought and oversold areas are filled with a smart gradient so visual emphasis increases when RSI meaningfully extends beyond the 70 and 30 regions, improving readability without overwhelming the panel.
🔹 Calculations
This section summarizes the main calculations and transformations used internally.
1. RSI Series
RSI is computed from the selected source and length using the standard RSI function:
rsi_val = ta.rsi(rsi_src, rsi_len)
2. Rolling Sample Collection
A float array stores recent RSI values. Each bar appends the newest RSI, and if the array exceeds the configured lookback, the oldest value is removed. Conceptually:
rsi_history.push(rsi_val)
if rsi_history.size() > lookback
rsi_history.shift()
This maintains a fixed size window that represents the most recent RSI behavior.
3. Mean, Variance, and Standard Deviation
The script computes the sample mean across the array. Variance is computed as sample variance using (n - 1) in the denominator, and standard deviation is the square root of that variance. These values serve both the dashboard display and the Gaussian overlay parameters.
4. Skewness and Excess Kurtosis
Skewness is calculated from the standardized third central moment with a small sample correction. Kurtosis is computed as excess kurtosis (kurtosis minus 3), so the normal baseline is 0. These two metrics summarize asymmetry and tail heaviness, which are the core ingredients for the Jarque Bera statistic.
5. Jarque Bera Statistic and Decision Rule
Using skewness S and excess kurtosis K, the Jarque Bera statistic is computed as:
JB = (n / 6.0) * (S^2 + 0.25 * K^2)
Normality is flagged using a fixed critical value:
is_normal = JB < 5.991
This produces a simple PASS/FAIL classification suitable for fast chart interpretation.
6. Histogram Binning and Scaling
The RSI domain is treated as 0 to 100 and divided into a configurable number of bins. Bin size is:
bin_size = 100.0 / bins
Each RSI sample maps to a bin index via floor(rsi / bin_size), with clamping to ensure the index stays within valid bounds. The script counts occurrences per bin, tracks the maximum frequency, and normalizes each bar height by freq/max_freq so the histogram remains visually stable and comparable as the window updates.
7. Gaussian Curve Overlay (Optional)
The Gaussian overlay uses the normal probability density function with mu as the sample mean and sigma as the sample standard deviation:
normal_pdf(x) = (1 / (sigma * sqrt(2*pi))) * exp(-0.5 * ((x - mu)/sigma)^2)
For drawing, the script samples x across the histogram width, evaluates the PDF, and normalizes it relative to its peak so the curve fits within the same visual height scale as the histogram.
Skrip sumber terbuka
Dalam semangat TradingView sebenar, pencipta skrip ini telah menjadikannya sumber terbuka, jadi pedagang boleh menilai dan mengesahkan kefungsiannya. Terima kasih kepada penulis! Walaupuan anda boleh menggunakan secara percuma, ingat bahawa penerbitan semula kod ini tertakluk kepada Peraturan Dalaman.
Penafian
Maklumat dan penerbitan adalah tidak bertujuan, dan tidak membentuk, nasihat atau cadangan kewangan, pelaburan, dagangan atau jenis lain yang diberikan atau disahkan oleh TradingView. Baca lebih dalam Terma Penggunaan.
Skrip sumber terbuka
Dalam semangat TradingView sebenar, pencipta skrip ini telah menjadikannya sumber terbuka, jadi pedagang boleh menilai dan mengesahkan kefungsiannya. Terima kasih kepada penulis! Walaupuan anda boleh menggunakan secara percuma, ingat bahawa penerbitan semula kod ini tertakluk kepada Peraturan Dalaman.
Penafian
Maklumat dan penerbitan adalah tidak bertujuan, dan tidak membentuk, nasihat atau cadangan kewangan, pelaburan, dagangan atau jenis lain yang diberikan atau disahkan oleh TradingView. Baca lebih dalam Terma Penggunaan.