DCF Valuation (FCFF) - Fair Value Table

PalgoX · study · 800 行 · 点赞 6 · 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/
// © polo2323 (original "Stocks Claude" valuation script) · DCF Claude v1: standalone, English, US/global edition of the WACC + DCF (FCFF) table, with formulas shown as text inside the table
//@version=6
indicator("DCF Valuation (FCFF) - Fair Value Table", shorttitle = "DCF Claude", overlay = true, precision = 2, dynamic_requests = true, max_bars_back = 1500)
 
// ═══════════════════════════════════════════════════════════════════════════
//  1) CONSTANTS + INPUTS
// ═══════════════════════════════════════════════════════════════════════════
const string SIZE_LARGE  = "Large"
const string SIZE_NORMAL = "Normal"
const string SIZE_SMALL  = "Small"
const string SIZE_TINY   = "Tiny"
 
const string TOP_LEFT      = "Top Left"
const string TOP_CENTER    = "Top Center"
const string TOP_RIGHT     = "Top Right"
const string MIDDLE_LEFT   = "Middle Left"
const string MIDDLE_CENTER = "Middle Center"
const string MIDDLE_RIGHT  = "Middle Right"
const string BOTTOM_LEFT   = "Bottom Left"
const string BOTTOM_CENTER = "Bottom Center"
const string BOTTOM_RIGHT  = "Bottom Right"
 
const string G_MAC = "1 · MACRO (AUTO FROM TRADINGVIEW)"
const string G_WACC = "2 · WACC (nominal, in the symbol currency)"
const string G_DCF = "3 · DCF"
const string G_EXT = "4 · ADDITIONAL MODEL INPUTS (ROE / ROIC / payout / Lynch / Graham)"
const string G_TBL = "5 · TABLE (show / position / size)"
const string G_COL = "6 · APPEARANCE"
 
// ── 1 · Macro ──
macro_src  = input.string('Auto (by symbol country)', 'Symbol set for inflation, GDP, risk-free rate and benchmark', options = ['Auto (by symbol country)', 'Custom symbols'], group = G_MAC, tooltip = "Auto: the script builds the TradingView symbols from the two-letter country code of the chart symbol (for example US gives ECONOMICS:USIRYY, ECONOMICS:USGDPYY, TVC:US10Y and the S&P 500). If a symbol does not exist, the fallback values below are used and a warning is shown. Custom: use the symbols typed in the boxes below.")
auto_macro = input.bool(true, 'Fetch inflation and GDP growth from TradingView economic data', group = G_MAC)
infl_sym   = input.symbol('ECONOMICS:USIRYY', 'Custom: inflation (YoY %) symbol', group = G_MAC)
gdp_sym    = input.symbol('ECONOMICS:USGDPYY', 'Custom: GDP growth (YoY %) symbol', group = G_MAC)
infl_man   = input.float(3.0, 'Fallback inflation % (if data is missing)', step = 0.5, group = G_MAC)
gdp_man    = input.float(2.0, 'Fallback GDP growth % (if data is missing)', step = 0.5, group = G_MAC)
infl_lt    = input.float(2.0, 'Long-term inflation target % (UPDATE WITH YOUR OWN VIEW)', step = 0.5, group = G_MAC)
infl_fade  = input.float(50.0, 'Terminal inflation fade % (0 = today inflation, 100 = long-term target)', minval = 0, maxval = 100, step = 10, group = G_MAC)
 
// ── 2 · WACC ──  (entered as percent)
rf_mode   = input.string('Auto (bond yield)', 'Risk-free rate source', options = ['Auto (bond yield)', 'Manual'], group = G_WACC)
rf_sym    = input.symbol('TVC:US10Y', 'Custom: risk-free symbol (10Y government bond)', group = G_WACC)
rf_manual = input.float(4.0, 'Manual / fallback risk-free rate % (UPDATE WITH CURRENT VALUE)', minval = 0, step = 0.25, group = G_WACC)
erp       = input.float(4.5, 'Equity risk premium (ERP) % (no TradingView source; UPDATE WITH CURRENT VALUE)', minval = 0, step = 0.25, group = G_WACC)
beta_mode = input.string('Calculate (vs benchmark)', 'Beta', options = ['Calculate (vs benchmark)', 'Manual'], group = G_WACC)
idx_sym   = input.symbol('SP:SPX', 'Custom / fallback benchmark index for beta', group = G_WACC, tooltip = "Examples: SP:SPX, NASDAQ:NDX, TVC:UKX, TVC:DAX, TVC:CAC40, TVC:NI225, TVC:HSI, ASX:XJO, NSE:NIFTY. In Auto mode this symbol is used when the country index cannot be loaded.")
beta_len  = input.int(300, 'Beta window (bars of the chart timeframe)', minval = 30, maxval = 1000, group = G_WACC)
beta_adj  = input.bool(true, 'Blume adjustment (0.67 × raw + 0.33)', group = G_WACC)
beta_man  = input.float(1.0, 'Manual beta', step = 0.05, group = G_WACC)
tax_mode  = input.string('Effective (TTM, auto)', 'Tax rate', options = ['Statutory (fixed)', 'Effective (TTM, auto)'], group = G_WACC)
tax_stat  = input.float(21.0, 'Statutory corporate tax % (fallback; US federal = 21)', minval = 0, maxval = 50, step = 1, group = G_WACC)
rd_mode   = input.string('Auto (interest / debt)', 'Cost of debt (pre-tax)', options = ['Rf + spread', 'Auto (interest / debt)'], group = G_WACC)
rd_spread = input.float(1.5, 'Credit spread % over Rf (fallback)', minval = 0, step = 0.25, group = G_WACC)
 
// ── 3 · DCF ──
dcf_years   = input.int(5, 'Explicit forecast period (years)', minval = 3, maxval = 10, group = G_DCF)
g_mode      = input.string('Auto (conservative: min)', 'Year-1 growth source', options = ['Auto (conservative: min)', 'Historical FCF CAGR', 'Analyst consensus (EPS)', 'Manual'], group = G_DCF)
g_manual    = input.float(10.0, 'Manual year-1 growth % (nominal)', step = 1, group = G_DCF)
g_min       = input.float(-10.0, 'Growth floor %', group = G_DCF)
g_max       = input.float(30.0, 'Growth cap %', group = G_DCF)
hist_win    = input.string('5 years', 'History window (FCF CAGR, EPS CAGR, average P/E and P/B)', options = ['3 years', '5 years'], group = G_DCF, tooltip = "The CAGRs use the quarterly TTM history that the script records from the balance-sheet updates it sees on the chart. At most this many calendar years are used. The average P/E and P/B are also taken over this window.")
gt_mode     = input.string('Auto (inflation + GDP)', 'Terminal growth source', options = ['Auto (inflation + GDP)', 'Manual'], group = G_DCF)
g_term      = input.float(2.5, 'Manual terminal growth % (nominal)', step = 0.25, group = G_DCF)
gt_cap      = input.float(3.5, 'Terminal growth cap % (in addition to the Rf and WACC limits)', minval = 0, step = 0.25, group = G_DCF, tooltip = "Terminal growth is always limited to: this cap, Rf minus 1 point, and WACC minus 1 point.")
fcf_base    = input.string('TTM', 'Base cash flow', options = ['TTM', '3-year average'], group = G_DCF, tooltip = "TTM: trailing-twelve-month free cash flow. 3-year average: mean of the quarterly TTM free-cash-flow records of the last 3 calendar years.")
fcf_has_int = input.bool(true, 'FCF already includes interest paid (add after-tax interest back to get FCFF)', group = G_DCF)
fv_th       = input.float(15.0, 'Undervalued / overvalued threshold %', minval = 1, group = G_DCF)
stale_days  = input.int(110, 'Stale balance-sheet warning (days)', minval = 30, maxval = 400, group = G_DCF)
 
// ── 4 · Additional model inputs ──
val_src     = input.string('Own average (symbol)', 'Multiples source (average P/E, P/B, growth)', options = ['Own average (symbol)', 'Fixed (boxes below)'], group = G_EXT, tooltip = "Own average: the symbol own average P/E and P/B over the history window feed the Graham base and defensive P/E. Fixed: the boxes below are used.")
gx_mode     = input.string('Auto', 'Growth (g) source for the Lynch P/E', options = ['Auto', 'Manual'], group = G_EXT, tooltip = "Auto: EPS CAGR over the history window (needs at least 2 years of recorded reports), else analyst FY EPS estimate, else last-12-month EPS growth.")
gx_man      = input.float(10.0, 'Manual g %', step = 0.5, group = G_EXT)
gx_cap      = input.float(25.0, 'g cap % (safety limit, not part of the formulas)', minval = 1, step = 1, group = G_EXT)
gx_real     = input.string('Nominal (original)', 'Growth measure for the Lynch P/E', options = ['Nominal (original)', 'Real (inflation-adjusted)'], group = G_EXT, tooltip = "Graham and Lynch formulas were calibrated on low-inflation US data. In high-inflation markets choose Real: g_real = (1 + g) / (1 + inflation) - 1.")
gr_pe0      = input.float(8.5, 'Graham: no-growth P/E (original 8.5)', minval = 1, step = 0.5, group = G_EXT)
gr_gmul     = input.float(2.0, 'Graham: growth multiplier (original 2, i.e. 2g)', minval = 0, step = 0.5, group = G_EXT)
gr_def_pe   = input.float(15.0, 'Graham defensive P/E (original 15; used when multiples are Fixed)', minval = 1, step = 0.5, group = G_EXT)
lynch_peg   = input.float(1.0, 'Lynch: target PEG (1 = fair, 0.5 = very cheap)', minval = 0.1, step = 0.1, group = G_EXT)
roe_term_sp = input.float(0.0, 'Terminal ROE/ROIC minus cost of capital (pts)', step = 0.5, group = G_EXT)
payout_mode = input.string('Auto (dividend / EPS)', 'Dividend payout ratio', options = ['Auto (dividend / EPS)', 'Manual'], group = G_EXT)
payout_man  = input.float(0.0, 'Manual payout ratio %', minval = 0, maxval = 100, group = G_EXT)
roe_cap     = input.float(80.0, 'ROE / ROIC cap % (in the models)', minval = 10, maxval = 300, group = G_EXT)
norm_n      = input.int(20, 'Normalization: median of the last N quarters', minval = 4, maxval = 40, group = G_EXT)
 
// ── 4 · Table ──
sizeInput = input.string(SIZE_SMALL, "Table size", options = [SIZE_LARGE, SIZE_NORMAL, SIZE_SMALL, SIZE_TINY], group = G_TBL)
show_frm  = input.bool(true, 'Show formulas as text inside the tables', group = G_TBL, tooltip = "Turn this off (or use a smaller table size) if a table is taller than your chart pane.")
show_ta   = input.bool(true, 'Table 1 · WACC + DCF', group = G_TBL)
loc_ta    = input.string(BOTTOM_LEFT, "Table 1 position", options = [TOP_LEFT, TOP_CENTER, TOP_RIGHT, MIDDLE_LEFT, MIDDLE_CENTER, MIDDLE_RIGHT, BOTTOM_LEFT, BOTTOM_CENTER, BOTTOM_RIGHT], group = G_TBL)
ofs_xa    = input.float(0.0, 'Table 1 · horizontal offset % (+ right, - left)', minval = -60, maxval = 60, step = 0.1, group = G_TBL, tooltip = "Offsets are a percentage of the chart size. A table anchored to a left corner cannot move left, one anchored to a top corner cannot move up.")
ofs_ya    = input.float(0.0, 'Table 1 · vertical offset % (+ down, - up)', minval = -60, maxval = 60, step = 0.1, group = G_TBL)
show_tb   = input.bool(true, 'Table 2 · additional inputs, sensitivity, data freshness, warnings', group = G_TBL)
loc_tb    = input.string(BOTTOM_RIGHT, "Table 2 position", options = [TOP_LEFT, TOP_CENTER, TOP_RIGHT, MIDDLE_LEFT, MIDDLE_CENTER, MIDDLE_RIGHT, BOTTOM_LEFT, BOTTOM_CENTER, BOTTOM_RIGHT], group = G_TBL)
ofs_xb    = input.float(0.0, 'Table 2 · horizontal offset % (+ right, - left)', minval = -60, maxval = 60, step = 0.1, group = G_TBL)
ofs_yb    = input.float(0.0, 'Table 2 · vertical offset % (+ down, - up)', minval = -60, maxval = 60, step = 0.1, group = G_TBL)
 
// ── 5 · Appearance ──
theme_mode = input.string('Auto', 'Table theme', options = ['Auto', 'Dark', 'Light'], group = G_COL, tooltip = 'Auto: picks dark or light from the chart background.')
accent_in  = input.color(#2962FF, 'Accent color (title bar)', group = G_COL)
show_line  = input.bool(true, 'Draw DCF fair-value line and label on the chart', group = G_COL)
 
 
// ═══════════════════════════════════════════════════════════════════════════
//  2) PALETTE + HELPERS
// ═══════════════════════════════════════════════════════════════════════════
string currency = syminfo.currency
 
float bgLum  = 0.299 * color.r(chart.bg_color) + 0.587 * color.g(chart.bg_color) + 0.114 * color.b(chart.bg_color)
bool  isDark = theme_mode == "Auto" ? (na(bgLum) ? true : bgLum < 128) : theme_mode == "Dark"
 
color cAccent = accent_in
color cPanel  = isDark ? #1E222D : #FFFFFF
color cZebra  = isDark ? #262B3A : #F3F5F9
color cSec    = isDark ? #2F3547 : #E3E8F0
color cSecTx  = isDark ? #8AB4FF : #1D4ED8
color cText   = isDark ? #E0E3EB : #1F2937
color cMuted  = isDark ? #9AA0AE : #5B6472
color cPosBg  = isDark ? #123B33 : #D9F5E5
color cPosTx  = isDark ? #3DDC97 : #0B6B3A
color cNegBg  = isDark ? #4A1C24 : #FDE2E4
color cNegTx  = isDark ? #FF7A88 : #B42318
color cWarnBg = isDark ? #4A3A12 : #FFF1CC
color cWarnTx = isDark ? #FFC857 : #8A5A00
color cInfoBg = isDark ? #14324F : #DCEBFF
color cInfoTx = isDark ? #6FB1FF : #1D4ED8
 
getSize(simple string userSize) =>
    switch userSize
        SIZE_LARGE  => size.large
        SIZE_NORMAL => size.normal
        SIZE_SMALL  => size.small
        SIZE_TINY   => size.tiny
        => size.small
 
getLoc(simple string userLoc) =>
    switch userLoc
        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_center
 
// status colors: 0 neutral · 1 positive · 2 negative · 3 warning · 4 info
f_stBg(int st) =>
    switch st
        1 => cPosBg
        2 => cNegBg
        3 => cWarnBg
        4 => cInfoBg
        => cPanel
 
f_stTx(int st) =>
    switch st
        1 => cPosTx
        2 => cNegTx
        3 => cWarnTx
        4 => cInfoTx
        => cText
 
f_stSolid(int st) =>
    switch st
        1 => #26A69A
        2 => #EF5350
        3 => #FFB74D
        4 => #42A5F5
        => color.silver
 
f_zb(int r) => r % 2 == 0 ? cPanel : cZebra
f_bgv(int st, int r) => st == 0 ? f_zb(r) : f_stBg(st)
f_txv(int st) => st == 0 ? cText : f_stTx(st)
 
// value below price = 2 (negative), above = 1 (positive)
f_st(float v, float px) => (na(v) or na(px)) ? 0 : (v < px ? 2 : 1)
 
f_n(float x) => na(x) ? "–" : str.tostring(x, '#.##')
 
f_big(float v) =>
    string r = "–"
    if not na(v)
        float a = math.abs(v)
        if a >= 1e12
            r := str.tostring(v / 1e12, '0.00') + " T"
        else if a >= 1e9
            r := str.tostring(v / 1e9, '0.00') + " B"
        else if a >= 1e6
            r := str.tostring(v / 1e6, '0.00') + " M"
        else if a >= 1e3
            r := str.tostring(v / 1e3, '0.00') + " K"
        else
            r := str.tostring(v, '0.00')
    r
 
f_val(float v) => na(v) ? "–" : str.tostring(v, '#.##') + " " + currency
 
f_delta(float v, float px) =>
    string s = "–"
    if not na(v) and not na(px) and px != 0
        float d = (v / px - 1) * 100
        s := (d >= 0 ? "▲ +" : "▼ ") + str.tostring(d, '#.##') + " %"
    s
 
f_fin(simple string id, simple string per) =>
    request.financial(syminfo.tickerid, id, per, ignore_invalid_symbol = true)
 
// value recorded "back" quarters ago (0 = latest record)
f_qa(array<float> a, int back) =>
    int n = array.size(a)
    (n - 1 - back) >= 0 ? array.get(a, n - 1 - back) : na
 
// median of the last k quarters of a recorded series (calendar window, na skipped)
f_medLast(array<float> a, array<float> tt, int k) =>
    float r = na
    int n = array.size(a)
    if n > 0 and array.size(tt) == n
        float cutm = array.get(tt, n - 1) - (k - 1) * 91.3125 * 86400000 - 45 * 86400000
        array<float> tmp = array.new_float(0)
        for i = 0 to n - 1
            float v = array.get(a, i)
            if not na(v) and array.get(tt, i) >= cutm
                array.push(tmp, v)
        if array.size(tmp) > 0
            r := array.median(tmp)
    r
 
// ── Table helpers (content starts one cell inside: the outer ring is used for offsets) ──
f_tnew(simple string loc, int cols, int rows) =>
    table.new(getLoc(loc), cols + 2, rows + 2, bgcolor = color.new(color.black, 100), frame_width = 0, border_width = 0)
 
f_pad(table t, int cols, int rows, string loc, float xo, float yo) =>
    bool aL = str.contains(loc, "Left")
    bool aR = str.contains(loc, "Right")
    bool aT = str.contains(loc, "Top")
    bool aB = str.contains(loc, "Bottom")
    float xl = aL ? math.max(xo, 0.0) : aR ? 0.0 : math.max(xo * 2, 0.0)
    float xr = aL ? 0.0 : aR ? math.max(-xo, 0.0) : math.max(-xo * 2, 0.0)
    float yt = aT ? math.max(yo, 0.0) : aB ? 0.0 : math.max(yo * 2, 0.0)
    float yb = aT ? 0.0 : aB ? math.max(-yo, 0.0) : math.max(-yo * 2, 0.0)
    color tr = color.new(color.black, 100)
    for r = 0 to rows + 1
        table.cell(t, 0, r, "", width = xl, text_size = size.tiny, bgcolor = tr)
        table.cell(t, cols + 1, r, "", width = xr, text_size = size.tiny, bgcolor = tr)
    for c = 1 to cols
        table.cell(t, c, 0, "", height = yt, text_size = size.tiny, bgcolor = tr)
        table.cell(t, c, rows + 1, "", height = yb, text_size = size.tiny, bgcolor = tr)
 
f_c(table t, int c, int r, string txt, color bg, color tc, string ha = text.align_center, bool bold = false) =>
    table.cell(t, c + 1, r + 1, " " + txt + " ", bgcolor = bg, text_color = tc, text_halign = ha, text_valign = text.align_center, text_size = getSize(sizeInput), text_formatting = bold ? text.format_bold : text.format_none)
 
f_m(table t, int c1, int r1, int c2, int r2) =>
    table.merge_cells(t, c1 + 1, r1 + 1, c2 + 1, r2 + 1)
 
f_title(table t, int cols, string txt) =>
    f_m(t, 0, 0, cols - 1, 0)
    f_c(t, 0, 0, txt, cAccent, color.white, text.align_center, true)
 
f_sec(table t, int cols, int r, string txt) =>
    f_m(t, 0, r, cols - 1, r)
    f_c(t, 0, r, "▌ " + txt, cSec, cSecTx, text.align_left, true)
 
f_head4(table t, int r, string a, string b, string c, string d) =>
    f_c(t, 0, r, a, cSec, cMuted, text.align_left, true)
    f_c(t, 1, r, b, cSec, cMuted, text.align_center, true)
    f_c(t, 2, r, c, cSec, cMuted, text.align_center, true)
    f_c(t, 3, r, d, cSec, cMuted, text.align_center, true)
 
// two label/value pairs per row
f_p4(table t, int r, string l1, string v1, string l2, string v2, int st1 = 0, int st2 = 0) =>
    f_c(t, 0, r, l1, f_zb(r), cMuted, text.align_left, false)
    f_c(t, 1, r, v1, f_bgv(st1, r), f_txv(st1), text.align_right, true)
    f_c(t, 2, r, l2, f_zb(r), cMuted, text.align_left, false)
    f_c(t, 3, r, v2, f_bgv(st2, r), f_txv(st2), text.align_right, true)
 
// warning row (merged)
f_wrow(table t, int cols, int r, string txt) =>
    f_m(t, 0, r, cols - 1, r)
    f_c(t, 0, r, "⚠ " + txt, cWarnBg, cWarnTx, text.align_left, false)
 
// formula rows (merged, muted text); returns the next free row
f_frms(table t, int cols, int r0, array<string> a) =>
    int rr = r0
    for i = 0 to array.size(a) - 1
        f_m(t, 0, rr, cols - 1, rr)
        f_c(t, 0, rr, "fx  " + array.get(a, i), f_zb(rr), cMuted, text.align_left, false)
        rr += 1
    rr
 
 
// ═══════════════════════════════════════════════════════════════════════════
//  3) FINANCIAL DATA  (balance sheet: latest quarter FQ · flows: TTM)
//     TradingView provides CAPITAL_EXPENDITURES and INTEREST_EXPENSE_ON_DEBT only for FH / FQ / FY,
//     so TTM capex is derived as FREE_CASH_FLOW(TTM) - CASH_F_OPERATING_ACTIVITIES(TTM) and interest uses the last fiscal year.
// ═══════════════════════════════════════════════════════════════════════════
eps      = f_fin("EARNINGS_PER_SHARE", "TTM")
eps_estY = f_fin("EARNINGS_ESTIMATE", "FY")
rev          = f_fin("TOTAL_REVENUE", "TTM")
op_income    = f_fin("OPER_INCOME", "TTM")
pretaxincome = f_fin("PRETAX_INCOME", "TTM")
interest_ttm = f_fin("INTEREST_EXPENSE_ON_DEBT", "FY")
tax_ttm      = f_fin("INCOME_TAX", "TTM")
cfo          = f_fin("CASH_F_OPERATING_ACTIVITIES", "TTM")
fcf_rep      = f_fin("FREE_CASH_FLOW", "TTM")
capex_fy     = f_fin("CAPITAL_EXPENDITURES", "FY")
capex        = (not na(fcf_rep) and not na(cfo)) ? fcf_rep - cfo : capex_fy
earn         = f_fin("NET_INCOME", "TTM")
 
equity     = f_fin("TOTAL_EQUITY", "FQ")
shares     = f_fin("TOTAL_SHARES_OUTSTANDING", "FQ")
net_debt   = f_fin("NET_DEBT", "FQ")
total_debt = f_fin("TOTAL_DEBT", "FQ")
cash_eq    = f_fin("CASH_N_EQUIVALENTS", "FQ")
 
float shs     = nz(shares, syminfo.shares_outstanding_total)
float nd      = not na(net_debt) ? net_debt : nz(total_debt, 0.0) - nz(cash_eq, 0.0)
float fcf_ttm = cfo - math.abs(nz(capex, 0.0))                       // FCF = operating cash flow - |capex|
 
// Dividends: sum of gross dividends over the last 365 calendar days
float div_raw = request.dividends(syminfo.tickerid, dividends.gross, gaps = barmerge.gaps_on, ignore_invalid_symbol = true)
var array<int>   dv_t = array.new_int(0)
var array<float> dv_v = array.new_float(0)
if not na(div_raw) and div_raw > 0
    array.push(dv_t, time)
    array.push(dv_v, div_raw)
float dps_ttm = 0.0
if array.size(dv_t) > 0
    for i = array.size(dv_t) - 1 to 0
        if array.get(dv_t, i) <= time - 365 * 86400000
            break
        dps_ttm += array.get(dv_v, i)
float div_yield = close > 0 ? dps_ttm / close * 100 : na
 
float bvps    = shs > 0 ? equity / shs : na
float roe_dec = equity > 0 ? earn / equity : na                      // on latest-quarter equity
float ebm_dec = rev > 0 ? op_income / rev : na                       // EBIT margin
 
 
// ═══════════════════════════════════════════════════════════════════════════
//  4) QUARTERLY HISTORY (one record each time a new balance sheet arrives)
//     Event: TTM revenue changed = new quarterly report
// ═══════════════════════════════════════════════════════════════════════════
bool newQ = not na(rev) and rev != nz(rev[1], -1.0)
var int rep_ts = na
var array<float> sq_t   = array.new_float(0)
var array<float> sq_fcf = array.new_float(0)
var array<float> sq_roe = array.new_float(0)
var array<float> sq_ebm = array.new_float(0)
var array<float> sq_eps = array.new_float(0)
 
if newQ
    rep_ts := time
    array.push(sq_t, float(time))
    array.push(sq_fcf, fcf_ttm)
    array.push(sq_roe, roe_dec)
    array.push(sq_ebm, ebm_dec)
    array.push(sq_eps, eps)
 
// value recorded "months" before the latest report (nearest record, +/- 45 days tolerance)
f_qAgo(array<float> a, float months) =>
    float r = na
    int n = array.size(sq_t)
    if n > 0 and array.size(a) == n
        float cut = array.get(sq_t, n - 1) - months * 30.4375 * 86400000.0 + 45 * 86400000.0
        for i = n - 1 to 0
            if array.get(sq_t, i) <= cut
                r := array.get(a, i)
                break
    r
 
// calendar years covered by the recorded history (first to last report, +/- 45 days tolerance), at most 5
f_spanY() =>
    int n = array.size(sq_t)
    n > 0 ? math.min(5, int(math.floor((array.get(sq_t, n - 1) - array.get(sq_t, 0) + 45 * 86400000) / (365.25 * 86400000)))) : 0
 
int win_y = hist_win == '3 years' ? 3 : 5
f_winY() => math.min(f_spanY(), win_y)
 
// bars inside the chosen window (3 / 5 calendar years) and the symbol own average P/E and P/B
bool val_sym = val_src == 'Own average (symbol)'
var array<int> bar_t = array.new_int(0)
var int bar_s2 = 0
array.push(bar_t, time)
while array.get(bar_t, bar_s2) < time - (win_y == 3 ? 1096 : 1826) * 86400000
    bar_s2 += 1
int lenW = math.max(1, math.min(bar_index - bar_s2 + 1, 1500))
f_mean(float x, int n) =>
    float s = math.sum(na(x) ? 0.0 : x, n)
    float c = math.sum(na(x) ? 0.0 : 1.0, n)
    c > 0 ? s / c : na
float pe_ratio = eps > 0 ? close / eps : na
float pb_ratio = bvps > 0 ? close / bvps : na
float pe_avg = f_mean(pe_ratio > 0 and pe_ratio <= 100 ? pe_ratio : na, lenW)
float pb_avg = f_mean(pb_ratio > 0 and pb_ratio <= 50 ? pb_ratio : na, lenW)
 
 
// ═══════════════════════════════════════════════════════════════════════════
//  5) MACRO (automatic) + WACC  (decimals, nominal)
// ═══════════════════════════════════════════════════════════════════════════
string cc = str.tostring(syminfo.country)
bool   mac_auto = macro_src == 'Auto (by symbol country)'
 
f_idx(string c) =>
    switch c
        "US" => "SP:SPX"
        "GB" => "TVC:UKX"
        "DE" => "TVC:DAX"
        "FR" => "TVC:CAC40"
        "JP" => "TVC:NI225"
        "HK" => "TVC:HSI"
        "AU" => "ASX:XJO"
        "IN" => "NSE:NIFTY"
        "CA" => "TSX:TSX"
        "TR" => "BIST:XU100"
        => idx_sym
 
string s_infl = mac_auto ? "ECONOMICS:" + cc + "IRYY" : infl_sym
string s_gdp  = mac_auto ? "ECONOMICS:" + cc + "GDPYY" : gdp_sym
string s_rf   = mac_auto ? "TVC:" + cc + "10Y" : rf_sym
string s_idx  = mac_auto ? f_idx(cc) : idx_sym
 
float rf_auto  = request.security(s_rf, "D", close / 100.0, ignore_invalid_symbol = true)
float cpi_auto = request.security(s_infl, "D", close / 100.0, ignore_invalid_symbol = true)
float gdp_auto = request.security(s_gdp, "D", close / 100.0, ignore_invalid_symbol = true)
float idx_a    = request.security(s_idx, timeframe.period, close, ignore_invalid_symbol = true)
float idx_b    = request.security(idx_sym, timeframe.period, close, ignore_invalid_symbol = true)
float idx_c    = na(idx_a) ? idx_b : idx_a
 
bool  rf_ok = rf_mode == 'Auto (bond yield)' and not na(rf_auto) and rf_auto > 0
float rf    = rf_ok ? rf_auto : rf_manual / 100
 
bool  cpi_ok = auto_macro and not na(cpi_auto)
bool  gdp_ok = auto_macro and not na(gdp_auto)
float infl   = cpi_ok ? cpi_auto : infl_man / 100
float gdp_g  = gdp_ok ? gdp_auto : gdp_man / 100
float infl_term = infl * (1 - infl_fade / 100) + (infl_lt / 100) * (infl_fade / 100)            // faded terminal inflation
float gT_auto   = (1 + math.max(0.0, math.min(0.04, gdp_g))) * (1 + infl_term) - 1               // (1 + real growth) × (1 + inflation) − 1
 
float ret  = close / close[1] - 1
float retb = idx_c / idx_c[1] - 1
float beta_raw  = ta.correlation(ret, retb, beta_len) * ta.stdev(ret, beta_len) / ta.stdev(retb, beta_len)
float beta_base = na(beta_raw) ? 1.0 : beta_raw
float beta_use  = beta_mode == 'Manual' ? beta_man : math.max(0.2, math.min(3.0, beta_adj ? 0.67 * beta_base + 0.33 : beta_base))
 
float Re = rf + beta_use * erp / 100                             // CAPM
 
float t_eff    = (not na(tax_ttm) and not na(pretaxincome) and pretaxincome > 0) ? math.max(0.10, math.min(0.35, math.abs(tax_ttm) / pretaxincome)) : na
float tax_rate = (tax_mode == 'Statutory (fixed)' or na(t_eff)) ? tax_stat / 100 : t_eff
 
float D_val    = nz(total_debt, 0.0)                              // financial debt (trade payables excluded)
float rd_stmt  = (D_val > 0 and not na(interest_ttm)) ? math.abs(interest_ttm) / D_val : na
bool  rd_ok    = not na(rd_stmt) and rd_stmt >= rf and rd_stmt <= rf + 0.20
float Rd_pre   = (rd_mode == 'Auto (interest / debt)' and rd_ok) ? rd_stmt : rf + rd_spread / 100
float Rd_post  = Rd_pre * (1 - tax_rate)                          // tax shield
 
float E_val = nz(close * shs, 0.0)
float V_val = E_val + D_val
float wE    = V_val > 0 ? E_val / V_val : 1.0
float wD    = 1 - wE
float WACC  = wE * Re + wD * Rd_post
 
float nopat   = op_income * (1 - tax_rate)
float ic0     = equity + nz(total_debt, 0.0) - nz(cash_eq, 0.0)         // invested capital
float roic_c  = ic0 > 0 ? nopat / ic0 * 100 : na
 
 
// ═══════════════════════════════════════════════════════════════════════════
//  6) DCF FUNCTION
//     Multi-stage: growth fades linearly from year-1 growth to terminal growth, Gordon terminal value.
//     Returns [value per share, enterprise value, PV of terminal value]
// ═══════════════════════════════════════════════════════════════════════════
f_dcf(float fcf0, float g1, float gT, float w, int n, float ndebt, float sh) =>
    float ps   = na
    float evv  = na
    float pvTv = na
    if not na(fcf0) and fcf0 > 0 and not na(w) and w > gT and sh > 0
        float f = fcf0
        float pvs = 0.0
        for t = 1 to n
            float gt = n > 1 ? g1 + (gT - g1) * (t - 1) / (n - 1) : g1
            f := f * (1 + gt)
            pvs += f / math.pow(1 + w, t)
        float tv = f * (1 + gT) / (w - gT)                       // Gordon growth
        pvTv := tv / math.pow(1 + w, n)
        evv  := pvs + pvTv
        ps   := (evv - ndebt) / sh                               // equity = EV - net debt
    [ps, evv, pvTv]
 
 
// ═══════════════════════════════════════════════════════════════════════════
//  7) LAST BAR: DCF
// ═══════════════════════════════════════════════════════════════════════════
var float dcf_ps   = na
var float dcf_ev   = na
var float dcf_pvtv = na
var float dcf_base = na
var float dcf_fcf0 = na
var float dcf_g1   = na
var float dcf_gT   = na
var float dcf_cagr = na
var float dcf_gan  = na
var string dcf_gsrc = ""
var string dcf_sig  = "–"
var int    dcf_sigst = 0
var bool   is_fin  = false
var float roe_use  = na
var float roic_use = na
var float payout_u = na
var float ebm_norm = na
var float peg_pe   = na
var float qg_nom_v = na
var float gr_pe0_v = na
var float gr_def_v = na
var array<float>  yr_f   = array.new_float(0)
var array<float>  yr_pv  = array.new_float(0)
var array<float>  sens   = array.new_float(9, na)
var array<string> warns  = array.new_string(0)
 
if barstate.islast
    is_fin := str.contains(str.lower(str.tostring(syminfo.sector)), "financ")
 
    // ── growth ──
    int   nq   = array.size(sq_fcf)
    int   yrs  = f_winY()
    float fcf_now = f_qa(sq_fcf, 0)
    float fcf_old = yrs >= 1 ? f_qAgo(sq_fcf, 12.0 * yrs) : na
    float cagr    = (yrs >= 2 and fcf_old > 0 and fcf_now > 0) ? math.pow(fcf_now / fcf_old, 1.0 / yrs) - 1 : na
    float g_an    = (eps_estY > 0 and eps > 0) ? eps_estY / eps - 1 : na
    float g_cagr_c = na(cagr) ? na : math.max(g_min / 100, math.min(g_max / 100, cagr))
    float g_an_c   = na(g_an) ? na : math.max(g_min / 100, math.min(g_max / 100, g_an))
    dcf_cagr := cagr
    dcf_gan  := g_an
 
    float g1 = g_manual / 100
    string gsrc = "manual"
    if g_mode == 'Historical FCF CAGR'
        if not na(g_cagr_c)
            g1 := g_cagr_c
            gsrc := "historical FCF CAGR"
    else if g_mode == 'Analyst consensus (EPS)'
        if not na(g_an_c)
            g1 := g_an_c
            gsrc := "analyst consensus"
    else if g_mode != 'Manual'
        if not na(g_cagr_c) and not na(g_an_c)
            g1 := math.min(g_cagr_c, g_an_c)
            gsrc := "min(CAGR, consensus)"
        else if not na(g_cagr_c)
            g1 := g_cagr_c
            gsrc := "historical FCF CAGR"
        else if not na(g_an_c)
            g1 := g_an_c
            gsrc := "analyst consensus"
    dcf_g1   := g1
    dcf_gsrc := gsrc
 
    // ── terminal growth: must stay below the cap, Rf and WACC ──
    float gT_in = gt_mode == 'Manual' ? g_term / 100 : gT_auto
    float gT    = math.min(math.min(gT_in, gt_cap / 100), math.min(rf - 0.01, WACC - 0.01))
    dcf_gT := gT
 
    // ── base cash flow ──
    float f3 = na
    if nq >= 1
        float cut3 = array.get(sq_t, nq - 1) - 11 * 91.3125 * 86400000 - 45 * 86400000     // last 3 calendar years
        float s3 = 0.0
        int   c3 = 0
        for k = 0 to nq - 1
            float fv = array.get(sq_fcf, k)
            if not na(fv) and array.get(sq_t, k) >= cut3
                s3 += fv
                c3 += 1
        f3 := c3 > 0 ? s3 / c3 : na
    float base_pref = fcf_base == 'TTM' ? fcf_ttm : f3
    float base_alt  = fcf_base == 'TTM' ? f3 : fcf_ttm
    float base0     = (not na(base_pref) and base_pref > 0) ? base_pref : ((not na(base_alt) and base_alt > 0) ? base_alt : na)
    float int_add   = (fcf_has_int and not na(interest_ttm)) ? math.abs(interest_ttm) * (1 - tax_rate) : 0.0
    float fcff0     = na(base0) ? na : base0 + int_add            // FCFF
    dcf_base := base0
    dcf_fcf0 := fcff0
 
    // ── DCF ──
    [ps0, ev0, pvtv0] = f_dcf(fcff0, g1, gT, WACC, dcf_years, nd, shs)
    dcf_ps   := ps0
    dcf_ev   := ev0
    dcf_pvtv := pvtv0
 
    float disc = (not na(ps0) and close > 0) ? ps0 / close - 1 : na
    dcf_sig   := na(disc) ? "–" : disc >= fv_th / 100 ? "UNDERVALUED (discount)" : disc <= -fv_th / 100 ? "OVERVALUED (premium)" : "FAIR"
    dcf_sigst := na(disc) ? 0 : disc >= fv_th / 100 ? 1 : disc <= -fv_th / 100 ? 2 : 3
 
    array.clear(yr_f)
    array.clear(yr_pv)
    if not na(fcff0) and fcff0 > 0 and WACC > gT
        float f = fcff0
        for t = 1 to dcf_years
            float gt = dcf_years > 1 ? g1 + (gT - g1) * (t - 1) / (dcf_years - 1) : g1
            f := f * (1 + gt)
            array.push(yr_f, f)
            array.push(yr_pv, f / math.pow(1 + WACC, t))
 
    // ── sensitivity: rows WACC -2 / 0 / +2 pts, columns terminal growth -2 / 0 / +2 pts ──
    for i = 0 to 2
        for j = 0 to 2
            float w_s = WACC + (i - 1) * 0.02
            float g_s = math.min(gT + (j - 1) * 0.02, w_s - 0.005)
            [p_s, e_s, t_s] = f_dcf(fcff0, g1, g_s, w_s, dcf_years, nd, shs)
            array.set(sens, i * 3 + j, p_s)
 
    // ── additional model inputs: normalized ROE / ROIC / margin / payout, growth, Lynch and Graham P/E ──
    float roe_norm = f_medLast(sq_roe, sq_t, norm_n)
    float roe_mix  = na(roe_norm) ? roe_dec : (na(roe_dec) ? roe_norm : 0.5 * roe_dec + 0.5 * roe_norm)
    float roe0     = na(roe_mix) ? na : math.max(-0.5, math.min(roe_cap / 100, roe_mix))
    float roic0    = na(roic_c) ? na : math.max(-0.5, math.min(roe_cap / 100, roic_c / 100))
    float pay      = payout_mode == 'Manual' ? payout_man / 100 : ((eps > 0 and not na(dps_ttm)) ? math.max(0.0, math.min(1.0, dps_ttm / eps)) : 0.0)
    roe_use  := roe0
    roic_use := roic0
    payout_u := pay
    ebm_norm := f_medLast(sq_ebm, sq_t, norm_n)
 
    float eps_p4  = f_qAgo(sq_eps, 12)
    float eps_o   = yrs >= 1 ? f_qAgo(sq_eps, 12.0 * yrs) : na
    float qg_cagr = (yrs >= 2 and eps_o > 0 and eps > 0) ? math.pow(eps / eps_o, 1.0 / yrs) - 1 : na
    float qg_yoy  = (eps_p4 > 0 and eps > 0) ? eps / eps_p4 - 1 : na
    float qg_raw  = gx_mode == 'Manual' ? gx_man / 100 : (not na(qg_cagr) ? qg_cagr : (not na(g_an) ? g_an : qg_yoy))
    float qg_nom  = na(qg_raw) ? na : math.max(0.0, math.min(gx_cap / 100, qg_raw))
    float qg_rl   = na(qg_raw) ? na : math.max(0.0, math.min(gx_cap / 100, (1 + qg_raw) / (1 + infl) - 1))
    float qg_use  = gx_real != 'Nominal (original)' ? qg_rl : qg_nom
    qg_nom_v := qg_nom
    gr_pe0_v := (val_sym and pe_avg > 0 and not na(qg_nom)) ? math.max(4.0, pe_avg - gr_gmul * qg_nom * 100) : gr_pe0
    gr_def_v := (val_sym and pe_avg > 0) ? pe_avg : gr_def_pe
 
    float eps_c = (yrs >= 1 and eps_o > 0 and eps > 0) ? math.pow(eps / eps_o, 1.0 / yrs) - 1 : na
    float g_peg = not na(qg_use) ? qg_use : (not na(g_an) ? g_an : (not na(eps_c) ? eps_c : g1))
    peg_pe := math.max(0.0, (g_peg * 100 + nz(div_yield, 0.0)) / lynch_peg)
 
    // ── warnings ──
    array.clear(warns)
    if mac_auto and (na(rf_auto) or na(cpi_auto) or na(gdp_auto))
        array.push(warns, "Some symbols for country " + cc + " could not be loaded (" + (na(rf_auto) ? "10Y yield " : "") + (na(cpi_auto) ? "inflation " : "") + (na(gdp_auto) ? "GDP " : "") + ") - fallback values are used. Switch to Custom symbols if needed.")
    if rf_mode == 'Auto (bond yield)' and not rf_ok
        array.push(warns, "Bond yield unavailable → manual Rf used.")
    if auto_macro and (not cpi_ok or not gdp_ok)
        array.push(warns, "Inflation / GDP series unavailable → fallback values used.")
    if beta_mode != 'Manual' and na(beta_raw)
        array.push(warns, "Beta could not be computed (no benchmark data) → 1.0 used.")
    if not timeframe.isdaily
        array.push(warns, "Chart is not 1D: the beta window is counted in chart bars; a daily chart is recommended.")
    if na(fcff0)
        array.push(warns, "FCF ≤ 0 or missing → DCF cannot be computed.")
    if gT < gT_in - 0.0001
        array.push(warns, "Terminal growth capped at " + str.tostring(gT * 100, '#.##') + " % (cap / Rf / WACC limit).")
    if WACC <= gT
        array.push(warns, "WACC ≤ terminal growth → DCF invalid.")
    if is_fin
        array.push(warns, "Bank / insurer / financial company: FCF-based DCF is not suitable (debt is operating). Use residual-income or P/B models instead.")
    if na(shs) or shs <= 0
        array.push(warns, "Share count unavailable.")
    if not na(rep_ts) and (timenow - rep_ts) / 86400000.0 > stale_days
        array.push(warns, "Last balance-sheet update was " + str.tostring(math.floor((timenow - rep_ts) / 86400000.0)) + " days ago → a new report may be due.")
 
// Chart: fair-value line + label
var line  fv_line = na
var label fv_lbl  = na
if barstate.islast and show_line and not na(dcf_ps)
    line.delete(fv_line)
    label.delete(fv_lbl)
    fv_line := line.new(bar_index - 1, dcf_ps, bar_index, dcf_ps, extend = extend.both, color = color.new(color.yellow, 0), width = 2)
    fv_lbl  := label.new(bar_index, dcf_ps, "DCF fair value " + f_n(dcf_ps) + "\n" + dcf_sig, style = label.style_label_left, color = f_stSolid(dcf_sigst), textcolor = color.black, size = size.small)
 
 
// ═══════════════════════════════════════════════════════════════════════════
//  8) TABLE: WACC + DCF
// ═══════════════════════════════════════════════════════════════════════════
var table tA = na
var table tB = na
if show_ta and barstate.islast
    int CA = 4
    int nY = array.size(yr_f)
    int RA = 1 + (1 + 4 + (show_frm ? 3 : 0)) + (1 + 6 + (show_frm ? 6 : 0)) + (1 + 3 + 1 + nY + 4 + 1 + (show_frm ? 5 : 0)) + 1
    table.delete(tA)
    tA := f_tnew(loc_ta, CA, RA)
    f_pad(tA, CA, RA, loc_ta, ofs_xa, ofs_ya)
 
    int r = 0
    f_title(tA, CA, "DCF (FCFF) & WACC  ·  " + syminfo.ticker + "  ·  nominal " + currency)
    r += 1
    f_sec(tA, CA, r, "MACRO (TradingView)")
    r += 1
    f_p4(tA, r, "Country · symbol set", cc + " · " + (mac_auto ? "auto" : "custom"), "Benchmark index", na(idx_a) ? (na(idx_b) ? "–" : idx_sym) : s_idx)
    r += 1
    f_p4(tA, r, "Inflation (YoY)", f_n(infl * 100) + " %" + (cpi_ok ? " · TV" : " · fallback"), "GDP growth (YoY)", f_n(gdp_g * 100) + " %" + (gdp_ok ? " · TV" : " · fallback"))
    r += 1
    f_p4(tA, r, "Terminal inflation (faded)", f_n(infl_term * 100) + " %", "Terminal growth (auto)", f_n(gT_auto * 100) + " %")
    r += 1
    f_p4(tA, r, "Real rate (Rf vs inflation)", f_n(((1 + rf) / (1 + infl) - 1) * 100) + " %", "Terminal growth used", f_n(dcf_gT * 100) + " %")
    r += 1
    if show_frm
        r := f_frms(tA, CA, r, array.from("Terminal inflation = Inflation × (1 − fade) + Long-term target × fade", "Terminal g (auto) = (1 + clamp(GDP growth, 0 %, 4 %)) × (1 + terminal inflation) − 1", "Terminal g used = min(terminal g, cap, Rf − 1 pt, WACC − 1 pt)"))
    f_sec(tA, CA, r, "WACC")
    r += 1
    f_p4(tA, r, "Risk-free rate (Rf)", f_n(rf * 100) + " %" + (rf_ok ? " · TV" : " · manual"), "Equity risk premium (ERP)", f_n(erp) + " % · manual")
    r += 1
    f_p4(tA, r, "Beta (raw → used)", f_n(beta_raw) + " → " + f_n(beta_use), "Cost of equity (Re)", f_n(Re * 100) + " %")
    r += 1
    f_p4(tA, r, "Cost of debt (pre-tax)", f_n(Rd_pre * 100) + " %" + (rd_ok and rd_mode == 'Auto (interest / debt)' ? " · statement" : " · Rf+spread"), "Tax rate", f_n(tax_rate * 100) + " %" + (tax_mode == 'Statutory (fixed)' or na(t_eff) ? " · statutory" : " · effective"))
    r += 1
    f_p4(tA, r, "Cost of debt (after tax)", f_n(Rd_post * 100) + " %", "Market cap (E)", f_big(E_val))
    r += 1
    f_p4(tA, r, "Financial debt (D)", f_big(D_val), "E/V · D/V", f_n(wE * 100) + "% · " + f_n(wD * 100) + "%")
    r += 1
    f_p4(tA, r, "WACC", f_n(WACC * 100) + " %", "ROIC − WACC (pts)", f_n(nz(roic_c) - WACC * 100), 4, nz(roic_c) - WACC * 100 > 0 ? 1 : 2)
    r += 1
    if show_frm
        r := f_frms(tA, CA, r, array.from("Re = Rf + β × ERP    (β used = 0.67 × raw β + 0.33 when Blume adjustment is on)", "Raw β = corr(r, r_benchmark) × σ(r) / σ(r_benchmark), r = bar-to-bar return", "Rd = |Interest expense| / Total debt  (accepted if Rf ≤ Rd ≤ Rf + 20 pts), else Rf + spread", "t = |Income tax| / Pre-tax income, clamped to 10–35 %  (or the statutory rate)", "WACC = E/(E+D) × Re + D/(E+D) × Rd × (1 − t)    ·    E = price × shares,  D = total debt", "ROIC = EBIT × (1 − t) / (Equity + Debt − Cash)"))
    f_sec(tA, CA, r, "DCF · FCFF · fair value per share")
    r += 1
    f_p4(tA, r, "Base FCF (" + (fcf_base == 'TTM' ? "TTM" : "3-yr avg") + ")", f_big(dcf_base), "FCFF base" + (fcf_has_int ? " (interest added back)" : ""), f_big(dcf_fcf0))
    r += 1
    f_p4(tA, r, "Year-1 growth (" + dcf_gsrc + ")", f_n(dcf_g1 * 100) + " %", "Terminal growth", f_n(dcf_gT * 100) + " %")
    r += 1
    f_p4(tA, r, "FCF CAGR (quarterly TTM)", na(dcf_cagr) ? "–" : f_n(dcf_cagr * 100) + " %", "Analyst EPS growth", na(dcf_gan) ? "–" : f_n(dcf_gan * 100) + " %")
    r += 1
    f_head4(tA, r, "Year", "FCFF", "Discount factor", "Present value")
    r += 1
    for t = 0 to array.size(yr_f) - 1
        f_c(tA, 0, r, str.tostring(t + 1), f_zb(r), cMuted, text.align_left)
        f_c(tA, 1, r, f_big(array.get(yr_f, t)), f_zb(r), cText, text.align_right, true)
        f_c(tA, 2, r, str.tostring(1 / math.pow(1 + WACC, t + 1), '0.000'), f_zb(r), cText, text.align_center)
        f_c(tA, 3, r, f_big(array.get(yr_pv, t)), f_zb(r), cText, text.align_right, true)
        r += 1
    f_p4(tA, r, "Terminal value (PV)", f_big(dcf_pvtv), "TV share of EV", na(dcf_ev) ? "–" : f_n(dcf_pvtv / dcf_ev * 100) + " %")
    r += 1
    f_p4(tA, r, "Enterprise value (EV)", f_big(dcf_ev), "Net debt", f_big(nd))
    r += 1
    f_p4(tA, r, "Equity value", f_big(dcf_ev - nd), "Shares outstanding", f_big(shs))
    r += 1
    f_p4(tA, r, "DCF per share", f_val(dcf_ps), "vs. current price", f_delta(dcf_ps, close), f_st(dcf_ps, close), f_st(dcf_ps, close))
    r += 1
    f_p4(tA, r, "Signal (± " + str.tostring(fv_th, '#.#') + " %)", dcf_sig, "Current price", f_val(close), dcf_sigst, 0)
    r += 1
    if show_frm
        r := f_frms(tA, CA, r, array.from("FCF = Operating cash flow − |CapEx|    ·    FCFF_0 = FCF + |Interest expense| × (1 − t)", "CAGR = (FCF_now / FCF_N years ago)^(1/N) − 1    ·    g_1 (auto) = min(FCF CAGR, analyst EPS growth)", "g_t = g_1 + (g_T − g_1) × (t − 1) / (N − 1)    ·    FCFF_t = FCFF_(t−1) × (1 + g_t)", "PV_t = FCFF_t / (1 + WACC)^t    ·    TV = FCFF_N × (1 + g_T) / (WACC − g_T)", "EV = Σ PV_t + TV / (1 + WACC)^N    ·    Equity = EV − Net debt    ·    Value per share = Equity / Shares"))
 
if show_tb and barstate.islast
    int CB = 4
    int nW = array.size(warns)
    int RB = 1 + (1 + 5 + (show_frm ? 6 : 0)) + 3 + (1 + 1 + 3 + (show_frm ? 1 : 0)) + (nW > 0 ? 1 + math.min(nW, 10) : 0) + 1
    table.delete(tB)
    tB := f_tnew(loc_tb, CB, RB)
    f_pad(tB, CB, RB, loc_tb, ofs_xb, ofs_yb)
 
    int r = 0
    f_title(tB, CB, "DCF support  ·  " + syminfo.ticker + "  ·  inputs, sensitivity, freshness")
    r += 1
    f_sec(tB, CB, r, "ADDITIONAL MODEL INPUTS")
    r += 1
    f_p4(tB, r, "ROE (current + normalized)", f_n(roe_use * 100) + " %", "ROIC (used)", f_n(roic_use * 100) + " %")
    r += 1
    f_p4(tB, r, "Normalized EBIT margin (median)", na(ebm_norm) ? "–" : f_n(ebm_norm * 100) + " %", "Dividend payout ratio", f_n(payout_u * 100) + " %")
    r += 1
    f_p4(tB, r, "Lynch fair P/E (g + dividend yield)", f_n(peg_pe), "Terminal ROE/ROIC − cost", f_n(roe_term_sp) + " pts")
    r += 1
    f_p4(tB, r, "Symbol avg P/E · P/B (" + hist_win + ")", f_n(pe_avg) + " · " + f_n(pb_avg), "Source", val_sym ? "symbol own average" : "fixed")
    r += 1
    f_p4(tB, r, "Avg growth (EPS CAGR, nominal)", na(qg_nom_v) ? "–" : f_n(qg_nom_v * 100) + " %", "Graham base P/E · defensive P/E", f_n(gr_pe0_v) + " · " + f_n(gr_def_v))
    r += 1
    if show_frm
        r := f_frms(tB, CB, r, array.from("ROE used = clamp(0.5 × latest ROE + 0.5 × median ROE of last N quarters, −50 %, cap)    ·    ROE = Net income / Equity", "ROIC used = clamp(EBIT × (1 − t) / (Equity + Debt − Cash), −50 %, cap)    ·    EBIT margin = EBIT / Revenue (median of N quarters)", "Payout = Dividends per share (last 365 days) / EPS  (or manual)    ·    Dividend yield = DPS / Price", "Lynch fair P/E = (growth % + dividend yield %) / target PEG    ·    g = EPS CAGR → analyst FY EPS growth → last-12-month EPS growth", "Avg P/E, P/B = mean of daily P/E (0–100) and P/B (0–50) over the window    ·    Graham base P/E = max(4, avg P/E − multiplier × g %)", "Graham defensive P/E = symbol average P/E (or the fixed value)    ·    Real g = (1 + g) / (1 + inflation) − 1 when Real is selected"))
    f_sec(tB, CB, r, "DATA FRESHNESS (quarterly balance sheet)")
    r += 1
    f_p4(tB, r, "Last quarterly update", na(rep_ts) ? "–" : str.format_time(rep_ts, "yyyy-MM-dd"), "Age (days)", na(rep_ts) ? "–" : str.tostring(math.floor((timenow - rep_ts) / 86400000.0)), 0, na(rep_ts) ? 0 : (timenow - rep_ts) / 86400000.0 > stale_days ? 3 : 1)
    r += 1
    f_p4(tB, r, "Next report (estimate)", na(rep_ts) ? "–" : str.format_time(rep_ts + 91 * 86400000, "yyyy-MM-dd"), "Quarters recorded", str.tostring(array.size(sq_fcf)))
    r += 1
    f_sec(tB, CB, r, "SENSITIVITY · DCF per share (rows: WACC, columns: terminal growth)")
    r += 1
    f_head4(tB, r, "WACC \\ g", f_n((dcf_gT - 0.02) * 100) + " %", f_n(dcf_gT * 100) + " %", f_n((dcf_gT + 0.02) * 100) + " %")
    r += 1
    for i = 0 to 2
        f_c(tB, 0, r, f_n((WACC + (i - 1) * 0.02) * 100) + " %", cSec, cMuted, text.align_left, true)
        for j = 0 to 2
            float sp = array.get(sens, i * 3 + j)
            int   ss = f_st(sp, close)
            f_c(tB, 1 + j, r, (i == 1 and j == 1 ? "◆ " : "") + f_val(sp), f_bgv(ss, r), f_txv(ss), text.align_center, i == 1 and j == 1)
        r += 1
    if show_frm
        r := f_frms(tB, CB, r, array.from("Each cell re-runs the full DCF with that row's WACC and that column's terminal growth (g ≤ WACC − 0.5 pt)"))
    if array.size(warns) > 0
        f_sec(tB, CB, r, "WARNINGS")
        r += 1
        for k = 0 to math.min(array.size(warns), 10) - 1
            f_wrow(tB, CB, r, array.get(warns, k))
            r += 1
    f_m(tB, 0, r, CB - 1, r)
    f_c(tB, 0, r, "Educational tool, not investment advice. Output depends on TradingView financial data and your assumptions.", cPanel, cMuted, text.align_center, false)

← 返回列表