IBD Distribution Days

kire_jovanosky · study · 252 行 · 点赞 18 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

//@version=6
// ─────────────────────────────────────────────────────────────────────────────
// IBD Distribution Days + Follow-Through Day + Power Trend
// (William O'Neil / Investor's Business Daily method)
//
// DISTRIBUTION DAY (red arrow above bar): close down >= 0.2% on higher volume
//   than the prior session. Counted while inside the lookback window and not
//   removed by a later rally of X% above its close.
//
// FOLLOW-THROUGH DAY (green arrow below bar, "FTD"): Day 4+ of a rally attempt,
//   index gains >= 1.25% on higher volume than the prior session.
//
// POWER TREND START (blue arrow below bar, "PT"): low above 21 EMA for 10 days,
//   21 EMA above 50 SMA for 5 days, 50 SMA rising, up close.
// POWER TREND END (red arrow below bar, "PT end"): 21 EMA drops below the
//   50 SMA, or a "circuit breaker" (close below 50 SMA while >10% off the peak).
//
// Use on a DAILY chart of an index/ETF that has volume (SPY, QQQ, NASDAQ:IXIC).
// ─────────────────────────────────────────────────────────────────────────────
indicator("IBD Distribution Days", shorttitle="IBD DDays", overlay=true, max_bars_back=505, max_labels_count=500)
 
// ── Inputs ───────────────────────────────────────────────────────────────────
GRP_WIN   = "Window"
GRP_RULES = "Distribution day rules (IBD / O'Neil)"
GRP_FTD   = "Follow-Through Day (FTD)"
GRP_PT    = "Power Trend"
GRP_VIS   = "Display"
GRP_LVL   = "Warning levels"
 
lookback = input.int(25, "Lookback window (trading days)", minval=1, maxval=500, group=GRP_WIN,
     tooltip="How many bars back (including the current one) to search for distribution days. IBD uses 25 sessions (about 5 weeks).")
 
minDropPct = input.float(0.2, "Minimum decline (%)", minval=0.0, step=0.05, group=GRP_RULES,
     tooltip="The close must be down at least this much vs. the prior close. IBD: 0.2%.")
useRally   = input.bool(true, "Remove a DD after the index rallies above it", group=GRP_RULES)
rallyPct   = input.float(5.0, "Rally that removes a DD (%)", minval=0.1, step=0.5, group=GRP_RULES,
     tooltip="A DD drops out of the count once any later close is at least this % above the DD's close. Commonly 5%; some use 6% for the Nasdaq.")
countStall = input.bool(false, "Also count stalling days", group=GRP_RULES,
     tooltip="Stalling day = higher volume than prior day, small gain, close in the lower half of the day's range. IBD does not publish exact thresholds, so this is an approximation.")
stallMaxPct = input.float(0.4, "Stalling day: max gain (%)", minval=0.0, step=0.05, group=GRP_RULES)
 
showFtd      = input.bool(true, "Mark follow-through days (green arrow)", group=GRP_FTD)
ftdGainPct   = input.float(1.25, "Min. gain on an FTD (%)", minval=0.1, step=0.05, group=GRP_FTD,
     tooltip="IBD currently cites 1.25%. Older IBD guidance used 1.0% and some sources use 1.7%.")
ftdMinDay    = input.int(4, "Earliest rally-attempt day for an FTD", minval=2, maxval=20, group=GRP_FTD)
ftdMaxDay    = input.int(0, "Latest rally-attempt day for an FTD (0 = no limit)", minval=0, maxval=250, group=GRP_FTD,
     tooltip="IBD says Day 4 or later. FTDs on Days 4-7 are usually considered strongest and later ones less reliable. Set e.g. 10 to ignore later ones.")
corrPct      = input.float(5.0, "Min. correction before a rally attempt counts (%)", minval=0.5, step=0.5, group=GRP_FTD,
     tooltip="The market must be at least this far below its recent peak when the rally attempt starts. Also used to detect a new correction after an FTD.")
peakLookback = input.int(60, "Look for the prior peak within (bars)", minval=10, maxval=250, group=GRP_FTD)
usePink      = input.bool(true, "Allow a 'pink' rally day as Day 1", group=GRP_FTD,
     tooltip="IBD also accepts a day that closes lower but in the upper half of its range as the start of a rally attempt.")
 
showPt     = input.bool(true, "Mark Power Trend start (blue arrow)", group=GRP_PT)
showPtEnd  = input.bool(true, "Mark Power Trend end (red arrow)", group=GRP_PT)
emaLen     = input.int(21, "Fast EMA length", minval=2, group=GRP_PT)
smaLen     = input.int(50, "Slow SMA length", minval=2, group=GRP_PT)
ptLowDays  = input.int(10, "Days the low must stay above the EMA", minval=1, group=GRP_PT)
ptEmaDays  = input.int(5, "Days the EMA must stay above the SMA", minval=1, group=GRP_PT)
useCircuit = input.bool(true, "End Power Trend on a 'circuit breaker'", group=GRP_PT,
     tooltip="Close below the slow SMA while the index is more than X% below its recent peak.")
circuitPct = input.float(10.0, "Circuit breaker drawdown (%)", minval=1.0, step=0.5, group=GRP_PT)
showMAs    = input.bool(false, "Plot the EMA / SMA", group=GRP_PT)
 
showRemoved = input.bool(true, "Show DDs removed by a rally (gray)", group=GRP_VIS)
showHistory = input.bool(false, "Show older DDs outside the window (faded)", group=GRP_VIS)
showTable   = input.bool(true, "Show info table", group=GRP_VIS)
tblPos      = input.string(position.top_right, "Table position", group=GRP_VIS,
     options=[position.top_left, position.top_center, position.top_right, position.middle_left, position.middle_center, position.middle_right, position.bottom_left, position.bottom_center, position.bottom_right])
colDist     = input.color(color.red, "Distribution day arrow", group=GRP_VIS)
colStall    = input.color(color.orange, "Stalling day arrow", group=GRP_VIS)
colRemoved  = input.color(color.gray, "Removed DD arrow", group=GRP_VIS)
colFtd      = input.color(color.green, "Follow-through day arrow", group=GRP_VIS)
colPt       = input.color(color.blue, "Power Trend start arrow", group=GRP_VIS)
colPtEnd    = input.color(color.red, "Power Trend end arrow", group=GRP_VIS)
 
cautionLvl = input.int(3, "Caution at (active count)", minval=1, group=GRP_LVL)
dangerLvl  = input.int(5, "Danger at (active count)", minval=1, group=GRP_LVL)
 
// ── Per-bar classification ───────────────────────────────────────────────────
float chgPct   = (close / close[1] - 1) * 100
bool  volUp    = volume > volume[1]
float rangeHL  = high - low
float closePos = rangeHL > 0 ? (close - low) / rangeHL : 0.5
 
bool isDist  = volUp and chgPct <= -minDropPct
bool isStall = countStall and volUp and chgPct > 0 and chgPct <= stallMaxPct and closePos <= 0.5
 
// ── Follow-Through Day state machine ─────────────────────────────────────────
// Day 1 = first up close (or "pink" upper-half close) after a correction low.
// The rally attempt dies if a later bar trades below the attempt low
// (the lower of the Day 0 and Day 1 lows). An FTD fires on Day >= 4 with a big
// gain on higher volume. Once an FTD fires, no new FTD is allowed until it fails
// (close below the FTD day's low) or a fresh correction starts from the post-FTD high.
var int   attDay      = 0
var float attLow      = na
var bool  ftdLock     = false
var float ftdLowRef   = na
var float postHigh    = na
var int   lastFtdTime = na
 
float peak     = ta.highest(high, peakLookback)
bool  day1Cand = close > close[1] or (usePink and closePos >= 0.5)
bool  ftdNow   = false
 
if ftdLock
    postHigh := math.max(postHigh, high)
    bool ftdFailed = close < ftdLowRef
    bool newCorr   = (postHigh - low) / postHigh * 100 >= corrPct
    if ftdFailed or newCorr
        ftdLock := false
 
if not ftdLock
    if attDay > 0 and low < attLow
        attDay := 0
    else if attDay > 0
        attDay += 1
        bool dayOK = attDay >= ftdMinDay and (ftdMaxDay == 0 or attDay <= ftdMaxDay)
        if dayOK and volUp and chgPct >= ftdGainPct
            ftdNow      := true
            ftdLock     := true
            ftdLowRef   := low
            postHigh    := high
            lastFtdTime := time
            attDay      := 0
    if attDay == 0 and not ftdNow
        float lo2 = math.min(low, low[1])
        if day1Cand and (peak - lo2) / peak * 100 >= corrPct
            attDay := 1
            attLow := lo2
 
// ── Power Trend ──────────────────────────────────────────────────────────────
float ema21 = ta.ema(close, emaLen)
float sma50 = ta.sma(close, smaLen)
float gapLow = low - ema21
float gapMA  = ema21 - sma50
 
bool lowAboveEma = ta.lowest(gapLow, ptLowDays) > 0
bool emaAboveSma = ta.lowest(gapMA, ptEmaDays) > 0
bool smaRising   = sma50 > sma50[1]
bool ptCond      = lowAboveEma and emaAboveSma and smaRising and close > close[1]
bool circuit     = useCircuit and close < sma50 and (peak - close) / peak * 100 >= circuitPct
 
var bool ptActive  = false
var int  ptSince   = na
var int  ptEndTime = na
bool ptStart = false
bool ptEnd   = false
 
if ptActive
    if ema21 < sma50 or circuit
        ptActive  := false
        ptEnd     := true
        ptEndTime := time
else if ptCond
    ptActive := true
    ptStart  := true
    ptSince  := time
 
// ── Distribution-day window scan ─────────────────────────────────────────────
// Walks from the current bar backwards through the window. runMax holds the
// highest close made AFTER the bar being examined, which is what decides
// whether a rally has already "removed" that distribution day.
var array<label> ddLabels = array.new<label>()
 
f_scan(bool draw) =>
    int dist    = 0
    int stall   = 0
    int removed = 0
    float runMax = na
    for k = 0 to lookback - 1
        float c = close[k]
        if na(c)
            break
        bool isD = isDist[k]
        bool isS = isStall[k]
        if isD or isS
            bool gone = useRally and not na(runMax) and runMax >= c * (1 + rallyPct / 100)
            if gone
                removed += 1
            else if isD
                dist += 1
            else
                stall += 1
            if draw and (not gone or showRemoved)
                color  col  = gone ? colRemoved : isD ? colDist : colStall
                string kind = isD ? "Distribution day" : "Stalling day"
                string tip  = kind + (gone ? " (removed by rally)" : "") + "\n" + str.format_time(time[k], "yyyy-MM-dd") + "\nChange: " + str.tostring(chgPct[k], "0.00") + "%" + "\nVolume vs prior day: +" + str.tostring((volume[k] / volume[k + 1] - 1) * 100, "0.0") + "%"
                array.push(ddLabels, label.new(x=bar_index - k, y=high[k], text="", xloc=xloc.bar_index, yloc=yloc.abovebar, color=col, style=label.style_arrowdown, size=size.small, tooltip=tip))
        runMax := na(runMax) ? c : math.max(runMax, c)
    [dist, stall, removed]
 
// Clear last draw, then rescan (draws only on the last bar)
if barstate.islast
    while array.size(ddLabels) > 0
        label.delete(array.pop(ddLabels))
 
[nDist, nStall, nRemoved] = f_scan(barstate.islast)
int total = nDist + nStall
 
// ── Plots ────────────────────────────────────────────────────────────────────
// Faded arrows for older DDs outside the window
bool histOK = showHistory and bar_index <= last_bar_index - lookback
plotshape(histOK and isDist,  "Older distribution day", shape.arrowdown, location.abovebar, color.new(colDist, 65),  size=size.tiny)
plotshape(histOK and isStall, "Older stalling day",     shape.arrowdown, location.abovebar, color.new(colStall, 65), size=size.tiny)
 
// Follow-through day (green), Power Trend start (blue), Power Trend end (red)
plotshape(showFtd and ftdNow,   "Follow-through day", shape.arrowup, location.belowbar, colFtd,   size=size.normal, text="FTD",    textcolor=colFtd)
plotshape(showPt and ptStart,   "Power Trend start",  shape.arrowup, location.belowbar, colPt,    size=size.normal, text="PT",     textcolor=colPt)
plotshape(showPtEnd and ptEnd,  "Power Trend end",    shape.arrowup, location.belowbar, colPtEnd, size=size.normal, text="PT end", textcolor=colPtEnd)
 
plot(showMAs ? ema21 : na, "EMA", color.new(color.blue, 0))
plot(showMAs ? sma50 : na, "SMA", color.new(color.red, 0))
 
// Rolling active count, readable in the Data Window / status line
plot(total, "Active DD count", display=display.data_window + display.status_line)
 
// ── Info table ───────────────────────────────────────────────────────────────
var table info = table.new(tblPos, 2, 11, bgcolor=color.new(#131722, 15), frame_color=color.new(color.gray, 40), frame_width=1, border_color=color.new(color.gray, 70), border_width=1)
 
f_row(int r, string name, string val, color valCol) =>
    table.cell(info, 0, r, name, text_color=color.new(color.white, 25), text_halign=text.align_left, text_size=size.small)
    table.cell(info, 1, r, val, text_color=valCol, text_halign=text.align_right, text_size=size.small)
 
float cumVol = ta.cum(nz(volume))
string warn = cumVol == 0 ? "No volume data on this symbol (try SPY / QQQ)" : not timeframe.isdaily ? "Switch to the Daily timeframe" : ""
color lvlCol = total >= dangerLvl ? color.red : total >= cautionLvl ? color.orange : color.green
string status = total >= dangerLvl ? "HEAVY - market under pressure" : total >= cautionLvl ? "Elevated - caution" : "Low"
 
if barstate.islast and showTable
    table.cell(info, 0, 0, "IBD Market Signals", text_color=color.white, text_halign=text.align_center, text_size=size.normal, bgcolor=color.new(color.gray, 55))
    table.merge_cells(info, 0, 0, 1, 0)
    f_row(1, "Window", str.tostring(lookback) + " bars", color.white)
    f_row(2, "Distribution days", str.tostring(nDist), colDist)
    f_row(3, "Stalling days", countStall ? str.tostring(nStall) : "off", countStall ? colStall : color.gray)
    f_row(4, "Removed by rally", useRally ? str.tostring(nRemoved) : "off", color.gray)
    f_row(5, "Active total", str.tostring(total), lvlCol)
    table.cell(info, 0, 6, status, text_color=color.white, text_halign=text.align_center, text_size=size.small, bgcolor=color.new(lvlCol, 55))
    table.merge_cells(info, 0, 6, 1, 6)
    f_row(7, "Rally attempt", attDay > 0 ? "Day " + str.tostring(attDay) : ftdLock ? "FTD in effect" : "none", attDay > 0 ? color.white : ftdLock ? colFtd : color.gray)
    f_row(8, "Last FTD", na(lastFtdTime) ? "none" : str.format_time(lastFtdTime, "yyyy-MM-dd"), na(lastFtdTime) ? color.gray : colFtd)
    f_row(9, "Power Trend", ptActive ? "ACTIVE since " + str.format_time(ptSince, "yyyy-MM-dd") : na(ptEndTime) ? "inactive" : "ended " + str.format_time(ptEndTime, "yyyy-MM-dd"), ptActive ? colPt : na(ptEndTime) ? color.gray : colPtEnd)
    table.cell(info, 0, 10, warn, text_color=color.white, text_halign=text.align_center, text_size=size.small, bgcolor=warn == "" ? color(na) : color.new(color.orange, 55))
    table.merge_cells(info, 0, 10, 1, 10)
 
// ── Alerts ───────────────────────────────────────────────────────────────────
alertcondition(isDist, "New distribution day", "Distribution day on {{ticker}}")
alertcondition(total >= cautionLvl and nz(total[1]) < cautionLvl, "DD count hit caution level", "{{ticker}}: active distribution-day count reached the caution level")
alertcondition(total >= dangerLvl and nz(total[1]) < dangerLvl, "DD count hit danger level", "{{ticker}}: active distribution-day count reached the danger level")
alertcondition(ftdNow, "Follow-through day", "Follow-through day on {{ticker}}")
alertcondition(ptStart, "Power Trend started", "Power Trend started on {{ticker}}")
alertcondition(ptEnd, "Power Trend ended", "Power Trend ended on {{ticker}}")

← 返回列表