Stock Report Metrics Simulator

gogaz · study · 578 行 · 点赞 8 · TradingView 原页

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

Pine Script

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © gogaz
 
//@version=6
indicator("Stock Report Metrics Simulator", overlay=true, max_lines_count=500, max_labels_count=500)
 
 
 
// ─────────────── Inputs ───────────────
gDisp  = "Display"
gData  = "Data"
gScr   = "Scoring"
gTheme = "Theme"
 
showTable = input.bool(true, "Show Metrics Table", group=gDisp)
tablePos  = input.string("top_right", "Table Position",
     options=["top_left","top_center","top_right",
              "middle_left","middle_center","middle_right",
              "bottom_left","bottom_center","bottom_right"],
     group=gDisp)
txtSize   = input.string("small", "Text Size",
     options=["tiny","small","normal","large"], group=gDisp)
 
showScoreMarkers     = input.bool(true,  "Show Score Change Markers", group=gDisp)
scoreChangeThreshold = input.float(1.0, "Min Score Change for Marker", minval=0.1, step=0.1, group=gScr)
 
tblBgCol  = input.color(color.black, "Table Background",       group=gTheme)
tblBgOpac = input.int(20,            "Table BG Transparency %", minval=0, maxval=100, group=gTheme)
rowBgCol  = input.color(color.black, "Row Background",         group=gTheme)
rowBgOpac = input.int(40,            "Row BG Transparency %",  minval=0, maxval=100, group=gTheme)
hdrBgCol  = input.color(#1565c0,     "Header Background",      group=gTheme)
navBgCol  = input.color(#0d47a1,     "Average Score BG",       group=gTheme)
subBgCol  = input.color(#424242,     "Section BG",             group=gTheme)
txtCol    = input.color(color.white, "Text Color",             group=gTheme)
 
benchSym    = input.symbol("SPX", "Market Benchmark",       group=gData)
autoEtf     = input.bool(true, "Auto-detect Sector/Industry ETF", group=gData,
     tooltip="Maps the symbol's sector/industry to a US ETF (US-listed symbols only). Manual ETFs below are used when auto is off, the symbol is not US-listed, or no match is found.")
sectorBench = input.symbol("XLI", "Manual Sector Benchmark ETF",   group=gData,
     tooltip="e.g. XLI=Industrials, XLK=Technology, XLF=Financials, XLV=Health Care")
indBench    = input.symbol("ITA", "Manual Industry Benchmark ETF", group=gData,
     tooltip="e.g. ITA=Aerospace & Defense, SMH=Semiconductors, IBB=Biotech")
 
normLB = input.int(252, "Momentum/Risk Normalization Lookback (bars)", minval=60, maxval=2000, group=gScr)
fundLB = input.int(756, "Fundamental/Valuation Lookback (bars)",       minval=120, maxval=4000, group=gScr)
 
isDaily = timeframe.isdaily and timeframe.multiplier == 1
 
// ─────────────── ETF auto-detection ───────────────
sectorEtf(s) =>
    switch s
        "Electronic Technology"    => "XLK"
        "Technology Services"      => "XLK"
        "Finance"                  => "XLF"
        "Health Technology"        => "XLV"
        "Health Services"          => "XLV"
        "Consumer Non-Durables"    => "XLP"
        "Distribution Services"    => "XLP"
        "Consumer Durables"        => "XLY"
        "Consumer Services"        => "XLY"
        "Retail Trade"             => "XLY"
        "Energy Minerals"          => "XLE"
        "Process Industries"       => "XLB"
        "Non-Energy Minerals"      => "XLB"
        "Producer Manufacturing"   => "XLI"
        "Industrial Services"      => "XLI"
        "Commercial Services"      => "XLI"
        "Transportation"           => "XLI"
        "Utilities"                => "XLU"
        "Communications"           => "XLC"
        => ""
 
industryEtf(s) =>
    switch s
        "Aerospace & Defense"               => "ITA"
        "Semiconductors"                    => "SMH"
        "Electronic Production Equipment"   => "SMH"
        "Biotechnology"                     => "IBB"
        "Pharmaceuticals: Major"            => "XPH"
        "Pharmaceuticals: Generic"          => "XPH"
        "Pharmaceuticals: Other"            => "XPH"
        "Medical Specialties"               => "IHI"
        "Managed Health Care"               => "IHF"
        "Hospital/Nursing Management"       => "IHF"
        "Packaged Software"                 => "IGV"
        "Internet Software/Services"        => "FDN"
        "Regional Banks"                    => "KRE"
        "Major Banks"                       => "KBE"
        "Investment Banks/Brokers"          => "KCE"
        "Property/Casualty Insurance"       => "KIE"
        "Life/Health Insurance"             => "KIE"
        "Multi-Line Insurance"              => "KIE"
        "Oil & Gas Production"              => "XOP"
        "Oilfield Services/Equipment"       => "OIH"
        "Coal"                              => "KOL"
        "Alternative Power Generation"      => "ICLN"
        "Homebuilding"                      => "ITB"
        "Precious Metals"                   => "GDX"
        "Steel"                             => "SLX"
        "Copper"                            => "COPX"
        "Other Metals/Minerals"             => "XME"
        "Agricultural Commodities/Milling"  => "MOO"
        "Airlines"                          => "JETS"
        "Trucking"                          => "IYT"
        "Railroads"                         => "IYT"
        "Air Freight/Couriers"              => "IYT"
        "Specialty Stores"                  => "XRT"
        "Internet Retail"                   => "XRT"
        "Restaurants"                       => "PEJ"
        "Casinos/Gaming"                    => "BJK"
        "Food: Major Diversified"           => "PBJ"
        "Motor Vehicles"                    => "CARZ"
        "Real Estate Investment Trusts"     => "VNQ"
        => ""
 
isUS       = syminfo.country == "US"
autoActive = autoEtf and isUS
autoSec    = sectorEtf(syminfo.sector)
autoInd    = industryEtf(syminfo.industry)
 
secSym = (autoActive and autoSec != "") ? autoSec : sectorBench
indSym = (autoActive and autoInd != "") ? autoInd : (autoActive and autoSec != "") ? autoSec : indBench
 
etfMode = not autoEtf ? "manual (auto off)" : not isUS ? "manual (non-US symbol)" : autoInd != "" ? "auto (industry match)" : autoSec != "" ? "auto (sector fallback)" : "manual (no match)"
 
// ─────────────── Price / returns ───────────────
price = close
ret1d = price / price[1] - 1
 
spxClose = request.security(benchSym, timeframe.period, close, ignore_invalid_symbol=true)
spxRet1d = spxClose / spxClose[1] - 1
secClose = request.security(secSym,   timeframe.period, close, ignore_invalid_symbol=true)
indClose = request.security(indSym,   timeframe.period, close, ignore_invalid_symbol=true)
 
// ─────────────── Risk metrics ───────────────
vol90   = ta.stdev(ret1d, 90) * math.sqrt(252)
sdA     = ta.stdev(ret1d, 252)
sdB     = ta.stdev(spxRet1d, 252)
corr252 = ta.correlation(ret1d, spxRet1d, 252)
beta    = (na(sdA) or na(sdB) or sdB == 0) ? na : corr252 * sdA / sdB
 
// ─────────────── Header stats ───────────────
hi52      = ta.highest(high, 252)
lo52      = ta.lowest(low, 252)
ddHigh    = hi52 > 0 ? price / hi52 - 1 : na
upFromLow = lo52 > 0 ? price / lo52 - 1 : na
avgVol20  = ta.sma(volume, 20)
 
newYear = year != year[1]
ytdOpen = ta.valuewhen(newYear, open, 0)
retYTD  = (not na(ytdOpen) and ytdOpen > 0) ? price / ytdOpen - 1 : na
 
// ─────────────── Momentum ───────────────
ret1w  = price / price[5]   - 1
ret1m  = price / price[21]  - 1
ret3m  = price / price[63]  - 1
ret6m  = price / price[126] - 1
ret12m = price / price[252] - 1
rsComp = 0.1*ret1w + 0.3*ret1m + 0.3*ret3m + 0.2*ret6m + 0.1*ret12m
 
// ─────────────── Risk magnitude detail ───────────────
bestDay90    = ta.highest(ret1d, 90)
worstDay90   = ta.lowest(ret1d, 90)
daysUp90     = math.sum(ret1d > 0 ? 1.0 : 0.0, 90)
daysDown90   = math.sum(ret1d < 0 ? 1.0 : 0.0, 90)
largestSwing = ta.highest((high - low) / close, 90)
 
// ─────────────── Sector / Industry excess returns ───────────────
sec1m = secClose / secClose[21]  - 1
sec3m = secClose / secClose[63]  - 1
sec1y = secClose / secClose[252] - 1
ind1m = indClose / indClose[21]  - 1
ind3m = indClose / indClose[63]  - 1
ind1y = indClose / indClose[252] - 1
 
excSec1m = ret1m  - sec1m
excSec3m = ret3m  - sec3m
excSec1y = ret12m - sec1y
excInd1m = ret1m  - ind1m
excInd3m = ret3m  - ind3m
excInd1y = ret12m - ind1y
 
relSecComp = 0.3*excSec1m + 0.4*excSec3m + 0.3*excSec1y
relIndComp = 0.3*excInd1m + 0.4*excInd3m + 0.3*excInd1y
 
// ─────────────── Earnings ───────────────
epsActual = request.earnings(syminfo.tickerid, earnings.actual,   barmerge.gaps_off)
epsEst    = request.earnings(syminfo.tickerid, earnings.estimate, barmerge.gaps_off)
epsSurp   = (not na(epsActual) and not na(epsEst) and epsEst != 0) ? (epsActual - epsEst) / math.abs(epsEst) : na
 
// ─────────────── Fundamentals (quarterly) ───────────────
revenueQ   = request.financial(syminfo.tickerid, "TOTAL_REVENUE",                 "FQ", barmerge.gaps_off, currency=syminfo.currency)
netIncQ    = request.financial(syminfo.tickerid, "NET_INCOME",                    "FQ", barmerge.gaps_off, currency=syminfo.currency)
equityQ    = request.financial(syminfo.tickerid, "TOTAL_EQUITY",                  "FQ", barmerge.gaps_off, currency=syminfo.currency)
grossQ     = request.financial(syminfo.tickerid, "GROSS_PROFIT",                  "FQ", barmerge.gaps_off, currency=syminfo.currency)
totalDebtQ = request.financial(syminfo.tickerid, "TOTAL_DEBT",                    "FQ", barmerge.gaps_off, currency=syminfo.currency)
currAssQ   = request.financial(syminfo.tickerid, "TOTAL_CURRENT_ASSETS",          "FQ", barmerge.gaps_off, currency=syminfo.currency)
currLiaQ   = request.financial(syminfo.tickerid, "TOTAL_CURRENT_LIABILITIES",     "FQ", barmerge.gaps_off, currency=syminfo.currency)
opCFQ      = request.financial(syminfo.tickerid, "CASH_F_OPERATING_ACTIVITIES",   "FQ", barmerge.gaps_off, currency=syminfo.currency)
 
netMargin   = (not na(revenueQ) and revenueQ > 0 and not na(netIncQ)) ? netIncQ / revenueQ : na
roe         = (not na(equityQ)  and equityQ  > 0 and not na(netIncQ)) ? netIncQ / equityQ  : na
grossMargin = (not na(revenueQ) and revenueQ > 0 and not na(grossQ))  ? grossQ  / revenueQ : na
 
// Year-over-year revenue growth: compare with the value 4 REPORTED QUARTERS ago (not 4 bars ago)
revChg    = not na(revenueQ) and revenueQ != nz(revenueQ[1])
revQ4ago  = ta.valuewhen(revChg, revenueQ, 4)
revGrowth = (not na(revenueQ) and not na(revQ4ago) and revQ4ago > 0) ? revenueQ / revQ4ago - 1 : na
 
currRatio = (not na(currAssQ) and not na(currLiaQ) and currLiaQ > 0) ? currAssQ / currLiaQ : na
debtToEq  = (not na(totalDebtQ) and not na(equityQ) and equityQ > 0) ? totalDebtQ / equityQ : na
ocfRatio  = (not na(opCFQ) and not na(netIncQ) and netIncQ > 0) ? math.max(-2.0, math.min(4.0, opCFQ / netIncQ)) : na
 
// ─────────────── Trailing-twelve-month data (P/E, P/S, cap) ───────────────
netIncTTM = request.financial(syminfo.tickerid, "NET_INCOME",               "TTM", barmerge.gaps_off, currency=syminfo.currency)
revTTM    = request.financial(syminfo.tickerid, "TOTAL_REVENUE",            "TTM", barmerge.gaps_off, currency=syminfo.currency)
shares    = request.financial(syminfo.tickerid, "TOTAL_SHARES_OUTSTANDING", "FQ",  barmerge.gaps_off)
 
mktCap = (not na(shares) and shares > 0) ? shares * price : na
peTTM  = (not na(mktCap) and not na(netIncTTM) and netIncTTM > 0) ? mktCap / netIncTTM : na
psTTM  = (not na(mktCap) and not na(revTTM)    and revTTM    > 0) ? mktCap / revTTM    : na
 
// ─────────────── Scoring helpers (ta.* always evaluated every bar) ───────────────
scoreH(src, lb) =>
    p = ta.percentrank(src, lb) / 100.0
    p * 9 + 1
 
scoreL(src, lb) =>
    p = ta.percentrank(src, lb) / 100.0
    (1 - p) * 9 + 1
 
// ─────────────── Fundamental sub-scores ───────────────
pw = (na(netMargin) ? 0.0 : 0.3) + (na(roe) ? 0.0 : 0.3) + (na(grossMargin) ? 0.0 : 0.2) + (na(revGrowth) ? 0.0 : 0.2)
profitComp  = pw > 0 ? (nz(netMargin) * 0.3 + nz(roe) * 0.3 + nz(grossMargin) * 0.2 + nz(revGrowth) * 0.2) / pw : na
profitScore = scoreH(profitComp, fundLB)
 
debtComp  = (na(currRatio) and na(debtToEq)) ? na : nz(currRatio, 1.5) - 0.5 * nz(debtToEq, 0)
debtScore = scoreH(debtComp, fundLB)
 
qualScore = scoreH(ocfRatio, fundLB)
 
var array<float> fundArr = array.new_float()
array.clear(fundArr)
if not na(profitScore)
    array.push(fundArr, profitScore)
if not na(debtScore)
    array.push(fundArr, debtScore)
if not na(qualScore)
    array.push(fundArr, qualScore)
fundScore = array.size(fundArr) > 0 ? array.avg(fundArr) : na
 
// ─────────────── Component scores ───────────────
// Earnings: fixed mapping (-20% surprise => 1, 0% => 5.5, +20% => 10)
earnScore = na(epsSurp) ? na : math.max(1.0, math.min(10.0, 5.5 + epsSurp / 0.20 * 4.5))
 
peScore = scoreL(peTTM, fundLB)
psScore = scoreL(psTTM, fundLB)
var array<float> valArr = array.new_float()
array.clear(valArr)
if not na(peScore)
    array.push(valArr, peScore)
if not na(psScore)
    array.push(valArr, psScore)
valScore = array.size(valArr) > 0 ? array.avg(valArr) : na
 
// Risk: volatility (normalized to a 30% "typical" level) and beta weighted equally
// Higher risk score = LOWER risk
riskComp  = na(vol90) ? na : 0.5 * (vol90 / 0.30) + 0.5 * nz(beta, 1.0)
riskScore = scoreL(riskComp, normLB)
 
momScore    = scoreH(rsComp,     normLB)
relSecScore = scoreH(relSecComp, normLB)
relIndScore = scoreH(relIndComp, normLB)
 
// ─────────────── Average score (5 components) ───────────────
var array<float> scoresArr = array.new_float()
array.clear(scoresArr)
if not na(earnScore)
    array.push(scoresArr, earnScore)
if not na(fundScore)
    array.push(scoresArr, fundScore)
if not na(valScore)
    array.push(scoresArr, valScore)
if not na(riskScore)
    array.push(scoresArr, riskScore)
if not na(momScore)
    array.push(scoresArr, momScore)
avgScore = array.size(scoresArr) > 0 ? array.avg(scoresArr) : na
 
// ─────────────── Score change detection ───────────────
scoreDelta = (na(avgScore) or na(avgScore[1])) ? 0.0 : avgScore - avgScore[1]
 
// Evaluate ta.* unconditionally, then apply the display toggle
x8up   = ta.crossover(avgScore, 8)
x4down = ta.crossunder(avgScore, 4)
x4up   = ta.crossover(avgScore, 4)
x8down = ta.crossunder(avgScore, 8)
 
scoreUpBig   = showScoreMarkers and not na(avgScore) and scoreDelta >=  scoreChangeThreshold
scoreDownBig = showScoreMarkers and not na(avgScore) and scoreDelta <= -scoreChangeThreshold
 
crossAbove8 = showScoreMarkers and x8up
crossBelow4 = showScoreMarkers and x4down
crossAbove4 = showScoreMarkers and x4up
crossBelow8 = showScoreMarkers and x8down
 
// ─────────────── Data checks ───────────────
barsAvail   = bar_index + 1
barsNeeded  = fundLB + 252
histOk      = barsAvail >= barsNeeded
 
// ─────────────── Suggestion / profile (rule-based labels) ───────────────
f_ge(v, t) => not na(v) and v >= t
f_lt(v, t) => not na(v) and v < t
 
compCount = array.size(scoresArr)
 
string profile = "Neutral / mixed"
int    tone    = 0      // 1 = positive, -1 = caution, 0 = neutral
 
if compCount < 3
    profile := "Not enough data"
else if f_ge(valScore, 7) and f_ge(fundScore, 5) and f_ge(riskScore, 4)
    profile := "Value for money"
    tone := 1
else if f_ge(fundScore, 7) and f_ge(riskScore, 6)
    profile := "Quality compounder"
    tone := 1
else if f_ge(revGrowth, 0.15) and f_ge(momScore, 6)
    profile := "Growth story"
    tone := 1
else if f_ge(momScore, 8) and f_ge(relSecScore, 6)
    profile := "Momentum leader"
    tone := 1
else if f_ge(earnScore, 7) and f_ge(momScore, 6) and f_lt(fundScore, 5)
    profile := "Turnaround (improving, fundamentals still weak)"
    tone := 0
else if f_ge(riskScore, 8) and f_ge(avgScore, 5)
    profile := "Defensive / low risk"
    tone := 1
else if f_ge(valScore, 7) and (f_lt(fundScore, 4) or f_lt(momScore, 4))
    profile := "Cheap but weak (value-trap risk)"
    tone := -1
else if f_ge(earnScore, 7) and f_lt(momScore, 4)
    profile := "Earnings beat, price lagging"
    tone := 0
else if not na(riskScore) and riskScore <= 3
    profile := "Speculative / high risk"
    tone := -1
else if f_lt(avgScore, 4)
    profile := "Weak across the board"
    tone := -1
 
lossMaking = not na(netMargin) and netMargin < 0
bigSurp    = not na(epsSurp) and math.abs(epsSurp) > 0.5
 
string flags = (lossMaking ? "Loss-making; " : "") + (bigSurp ? "Extreme EPS surprise; " : "") + (not histOk ? "Short history; " : "") + (compCount < 4 ? "Few comps; " : "") + (na(peTTM) ? "No P/E; " : "")
flags := flags == "" ? "None" : flags
 
profileBg = tone > 0 ? color.new(#2e7d32, 0) : tone < 0 ? color.new(#c62828, 0) : color.new(#ef6c00, 0)
 
// ─────────────── Formatting ───────────────
fP(v)     => na(v) ? "n/a" : str.tostring(v * 100, "0.00") + "%"
fPplus(v) => na(v) ? "n/a" : (v >= 0 ? "+" : "") + str.tostring(v * 100, "0.00") + "%"
fN(v, f)  => na(v) ? "n/a" : str.tostring(v, f)
fS(v)     => na(v) ? "n/a" : str.tostring(v, "0.0")
fVol(v)   => na(v) ? "n/a" : v >= 1e9 ? str.tostring(v/1e9, "0.00") + "B" : v >= 1e6 ? str.tostring(v/1e6, "0.0") + "M" : v >= 1e3 ? str.tostring(v/1e3, "0.0") + "K" : str.tostring(v, "0")
fCap(v)   => na(v) ? "n/a" : v >= 1e12 ? str.tostring(v/1e12, "0.00") + "T" : v >= 1e9 ? str.tostring(v/1e9, "0.00") + "B" : v >= 1e6 ? str.tostring(v/1e6, "0.0") + "M" : str.tostring(v, "0")
 
sectorName   = syminfo.sector   == "" ? "n/a" : syminfo.sector
industryName = syminfo.industry == "" ? "n/a" : syminfo.industry
 
scoreColor(v) =>
    na(v) ? color.gray :
     v >= 8 ? color.new(#2e7d32, 0) :
     v >= 4 ? color.new(#ef6c00, 0) :
              color.new(#c62828, 0)
 
tblPos = switch tablePos
    "top_left"      => position.top_left
    "top_center"    => position.top_center
    "top_right"     => position.top_right
    "middle_left"   => position.middle_left
    "middle_center" => position.middle_center
    "middle_right"  => position.middle_right
    "bottom_left"   => position.bottom_left
    "bottom_center" => position.bottom_center
    "bottom_right"  => position.bottom_right
    => position.top_right
 
tblSz = switch txtSize
    "tiny"   => size.tiny
    "small"  => size.small
    "normal" => size.normal
    "large"  => size.large
    => size.small
 
tblBg = color.new(tblBgCol, tblBgOpac)
rowBg = color.new(rowBgCol, rowBgOpac)
hdrBg = color.new(hdrBgCol, 0)
navBg = color.new(navBgCol, 0)
subBg = color.new(subBgCol, 0)
 
// ─────────────── Table (23 rows) ───────────────
var table tbl = table.new(tblPos, 3, 23, border_width=1, frame_width=1,
     frame_color=color.new(color.gray, 50), bgcolor=tblBg)
 
if showTable and barstate.islast
    table.cell(tbl, 0, 0, isDaily ? "Component" : "Component (use 1D chart!)", text_color=txtCol, bgcolor=isDaily ? hdrBg : color.new(#c62828, 0), text_size=tblSz)
    table.cell(tbl, 1, 0, "Value",           text_color=txtCol, bgcolor=hdrBg, text_size=tblSz)
    table.cell(tbl, 2, 0, "Score / Detail",  text_color=txtCol, bgcolor=hdrBg, text_size=tblSz)
 
    table.cell(tbl, 0, 1, "AVERAGE SCORE", text_color=txtCol, bgcolor=navBg, text_size=tblSz)
    table.cell(tbl, 1, 1, array.size(scoresArr) > 0 ? str.tostring(array.size(scoresArr)) + " of 5 comps" : "n/a",
         text_color=txtCol, bgcolor=navBg, text_size=tblSz)
    table.cell(tbl, 2, 1, fS(avgScore), text_color=txtCol, bgcolor=scoreColor(avgScore), text_size=tblSz)
 
    table.cell(tbl, 0, 2, "Earnings", text_color=txtCol, bgcolor=rowBg, text_size=tblSz)
    table.cell(tbl, 1, 2, "EPS Surprise: " + fP(epsSurp), text_color=txtCol, bgcolor=rowBg, text_size=tblSz,
         tooltip="EPS Surprise: " + fP(epsSurp) +
                 "\nScore mapping: -20% = 1, 0% = 5.5, +20% = 10" +
                 "\n\nSub-factors in report: 3\nAvailable here: 1 (Surprise)\n" +
                 "Missing: Estimate Revisions, Recommendation Changes (not exposed by Pine)")
    table.cell(tbl, 2, 2, fS(earnScore), text_color=txtCol, bgcolor=scoreColor(earnScore), text_size=tblSz)
 
    table.cell(tbl, 0, 3, "Fundamental", text_color=txtCol, bgcolor=rowBg, text_size=tblSz)
    table.cell(tbl, 1, 3, "NetMgn " + fP(netMargin) + "  ROE " + fP(roe), text_color=txtCol, bgcolor=rowBg, text_size=tblSz,
         tooltip="PROFITABILITY  " + fS(profitScore) + "\n  Rev growth (YoY) " + fP(revGrowth) +
                 "\n  Net margin " + fP(netMargin) +
                 "\n  ROE (quarterly) " + fP(roe) +
                 "\n  Gross margin " + fP(grossMargin) +
                 "\n\nDEBT  " + fS(debtScore) +
                 "\n  Current ratio " + fN(currRatio, "0.00") +
                 "\n  Debt/Equity " + fN(debtToEq, "0.00") +
                 "\n\nEARNINGS QUALITY  " + fS(qualScore) +
                 "\n  OCF / Net Income " + fN(ocfRatio, "0.00"))
    table.cell(tbl, 2, 3, fS(fundScore), text_color=txtCol, bgcolor=scoreColor(fundScore), text_size=tblSz)
 
    table.cell(tbl, 0, 4, "Relative Valuation", text_color=txtCol, bgcolor=rowBg, text_size=tblSz)
    table.cell(tbl, 1, 4, "P/E " + fN(peTTM, "0.0") + "  P/S " + fN(psTTM, "0.0"), text_color=txtCol, bgcolor=rowBg, text_size=tblSz,
         tooltip="Based on trailing-twelve-month net income / revenue\nP/E score " + fS(peScore) + "  P/S score " + fS(psScore) +
                 "\nScored vs the stock's own history")
    table.cell(tbl, 2, 4, fS(valScore), text_color=txtCol, bgcolor=scoreColor(valScore), text_size=tblSz)
 
    table.cell(tbl, 0, 5, "Risk", text_color=txtCol, bgcolor=rowBg, text_size=tblSz)
    table.cell(tbl, 1, 5, "Vol " + fP(vol90) + "  β " + fN(beta, "0.00"), text_color=txtCol, bgcolor=rowBg, text_size=tblSz,
         tooltip="Higher score = lower risk (vs own history)" +
                 "\n90d: Best " + fP(bestDay90) + ", Worst " + fP(worstDay90) +
                 ", Up " + str.tostring(daysUp90, "0") + " / Down " + str.tostring(daysDown90, "0") + " days" +
                 ", Largest swing " + fP(largestSwing) +
                 "\n252d: Corr " + fN(corr252, "0.00") + ", Beta " + fN(beta, "0.00"))
    table.cell(tbl, 2, 5, fS(riskScore), text_color=txtCol, bgcolor=scoreColor(riskScore), text_size=tblSz)
 
    table.cell(tbl, 0, 6, "Price Momentum", text_color=txtCol, bgcolor=rowBg, text_size=tblSz)
    table.cell(tbl, 1, 6, "RS " + fP(rsComp), text_color=txtCol, bgcolor=rowBg, text_size=tblSz,
         tooltip="Weighted 1W/1M/3M/6M/1Y return\nNote: report uses RS-100 composite + seasonality (50/50); Pine can't replicate seasonality cleanly")
    table.cell(tbl, 2, 6, fS(momScore), text_color=txtCol, bgcolor=scoreColor(momScore), text_size=tblSz)
 
    table.cell(tbl, 0, 7, "Sector", text_color=txtCol, bgcolor=rowBg, text_size=tblSz)
    table.cell(tbl, 1, 7, sectorName + "  Δ3M " + fPplus(excSec3m), text_color=txtCol, bgcolor=rowBg, text_size=tblSz,
         tooltip="Sector: " + sectorName + "  vs  " + secSym +
                 "\n1M excess " + fPplus(excSec1m) +
                 "\n3M excess " + fPplus(excSec3m) +
                 "\n1Y excess " + fPplus(excSec1y))
    table.cell(tbl, 2, 7, fS(relSecScore), text_color=txtCol, bgcolor=scoreColor(relSecScore), text_size=tblSz)
 
    table.cell(tbl, 0, 8, "Industry", text_color=txtCol, bgcolor=rowBg, text_size=tblSz)
    table.cell(tbl, 1, 8, industryName + "  Δ3M " + fPplus(excInd3m), text_color=txtCol, bgcolor=rowBg, text_size=tblSz,
         tooltip="Industry: " + industryName + "  vs  " + indSym +
                 "\n1M excess " + fPplus(excInd1m) +
                 "\n3M excess " + fPplus(excInd3m) +
                 "\n1Y excess " + fPplus(excInd1y))
    table.cell(tbl, 2, 8, fS(relIndScore), text_color=txtCol, bgcolor=scoreColor(relIndScore), text_size=tblSz)
 
    table.cell(tbl, 0, 9, "PRICE / PERFORMANCE", text_color=txtCol, bgcolor=subBg, text_size=tblSz)
    table.cell(tbl, 1, 9, "",                     text_color=txtCol, bgcolor=subBg)
    table.cell(tbl, 2, 9, "",                     text_color=txtCol, bgcolor=subBg)
 
    table.cell(tbl, 0, 10, "Last Price", text_color=txtCol, bgcolor=rowBg, text_size=tblSz)
    table.cell(tbl, 1, 10, fN(price, "0.00"), text_color=txtCol, bgcolor=rowBg, text_size=tblSz)
    table.cell(tbl, 2, 10, "52W High: " + fN(hi52, "0.00"), text_color=txtCol, bgcolor=rowBg, text_size=tblSz)
 
    table.cell(tbl, 0, 11, "% from 52W High", text_color=txtCol, bgcolor=rowBg, text_size=tblSz)
    table.cell(tbl, 1, 11, fP(ddHigh), text_color=txtCol, bgcolor=rowBg, text_size=tblSz)
    table.cell(tbl, 2, 11, "52W Low: " + fN(lo52, "0.00"), text_color=txtCol, bgcolor=rowBg, text_size=tblSz)
 
    table.cell(tbl, 0, 12, "YTD Return", text_color=txtCol, bgcolor=rowBg, text_size=tblSz)
    table.cell(tbl, 1, 12, fP(retYTD), text_color=txtCol, bgcolor=rowBg, text_size=tblSz)
    table.cell(tbl, 2, 12, "Avg Vol 20d: " + fVol(avgVol20), text_color=txtCol, bgcolor=rowBg, text_size=tblSz)
 
    table.cell(tbl, 0, 13, "1M / 3M Return", text_color=txtCol, bgcolor=rowBg, text_size=tblSz)
    table.cell(tbl, 1, 13, fP(ret1m) + " / " + fP(ret3m), text_color=txtCol, bgcolor=rowBg, text_size=tblSz)
    table.cell(tbl, 2, 13, "Up from 52W Low: " + fP(upFromLow), text_color=txtCol, bgcolor=rowBg, text_size=tblSz)
 
    table.cell(tbl, 0, 14, "1Y Return", text_color=txtCol, bgcolor=rowBg, text_size=tblSz)
    table.cell(tbl, 1, 14, fP(ret12m), text_color=txtCol, bgcolor=rowBg, text_size=tblSz)
    table.cell(tbl, 2, 14, "Mkt Cap: " + fCap(mktCap) + " " + syminfo.currency, text_color=txtCol, bgcolor=rowBg, text_size=tblSz)
 
    table.cell(tbl, 0, 15, "RISK DETAIL (90D)", text_color=txtCol, bgcolor=subBg, text_size=tblSz)
    table.cell(tbl, 1, 15, "",                  text_color=txtCol, bgcolor=subBg)
    table.cell(tbl, 2, 15, "",                  text_color=txtCol, bgcolor=subBg)
 
    table.cell(tbl, 0, 16, "Best / Worst Day", text_color=txtCol, bgcolor=rowBg, text_size=tblSz)
    table.cell(tbl, 1, 16, fP(bestDay90) + " / " + fP(worstDay90), text_color=txtCol, bgcolor=rowBg, text_size=tblSz)
    table.cell(tbl, 2, 16, "Up/Down: " + str.tostring(daysUp90, "0") + "/" + str.tostring(daysDown90, "0"),
         text_color=txtCol, bgcolor=rowBg, text_size=tblSz)
 
    table.cell(tbl, 0, 17, "Correlation / Beta", text_color=txtCol, bgcolor=rowBg, text_size=tblSz)
    table.cell(tbl, 1, 17, fN(corr252, "0.00") + " / " + fN(beta, "0.00"), text_color=txtCol, bgcolor=rowBg, text_size=tblSz)
    table.cell(tbl, 2, 17, "Largest swing: " + fP(largestSwing), text_color=txtCol, bgcolor=rowBg, text_size=tblSz)
 
    table.cell(tbl, 0, 18, "Benchmarks", text_color=txtCol, bgcolor=rowBg, text_size=tblSz)
    table.cell(tbl, 1, 18, "Mkt " + benchSym + "  Sec " + secSym + "  Ind " + indSym, text_color=txtCol, bgcolor=rowBg, text_size=tblSz,
         tooltip="ETF selection mode: " + etfMode +
                 "\nSector: " + sectorName + "\nIndustry: " + industryName)
    table.cell(tbl, 2, 18, etfMode, text_color=txtCol, bgcolor=rowBg, text_size=tblSz)
 
    table.cell(tbl, 0, 19, "Data Check", text_color=txtCol, bgcolor=rowBg, text_size=tblSz)
    table.cell(tbl, 1, 19, "Bars: " + str.tostring(barsAvail) + " / " + str.tostring(barsNeeded) + " needed", text_color=txtCol, bgcolor=rowBg, text_size=tblSz)
    table.cell(tbl, 2, 19, histOk ? "OK" : "Short history", text_color=txtCol, bgcolor=histOk ? color.new(#2e7d32, 0) : color.new(#ef6c00, 0), text_size=tblSz)
 
    table.cell(tbl, 0, 20, "As of", text_color=txtCol, bgcolor=rowBg, text_size=tblSz)
    table.cell(tbl, 1, 20, str.format_time(time, "yyyy-MM-dd", syminfo.timezone), text_color=txtCol, bgcolor=rowBg, text_size=tblSz)
    table.cell(tbl, 2, 20, syminfo.tickerid, text_color=txtCol, bgcolor=rowBg, text_size=tblSz)
 
    table.cell(tbl, 0, 21, "Profile", text_color=txtCol, bgcolor=rowBg, text_size=tblSz)
    table.cell(tbl, 1, 21, profile, text_color=txtCol, bgcolor=profileBg, text_size=tblSz,
         tooltip="Rules (first match wins; Risk score high = low risk):" +
                 "\nValue for money: Val>=7, Fund>=5, Risk>=4" +
                 "\nQuality compounder: Fund>=7, Risk>=6" +
                 "\nGrowth story: Rev growth>=15%, Momentum>=6" +
                 "\nMomentum leader: Momentum>=8, Sector rel>=6" +
                 "\nTurnaround: Earn>=7, Momentum>=6, Fund<5" +
                 "\nDefensive: Risk>=8, Avg>=5" +
                 "\nCheap but weak: Val>=7 and (Fund<4 or Mom<4)" +
                 "\nEarnings beat, price lagging: Earn>=7, Mom<4" +
                 "\nSpeculative: Risk<=3" +
                 "\nWeak: Avg<4" +
                 "\nNeeds at least 3 of 5 components")
    table.cell(tbl, 2, 21, tone > 0 ? "Positive" : tone < 0 ? "Caution" : "Neutral", text_color=txtCol, bgcolor=profileBg, text_size=tblSz)
 
    table.cell(tbl, 0, 22, "Flags", text_color=txtCol, bgcolor=rowBg, text_size=tblSz)
    table.cell(tbl, 1, 22, flags, text_color=txtCol, bgcolor=rowBg, text_size=tblSz)
    table.cell(tbl, 2, 22, "", text_color=txtCol, bgcolor=rowBg)
 
// ─────────────── Visual markers on chart ───────────────
plotshape(scoreUpBig,   title="Score Up",   style=shape.triangleup,   location=location.belowbar, color=color.new(#2e7d32, 0), size=size.small, text="↑")
plotshape(scoreDownBig, title="Score Down", style=shape.triangledown, location=location.abovebar, color=color.new(#c62828, 0), size=size.small, text="↓")
 
plotshape(crossAbove8,  title="Cross > 8",  style=shape.circle,  location=location.belowbar, color=color.new(#2e7d32, 0), size=size.tiny, text="8+")
plotshape(crossBelow4,  title="Cross < 4",  style=shape.circle,  location=location.abovebar, color=color.new(#c62828, 0), size=size.tiny, text="4-")
plotshape(crossAbove4,  title="Cross > 4",  style=shape.diamond, location=location.belowbar, color=color.new(#ef6c00, 0), size=size.tiny)
plotshape(crossBelow8,  title="Cross < 8",  style=shape.diamond, location=location.abovebar, color=color.new(#ef6c00, 0), size=size.tiny)
 
if scoreUpBig or scoreDownBig
    label.new(bar_index, scoreUpBig ? low : high,
         text=str.tostring(avgScore, "0.0"),
         style=scoreUpBig ? label.style_label_up : label.style_label_down,
         color=scoreUpBig ? color.new(#2e7d32, 20) : color.new(#c62828, 20),
         textcolor=color.white, size=size.small)
 
// ─────────────── Data window plots (no effect on chart scale) ───────────────
plot(avgScore,    "Average Score",      display=display.data_window)
plot(earnScore,   "Earnings Score",     display=display.data_window)
plot(fundScore,   "Fundamental Score",  display=display.data_window)
plot(valScore,    "Valuation Score",    display=display.data_window)
plot(riskScore,   "Risk Score",         display=display.data_window)
plot(momScore,    "Momentum Score",     display=display.data_window)
plot(relSecScore, "Sector Rel Score",   display=display.data_window)
plot(relIndScore, "Industry Rel Score", display=display.data_window)
 
// ─────────────── Alerts ───────────────
alertcondition(x8up,         "Average score crossed above 8", "Average score crossed above 8")
alertcondition(x4down,       "Average score crossed below 4", "Average score crossed below 4")
alertcondition(x4up,         "Average score crossed above 4", "Average score crossed above 4")
alertcondition(x8down,       "Average score crossed below 8", "Average score crossed below 8")
alertcondition(scoreUpBig,   "Average score jumped up",      "Average score rose by at least the marker threshold")
alertcondition(scoreDownBig, "Average score dropped",        "Average score fell by at least the marker threshold")

← 返回列表