Minervini Code 33 Matrix

kire_jovanosky · study · 222 行 · 点赞 4 · TradingView 原页

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

Pine Script

//@version=6
 
// =============================================================================
// MINERVINI "CODE 33" FUNDAMENTAL ACCELERATION MATRIX
// -----------------------------------------------------------------------------
// A stock flashes a Code 33 signal when EPS growth, Sales (Revenue) growth,
// and Net Profit Margin have EACH been increasing for 3 straight reported
// quarters (each quarter's YoY figure stronger than the one before it).
// Code 32 = the same 3-quarter acceleration pattern in 2 of the 3 metrics.
// Code 31 = in just 1 of the 3. Code 1 = a single quarter's acceleration in
// at least one metric (weaker, no 3-quarter run required).
//
// Per Minervini's own rules, fundamentals alone are not enough — a genuine
// setup also needs Stage 2 price confirmation. This version adds a basic
// Trend Template check (price above rising 50/200-day MAs) alongside the
// fundamental matrix, plus flags for the negative patterns he warns about
// (margin erosion, EPS-only "margin plays", and post-spike deceleration).
//
// Works on stocks with quarterly earnings history on TradingView. Availability
// of fundamental data depends on your TradingView data plan/exchange coverage.
// =============================================================================
 
indicator("Minervini Code 33 Matrix", overlay = true)
 
// ============================== INPUTS ======================================
grpTable       = "Table"
tablePosInput  = input.string("Top Right", "Position", options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left", "Middle Right"], group = grpTable)
tableSizeInput = input.string("Normal", "Text Size", options = ["Tiny", "Small", "Normal", "Large"], group = grpTable)
 
grpCalc         = "Calculation"
epsTypeInput    = input.string("Diluted", "EPS Type", options = ["Diluted", "Basic"], group = grpCalc)
requirePositive = input.bool(true, "Require Positive Growth", group = grpCalc, tooltip = "ON: EPS/Sales rows only count as accelerating if all 3 quarters are positive AND increasing; the Margin row only counts if all 3 net margins are positive AND increasing. OFF: only the increasing (accelerating) pattern is required, even if values are negative.")
 
grpTrend       = "Stage 2 Price Confirmation"
fastMaLenInput = input.int(50, "Fast MA Length", group = grpTrend, minval = 1)
slowMaLenInput = input.int(200, "Slow MA Length", group = grpTrend, minval = 1)
maRiseLookback = input.int(20, "Slow MA 'Rising' Lookback (bars)", group = grpTrend, minval = 1, tooltip = "The slow MA must be higher now than this many bars ago to count as rising.")
 
// ============================== FETCH FUNDAMENTALS ===========================
epsGrowthID = epsTypeInput == "Diluted" ? "EARNINGS_PER_SHARE_DILUTED_ONE_YEAR_GROWTH" : "EARNINGS_PER_SHARE_BASIC_ONE_YEAR_GROWTH"
 
salesRaw     = request.financial(syminfo.tickerid, "TOTAL_REVENUE", "FQ", ignore_invalid_symbol = true)
epsGrowthQ   = request.financial(syminfo.tickerid, epsGrowthID, "FQ", ignore_invalid_symbol = true)
salesGrowthQ = request.financial(syminfo.tickerid, "REVENUE_ONE_YEAR_GROWTH", "FQ", ignore_invalid_symbol = true)
marginQ      = request.financial(syminfo.tickerid, "NET_MARGIN", "FQ", ignore_invalid_symbol = true)
 
// ============================== BUILD QUARTER HISTORY =========================
// The FQ series holds one constant value through a quarter, then steps to a
// new value the moment a new report lands. We watch salesRaw (a raw dollar
// figure that virtually never repeats bar-for-bar) as a "heartbeat" to detect
// that step, and archive one entry per reported quarter for all 3 metrics.
var epsGrowthHist   = array.new_float(0)
var salesGrowthHist = array.new_float(0)
var marginHist      = array.new_float(0)
 
isNewQuarter = not na(salesRaw) and (na(salesRaw[1]) or salesRaw != salesRaw[1])
 
if isNewQuarter
    array.push(epsGrowthHist, epsGrowthQ)
    array.push(salesGrowthHist, salesGrowthQ)
    array.push(marginHist, marginQ)
    if array.size(epsGrowthHist) > 8
        array.shift(epsGrowthHist)
        array.shift(salesGrowthHist)
        array.shift(marginHist)
 
// ============================== FUNDAMENTAL LOGIC (every bar) =================
// Computed unconditionally (not just at barstate.islast) so alertcondition()
// can reference these values, per Pine's rule that alertcondition() must sit
// in the global scope rather than inside an "if" block.
n = array.size(epsGrowthHist)
haveEnoughData = n >= 3
 
epsG0 = haveEnoughData ? array.get(epsGrowthHist, n - 1) : na
epsG1 = haveEnoughData ? array.get(epsGrowthHist, n - 2) : na
epsG2 = haveEnoughData ? array.get(epsGrowthHist, n - 3) : na
 
salG0 = haveEnoughData ? array.get(salesGrowthHist, n - 1) : na
salG1 = haveEnoughData ? array.get(salesGrowthHist, n - 2) : na
salG2 = haveEnoughData ? array.get(salesGrowthHist, n - 3) : na
 
marM0 = haveEnoughData ? array.get(marginHist, n - 1) : na
marM1 = haveEnoughData ? array.get(marginHist, n - 2) : na
marM2 = haveEnoughData ? array.get(marginHist, n - 3) : na
 
// --- 3-quarter acceleration (Code "_3" tier) ---
epsSeqUp = not na(epsG0) and not na(epsG1) and not na(epsG2) and epsG0 > epsG1 and epsG1 > epsG2
salSeqUp = not na(salG0) and not na(salG1) and not na(salG2) and salG0 > salG1 and salG1 > salG2
marSeqUp = not na(marM0) and not na(marM1) and not na(marM2) and marM0 > marM1 and marM1 > marM2
 
epsPosOk = not requirePositive or (epsG0 > 0 and epsG1 > 0 and epsG2 > 0)
salPosOk = not requirePositive or (salG0 > 0 and salG1 > 0 and salG2 > 0)
marPosOk = not requirePositive or (marM0 > 0 and marM1 > 0 and marM2 > 0)
 
epsAccel = epsSeqUp and epsPosOk
salAccel = salSeqUp and salPosOk
marAccel = marSeqUp and marPosOk
 
accelCount3Q = (epsAccel ? 1 : 0) + (salAccel ? 1 : 0) + (marAccel ? 1 : 0)
code33       = accelCount3Q == 3
 
// --- 1-quarter acceleration (weaker "Code 1" tier, used only as a fallback) ---
epsAccel1Q = not na(epsG0) and not na(epsG1) and epsG0 > epsG1 and (not requirePositive or epsG0 > 0)
salAccel1Q = not na(salG0) and not na(salG1) and salG0 > salG1 and (not requirePositive or salG0 > 0)
marAccel1Q = not na(marM0) and not na(marM1) and marM0 > marM1 and (not requirePositive or marM0 > 0)
accelCount1Q = (epsAccel1Q ? 1 : 0) + (salAccel1Q ? 1 : 0) + (marAccel1Q ? 1 : 0)
 
codeLabel = accelCount3Q == 3 ? "CODE 33" : accelCount3Q == 2 ? "CODE 32" : accelCount3Q == 1 ? "CODE 31" : accelCount1Q > 0 ? "CODE 1" : "NO CODE"
 
// --- Negative-signal warnings (from Minervini's "watch for" list) ---
marginEroding  = not na(marM0) and not na(marM2) and marM0 < marM2
pureMarginPlay = not na(salG0) and not na(epsG0) and salG0 <= 0 and epsG0 > 0
sharpDecel     = not na(epsG0) and not na(epsG1) and epsG1 >= 50 and epsG0 < epsG1 * 0.5
 
warnParts = array.new_string(0)
if marginEroding
    array.push(warnParts, "Margin eroding vs. 2Q ago")
if pureMarginPlay
    array.push(warnParts, "EPS+ but sales flat/negative (pure margin play)")
if sharpDecel
    array.push(warnParts, "Sharp EPS deceleration after a strong quarter")
warningText = array.size(warnParts) > 0 ? array.join(warnParts, "; ") : "None detected"
hasWarning  = array.size(warnParts) > 0
 
// ============================== STAGE 2 PRICE CONFIRMATION (every bar) =========
fastMa       = ta.sma(close, fastMaLenInput)
slowMa       = ta.sma(close, slowMaLenInput)
slowMaRising = slowMa > slowMa[maRiseLookback]
stage2       = close > fastMa and close > slowMa and fastMa > slowMa and slowMaRising
 
actionable = code33 and stage2
 
// ============================== TABLE STYLE ====================================
tablePos = switch tablePosInput
    "Top Right"    => position.top_right
    "Top Left"     => position.top_left
    "Bottom Right" => position.bottom_right
    "Bottom Left"  => position.bottom_left
    "Middle Right" => position.middle_right
    => position.top_right
 
tableSize = switch tableSizeInput
    "Tiny"   => size.tiny
    "Small"  => size.small
    "Normal" => size.normal
    "Large"  => size.large
    => size.normal
 
colHeaderBg  = color.new(#1B1F3B, 0)
colHeaderTx  = color.white
colRowBg     = color.new(#0E1117, 0)
colLabelTx   = color.white
colGoodBg    = color.new(color.green, 75)
colBadBg     = color.new(color.red, 82)
colWarnBg    = color.new(color.orange, 80)
colGoodTx    = color.lime
colBadTx     = color.red
colWarnTx    = color.orange
colNeutralTx = color.gray
 
f_pct(val) =>
    na(val) ? "n/a" : str.tostring(val, "0.00") + "%"
 
f_valColor(val) =>
    na(val) ? colNeutralTx : (val > 0 ? color.lime : color.red)
 
// ============================== RENDER TABLE ====================================
var matrixTable = table.new(tablePos, 5, 7, border_width = 1, frame_width = 2, frame_color = color.new(color.gray, 40))
 
if barstate.islast
    table.cell(matrixTable, 0, 0, "Code 33 Matrix", bgcolor = colHeaderBg, text_color = colHeaderTx, text_size = tableSize, text_halign = text.align_left)
    table.cell(matrixTable, 1, 0, "2Q Ago",   bgcolor = colHeaderBg, text_color = colHeaderTx, text_size = tableSize)
    table.cell(matrixTable, 2, 0, "1Q Ago",   bgcolor = colHeaderBg, text_color = colHeaderTx, text_size = tableSize)
    table.cell(matrixTable, 3, 0, "Latest Q", bgcolor = colHeaderBg, text_color = colHeaderTx, text_size = tableSize)
    table.cell(matrixTable, 4, 0, "Accel?",   bgcolor = colHeaderBg, text_color = colHeaderTx, text_size = tableSize, tooltip = "Checkmark = this metric's year-over-year figure increased for 3 straight reported quarters (Minervini's definition of acceleration).")
 
    if not haveEnoughData
        table.cell(matrixTable, 0, 1, "Not enough quarterly fundamental data for this symbol (" + str.tostring(n) + "/3 quarters found). Works on stocks with earnings history.", bgcolor = colRowBg, text_color = color.orange, text_size = tableSize, text_halign = text.align_left)
        table.merge_cells(matrixTable, 0, 1, 4, 6)
    else
        // --- Row 1: EPS growth ---
        table.cell(matrixTable, 0, 1, "EPS Growth (YoY)", bgcolor = colRowBg, text_color = colLabelTx, text_size = tableSize, text_halign = text.align_left)
        table.cell(matrixTable, 1, 1, f_pct(epsG2), bgcolor = colRowBg, text_color = f_valColor(epsG2), text_size = tableSize, text_font_family = font.family_monospace)
        table.cell(matrixTable, 2, 1, f_pct(epsG1), bgcolor = colRowBg, text_color = f_valColor(epsG1), text_size = tableSize, text_font_family = font.family_monospace)
        table.cell(matrixTable, 3, 1, f_pct(epsG0), bgcolor = colRowBg, text_color = f_valColor(epsG0), text_size = tableSize, text_font_family = font.family_monospace)
        table.cell(matrixTable, 4, 1, epsAccel ? "✓" : "✗", bgcolor = epsAccel ? colGoodBg : colBadBg, text_color = epsAccel ? colGoodTx : colBadTx, text_size = tableSize)
 
        // --- Row 2: Sales growth ---
        table.cell(matrixTable, 0, 2, "Sales Growth (YoY)", bgcolor = colRowBg, text_color = colLabelTx, text_size = tableSize, text_halign = text.align_left)
        table.cell(matrixTable, 1, 2, f_pct(salG2), bgcolor = colRowBg, text_color = f_valColor(salG2), text_size = tableSize, text_font_family = font.family_monospace)
        table.cell(matrixTable, 2, 2, f_pct(salG1), bgcolor = colRowBg, text_color = f_valColor(salG1), text_size = tableSize, text_font_family = font.family_monospace)
        table.cell(matrixTable, 3, 2, f_pct(salG0), bgcolor = colRowBg, text_color = f_valColor(salG0), text_size = tableSize, text_font_family = font.family_monospace)
        table.cell(matrixTable, 4, 2, salAccel ? "✓" : "✗", bgcolor = salAccel ? colGoodBg : colBadBg, text_color = salAccel ? colGoodTx : colBadTx, text_size = tableSize)
 
        // --- Row 3: Net margin ---
        table.cell(matrixTable, 0, 3, "Net Margin", bgcolor = colRowBg, text_color = colLabelTx, text_size = tableSize, text_halign = text.align_left)
        table.cell(matrixTable, 1, 3, f_pct(marM2), bgcolor = colRowBg, text_color = f_valColor(marM2), text_size = tableSize, text_font_family = font.family_monospace)
        table.cell(matrixTable, 2, 3, f_pct(marM1), bgcolor = colRowBg, text_color = f_valColor(marM1), text_size = tableSize, text_font_family = font.family_monospace)
        table.cell(matrixTable, 3, 3, f_pct(marM0), bgcolor = colRowBg, text_color = f_valColor(marM0), text_size = tableSize, text_font_family = font.family_monospace)
        table.cell(matrixTable, 4, 3, marAccel ? "✓" : "✗", bgcolor = marAccel ? colGoodBg : colBadBg, text_color = marAccel ? colGoodTx : colBadTx, text_size = tableSize)
 
        // --- Row 4: Stage 2 price confirmation ---
        table.cell(matrixTable, 0, 4, "Stage 2 Trend", bgcolor = colRowBg, text_color = colLabelTx, text_size = tableSize, text_halign = text.align_left)
        table.cell(matrixTable, 1, 4, "Px > " + str.tostring(fastMaLenInput) + "/" + str.tostring(slowMaLenInput) + " MA, MA rising", bgcolor = colRowBg, text_color = colNeutralTx, text_size = tableSize, text_halign = text.align_left)
        table.merge_cells(matrixTable, 1, 4, 3, 4)
        table.cell(matrixTable, 4, 4, stage2 ? "✓" : "✗", bgcolor = stage2 ? colGoodBg : colBadBg, text_color = stage2 ? colGoodTx : colBadTx, text_size = tableSize)
 
        // --- Row 5: warnings ---
        table.cell(matrixTable, 0, 5, "Warnings", bgcolor = colRowBg, text_color = colLabelTx, text_size = tableSize, text_halign = text.align_left)
        table.cell(matrixTable, 1, 5, warningText, bgcolor = hasWarning ? colWarnBg : colRowBg, text_color = hasWarning ? colWarnTx : colNeutralTx, text_size = tableSize, text_halign = text.align_left)
        table.merge_cells(matrixTable, 1, 5, 4, 5)
 
        // --- Row 6: overall status ---
        statusTxt = codeLabel + (code33 ? " — fundamentals accelerating" : " — fundamentals not fully aligned") + (stage2 ? " | Stage 2 ✓" : " | Stage 2 ✗") + (actionable ? "  ★ ACTIONABLE SETUP" : "")
        statusBg  = actionable ? colGoodBg : (code33 ? colWarnBg : colBadBg)
        statusTx  = actionable ? colGoodTx : (code33 ? colWarnTx : colBadTx)
        table.cell(matrixTable, 0, 6, statusTxt, bgcolor = statusBg, text_color = statusTx, text_size = tableSize, text_halign = text.align_center)
        table.merge_cells(matrixTable, 0, 6, 4, 6)
 
// ============================== ALERTS ====================================
alertcondition(code33, title = "Code 33 (fundamentals only)", message = "{{ticker}}: Code 33 fundamental acceleration triggered.")
alertcondition(actionable, title = "Code 33 + Stage 2 (actionable)", message = "{{ticker}}: Code 33 fundamentals + Stage 2 price confirmation — actionable setup.")

← 返回列表