本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © jabez4jc
//@version=6
// @description Machine learning building blocks for Pine Script, written for speed: k-nearest-neighbour search over a
// ring-buffer dataset with partial-distance pruning and chronological spacing, Lorentzian / Euclidean /
// Manhattan / Chebyshev distances, distance-weighted voting, Fisher-ratio feature weights, a Lorentzian
// direction classifier with volatility, regime and ADX filters, Nadaraya-Watson kernel regression with
// precomputed weights, and binned kernel density estimation with Silverman / Scott bandwidths, CDF,
// quantiles and mode.
library("MLToolkit", overlay = true)
//#region ———————————————————— Enums and kernels
// @enum Distance metrics for nearest-neighbour search.
// @field lorentzian Sum of log(1 + |difference|): robust to outliers, keeps neighbours along each feature axis.
// @field euclidean Sum of squared differences (the square root is skipped; the ranking is the same).
// @field manhattan Sum of absolute differences.
// @field chebyshev Largest absolute difference.
export enum Metric
lorentzian = "Lorentzian"
euclidean = "Euclidean"
manhattan = "Manhattan"
chebyshev = "Chebyshev"
// @enum How neighbours vote.
// @field uniform Every neighbour counts the same.
// @field inverse Weight 1 / (distance + epsilon): closer neighbours count more.
// @field kernel Weight exp(-distance / mean neighbour distance): a smooth version of inverse.
export enum Weighting
uniform = "Uniform"
inverse = "Inverse Distance"
kernel = "Kernel"
// @enum Smoothing kernels for density estimation and kernel regression.
// @field gaussian Gaussian (unbounded support, truncated at 4 bandwidths).
// @field rationalQuadratic Rational quadratic, a mixture of Gaussians of different widths (shape set by alpha).
// @field epanechnikov Epanechnikov (compact support, statistically efficient).
// @field triangular Triangular (compact support).
// @field uniform Uniform box (compact support).
export enum Kernel
gaussian = "Gaussian"
rationalQuadratic = "Rational Quadratic"
epanechnikov = "Epanechnikov"
triangular = "Triangular"
uniform = "Uniform"
// @function Kernel value at a scaled distance.
// @param k (Kernel) The kernel.
// @param u (series float) Distance divided by the bandwidth.
// @param alpha (series float) Rational quadratic shape (larger = closer to Gaussian). Optional. Default is 1.
// @returns (float) The kernel value (not normalised).
export kernelValue(Kernel k, float u, float alpha = 1.0) =>
float a = math.abs(u)
switch k
Kernel.gaussian => math.exp(-0.5 * u * u)
Kernel.rationalQuadratic => math.pow(1 + u * u / (2 * alpha), -alpha)
Kernel.epanechnikov => a <= 1 ? 1 - u * u : 0.0
Kernel.triangular => a <= 1 ? 1 - a : 0.0
=> a <= 1 ? 1.0 : 0.0
// Distance beyond which a kernel is negligible (or zero), in bandwidths
kernelReach(Kernel k) =>
k == Kernel.gaussian ? 4.0 : k == Kernel.rationalQuadratic ? 8.0 : 1.0
//#endregion
//#region ———————————————————— Features and distances
// @function Rolling min-max scaling to 0..1 (0.5 when the window is flat).
// @param x (series float) Value.
// @param len (series int) Window, in bars.
// @returns (float) The scaled value.
export minMax(float x, int len) =>
float lo = ta.lowest(x, len)
float hi = ta.highest(x, len)
hi > lo ? (x - lo) / (hi - lo) : 0.5
// @function Rolling z-score: distance from the mean in standard deviations.
// @param x (series float) Value.
// @param len (series int) Window, in bars.
// @returns (float) The z-score (0 when the window is flat).
export zScore(float x, int len) =>
float sd = ta.stdev(x, len)
sd > 0 ? (x - ta.sma(x, len)) / sd : 0.0
// @function Squashes an unbounded value into -1..+1 with tanh(x / scale).
// @param x (series float) Value.
// @param scale (series float) Value that maps to about 0.76.
// @returns (float) The squashed value.
export squash(float x, float scale) =>
2 / (1 + math.exp(-2 * x / scale)) - 1
// Adds one feature's weighted difference to a running distance
accumulate(Metric metric, float acc, float diff, float w) =>
switch metric
Metric.lorentzian => acc + w * math.log(1 + diff)
Metric.euclidean => acc + w * diff * diff
Metric.manhattan => acc + w * diff
=> math.max(acc, w * diff)
// @function Distance between two feature vectors of the same size.
// @param a (array<float>) First vector.
// @param b (array<float>) Second vector.
// @param metric (Metric) Distance metric. Optional. Default is `Metric.lorentzian`.
// @param weights (array<float>) Per-feature weights; an empty array weighs every feature 1. Optional.
// @returns (float) The distance.
export distance(array<float> a, array<float> b, Metric metric = Metric.lorentzian, array<float> weights = na) =>
bool useW = not na(weights) and weights.size() > 0
float d = 0.0
for [j, va] in a
float diff = math.abs(va - b.get(j))
d := accumulate(metric, d, diff, useW ? weights.get(j) : 1.0)
d
//#endregion
//#region ———————————————————— Dataset (ring buffer)
// @type A fixed-capacity training set stored as a ring buffer: adding a sample overwrites the oldest one in O(1)
// instead of shifting arrays. Create it with `newDataset()` in a `var` declaration.
// @field x Feature matrix, one row per sample.
// @field y Labels.
// @field bars Bar index at which each sample was added.
// @field weights Per-feature weights used by `knn()` (empty = equal weights). See `fisherWeights()`.
// @field capacity Maximum number of samples.
// @field count Samples stored.
// @field head Slot the next sample is written to.
export type Dataset
matrix<float> x
array<float> y
array<int> bars
array<float> weights
int capacity
int count = 0
int head = 0
// @function Creates an empty dataset.
// @param nFeatures (series int) Features per sample.
// @param capacity (series int) Maximum samples kept (the oldest are overwritten).
// @returns (Dataset) The dataset.
export newDataset(int nFeatures, int capacity) =>
Dataset.new(matrix.new<float>(capacity, nFeatures, na), array.new<float>(capacity, na), array.new<int>(capacity, na), array.new<float>(), capacity)
// Ring-buffer slot of the i-th newest sample (0 = newest)
slot(Dataset d, int i) =>
(d.head - 1 - i + 2 * d.capacity) % d.capacity
// @function Adds a sample (skipped when any feature or the label is `na`).
// @param d (Dataset) The dataset.
// @param features (array<float>) Feature vector.
// @param label (series float) Label, e.g. +1 / -1 / 0.
// @returns (bool) The sample was added.
export method add(Dataset d, array<float> features, float label) =>
bool ok = not na(label)
for v in features
ok := ok and not na(v)
if ok
for [j, v] in features
d.x.set(d.head, j, v)
d.y.set(d.head, label)
d.bars.set(d.head, bar_index)
d.head := (d.head + 1) % d.capacity
d.count := math.min(d.count + 1, d.capacity)
ok
// @function Feature weights from the Fisher ratio of each feature: (mean of positive-label samples - mean of
// negative-label samples)^2 / (variance of each group summed), scaled so the best feature is 1 and floored.
// Features that separate the classes well get more say in the distance. Stores them in `d.weights`.
// @param d (Dataset) The dataset (labels > 0 vs < 0; zero labels are ignored).
// @param minWeight (series float) Smallest weight a feature can get (0-1). Optional. Default is 0.25.
// @param minSamples (series int) Samples needed per class before weights are computed. Optional. Default is 20.
// @returns (array<float>) The weights (also stored in the dataset; empty until there are enough samples).
export method fisherWeights(Dataset d, float minWeight = 0.25, int minSamples = 20) =>
int nf = d.x.columns()
array<float> sumP = array.new<float>(nf, 0.0)
array<float> sqP = array.new<float>(nf, 0.0)
array<float> sumN = array.new<float>(nf, 0.0)
array<float> sqN = array.new<float>(nf, 0.0)
int nP = 0
int nN = 0
for i = 0 to math.max(d.count - 1, 0)
int r = slot(d, i)
float lbl = d.y.get(r)
if not na(lbl) and lbl != 0
bool pos = lbl > 0
nP += pos ? 1 : 0
nN += pos ? 0 : 1
for j = 0 to nf - 1
float v = d.x.get(r, j)
if pos
sumP.set(j, sumP.get(j) + v)
sqP.set(j, sqP.get(j) + v * v)
else
sumN.set(j, sumN.get(j) + v)
sqN.set(j, sqN.get(j) + v * v)
if nP >= minSamples and nN >= minSamples
array<float> ratio = array.new<float>(nf, 0.0)
for j = 0 to nf - 1
float mP = sumP.get(j) / nP
float mN = sumN.get(j) / nN
float vP = math.max(sqP.get(j) / nP - mP * mP, 0)
float vN = math.max(sqN.get(j) / nN - mN * mN, 0)
ratio.set(j, math.pow(mP - mN, 2) / (vP + vN + 1e-12))
float top = ratio.max()
d.weights := array.new<float>(nf, 1.0)
for j = 0 to nf - 1
d.weights.set(j, top > 0 ? math.max(minWeight, ratio.get(j) / top) : 1.0)
d.weights
//#endregion
//#region ———————————————————— k-nearest neighbours
// @type Result of a neighbour search.
// @field vote Sum of neighbour labels, weighted by the voting scheme (with uniform voting and labels of +1 / -1 this
// is the number of up neighbours minus down neighbours).
// @field probUp Weighted share of neighbours with a positive label (0-1), `na` when none were found.
// @field meanLabel Weighted mean label (useful for regression targets).
// @field meanDist Mean distance to the neighbours (a confidence gauge: smaller = closer analogues).
// @field found Neighbours found (at most k).
export type Neighbors
float vote
float probUp
float meanLabel
float meanDist
int found
// Distance from the query to dataset row r, stopped early once it exceeds `bound` (partial-distance pruning)
rowDistance(Dataset d, int r, array<float> q, Metric metric, float bound) =>
bool useW = d.weights.size() > 0
float dist = 0.0
for [j, vq] in q
float diff = math.abs(vq - d.x.get(r, j))
dist := accumulate(metric, dist, diff, useW ? d.weights.get(j) : 1.0)
if dist > bound
break
dist
// @function Finds the k nearest stored samples to a query and lets them vote. Keeps the k best in a small buffer and
// tracks the current worst, so a candidate's distance stops accumulating as soon as it cannot qualify.
// `spacing` visits every n-th sample (chronological spacing), which both speeds the search up and avoids
// neighbours that are just consecutive bars of the same move.
// @param d (Dataset) The training set.
// @param q (array<float>) Query feature vector.
// @param k (series int) Neighbours.
// @param metric (Metric) Distance metric. Optional. Default is `Metric.lorentzian`.
// @param weighting (Weighting) Voting scheme. Optional. Default is `Weighting.uniform`.
// @param spacing (series int) Visit every n-th sample, newest first. Optional. Default is 1.
// @param skipNewest (series int) Samples at the newest end to skip. Optional. Default is 0.
// @returns (Neighbors) The vote and neighbour statistics.
export method knn(Dataset d, array<float> q, int k, Metric metric = Metric.lorentzian, Weighting weighting = Weighting.uniform, int spacing = 1, int skipNewest = 0) =>
array<float> bestD = array.new<float>()
array<float> bestY = array.new<float>()
float worst = 1e300
int worstIdx = -1
if d.count > skipNewest and k > 0
for i = skipNewest to d.count - 1 by math.max(1, spacing)
int r = slot(d, i)
float dist = rowDistance(d, r, q, metric, bestD.size() < k ? 1e300 : worst)
if bestD.size() < k
bestD.push(dist)
bestY.push(d.y.get(r))
if bestD.size() == k
worst := bestD.max()
worstIdx := bestD.indexof(worst)
else if dist < worst
bestD.set(worstIdx, dist)
bestY.set(worstIdx, d.y.get(r))
worst := bestD.max()
worstIdx := bestD.indexof(worst)
int n = bestD.size()
float mean = n > 0 ? bestD.avg() : na
float vote = 0.0
float wSum = 0.0
float wUp = 0.0
for [i, dist] in bestD
float w = switch weighting
Weighting.uniform => 1.0
Weighting.inverse => 1.0 / (dist + 1e-9)
=> math.exp(-dist / math.max(mean, 1e-9))
float lbl = bestY.get(i)
vote += w * lbl
wSum += w
wUp += lbl > 0 ? w : 0.0
Neighbors.new(vote, wSum > 0 ? wUp / wSum : na, wSum > 0 ? vote / wSum : na, mean, n)
//#endregion
//#region ———————————————————— Lorentzian direction classifier
// @function Direction label for training: +1 if `src` is higher than `horizon` bars ago, -1 if lower, 0 if equal.
// Pair it with the features as they were `horizon` bars ago, so no sample uses future data.
// @param src (series float) Price source.
// @param horizon (series int) Bars ahead the label looks.
// @returns (int) +1, -1 or 0 (`na` while history is short).
export directionLabel(float src, int horizon) =>
na(src[horizon]) ? na : src > src[horizon] ? 1 : src < src[horizon] ? -1 : 0
// @function Lorentzian classification: the uniform vote of the k nearest samples by Lorentzian distance, visiting
// every `spacing`-th sample. With +1 / -1 / 0 labels the result ranges from -k to +k.
// @param d (Dataset) The training set.
// @param q (array<float>) Current features.
// @param k (series int) Neighbours. Optional. Default is 8.
// @param spacing (series int) Chronological spacing. Optional. Default is 4.
// @returns (float) The prediction (positive = bullish).
export method lorentzianPredict(Dataset d, array<float> q, int k = 8, int spacing = 4) =>
d.knn(q, k, Metric.lorentzian, Weighting.uniform, spacing).vote
// @function Volatility filter: recent volatility above the longer-term level (markets that are moving).
// @param fast (simple int) Fast ATR length. Optional. Default is 1.
// @param slow (simple int) Slow ATR length. Optional. Default is 10.
// @returns (bool) Recent ATR is above the slow ATR.
export filterVolatility(simple int fast = 1, simple int slow = 10) =>
ta.atr(fast) > ta.atr(slow)
// @function Regime filter: the slope of a smoothed source, in ATRs per bar, is at least `threshold` in absolute
// terms (trending rather than ranging). Use a negative threshold to accept mild slopes.
// @param src (series float) Price source.
// @param len (simple int) EMA and ATR length. Optional. Default is 20.
// @param threshold (series float) Minimum absolute slope in ATRs per bar. Optional. Default is 0.05.
// @returns (bool) The market is trending by this measure.
export filterRegime(float src, simple int len = 20, float threshold = 0.05) =>
float ema = ta.ema(src, len)
float atr = ta.atr(len)
atr > 0 ? math.abs(ema - ema[1]) / atr >= threshold : false
// @function ADX filter: trend strength at or above a threshold.
// @param len (simple int) DMI / ADX length. Optional. Default is 14.
// @param threshold (series float) Minimum ADX. Optional. Default is 20.
// @returns (bool) ADX is at least the threshold.
export filterAdx(simple int len = 14, float threshold = 20) =>
[_, _, adx] = ta.dmi(len, len)
adx >= threshold
//#endregion
//#region ———————————————————— Kernel regression
// @function Precomputes Nadaraya-Watson weights for lags 0..lookback-1, so the regression costs one dot product per
// bar instead of recomputing every kernel value. Declare the result with `var`.
// @param k (Kernel) Kernel.
// @param lookback (series int) Bars used.
// @param bandwidth (series float) Bandwidth, in bars (larger = smoother).
// @param alpha (series float) Rational quadratic shape. Optional. Default is 1.
// @returns (array<float>) The weights, newest bar first.
export kernelWeights(Kernel k, int lookback, float bandwidth, float alpha = 1.0) =>
array<float> w = array.new<float>(lookback, 0.0)
for i = 0 to lookback - 1
w.set(i, kernelValue(k, i / bandwidth, alpha))
w
// @function Nadaraya-Watson kernel regression estimate of `src` with precomputed weights (see `kernelWeights()`).
// Uses only current and past bars, so it does not repaint. Call it once per bar, unconditionally.
// @param src (series float) Series to smooth.
// @param weights (array<float>) Weights from `kernelWeights()`, newest bar first.
// @returns (float) The estimate, `na` until any weighted bar has data.
export nadarayaWatson(float src, array<float> weights) =>
float num = 0.0
float den = 0.0
for [i, w] in weights
float v = src[i]
if not na(v) and w > 0
num += w * v
den += w
den > 0 ? num / den : na
//#endregion
//#region ———————————————————— Kernel density estimation
// @type A kernel density estimate on an evenly spaced grid.
// @field lo Grid start.
// @field step Grid spacing.
// @field pdf Density at each grid point (integrates to 1).
// @field cdf Cumulative share at each grid point (0-1).
// @field bandwidth Bandwidth used.
export type Density
float lo
float step
array<float> pdf
array<float> cdf
float bandwidth
// @function Silverman's rule-of-thumb bandwidth: 0.9 x min(standard deviation, IQR / 1.34) x n^(-1/5). Robust to
// skewed and heavy-tailed samples.
// @param samples (array<float>) Samples.
// @returns (float) The bandwidth (`na` for fewer than 2 samples).
export bandwidthSilverman(array<float> samples) =>
int n = samples.size()
float sd = n > 1 ? samples.stdev(false) : na
float iqr = n > 1 ? samples.percentile_linear_interpolation(75) - samples.percentile_linear_interpolation(25) : na
float spread = iqr > 0 ? math.min(sd, iqr / 1.34) : sd
n > 1 ? 0.9 * spread * math.pow(n, -0.2) : na
// @function Scott's rule bandwidth: 1.06 x standard deviation x n^(-1/5). Best for near-normal samples.
// @param samples (array<float>) Samples.
// @returns (float) The bandwidth (`na` for fewer than 2 samples).
export bandwidthScott(array<float> samples) =>
int n = samples.size()
n > 1 ? 1.06 * samples.stdev(false) * math.pow(n, -0.2) : na
// @function Binned kernel density estimate. Samples are spread onto the grid by linear binning (each sample splits its
// weight between its two nearest grid points), then the grid is convolved with the kernel truncated where
// it is negligible. Cost is O(samples + bins x kernel width) instead of O(samples x bins).
// @param samples (array<float>) Samples.
// @param bins (series int) Grid points. Optional. Default is 100.
// @param bandwidth (series float) Bandwidth; `na` uses Silverman's rule. Optional.
// @param kernel (Kernel) Kernel. Optional. Default is `Kernel.gaussian`.
// @param lo (series float) Grid start; `na` = lowest sample - 3 bandwidths. Optional.
// @param hi (series float) Grid end; `na` = highest sample + 3 bandwidths. Optional.
// @returns (Density) The estimate, or `na` for an empty sample.
export kde(array<float> samples, int bins = 100, float bandwidth = na, Kernel kernel = Kernel.gaussian, float lo = na, float hi = na) =>
Density out = na
int n = samples.size()
if n > 0
int nb = math.max(bins, 10)
float h = na(bandwidth) ? bandwidthSilverman(samples) : bandwidth
h := na(h) or h <= 0 ? math.max(math.abs(samples.avg()) * 1e-3, 1e-6) : h
float a = na(lo) ? samples.min() - 3 * h : lo
float b = na(hi) ? samples.max() + 3 * h : hi
float step = (b - a) / (nb - 1)
// 1. Linear binning
array<float> counts = array.new<float>(nb, 0.0)
for v in samples
float pos = (v - a) / step
if pos >= 0 and pos <= nb - 1
int i0 = math.min(int(math.floor(pos)), nb - 2)
float frac = pos - i0
counts.set(i0, counts.get(i0) + 1 - frac)
counts.set(i0 + 1, counts.get(i0 + 1) + frac)
// 2. Kernel values by grid offset, cut off where the kernel is negligible
int span = math.max(0, math.min(nb - 1, int(math.ceil(kernelReach(kernel) * h / step))))
array<float> kw = array.new<float>(span + 1, 0.0)
for o = 0 to span
kw.set(o, kernelValue(kernel, o * step / h))
// 3. Convolution
array<float> pdf = array.new<float>(nb, 0.0)
for [i, c] in counts
if c > 0
for j = math.max(0, i - span) to math.min(nb - 1, i + span)
pdf.set(j, pdf.get(j) + c * kw.get(math.abs(j - i)))
// 4. Normalise to unit area and accumulate the CDF (midpoint rule)
float area = pdf.sum() * step
array<float> cdf = array.new<float>(nb, 0.0)
float run = 0.0
for i = 0 to nb - 1
float dens = area > 0 ? pdf.get(i) / area : 0.0
pdf.set(i, dens)
cdf.set(i, math.min(1.0, (run + dens / 2) * step))
run += dens
out := Density.new(a, step, pdf, cdf, h)
out
// Linear interpolation of a grid array at x (clamped to the grid)
gridAt(Density d, array<float> arr, float x) =>
int nb = arr.size()
float pos = math.max(0.0, math.min((x - d.lo) / d.step, nb - 1))
int i0 = math.min(int(math.floor(pos)), nb - 2)
arr.get(i0) + (pos - i0) * (arr.get(i0 + 1) - arr.get(i0))
// @function Density at a value (linear interpolation; 0 outside the grid).
// @param d (Density) The estimate.
// @param x (series float) Value.
// @returns (float) The density.
export method densityAt(Density d, float x) =>
x < d.lo or x > d.lo + d.step * (d.pdf.size() - 1) ? 0.0 : gridAt(d, d.pdf, x)
// @function Share of the distribution at or below a value (0 below the grid, 1 above it).
// @param d (Density) The estimate.
// @param x (series float) Value.
// @returns (float) The cumulative share (0-1).
export method cdfAt(Density d, float x) =>
x <= d.lo ? 0.0 : x >= d.lo + d.step * (d.cdf.size() - 1) ? 1.0 : gridAt(d, d.cdf, x)
// @function Value below which a share `p` of the distribution lies (inverse CDF, interpolated).
// @param d (Density) The estimate.
// @param p (series float) Share, 0-1.
// @returns (float) The quantile.
export method quantile(Density d, float p) =>
int nb = d.cdf.size()
float out = d.lo + d.step * (nb - 1)
if p <= d.cdf.first()
out := d.lo
else
for i = 1 to nb - 1
float c1 = d.cdf.get(i)
if c1 >= p
float c0 = d.cdf.get(i - 1)
out := d.lo + d.step * (i - 1 + (c1 > c0 ? (p - c0) / (c1 - c0) : 0.0))
break
out
// @function The value with the highest density (the distribution's peak).
// @param d (Density) The estimate.
// @returns (float) The mode.
export method mode(Density d) =>
d.lo + d.step * d.pdf.indexof(d.pdf.max())
//#endregion
//#region ———————————————————— Demo
// Five features scaled to 0..1: RSI, squashed CCI, ADX, min-max scaled distance from an EMA, squashed volume z-score
var Dataset demoSet = newDataset(5, 1000)
[demoPlus, demoMinus, demoAdx] = ta.dmi(14, 14)
float f1 = ta.rsi(close, 14) / 100
float f2 = squash(ta.cci(hlc3, 20), 100) * 0.5 + 0.5
float f3 = demoAdx / 100
float f4 = minMax(close - ta.ema(close, 20), 50)
float f5 = squash(zScore(volume, 50), 2) * 0.5 + 0.5
array<float> demoNow = array.from(f1, f2, f3, f4, f5)
array<float> demoPast = array.from(f1[4], f2[4], f3[4], f4[4], f5[4])
// Train on the features of 4 bars ago with what price did since then; refresh the Fisher feature weights every 50 bars
int demoLabel = directionLabel(close, 4)
if barstate.isconfirmed
demoSet.add(demoPast, demoLabel)
if bar_index % 50 == 0
demoSet.fisherWeights()
// Lorentzian classification, shown as bar colours when the volatility, regime and ADX filters agree
float demoPrediction = demoSet.lorentzianPredict(demoNow, 8, 4)
bool demoFiltersOk = filterVolatility() and filterRegime(close) and filterAdx()
barcolor(demoFiltersOk ? (demoPrediction > 0 ? color.new(color.teal, 30) : demoPrediction < 0 ? color.new(color.red, 30) : na) : na)
// The same data with Euclidean distance and inverse-distance voting; values are in the Data Window
Neighbors demoNn = demoSet.knn(demoNow, 8, Metric.euclidean, Weighting.inverse, 4)
plot(demoNn.probUp, "knn() probability up", display = display.data_window)
plot(demoNn.meanDist, "knn() mean neighbour distance", display = display.data_window)
plot(distance(demoNow, demoPast), "distance() now vs 4 bars ago", display = display.data_window)
// Nadaraya-Watson kernel regression with precomputed rational quadratic weights
var array<float> demoWeights = kernelWeights(Kernel.rationalQuadratic, 50, 8, 8)
float demoTrend = nadarayaWatson(close, demoWeights)
plot(demoTrend, "Kernel regression", demoTrend > demoTrend[1] ? color.teal : color.red, 2)
// KDE of RSI over the last 500 bars; the results go to the Pine Logs pane
var array<float> demoRsiHist = array.new<float>()
float demoRsi = ta.rsi(close, 14)
if not na(demoRsi)
demoRsiHist.push(demoRsi)
if demoRsiHist.size() > 500
demoRsiHist.shift()
if barstate.islastconfirmedhistory and demoRsiHist.size() > 50
Density demoKde = kde(demoRsiHist, 100, bandwidthScott(demoRsiHist), Kernel.epanechnikov, 0, 100)
log.info("RSI density: Silverman bandwidth {0,number,#.##}, Scott bandwidth {1,number,#.##}, mode {2,number,#.#}, 10% / 90% quantiles {3,number,#.#} / {4,number,#.#}, density now {5,number,#.####}, share below now {6,number,percent}, Gaussian kernel at 1 bandwidth {7,number,#.###}",
bandwidthSilverman(demoRsiHist), demoKde.bandwidth, demoKde.mode(), demoKde.quantile(0.1), demoKde.quantile(0.9), demoKde.densityAt(demoRsi), demoKde.cdfAt(demoRsi), kernelValue(Kernel.gaussian, 1))
//#endregion