本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("Naive Bayes AI - Direction Probability [Dots3Red]",
shorttitle = "Naive Bayes AI [D3R]",
overlay = false,
max_labels_count = 500)
// Inputs
C_TXT = color.new(#f8fafc, 0)
C_DIM = color.new(#94a3b8, 0)
C_BG = color.new(#131722, 5)
C_BORD = color.new(#334155, 0)
C_GOOD = color.new(#00c896, 0)
C_BAD = color.new(#ff4466, 0)
C_UP = color.new(#00ff88, 0)
C_DN = color.new(#ff1e56, 0)
// C_UP = color.new(#00f0ff, 0)
// C_DN = color.new(#ff00aa, 0)
C_AMBER = color.new(#ffb700, 0)
C_BAR = color.new(#b2b5be,0)
GRP_ML = "🧠 Model"
GRP_FT = "📐 Features"
GRP_VIS = "🎨 Visuals"
GRP_HUD = "🖥️ Dashboard"
horizon = input.int(10, "Prediction Horizon (bars)", minval=1, maxval=100, group=GRP_ML,
tooltip="The model predicts whether the close this many bars ahead will be higher or lower than the current close.")
win_size = input.int(500, "Training Window (samples)", minval=100, maxval=3000, group=GRP_ML,
tooltip="The model learns from the most recent samples whose outcome is already known. Older samples are dropped, so the model adapts as the market changes.")
min_train = input.int(150, "Min Samples Before Predicting", minval=50, group=GRP_ML)
thresh = input.float(60, "Signal Threshold (%)", minval=51, maxval=95, step=1, group=GRP_ML,
tooltip="A bullish signal needs P(up) at or above this level, a bearish signal needs P(up) at or below 100 minus this level.")
rsi_len = input.int(14, "RSI Length", minval=2, group=GRP_FT)
ema_len = input.int(20, "Trend EMA Length", minval=2, group=GRP_FT)
roc_len = input.int(10, "Rate of Change Length", minval=1, group=GRP_FT)
vol_len = input.int(20, "Volume Average Length", minval=2, group=GRP_FT)
atr_len = input.int(14, "ATR Length", minval=2, group=GRP_FT)
col_bull = input.color(#00ff88, "Bullish Color", group=GRP_VIS)
col_bear = input.color(#ff1e56, "Bearish Color", group=GRP_VIS)
w_line = input.int(2, "Probability Line Thickness", minval=1, maxval=6, group=GRP_VIS)
col_lvl = input.color(#64748b, "Level Lines Color", group=GRP_VIS)
show_bg = input.bool(true, "Shade Signal Zones", group=GRP_VIS)
bg_tr = input.int(88, "Shade Transparency", minval=50, maxval=98, group=GRP_VIS)
show_lbl = input.bool(true, "Signal Labels on Price Chart", group=GRP_VIS)
use_bars = input.bool(false, "Use Gray Bars", group=GRP_VIS)
show_hud = input.bool(true, "Show Dashboard (on price chart)", group=GRP_HUD)
hud_pos = input.string("Top Right", "Position",
options=["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group=GRP_HUD)
float atr = ta.atr(atr_len)
float ema_t = ta.ema(close, ema_len)
float vol_ma = ta.sma(nz(volume), vol_len)
float f0 = ta.rsi(close, rsi_len)
float f1 = atr > 0 ? (close - ema_t) / atr : 0.0
float f2 = ta.roc(close, roc_len)
float f3 = vol_ma > 0 ? nz(volume) / vol_ma : 1.0
var float[] b0 = array.new<float>()
var float[] b1 = array.new<float>()
var float[] b2 = array.new<float>()
var float[] b3 = array.new<float>()
var int[] b_y = array.new<int>()
var float[] sx = array.new<float>(8, 0.0)
var float[] sx2 = array.new<float>(8, 0.0)
var float[] cnt = array.new<float>(2, 0.0)
f_acc(int f, int c, float x, float sgn) =>
int idx = f * 2 + c
array.set(sx, idx, array.get(sx, idx) + sgn * x)
array.set(sx2, idx, array.get(sx2, idx) + sgn * x * x)
f_add(float x0, float x1, float x2, float x3, int y, float sgn) =>
f_acc(0, y, x0, sgn)
f_acc(1, y, x1, sgn)
f_acc(2, y, x2, sgn)
f_acc(3, y, x3, sgn)
array.set(cnt, y, array.get(cnt, y) + sgn)
f_loglik(int c, float[] x, float total) =>
float n = array.get(cnt, c)
float ll = math.log(n / total)
for f = 0 to 3
int idx = f * 2 + c
float mu = array.get(sx, idx) / n
float v = math.max(array.get(sx2, idx) / n - mu * mu, 1e-6)
float xv = array.get(x, f)
ll += -0.5 * math.log(2.0 * math.pi * v) - (xv - mu) * (xv - mu) / (2.0 * v)
ll
if barstate.isconfirmed and bar_index > horizon and not na(f0[horizon]) and not na(f2[horizon]) and not na(f1[horizon]) and not na(f3[horizon])
int y = close > close[horizon] ? 1 : 0
f_add(f0[horizon], f1[horizon], f2[horizon], f3[horizon], y, 1.0)
array.push(b0, f0[horizon])
array.push(b1, f1[horizon])
array.push(b2, f2[horizon])
array.push(b3, f3[horizon])
array.push(b_y, y)
if array.size(b_y) > win_size
f_add(array.shift(b0), array.shift(b1), array.shift(b2), array.shift(b3), array.shift(b_y), -1.0)
float total = array.get(cnt, 0) + array.get(cnt, 1)
bool ready = total >= math.min(min_train, win_size) and array.get(cnt, 0) >= 10 and array.get(cnt, 1) >= 10 and not na(f0) and not na(f2)
float p_up = na
if ready
float[] xnow = array.from(f0, f1, f2, f3)
float l1 = f_loglik(1, xnow, total)
float l0 = f_loglik(0, xnow, total)
float dd = math.max(-50.0, math.min(50.0, l0 - l1))
p_up := 1.0 / (1.0 + math.exp(dd))
float th = thresh / 100.0
int sig = na(p_up) ? 0 : p_up >= th ? 1 : p_up <= 1.0 - th ? -1 : 0
var float n_bs = 0.0
var float h_bs = 0.0
var float n_ss = 0.0
var float h_ss = 0.0
var float n_all = 0.0
var float h_all = 0.0
var float n_upo = 0.0
if barstate.isconfirmed and bar_index > horizon
bool went_up = close > close[horizon]
int s_past = sig[horizon]
if s_past == 1
n_bs += 1.0
h_bs += went_up ? 1.0 : 0.0
else if s_past == -1
n_ss += 1.0
h_ss += close < close[horizon] ? 1.0 : 0.0
if not na(p_up[horizon])
n_all += 1.0
n_upo += went_up ? 1.0 : 0.0
h_all += (p_up[horizon] >= 0.5) == went_up ? 1.0 : 0.0
// Dashboard
f_hud_pos(string s) =>
switch s
"Top Right" => position.top_right
"Top Left" => position.top_left
"Bottom Right" => position.bottom_right
=> position.bottom_left
f_rate(float h, float n) =>
n >= 10 ? str.tostring(math.round(h / n * 100.0)) + "% (n=" + str.tostring(int(n)) + ")" : "Collecting… (n=" + str.tostring(int(n)) + ")"
var table hud = table.new(f_hud_pos(hud_pos), 2, 8,
bgcolor=C_BG, border_color=C_BORD,
border_width=1, frame_color=C_BORD, frame_width=2,
force_overlay=true)
if show_hud and barstate.islast
color bgA = color.new(#1e293b, 40)
color bgB = color.new(#0f172a, 40)
table.cell(hud, 0, 0, "NAIVE BAYES AI [D3R]", text_color=C_TXT,
bgcolor=color.new(#1e293b, 0), text_size=size.small, text_halign=text.align_center)
table.merge_cells(hud, 0, 0, 1, 0)
table.cell(hud, 0, 1, "P(up) in " + str.tostring(horizon) + " bars", text_color=C_DIM, bgcolor=bgA, text_size=size.small)
table.cell(hud, 1, 1, na(p_up) ? "Training…" : str.tostring(math.round(p_up * 100)) + "%",
text_color = na(p_up) ? C_DIM : p_up >= 0.5 ? C_UP : C_DN, bgcolor=bgA, text_size=size.small, text_halign=text.align_center)
table.cell(hud, 0, 2, "Signal", text_color=C_DIM, bgcolor=bgB, text_size=size.small)
table.cell(hud, 1, 2, sig == 1 ? "▲ Bullish" : sig == -1 ? "▼ Bearish" : "Neutral",
text_color = sig == 1 ? C_UP : sig == -1 ? C_DN : C_DIM, bgcolor=bgB, text_size=size.small, text_halign=text.align_center)
table.cell(hud, 0, 3, "Bullish Signal Accuracy", text_color=C_DIM, bgcolor=bgA, text_size=size.small,
tooltip="Share of bars with a bullish signal where the close " + str.tostring(horizon) + " bars later was higher.")
table.cell(hud, 1, 3, f_rate(h_bs, n_bs), text_color=C_TXT, bgcolor=bgA, text_size=size.small, text_halign=text.align_center)
table.cell(hud, 0, 4, "Bearish Signal Accuracy", text_color=C_DIM, bgcolor=bgB, text_size=size.small,
tooltip="Share of bars with a bearish signal where the close " + str.tostring(horizon) + " bars later was lower.")
table.cell(hud, 1, 4, f_rate(h_ss, n_ss), text_color=C_TXT, bgcolor=bgB, text_size=size.small, text_halign=text.align_center)
float base = n_all > 0 ? math.max(n_upo, n_all - n_upo) / n_all * 100.0 : na
table.cell(hud, 0, 5, "All-Bar Accuracy vs Baseline", text_color=C_DIM, bgcolor=bgA, text_size=size.small,
tooltip="Model: share of all predictions (P above or below 50%) that were right. Baseline: what you'd score by always guessing the more common outcome. The model only adds value if it beats the baseline.")
table.cell(hud, 1, 5, n_all >= 10 ? str.tostring(math.round(h_all / n_all * 100.0)) + "% vs " + str.tostring(math.round(base)) + "%" : "Collecting…",
text_color = n_all >= 10 ? (h_all / n_all * 100.0 > base ? C_GOOD : C_BAD) : C_DIM, bgcolor=bgA, text_size=size.small, text_halign=text.align_center)
table.cell(hud, 0, 6, "Training Samples", text_color=C_DIM, bgcolor=bgB, text_size=size.small)
table.cell(hud, 1, 6, str.tostring(int(total)) + " / " + str.tostring(win_size), text_color=C_TXT, bgcolor=bgB, text_size=size.small, text_halign=text.align_center)
table.cell(hud, 0, 7, "Features", text_color=C_DIM, bgcolor=bgA, text_size=size.small)
table.cell(hud, 1, 7, "RSI · Trend dist · ROC · Rel. volume", text_color=C_AMBER, bgcolor=bgA, text_size=size.small, text_halign=text.align_center)
// Visual
float p_pct = p_up * 100.0
plot(p_pct, "P(up) %", color=color.from_gradient(nz(p_pct, 50), 100 - thresh, thresh, col_bear, col_bull), linewidth=w_line)
hline(thresh, "Bullish Threshold", color=col_lvl, linestyle=hline.style_dashed)
hline(50, "50%", color=col_lvl, linestyle=hline.style_dotted)
hline(100 - thresh, "Bearish Threshold", color=col_lvl, linestyle=hline.style_dashed)
bgcolor(show_bg and sig == 1 ? color.new(col_bull, bg_tr) : show_bg and sig == -1 ? color.new(col_bear, bg_tr) : na, title="Signal Zone")
bool sig_start = barstate.isconfirmed and sig != 0 and sig != sig[1]
if show_lbl and sig_start
label.new(bar_index, sig == 1 ? low : high, (sig == 1 ? "AI ▲ " : "AI ▼ ") + str.tostring(math.round(p_up * 100)) + "%",
style = sig == 1 ? label.style_label_up : label.style_label_down,
color = color.new(#000000, 100),
textcolor = sig == 1 ? col_bull : col_bear,
size = size.small,
force_overlay = true)
// Alert
alertcondition(sig_start and sig == 1, "AI Bullish Signal", "D3R Naive Bayes AI: bullish probability signal on {{ticker}}")
alertcondition(sig_start and sig == -1, "AI Bearish Signal", "D3R Naive Bayes AI: bearish probability signal on {{ticker}}")
barcolor( use_bars ? C_BAR: na)