Valuation Check - Abhinay Trader

abhinaytrader · study · 171 行 · 点赞 14 · TradingView 原页

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

Pine Script

//@version=6
// Valuation Check (final): is the stock priced Cheap, Neutral or Expensive versus its OWN history?
//
// Only metrics that are (a) available from TradingView's own data for almost every stock and
// (b) not distorted by analyst-estimate gaps or GAAP-vs-adjusted mismatches:
//
//   Non-financial companies           Banks / NBFCs / insurers
//   1. P/E          vs own median     1. P/E vs own median
//   2. EV/EBITDA    vs own median     2. P/B vs own median
//   3. FCF yield    vs own median
//
// Each metric votes Cheap / Neutral / Expensive (default: 15% or more below / above its own
// N-year median). Verdict = majority of the metrics that have data.
// Use on a Daily, Weekly or Monthly chart. A valuation screen, not a buy/sell signal.
indicator("Valuation Check", shorttitle = "Valuation", overlay = true, max_bars_back = 5000)
 
// ───────── Inputs ─────────
histYears = input.int(5, "Compare against own median of last N years", minval = 1, maxval = 15)
band      = input.float(15.0, "Cheap / expensive band (%)", minval = 1,
     tooltip = "15 = Cheap when 15% or more cheaper than its own median, Expensive when 15% or more dearer.")
finMode   = input.string("Auto", "Treat as bank / financial", options = ["Auto", "Yes", "No"],
     tooltip = "Financials use P/B instead of EV/EBITDA and FCF yield. Auto uses TradingView's sector.")
tblPos    = input.string("Top Right", "Table position",
     options = ["Top Left", "Top Right", "Bottom Left", "Bottom Right", "Middle Right"])
txtSize   = input.string("Normal", "Text size", options = ["Small", "Normal", "Large"])
 
// ───────── Raw data ─────────
// Money fields are converted to the chart's price currency; the share count is not money.
finCur(string id, string period) =>
    request.financial(syminfo.tickerid, id, period, ignore_invalid_symbol = true, currency = syminfo.currency)
 
epsTTM = finCur("EARNINGS_PER_SHARE_DILUTED", "TTM")
debt   = finCur("TOTAL_DEBT", "FQ")
cash   = finCur("CASH_N_SHORT_TERM_INVEST", "FQ")
ebitda = finCur("EBITDA", "TTM")
fcf    = finCur("FREE_CASH_FLOW", "TTM")
bvps   = finCur("BOOK_VALUE_PER_SHARE", "FQ")
shares = request.financial(syminfo.tickerid, "TOTAL_SHARES_OUTSTANDING", "FQ", ignore_invalid_symbol = true)
 
isFin = finMode == "Yes" or (finMode == "Auto" and syminfo.sector == "Finance")
 
barsPerYear = timeframe.isdaily ? 252 : timeframe.isweekly ? 52 : timeframe.ismonthly ? 12 : 0
histLen     = barsPerYear * histYears
tfOk        = barsPerYear > 0
 
// Median of a positive series over the last `maxLen` bars where it had data (needs >= 1 year of samples)
histMedian(float v, int maxLen, int minLen) =>
    var a = array.new_float()
    if not na(v) and v > 0 and maxLen > 0
        a.push(v)
        if a.size() > maxLen
            a.shift()
    a.size() >= minLen and minLen > 0 ? a.median() : float(na)
 
// Vote: +1 Cheap, 0 Neutral, -1 Expensive, na = no vote.
// lowIsCheap = true for multiples (P/E, EV/EBITDA, P/B); false for yields (FCF yield).
vote(float v, float med, bool lowIsCheap) =>
    float r = na(v) or na(med) ? float(na) : v / med
    na(r) ? float(na) :
         r < 1 - band / 100 ? (lowIsCheap ? 1.0 : -1.0) :
         r > 1 + band / 100 ? (lowIsCheap ? -1.0 : 1.0) : 0.0
 
// ───────── Metrics ─────────
// 1. P/E (losses -> no vote)
pe    = epsTTM > 0 ? close / epsTTM : float(na)
peMed = histMedian(pe, histLen, barsPerYear)
vPE   = vote(pe, peMed, true)
 
// 2a. EV/EBITDA (non-financials; negative EBITDA -> no vote)
mcap     = shares > 0 ? close * shares : float(na)
ev       = na(mcap) ? float(na) : mcap + nz(debt) - nz(cash)
evEbitda = not isFin and ebitda > 0 and ev > 0 ? ev / ebitda : float(na)
evMed    = histMedian(evEbitda, histLen, barsPerYear)
vEV      = vote(evEbitda, evMed, true)
 
// 3a. FCF yield % (non-financials; negative FCF -> no vote)
fcfYield = not isFin and mcap > 0 and fcf > 0 ? fcf / mcap * 100 : float(na)
fcfMed   = histMedian(fcfYield, histLen, barsPerYear)
vFCF     = vote(fcfYield, fcfMed, false)
 
// 2b. P/B (financials only)
pb    = isFin and bvps > 0 ? close / bvps : float(na)
pbMed = histMedian(pb, histLen, barsPerYear)
vPB   = vote(pb, pbMed, true)
 
// ───────── Verdict ─────────
isVal(float v) => na(v) ? 0 : 1
isEq(float v, float t) => not na(v) and v == t ? 1 : 0
 
valid      = isVal(vPE) + isVal(vEV) + isVal(vFCF) + isVal(vPB)
cheapVotes = isEq(vPE, 1) + isEq(vEV, 1) + isEq(vFCF, 1) + isEq(vPB, 1)
expVotes   = isEq(vPE, -1) + isEq(vEV, -1) + isEq(vFCF, -1) + isEq(vPB, -1)
 
verdict = not tfOk ? "USE D / W / M CHART" : valid == 0 ? "NO DATA" :
     cheapVotes * 2 > valid ? "CHEAP" : expVotes * 2 > valid ? "EXPENSIVE" : "NEUTRAL"
 
// Values also visible in the Data Window
plot(pe,       "P/E",                  display = display.data_window)
plot(peMed,    "P/E own median",       display = display.data_window)
plot(evEbitda, "EV/EBITDA",            display = display.data_window)
plot(evMed,    "EV/EBITDA own median", display = display.data_window)
plot(fcfYield, "FCF yield %",          display = display.data_window)
plot(fcfMed,   "FCF yield own median", display = display.data_window)
plot(pb,       "P/B",                  display = display.data_window)
plot(pbMed,    "P/B own median",       display = display.data_window)
 
// ───────── Table ─────────
cGreen = color.new(#26a69a, 0)
cRed   = color.new(#ef5350, 0)
cGray  = color.new(#787b86, 0)
cWhite = color.white
cBg    = color.new(#131722, 10)
cHead  = color.new(#2a2e39, 0)
 
posOf(string p) =>
    switch p
        "Top Left"     => position.top_left
        "Bottom Left"  => position.bottom_left
        "Bottom Right" => position.bottom_right
        "Middle Right" => position.middle_right
        => position.top_right
 
sizeOf(string s) =>
    switch s
        "Small" => size.small
        "Large" => size.large
        => size.normal
 
fmt(float v, string f) => na(v) ? "n/a" : str.tostring(v, f)
fmtPct(float v) => na(v) ? "n/a" : str.tostring(v, "#.##") + "%"
diffOf(float v, float med) =>
    na(v) or na(med) ? "n/a" : (v >= med ? "+" : "") + str.tostring(math.round((v / med - 1) * 100)) + "%"
readOf(float v) => na(v) ? "n/a" : v == 1 ? "Cheap" : v == -1 ? "Expensive" : "Neutral"
colOf(float v)  => na(v) ? cGray : v == 1 ? cGreen : v == -1 ? cRed : cGray
 
var table t = table.new(posOf(tblPos), 5, 6, bgcolor = cBg, border_width = 1, border_color = cHead)
 
row(int r, string name, string now, string med, string diff, float v, string sz) =>
    table.cell(t, 0, r, name, text_color = cWhite,   text_size = sz, text_halign = text.align_left)
    table.cell(t, 1, r, now,  text_color = cWhite,   text_size = sz)
    table.cell(t, 2, r, med,  text_color = cGray,    text_size = sz)
    table.cell(t, 3, r, diff, text_color = cGray,    text_size = sz)
    table.cell(t, 4, r, readOf(v), text_color = colOf(v), text_size = sz)
 
if barstate.islast
    sz  = sizeOf(txtSize)
    yrs = str.tostring(histYears) + "y median"
    table.cell(t, 0, 0, syminfo.ticker + (isFin ? " (financial)" : ""), text_color = cWhite, bgcolor = cHead, text_size = sz)
    table.cell(t, 1, 0, "Now",         text_color = cWhite, bgcolor = cHead, text_size = sz)
    table.cell(t, 2, 0, yrs,           text_color = cWhite, bgcolor = cHead, text_size = sz)
    table.cell(t, 3, 0, "vs median",   text_color = cWhite, bgcolor = cHead, text_size = sz)
    table.cell(t, 4, 0, "Read",        text_color = cWhite, bgcolor = cHead, text_size = sz)
 
    row(1, "P/E", epsTTM <= 0 ? "loss" : fmt(pe, "#.#"), fmt(peMed, "#.#"), diffOf(pe, peMed), vPE, sz)
 
    if isFin
        row(2, "P/B", fmt(pb, "#.##"), fmt(pbMed, "#.##"), diffOf(pb, pbMed), vPB, sz)
    else
        row(2, "EV/EBITDA", ebitda <= 0 ? "neg. EBITDA" : fmt(evEbitda, "#.#"), fmt(evMed, "#.#"),
             diffOf(evEbitda, evMed), vEV, sz)
        row(3, "FCF yield", fcf <= 0 ? "neg. FCF" : fmtPct(fcfYield), fmtPct(fcfMed),
             diffOf(fcfYield, fcfMed), vFCF, sz)
 
    rv = isFin ? 3 : 4
    table.cell(t, 0, rv, "Votes: " + str.tostring(cheapVotes) + " cheap · " + str.tostring(expVotes) +
         " expensive · " + str.tostring(valid) + " with data", text_color = cGray, text_size = size.small)
    table.merge_cells(t, 0, rv, 4, rv)
 
    vCol = verdict == "CHEAP" ? cGreen : verdict == "EXPENSIVE" ? cRed : cGray
    table.cell(t, 0, rv + 1, "VERDICT: " + verdict, text_color = cWhite, bgcolor = vCol, text_size = sz)
    table.merge_cells(t, 0, rv + 1, 4, rv + 1)

← 返回列表