Financials Dashboard - Financials Margins

PalgoX · study · 907 行 · 点赞 12 · TradingView 原页

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

Pine Script

//@version=6
indicator("Financials Dashboard · Returns + Financials + Margins", shorttitle = "FIN DASH", overlay = false, max_boxes_count = 500, max_labels_count = 500, max_lines_count = 100, max_polylines_count = 100)
 
// ═══════════════════════════════════════════════════════════════════════════════
//  FINANCIALS DASHBOARD  –  separate pane below the chart (overlay = false), three panels side by side
//
//  LEFT   : RETURNS COMPARISON -> stock · S&P 500 · Nasdaq 100 · Gold (all changeable). All start at 0% N months ago and
//           the lines show cumulative % return up to today (is the stock beating the indices and gold?)
//  MIDDLE : FINANCIAL COLUMNS  -> VIEW 1: Q1|Q2|Q3|Q4, each group shows the last 3 years + TTM
//                                 VIEW 2: last 4 quarters, each with Revenue / Gross / Operating / Net + TTM
//           (+ ROE/10 and P/B lines)
//  RIGHT  : CASH & INVESTMENT panel, last N (max 8) quarters: COLUMNS = FCF (quarterly) and Net Working Capital (Current Assets - Current Liabilities, quarterly);
//           LINES = Capex/Net Income % (TTM), EPS growth % (TTM, year over year), FCF/Net Income % (TTM), Debt/Equity %, Net Debt/EBITDA % (TTM). Number of quarters is selectable (2-8). Large numbers are written with K / M / B / T.
//
//  Data: request.financial (FQ / TTM) + daily closes (request.security, 4 calls). TTM capex is not available directly, so it is computed from the sum of the last 4 quarters. Nothing is drawn on the price chart.
//  Panel widths are set in the "Layout" inputs; everything stretches automatically to the number of bars visible on screen.
//  Educational tool, not financial advice.
// ═════════════════════════════════════════════════════════════════
 
// ── Inputs ────────────────────────────────────────────────────────────────────
viewMode = input.string('Quarters × 3 Years + TTM', 'View', options = ['Quarters × 3 Years + TTM', 'Revenue → Profit Conversion (Last 4 Quarters + TTM)'], group = 'View')
metric   = input.string('Net Income', 'Metric (view 1 only)', options = ['Revenue', 'Gross Profit', 'Operating Income', 'Pre-tax Income', 'EBITDA', 'Net Income', 'Free Cash Flow', 'Gross Margin %', 'Operating Margin %', 'EBITDA Margin %', 'Net Margin % (Revenue→Net Income)', 'Net Income / Operating Income %'], group = 'View')
lagDays  = input.int(20, 'Reporting lag (days)', minval = -60, maxval = 90, group = 'View', tooltip = 'To find the quarter number, the script goes back this many days from the date the data appears on the chart and uses the last calendar quarter that ended before that date.\n\nMany companies publish results roughly 30-80 days after quarter end, so 20 is a reasonable default. Change it if the labels (year/quarter) look wrong. If the data appears on the quarter-END date, try -15.')
tzName   = input.string('America/New_York', 'Time zone', group = 'View', tooltip = 'Used for dates and month labels. Any IANA time zone name works, e.g. Europe/London, Asia/Tokyo, UTC.')
 
fitScreen = input.bool(true, 'Stretch to screen width (based on visible bars)', group = 'Style', tooltip = 'When on, column width is calculated automatically from the number of visible bars and the dashboard is aligned to the last visible bar on the right. If it does not update after scrolling or zooming, toggle the indicator off and on once, or open the settings and press OK.')
bw       = input.int(3, 'Column width (bars) – if stretching is off', minval = 2, maxval = 30, group = 'Style')
fillPct  = input.int(96, 'Stretch ratio (%)', minval = 50, maxval = 100, group = 'Style')
gapIn    = input.int(1, 'Gap between columns (bars)', minval = 0, maxval = 4, group = 'Style')
gapGrp   = input.int(3, 'Extra gap between groups (bars)', minval = 0, maxval = 10, group = 'Style')
lblSize  = input.string('Small', 'Label size', options = ['Tiny', 'Small', 'Normal'], group = 'Style')
showVals = input.bool(true, 'Show value above column', group = 'Style')
hlLast   = input.bool(true, 'Outline the latest reported quarter', group = 'Style')
 
cY1   = input.color(#64748b, 'Oldest year', inline = 'y', group = 'Colors')
cY2   = input.color(#3b82f6, 'Middle', inline = 'y', group = 'Colors')
cY3   = input.color(#8b5cf6, 'Newest', inline = 'y', group = 'Colors')
cTTM  = input.color(#f59e0b, 'TTM', inline = 'y2', group = 'Colors')
cNeg  = input.color(#ef4444, 'Negative', inline = 'y2', group = 'Colors')
cRev  = input.color(#3b82f6, 'Revenue', inline = 'c', group = 'Colors (Conversion view)')
cGp   = input.color(#14b8a6, 'Gross', inline = 'c', group = 'Colors (Conversion view)')
cOi   = input.color(#f59e0b, 'Operating', inline = 'c2', group = 'Colors (Conversion view)')
cNi   = input.color(#22c55e, 'Net', inline = 'c2', group = 'Colors (Conversion view)')
 
// Number of bars visible on screen and the right-most visible bar (must be evaluated on every bar)
int sinceL = ta.barssince(time < chart.left_visible_bar_time)
int sinceR = ta.barssince(time <= chart.right_visible_bar_time)
int visBars   = (na(sinceL) ? bar_index + 1 : sinceL) - nz(sinceR, 0)
int anchorIdx = bar_index - nz(sinceR, 0)
 
showRoe  = input.bool(true, 'ROE/10 line (polyline)', inline = 'l1', group = 'Lines (ROE/10 and P/B)')
cRoe     = input.color(#ec4899, '', inline = 'l1', group = 'Lines (ROE/10 and P/B)')
showPb   = input.bool(true, 'P/B line (polyline)', inline = 'l2', group = 'Lines (ROE/10 and P/B)')
cPb      = input.color(#22d3ee, '', inline = 'l2', group = 'Lines (ROE/10 and P/B)')
lineMode = input.string('Separate bands (readable)', 'Line scale', options = ['Separate bands (readable)', 'Shared scale'], group = 'Lines (ROE/10 and P/B)', tooltip = 'Separate bands: ROE/10 sits in the upper band and P/B in the lower band, each stretched over its own min-max range, so the shapes stay readable even when the numbers are far apart. Real values are written above/below the points.\nShared scale: both lines use the same scale (their levels relative to each other are preserved).\n\nROE = EPS (TTM) / Book value per share (BVPS, latest quarter) × 100;  P/B = close on that day / BVPS. The lines are normalized to the pane so they do not get mixed up with the column units.')
 
showTbl  = input.bool(true, 'Show right panel (Capex / EPS / FCF / Debt lines, FCF and working capital columns)', group = 'Right Panel')
cCx      = input.color(#f97316, 'Capex/Net income', inline = 'r1', group = 'Right Panel')
cEg      = input.color(#a78bfa, 'EPS growth', inline = 'r1', group = 'Right Panel')
cFp      = input.color(#22c55e, 'FCF/Net income', inline = 'r1', group = 'Right Panel')
cFc      = input.color(#14b8a6, 'FCF column', inline = 'r2', group = 'Right Panel')
cNw      = input.color(#3b82f6, 'Working cap. column', inline = 'r2', group = 'Right Panel')
cDe      = input.color(#eab308, 'Debt/Equity', inline = 'r3', group = 'Right Panel')
cNd      = input.color(#e879f9, 'Net debt/EBITDA', inline = 'r3', group = 'Right Panel')
qSel     = input.int(8, 'Number of quarters (max 8)', minval = 2, maxval = 8, group = 'Right Panel', tooltip = 'How many quarters the right panel shows. If there is less data, only the available quarters are shown.')
showPtLbl = input.bool(true, 'Show values on points and columns (same style as the middle panel)', group = 'Right Panel')
 
leftPct  = input.int(34, 'Left panel (returns chart) width %', minval = 15, maxval = 60, group = 'Layout', tooltip = 'Percentage of the number of visible bars. Adjust the middle panel and the right panel (the remaining %) accordingly. If the right panel does not fit, make the middle panel smaller.')
midPct   = input.int(38, 'Middle panel (financial columns) width %', minval = 20, maxval = 70, group = 'Layout', tooltip = 'The remaining percentage (100 - left - middle) goes to the right panel. If the left panel is off, the middle panel also uses that share.')
hPct     = input.int(100, 'Dashboard height (% of pane)', minval = 15, maxval = 100, step = 5, group = 'Layout', tooltip = 'Separate pane: keep 100. To use the dashboard INSIDE the main chart pane, move the indicator to the main pane with "No scale" (see description) and set e.g. 30-40 here: the dashboard then stays in the bottom part of the pane, no matter how you zoom, scroll or move the price scale. Also set the chart bottom margin (Settings > Scales and lines > Scale margins) to the same % so candles do not run under the dashboard.')
bgTr     = input.int(95, 'Panel background transparency (%)', minval = 0, maxval = 100, group = 'Layout', tooltip = 'Use a lower value (e.g. 10-30) when the dashboard sits on top of the price chart, so candles do not show through the panels.')
 
showPerf   = input.bool(true, 'Show returns chart (left panel)', group = 'Returns Chart')
perfMonths = input.int(12, 'Lookback (months)', minval = 3, maxval = 36, group = 'Returns Chart', tooltip = 'The close this many months ago is treated as 0%; the stock and the comparison assets are drawn as cumulative % return from the same starting point.')
symIdx     = input.symbol('SP:SPX', 'Comparison 1 (symbol)', group = 'Returns Chart', tooltip = 'Click the symbol box and pick any symbol you like: an index (NASDAQ:NDX), a currency pair (FX_IDC:EURUSD), a commodity (TVC:SILVER), crypto (BINANCE:BTCUSDT) etc. Price data comes from the daily close.')
nmIdx      = input.string('', 'Comparison 1 · display name (empty = automatic)', group = 'Returns Chart')
symFx      = input.symbol('NASDAQ:NDX', 'Comparison 2 (symbol)', group = 'Returns Chart')
nmFx       = input.string('', 'Comparison 2 · display name (empty = automatic)', group = 'Returns Chart')
symGold    = input.symbol('OANDA:XAUUSD', 'Comparison 3 (symbol)', group = 'Returns Chart')
nmGold     = input.string('', 'Comparison 3 · display name (empty = automatic)', group = 'Returns Chart')
cPS        = input.color(#10b981, 'Stock', inline = 'p1', group = 'Returns Chart')
cPB        = input.color(#3b82f6, 'Comp. 1', inline = 'p1', group = 'Returns Chart')
cPU        = input.color(#f97316, 'Comp. 2', inline = 'p2', group = 'Returns Chart')
cPG        = input.color(#eab308, 'Comp. 3', inline = 'p2', group = 'Returns Chart')
 
var lsz = lblSize == 'Tiny' ? size.tiny : lblSize == 'Normal' ? size.normal : size.small
 
// ── Financial data (every bar; 20 static requests) ─────────────────────────────────
float rev_q = request.financial(syminfo.tickerid, 'TOTAL_REVENUE',   'FQ',  ignore_invalid_symbol = true)
float gp_q  = request.financial(syminfo.tickerid, 'GROSS_PROFIT',    'FQ',  ignore_invalid_symbol = true)
float oi_q  = request.financial(syminfo.tickerid, 'OPER_INCOME',     'FQ',  ignore_invalid_symbol = true)
float pt_q  = request.financial(syminfo.tickerid, 'PRETAX_INCOME',   'FQ',  ignore_invalid_symbol = true)
float ni_q  = request.financial(syminfo.tickerid, 'NET_INCOME',      'FQ',  ignore_invalid_symbol = true)
float eb_q  = request.financial(syminfo.tickerid, 'EBITDA',          'FQ',  ignore_invalid_symbol = true)
float fc_q  = request.financial(syminfo.tickerid, 'FREE_CASH_FLOW',  'FQ',  ignore_invalid_symbol = true)
 
float rev_t = request.financial(syminfo.tickerid, 'TOTAL_REVENUE',   'TTM', ignore_invalid_symbol = true)
float gp_t  = request.financial(syminfo.tickerid, 'GROSS_PROFIT',    'TTM', ignore_invalid_symbol = true)
float oi_t  = request.financial(syminfo.tickerid, 'OPER_INCOME',     'TTM', ignore_invalid_symbol = true)
float pt_t  = request.financial(syminfo.tickerid, 'PRETAX_INCOME',   'TTM', ignore_invalid_symbol = true)
float ni_t  = request.financial(syminfo.tickerid, 'NET_INCOME',      'TTM', ignore_invalid_symbol = true)
float eb_t  = request.financial(syminfo.tickerid, 'EBITDA',          'TTM', ignore_invalid_symbol = true)
float fc_t  = request.financial(syminfo.tickerid, 'FREE_CASH_FLOW',  'TTM', ignore_invalid_symbol = true)
 
float eps_t = request.financial(syminfo.tickerid, 'EARNINGS_PER_SHARE',     'TTM', ignore_invalid_symbol = true)
float bv_q  = request.financial(syminfo.tickerid, 'BOOK_VALUE_PER_SHARE',    'FQ',  ignore_invalid_symbol = true)
float cx_q  = request.financial(syminfo.tickerid, 'CAPITAL_EXPENDITURES',  'FQ',  ignore_invalid_symbol = true)
float ca_q  = request.financial(syminfo.tickerid, 'TOTAL_CURRENT_ASSETS',   'FQ',  ignore_invalid_symbol = true)
float td_q  = request.financial(syminfo.tickerid, 'TOTAL_DEBT',   'FQ',  ignore_invalid_symbol = true)
float te_q  = request.financial(syminfo.tickerid, 'TOTAL_EQUITY',   'FQ',  ignore_invalid_symbol = true)
float nd_q  = request.financial(syminfo.tickerid, 'NET_DEBT',   'FQ',  ignore_invalid_symbol = true)
float cl_q  = request.financial(syminfo.tickerid, 'TOTAL_CURRENT_LIABILITIES', 'FQ', ignore_invalid_symbol = true)
 
// ── Comparison data: daily closes (stock · S&P 500 · Nasdaq 100 · gold). calc_bars_count limits the requested history (memory) ───────
float pxS = request.security(syminfo.tickerid, 'D', close, ignore_invalid_symbol = true, calc_bars_count = 1300)
float pxB = request.security(symIdx,  'D', close, ignore_invalid_symbol = true, calc_bars_count = 1300)
float pxU = request.security(symFx,   'D', close, ignore_invalid_symbol = true, calc_bars_count = 1300)
float pxG = request.security(symGold, 'D', close, ignore_invalid_symbol = true, calc_bars_count = 1300)
var array<int>   dT = array.new<int>()
var array<float> dS = array.new<float>()
var array<float> dB = array.new<float>()
var array<float> dU = array.new<float>()
var array<float> dG = array.new<float>()
// On the first bar of every new day the previous bar's values are stored (on daily and higher charts, every bar)
bool dayChg = timeframe.change('D')
if dayChg and showPerf and bar_index > 0
    dT.push(time[1])
    dS.push(pxS[1])
    dB.push(pxB[1])
    dU.push(pxU[1])
    dG.push(pxG[1])
    if dT.size() > 1300
        dT.shift()
        dS.shift()
        dB.shift()
        dU.shift()
        dG.shift()
var array<string> mEN = array.from('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')
 
// ── Helpers ────────────────────────────────────────────────────────────────
// True if the value changed versus the previous bar (= new financial report published)
f_chg(x) =>
    not na(x) and bar_index > 0 and (na(x[1]) or x != x[1])
 
// Timestamp -> quarter key (year * 4 + quarter - 1). Goes back lagDays and finds
// the last calendar quarter that ended before that date.
f_key(t) =>
    int lagged = t - lagDays * 86400000
    int y = year(lagged, tzName)
    int m = month(lagged, tzName)
    int qc = math.ceil(m / 3.0)
    int q = qc - 1
    int yy = y
    if q == 0
        q := 4
        yy := y - 1
    yy * 4 + (q - 1)
 
// Calculate the selected metric
f_met(m, r, g, o, p, n, e, f) =>
    float out = switch m
        'Revenue'                       => r
        'Gross Profit'                    => g
        'Operating Income'               => o
        'Pre-tax Income'            => p
        'EBITDA'              => e
        'Net Income'                     => n
        'Free Cash Flow'         => f
        'Gross Margin %'                 => r != 0 ? g / r * 100 : na
        'Operating Margin %'            => r != 0 ? o / r * 100 : na
        'EBITDA Margin %'               => r != 0 ? e / r * 100 : na
        'Net Margin % (Revenue→Net Income)'  => r != 0 ? n / r * 100 : na
        'Net Income / Operating Income %'   => o != 0 ? n / o * 100 : na
        => float(na)
    out
 
// ── Past quarters (filled when a new report is published) ───────────────────
var array<int>   pk = array.new<int>()
var array<float> aR = array.new<float>()
var array<float> aG = array.new<float>()
var array<float> aO = array.new<float>()
var array<float> aP = array.new<float>()
var array<float> aN = array.new<float>()
var array<float> aE = array.new<float>()
var array<float> aF = array.new<float>()
var array<float> aEps = array.new<float>()
var array<float> aBv  = array.new<float>()
var array<float> aPx  = array.new<float>()
var array<float> aCx  = array.new<float>()    // capex (quarterly)
var array<float> aNwc = array.new<float>()    // net working capital = current assets - current liabilities (quarterly)
var array<float> aNiT = array.new<float>()    // net income TTM
var array<float> aFcT = array.new<float>()    // FCF TTM
var array<float> aTd  = array.new<float>()    // total debt
var array<float> aTe  = array.new<float>()    // total equity
var array<float> aNd  = array.new<float>()    // net debt
var array<float> aEbT = array.new<float>()    // EBITDA TTM
 
// (each call on its own line so that `or` does not short-circuit the evaluation)
bool chg1 = f_chg(rev_q)
bool chg2 = f_chg(ni_q)
bool chg3 = f_chg(oi_q)
bool chg = chg1 or chg2 or chg3
if chg
    int k = f_key(time)
    bool older = pk.size() > 0 and k < pk.last()
    if not older
        bool same = pk.size() > 0 and k == pk.last()
        if same
            int li = pk.size() - 1
            aR.set(li, rev_q)
            aG.set(li, gp_q)
            aO.set(li, oi_q)
            aP.set(li, pt_q)
            aN.set(li, ni_q)
            aE.set(li, eb_q)
            aF.set(li, fc_q)
            aEps.set(li, eps_t)
            aBv.set(li, bv_q)
            aPx.set(li, close)
            aCx.set(li, cx_q)
            aNwc.set(li, ca_q - cl_q)
            aNiT.set(li, ni_t)
            aFcT.set(li, fc_t)
            aTd.set(li, td_q)
            aTe.set(li, te_q)
            aNd.set(li, nd_q)
            aEbT.set(li, eb_t)
        else
            pk.push(k)
            aR.push(rev_q)
            aG.push(gp_q)
            aO.push(oi_q)
            aP.push(pt_q)
            aN.push(ni_q)
            aE.push(eb_q)
            aF.push(fc_q)
            aEps.push(eps_t)
            aBv.push(bv_q)
            aPx.push(close)
            aCx.push(cx_q)
            aNwc.push(ca_q - cl_q)
            aNiT.push(ni_t)
            aFcT.push(fc_t)
            aTd.push(td_q)
            aTe.push(te_q)
            aNd.push(nd_q)
            aEbT.push(eb_t)
 
// Metric / ROE % / P/B for stored quarter idx (na if idx < 0)
f_entMet(m, idx) =>
    float out = na
    if idx >= 0 and idx < pk.size()
        out := f_met(m, aR.get(idx), aG.get(idx), aO.get(idx), aP.get(idx), aN.get(idx), aE.get(idx), aF.get(idx))
    out
 
f_entRoe(idx) =>
    float out = na
    if idx >= 0 and idx < pk.size()
        float b = aBv.get(idx)
        if b > 0
            out := aEps.get(idx) / b * 100
    out
 
f_entPb(idx) =>
    float out = na
    if idx >= 0 and idx < pk.size()
        float b = aBv.get(idx)
        if b > 0
            out := aPx.get(idx) / b
    out
 
// ── Drawing objects ────────────────────────────────────────────────────────────
var array<box>   bxs  = array.new<box>()
var array<label> lbs  = array.new<label>()
var array<polyline> pls = array.new<polyline>()
var array<line>  glines = array.new<line>()
var line         axis = line.new(na, na, na, na, color = chart.fg_color)
var table        tbl  = table.new(position.top_left, 1, 1, border_width = 0)
 
// Line drawer: vals (real values) are normalized to the [a,b] band using lo-hi
f_drawLine(array<float> vals, array<int> segs, array<int> xs, float lo, float hi, float a, float b, color col, bool above) =>
    int prevSeg = -999
    array<chart.point> pts = array.new<chart.point>()
    int cntV = vals.size()
    for i = 0 to cntV - 1
        float v = vals.get(i)
        int sg = segs.get(i)
        if sg != prevSeg
            if pts.size() >= 2
                pls.push(polyline.new(pts, curved = false, closed = false, xloc = xloc.bar_index, line_color = col, line_width = 2))
            pts := array.new<chart.point>()
            prevSeg := sg
        if not na(v)
            float y = hi == lo ? (a + b) / 2 : a + (v - lo) / (hi - lo) * (b - a)
            int x = xs.get(i)
            pts.push(chart.point.from_index(x, y))
            lbs.push(label.new(x, y, '', style = label.style_circle, color = col, size = size.tiny))
            lbs.push(label.new(x, y, str.tostring(v, '#.##'), style = above ? label.style_label_down : label.style_label_up, textcolor = col, color = color(na), size = lsz))
    if pts.size() >= 2
        pls.push(polyline.new(pts, curved = false, closed = false, xloc = xloc.bar_index, line_color = col, line_width = 2))
 
// Shorten large numbers with K / M / B / T (thousand, million, billion, trillion)
f_fmt(float v) =>
    string out = '–'
    if not na(v)
        float a = math.abs(v)
        string sg = v < 0 ? '-' : ''
        out := a >= 1e12 ? sg + str.tostring(a / 1e12, '#.##') + 'T' : a >= 1e9 ? sg + str.tostring(a / 1e9, '#.##') + 'B' : a >= 1e6 ? sg + str.tostring(a / 1e6, '#.##') + 'M' : a >= 1e3 ? sg + str.tostring(a / 1e3, '#.##') + 'K' : sg + str.tostring(a, '#.##')
    out
 
// Right panel: draws one percentage series (in its own band and scale) as a polyline.
// Numbers look like the middle panel: label size (lsz), chart text color, above the point. Left edge: series name + LAST value.
f_strip(array<float> vals, array<int> xs, float yBot, float yTop, color col, string cap, int xCap, bool ptl) =>
    float lo = na
    float hi = na
    int   n  = vals.size()
    for i = 0 to n - 1
        float v = vals.get(i)
        if not na(v)
            lo := na(lo) ? v : math.min(lo, v)
            hi := na(hi) ? v : math.max(hi, v)
    float lastV = vals.get(n - 1)
    float hS    = yTop - yBot
    lbs.push(label.new(xCap, yBot + hS * 0.68, cap, style = label.style_label_left, textcolor = col, color = color(na), size = lsz, text_formatting = text.format_bold))
    lbs.push(label.new(xCap, yBot + hS * 0.26, 'Last: ' + (na(lastV) ? '–' : str.tostring(lastV, '#.#') + '%'), style = label.style_label_left, textcolor = chart.fg_color, color = color(na), size = lsz, text_formatting = text.format_bold))
    if not na(lo)
        float bandH = hS * 0.50
        float y1    = yBot + hS * 0.06
        array<chart.point> pts = array.new<chart.point>()
        if lo < 0 and hi > 0
            float y0 = y1 + (0 - lo) / (hi - lo) * bandH
            glines.push(line.new(xs.get(0), y0, xs.get(n - 1), y0, color = color.new(chart.fg_color, 70), style = line.style_dashed, width = 1))
        for i = 0 to n - 1
            float v = vals.get(i)
            if na(v)
                if pts.size() >= 2
                    pls.push(polyline.new(pts, curved = false, closed = false, xloc = xloc.bar_index, line_color = col, line_width = 2))
                pts := array.new<chart.point>()
            else
                float y = hi == lo ? y1 + bandH / 2 : y1 + (v - lo) / (hi - lo) * bandH
                pts.push(chart.point.from_index(xs.get(i), y))
                lbs.push(label.new(xs.get(i), y, '●', style = label.style_none, textcolor = col, size = size.tiny))
                if ptl
                    lbs.push(label.new(xs.get(i), y, str.tostring(v, '#.#') + '%', style = label.style_label_down, textcolor = chart.fg_color, color = color(na), size = lsz))
        if pts.size() >= 2
            pls.push(polyline.new(pts, curved = false, closed = false, xloc = xloc.bar_index, line_color = col, line_width = 2))
    true
 
// Index of the stored quarter whose key is k (-1 if none)
f_idxKey(int k) =>
    int out = -1
    for i = 0 to pk.size() - 1
        if pk.get(i) == k
            out := i
    out
 
// Display name of a comparison symbol: the custom name if given, otherwise a readable name for well-known ones, otherwise the symbol itself
f_nm(string sym, string custom) =>
    array<string> pr = str.split(sym, ':')
    string t = str.upper(pr.get(pr.size() - 1))
    string o = custom != '' ? custom : t == 'SPX' ? 'S&P 500' : t == 'NDX' ? 'NASDAQ 100' : (t == 'GOLD' or t == 'XAUUSD') ? 'GOLD (XAU/USD)' : t
    o
 
// Returns chart: draws one series (matrix column) as a polyline and puts a colored dot at the end
f_polyS(matrix<float> pm, int col, array<int> xsA, float pLo, float pHi, float yb, float yt, color cl, int lw) =>
    array<chart.point> pts = array.new<chart.point>()
    int   xp  = -1
    int   lxv = na
    float lyv = na
    for r = 0 to pm.rows() - 1
        float p = pm.get(r, col)
        if not na(p)
            int   x = xsA.get(r)
            float y = yb + (p - pLo) / (pHi - pLo) * (yt - yb)
            if x == xp and pts.size() > 0
                pts.set(pts.size() - 1, chart.point.from_index(x, y))
            else
                pts.push(chart.point.from_index(x, y))
            xp  := x
            lxv := x
            lyv := y
    if pts.size() >= 2
        pls.push(polyline.new(pts, curved = false, closed = false, xloc = xloc.bar_index, line_color = cl, line_width = lw))
    if not na(lyv)
        lbs.push(label.new(lxv, lyv, '', style = label.style_circle, color = cl, size = size.tiny))
    true
 
// Left panel: cumulative return of four assets (start = 0%)
f_perf(int xL, int wL, float yLow, float yHigh) =>
    float H  = yHigh - yLow
    float yb = yLow + H * 0.12
    float yt = yHigh - H * 0.21
    color cGrid = color.new(chart.fg_color, 88)
    color cZero = color.new(chart.fg_color, 55)
    color cTxt  = color.new(chart.fg_color, 35)
    color cUp   = #22c55e
    color cDn   = #ef4444
 
    array<int>   tt = dT.copy()
    array<float> vS = dS.copy()
    array<float> vB = dB.copy()
    array<float> vU = dU.copy()
    array<float> vG = dG.copy()
    tt.push(time)
    vS.push(pxS)
    vB.push(pxB)
    vU.push(pxU)
    vG.push(pxG)
    int nT = tt.size()
    int t1 = tt.get(nT - 1)
    int tm = year(t1, tzName) * 12 + month(t1, tzName) - 1 - perfMonths
    int t0 = timestamp(tzName, int(math.floor(tm / 12.0)), tm % 12 + 1, dayofmonth(t1, tzName), 0, 0, 0)
    int i0 = 0
    for i = 0 to nT - 1
        if tt.get(i) >= t0
            i0 := i
            break
    int n = nT - i0
 
    lbs.push(label.new(xL + 1, yHigh - H * 0.045, str.tostring(perfMonths) + '-MONTH RETURN (%)', style = label.style_label_left, textcolor = chart.fg_color, color = color(na), size = size.small, text_formatting = text.format_bold))
    if n < 5
        lbs.push(label.new(xL + int(wL / 2), (yb + yt) / 2, 'Not enough price history (scroll the chart further back)', style = label.style_none, textcolor = cTxt, size = size.small))
    else
        int   tS     = tt.get(i0)
        float spanT  = math.max(t1 - tS, 1)
        matrix<float> pm = matrix.new<float>(n, 4, na)
        array<float>  last = array.new_float(4, na)
        float lo = 0.0
        float hi = 0.0
        for c = 0 to 3
            array<float> src = vS
            if c == 1
                src := vB
            else if c == 2
                src := vU
            else if c == 3
                src := vG
            float base = na
            for r = 0 to n - 1
                float v = src.get(i0 + r)
                if na(base) and not na(v) and v > 0
                    base := v
                if not na(base) and not na(v)
                    float p = (v / base - 1) * 100
                    pm.set(r, c, p)
                    lo := math.min(lo, p)
                    hi := math.max(hi, p)
                    last.set(c, p)
        float pad = math.max((hi - lo) * 0.08, 1.0)
        float pLo = lo - pad
        float pHi = hi + pad
        int   xP0 = xL + int(math.round(wL * 0.10))
        int   xP1 = xL + wL - 1 - int(math.round(wL * 0.04))
        float wP  = math.max(xP1 - xP0, 1)
 
        // horizontal grid: "nice" steps (1-2-2.5-5-10)
        float raw = (hi - lo) / 5.0
        if raw <= 0
            raw := 1.0
        float mag = math.pow(10, math.floor(math.log10(raw)))
        float nm  = raw / mag
        float stp = (nm <= 1 ? 1.0 : nm <= 2 ? 2.0 : nm <= 2.5 ? 2.5 : nm <= 5 ? 5.0 : 10.0) * mag
        float gv  = math.ceil(pLo / stp) * stp
        int   gi  = 0
        while gv <= pHi and gi < 14
            float gy = yb + (gv - pLo) / (pHi - pLo) * (yt - yb)
            bool  isZ = math.abs(gv) < stp * 0.001
            glines.push(line.new(xL + 1, gy, xL + wL - 2, gy, color = isZ ? cZero : cGrid, style = isZ ? line.style_dashed : line.style_solid, width = 1))
            lbs.push(label.new(xL + 1, gy, (gv > 0 ? '+' : '') + str.tostring(gv, '#.##') + '%', style = label.style_label_left, textcolor = cTxt, color = color(na), size = size.tiny))
            gv += stp
            gi += 1
 
        // month labels (bottom)
        int ym    = year(tS, tzName) * 12 + month(tS, tzName) - 1
        int stepM = perfMonths <= 14 ? 2 : perfMonths <= 24 ? 3 : 6
        for k = 1 to perfMonths + 1
            int mi = ym + k
            if mi % stepM == 0
                int tk = timestamp(tzName, int(math.floor(mi / 12.0)), mi % 12 + 1, 1, 0, 0, 0)
                if tk > tS and tk <= t1
                    int xk = xP0 + int(math.round((tk - tS) / spanT * wP))
                    string mt2 = mEN.get(mi % 12) + (mi % 12 == 0 ? "'" + str.tostring(int(math.floor(mi / 12.0)) % 100, '00') : '')
                    lbs.push(label.new(xk, yLow + H * 0.055, mt2, style = label.style_none, textcolor = cTxt, size = size.tiny))
 
        // lines (stock on top)
        array<int> xsA = array.new_int()
        for r = 0 to n - 1
            xsA.push(xP0 + int(math.round((tt.get(i0 + r) - tS) / spanT * wP)))
        f_polyS(pm, 1, xsA, pLo, pHi, yb, yt, cPB, 2)
        f_polyS(pm, 2, xsA, pLo, pHi, yb, yt, cPU, 2)
        f_polyS(pm, 3, xsA, pLo, pHi, yb, yt, cPG, 2)
        f_polyS(pm, 0, xsA, pLo, pHi, yb, yt, cPS, 3)
 
        // legend + last values (2 × 2)
        array<string> nmL = array.from(syminfo.ticker, f_nm(symIdx, nmIdx), f_nm(symFx, nmFx), f_nm(symGold, nmGold))
        array<color>  clL = array.from(cPS, cPB, cPU, cPG)
        for c = 0 to 3
            float lv = last.get(c)
            string tx = '● ' + nmL.get(c) + '  ' + (na(lv) ? '–' : (lv > 0 ? '+' : '') + str.tostring(lv, '#.#') + '%')
            lbs.push(label.new(xL + 1 + (c % 2) * int(wL / 2), yHigh - H * (c < 2 ? 0.105 : 0.150), tx, style = label.style_label_left, textcolor = clL.get(c), color = color(na), size = size.small, text_formatting = text.format_bold))
        float ls = last.get(0)
        float lb = last.get(1)
        if not na(ls) and not na(lb)
            float al = ls - lb
            lbs.push(label.new(xL + wL - 2, yHigh - H * 0.045, 'vs ' + nmL.get(1) + '  ' + (al > 0 ? '+' : '') + str.tostring(al, '#.#') + ' pts', style = label.style_label_right, textcolor = al >= 0 ? cUp : cDn, color = color(na), size = size.small, text_formatting = text.format_bold))
    true
 
if barstate.islast
    // Delete the previous drawings
    while bxs.size() > 0
        box.delete(bxs.pop())
    while lbs.size() > 0
        label.delete(lbs.pop())
    while pls.size() > 0
        polyline.delete(pls.pop())
    while glines.size() > 0
        line.delete(glines.pop())
    axis.set_xy1(na, na)
    axis.set_xy2(na, na)
    table.cell(tbl, 0, 0, '')
 
    int cnt = pk.size()
    bool hasData = cnt > 0 or not na(rev_t) or not na(ni_t)
    bool modeA = viewMode == 'Quarters × 3 Years + TTM'
    bool isPct = modeA and str.endswith(metric, '%')
 
    if not hasData
        table.cell(tbl, 0, 0, 'No financial data found for ' + syminfo.ticker + ' (is the symbol a stock? is there enough chart history?)', text_color = chart.fg_color, text_size = size.normal, text_halign = text.align_left)
    else
        // ── Prepare the data arrays ──
        array<float>  pv = array.new<float>()
        array<int>    pg = array.new<int>()
        array<string> pl = array.new<string>()
        array<color>  pc = array.new<color>()
        array<bool>   ph = array.new<bool>()
        array<string> gn = array.new<string>()
        array<color>  yc = array.from(cY1, cY2, cY3)
        array<float>  lr = array.new<float>()
        array<float>  lp = array.new<float>()
        array<int>    lseg = array.new<int>()
        float roeNow = bv_q > 0 ? eps_t / bv_q * 10 : na
        float pbNow  = bv_q > 0 ? close / bv_q : na
 
        if modeA
            for q = 1 to 4
                gn.push('Q' + str.tostring(q))
                array<int> ix = array.new<int>()
                if cnt > 0
                    for j = cnt - 1 to 0
                        if ix.size() < 3 and pk.get(j) % 4 == q - 1
                            ix.push(j)
                int have = ix.size()
                int pad = 3 - have
                for s = 0 to 2
                    pg.push(q - 1)
                    if s < pad
                        pv.push(na)
                        pl.push('–')
                        pc.push(color(na))
                        ph.push(false)
                        lr.push(na)
                        lp.push(na)
                        lseg.push(q - 1)
                    else
                        int e = ix.get(have - 1 - (s - pad))
                        float v = f_met(metric, aR.get(e), aG.get(e), aO.get(e), aP.get(e), aN.get(e), aE.get(e), aF.get(e))
                        int yy = int(math.floor(pk.get(e) / 4.0))
                        pv.push(v)
                        pl.push("'" + str.tostring(yy % 100, '00'))
                        pc.push(v < 0 ? color.new(cNeg, s == 0 ? 65 : s == 1 ? 35 : 0) : yc.get(s))
                        ph.push(hlLast and e == cnt - 1)
                        float roeA = f_entRoe(e)
                        lr.push(na(roeA) ? na : roeA / 10)
                        lp.push(f_entPb(e))
                        lseg.push(q - 1)
            // TTM group
            float vt = f_met(metric, rev_t, gp_t, oi_t, pt_t, ni_t, eb_t, fc_t)
            gn.push('TTM')
            pg.push(4)
            pv.push(vt)
            pl.push('TTM')
            pc.push(vt < 0 ? cNeg : cTTM)
            ph.push(false)
            lr.push(roeNow)
            lp.push(pbNow)
            lseg.push(4)
        else
            array<color> mc = array.from(cRev, cGp, cOi, cNi)
            array<string> ml = array.from('R', 'G', 'O', 'N')
            int kk = math.min(4, cnt)
            int gcount = 0
            if kk > 0
                for gi = 0 to kk - 1
                    int e = cnt - kk + gi
                    int qn = pk.get(e) % 4 + 1
                    int yy = int(math.floor(pk.get(e) / 4.0))
                    gn.push('Q' + str.tostring(qn) + "'" + str.tostring(yy % 100, '00'))
                    array<float> vals = array.from(aR.get(e), aG.get(e), aO.get(e), aN.get(e))
                    float roeB = f_entRoe(e)
                    for b = 0 to 3
                        float v = vals.get(b)
                        pg.push(gcount)
                        pv.push(v)
                        pl.push(ml.get(b))
                        pc.push(v < 0 ? cNeg : mc.get(b))
                        ph.push(hlLast and e == cnt - 1)
                        lr.push(b == 0 ? (na(roeB) ? na : roeB / 10) : na)
                        lp.push(b == 0 ? f_entPb(e) : na)
                        lseg.push(0)
                    gcount += 1
            gn.push('TTM')
            array<float> tv = array.from(rev_t, gp_t, oi_t, ni_t)
            for b = 0 to 3
                float v = tv.get(b)
                pg.push(gcount)
                pv.push(v)
                pl.push(ml.get(b))
                pc.push(v < 0 ? cNeg : mc.get(b))
                ph.push(false)
                lr.push(b == 0 ? roeNow : na)
                lp.push(b == 0 ? pbNow : na)
                lseg.push(0)
 
        // ── Unit and scale ──
        array<float> pvRaw = pv.copy()          // real values for the labels (before scaling)
        int nb = pv.size()
        int ng = gn.size()
        float maxAbs = 0.0
        for i = 0 to nb - 1
            float v0 = pv.get(i)
            if not na(v0)
                maxAbs := math.max(maxAbs, math.abs(v0))
        float div = isPct ? 1.0 : maxAbs >= 1e9 ? 1e9 : maxAbs >= 1e6 ? 1e6 : 1.0
        string unit = isPct ? '%' : syminfo.currency + ' · K/M/B/T'
 
        float mx = 0.0
        float mn = 0.0
        for i = 0 to nb - 1
            float v1 = pv.get(i)
            if not na(v1)
                float sv = v1 / div
                pv.set(i, sv)
                mx := math.max(mx, sv)
                mn := math.min(mn, sv)
        float rng = mx - mn
        if rng == 0
            rng := 1.0
        float yHdr  = mx + rng * 0.24
        float yYear = mn - rng * (mn < 0 ? 0.12 : 0.03)
        float yLow  = yYear - rng * 0.12
        float yHigh = yHdr + (yHdr - yLow) * 0.24          // room at the top for panel titles + legend
 
        // ── Horizontal layout: left (returns) | middle (financials) | right (cash & investment) ──
        int vb   = math.max(10, math.min(visBars, anchorIdx + 1))
        int xs0  = anchorIdx - vb + 1
        int wL   = showPerf ? int(math.round(vb * leftPct / 100.0)) : 0
        int wM   = int(math.round(vb * (showPerf ? midPct : midPct + leftPct) / 100.0))
        int gz   = math.max(1, int(vb / 200))
        int xLp  = xs0
        int xMp  = xs0 + wL + (wL > 0 ? gz : 0)
        int xRp  = xMp + wM + gz
        int bwUse = bw
        if fitScreen
            float avail = wM * fillPct / 100.0
            bwUse := math.max(1, int(math.floor((avail - (nb - 1) * gapIn - (ng - 1) * gapGrp) / nb)))
 
        // ── X positions (left to right, relative) ──
        array<int> bxl = array.new<int>()
        array<int> gxa = array.new<int>(ng, 0)
        array<int> gxb = array.new<int>(ng, 0)
        int xx = 0
        int gprev = -1
        int lastRight = 0
        for i = 0 to nb - 1
            int g = pg.get(i)
            if g != gprev
                if gprev != -1
                    xx += gapGrp
                gxa.set(g, xx)
                gprev := g
            bxl.push(xx)
            gxb.set(g, xx + bwUse - 1)
            lastRight := xx + bwUse - 1
            xx += bwUse + gapIn
        int off = xMp + math.max(int(math.floor((wM - (lastRight + 1)) / 2.0)), 0)
 
        // ── Panel backgrounds (card look) ──
        color pbg = color.new(chart.fg_color, bgTr)
        color pbd = color.new(chart.fg_color, 84)
        if wL > 0
            bxs.push(box.new(xLp, yHigh, xLp + wL - 1, yLow, border_color = pbd, border_width = 1, bgcolor = pbg))
        bxs.push(box.new(xMp, yHigh, xMp + wM - 1, yLow, border_color = pbd, border_width = 1, bgcolor = pbg))
        if showTbl and anchorIdx > xRp
            bxs.push(box.new(xRp, yHigh, anchorIdx, yLow, border_color = color.new(chart.fg_color, 70), border_width = 2, bgcolor = pbg))
        if wL > 0
            f_perf(xLp, wL, yLow, yHigh)
 
        // ── Columns ──
        for i = 0 to nb - 1
            float v = pv.get(i)
            int xl = off + bxl.get(i)
            int xc = xl + int(math.round((bwUse - 1) / 2.0))
            if not na(v)
                color bc = ph.get(i) ? chart.fg_color : color(na)
                bxs.push(box.new(left = xl, top = math.max(v, 0.0), right = xl + bwUse - 1, bottom = math.min(v, 0.0), border_color = bc, border_width = 2, bgcolor = pc.get(i)))
                if showVals
                    string vt2 = isPct ? str.tostring(v, '#.#') + '%' : f_fmt(pvRaw.get(i))
                    if v >= 0
                        lbs.push(label.new(xc, v, vt2, style = label.style_label_down, textcolor = chart.fg_color, color = color(na), size = lsz))
                    else
                        lbs.push(label.new(xc, v, vt2, style = label.style_label_up, textcolor = chart.fg_color, color = color(na), size = lsz))
            // Bottom label (year / column abbreviation)
            lbs.push(label.new(xc, yYear, pl.get(i), style = label.style_label_up, textcolor = chart.fg_color, color = color(na), size = lsz))
 
        // ── ROE/10 and P/B lines (normalized to the pane, labeled with the real value) ──
        if showRoe or showPb
            array<int> lx = array.new<int>()
            for i = 0 to nb - 1
                int xl2 = off + bxl.get(i)
                int g2 = pg.get(i)
                lx.push(modeA ? xl2 + int(math.round((bwUse - 1) / 2.0)) : off + int(math.round((gxa.get(g2) + gxb.get(g2)) / 2.0)))
            float rLo = na
            float rHi = na
            float pLo = na
            float pHi = na
            for i = 0 to nb - 1
                float rv = lr.get(i)
                float pbv = lp.get(i)
                if not na(rv)
                    rLo := na(rLo) ? rv : math.min(rLo, rv)
                    rHi := na(rHi) ? rv : math.max(rHi, rv)
                if not na(pbv)
                    pLo := na(pLo) ? pbv : math.min(pLo, pbv)
                    pHi := na(pHi) ? pbv : math.max(pHi, pbv)
            bool joint = lineMode == 'Shared scale'
            float jLo = na
            float jHi = na
            if showRoe and not na(rLo)
                jLo := rLo
                jHi := rHi
            if showPb and not na(pLo)
                jLo := na(jLo) ? pLo : math.min(jLo, pLo)
                jHi := na(jHi) ? pHi : math.max(jHi, pHi)
            float bLo = mn + rng * 0.10
            float bHi = mx + rng * 0.18
            float spn = bHi - bLo
            float roA = joint ? bLo : bLo + spn * 0.58
            float roB = bHi
            float pbA = bLo
            float pbB = joint ? bHi : bLo + spn * 0.42
            if showRoe and not na(rLo)
                f_drawLine(lr, lseg, lx, joint ? jLo : rLo, joint ? jHi : rHi, roA, roB, cRoe, true)
            if showPb and not na(pLo)
                f_drawLine(lp, lseg, lx, joint ? jLo : pLo, joint ? jHi : pHi, pbA, pbB, cPb, false)
 
        // Group titles (Q1.. / TTM) – top
        for g = 0 to ng - 1
            int gc = off + int(math.round((gxa.get(g) + gxb.get(g)) / 2.0))
            lbs.push(label.new(gc, yHdr, gn.get(g), style = label.style_none, textcolor = chart.fg_color, size = size.normal))
 
        // Invisible filler box: the pane scale covers the whole dashboard; when hPct < 100 it also reserves empty space ABOVE the dashboard (dashboard stays at the bottom)
        bxs.push(box.new(left = off, top = yLow + (yHigh - yLow) * 100.0 / hPct, right = off, bottom = yLow, border_color = color(na), bgcolor = color(na)))
 
        // Horizontal axis
        axis.set_xy1(off, 0.0)
        axis.set_xy2(off + lastRight, 0.0)
 
        // ── Middle and right panel titles + legend (with labels) ──
        float Hh = yHigh - yLow
        string ttl = (modeA ? metric : 'Revenue → Profit Conversion') + ' · ' + syminfo.ticker + ' (' + unit + ')'
        lbs.push(label.new(xMp + 1, yHigh - Hh * 0.045, ttl, style = label.style_label_left, textcolor = chart.fg_color, color = color(na), size = size.small, text_formatting = text.format_bold))
        if showTbl
            lbs.push(label.new(xRp + 1, yHigh - Hh * 0.045, 'CASH & INVESTMENT · LAST ' + str.tostring(qSel) + ' QUARTERS (ratios TTM)', style = label.style_label_left, textcolor = chart.fg_color, color = color(na), size = size.small, text_formatting = text.format_bold))
        array<string> lgT = array.new<string>()
        array<color>  lgC = array.new<color>()
        if modeA
            lgT.push('■ Oldest year')
            lgC.push(cY1)
            lgT.push('■ Middle')
            lgC.push(cY2)
            lgT.push('■ Newest')
            lgC.push(cY3)
            lgT.push('■ TTM')
            lgC.push(cTTM)
        else
            lgT.push('■ R=Revenue')
            lgC.push(cRev)
            lgT.push('■ G=Gross')
            lgC.push(cGp)
            lgT.push('■ O=Operating')
            lgC.push(cOi)
            lgT.push('■ N=Net')
            lgC.push(cNi)
        if showRoe
            lgT.push('● ROE/10')
            lgC.push(cRoe)
        if showPb
            lgT.push('● PD/DD')
            lgC.push(cPb)
        int nLg = lgT.size()
        for i = 0 to nLg - 1
            lbs.push(label.new(xMp + 1 + int(math.floor(wM * i / float(nLg))), yHigh - Hh * 0.105, lgT.get(i), style = label.style_label_left, textcolor = lgC.get(i), color = color(na), size = size.small))
 
        // ── Right panel: N quarters · 5 line bands + FCF / working capital columns ──
        if showTbl and anchorIdx - xRp >= 8 and cnt > 0
            int   kq   = math.min(qSel, cnt)
            int   xa   = xRp + 1
            int   xb   = anchorIdx - 1
            float wP2  = xb - xa
            int   mLft = int(math.round(wP2 * 0.30))
            float slot = math.max((wP2 - mLft - 1) / kq, 1.0)
            int   bwC  = math.max(1, int(math.floor(slot * 0.36)))
            color cMu  = color.new(chart.fg_color, 20)
 
            array<float>  vCx = array.new<float>()
            array<float>  vEg = array.new<float>()
            array<float>  vFp = array.new<float>()
            array<float>  vDe = array.new<float>()
            array<float>  vNd = array.new<float>()
            array<float>  vF  = array.new<float>()
            array<float>  vN  = array.new<float>()
            array<int>    xq  = array.new<int>()
            array<string> ql  = array.new<string>()
            for c = 0 to kq - 1
                int e   = cnt - kq + c
                int key = pk.get(e)
                // Capex TTM = sum of the last 4 quarters' capex (if all 4 quarters are stored)
                float cxs = 0.0
                bool  cxOk = true
                for d = 0 to 3
                    int ix = f_idxKey(key - d)
                    if ix < 0
                        cxOk := false
                    else
                        float cv = aCx.get(ix)
                        if na(cv)
                            cxOk := false
                        else
                            cxs += cv
                float niT = aNiT.get(e)
                vCx.push((cxOk and niT > 0) ? math.abs(cxs) / niT * 100 : na)
                int   ey   = f_idxKey(key - 4)
                float epsN = aEps.get(e)
                float epsP = ey >= 0 ? aEps.get(ey) : na
                vEg.push((not na(epsN) and not na(epsP) and epsP != 0) ? (epsN - epsP) / math.abs(epsP) * 100 : na)
                float fcT = aFcT.get(e)
                vFp.push((not na(fcT) and niT > 0) ? fcT / niT * 100 : na)
                float tdv = aTd.get(e)
                float tev = aTe.get(e)
                vDe.push((not na(tdv) and not na(tev) and tev > 0) ? tdv / tev * 100 : na)
                float ndv = aNd.get(e)
                float ebv = aEbT.get(e)
                vNd.push((not na(ndv) and not na(ebv) and ebv > 0) ? ndv / ebv * 100 : na)
                vF.push(aF.get(e))
                vN.push(aNwc.get(e))
                xq.push(xa + mLft + int(math.round((c + 0.5) * slot)))
                ql.push('Q' + str.tostring(key % 4 + 1) + "'" + str.tostring(int(math.floor(key / 4.0)) % 100, '00'))
 
            // line bands (each on its own scale)
            f_strip(vCx, xq, yHigh - Hh * 0.195, yHigh - Hh * 0.09, cCx, 'Capex/NI%', xa, showPtLbl)
            f_strip(vEg, xq, yHigh - Hh * 0.310, yHigh - Hh * 0.205, cEg, 'EPS gr.%', xa, showPtLbl)
            f_strip(vFp, xq, yHigh - Hh * 0.425, yHigh - Hh * 0.320, cFp, 'FCF/NI%', xa, showPtLbl)
            f_strip(vDe, xq, yHigh - Hh * 0.540, yHigh - Hh * 0.435, cDe, 'Debt/Eq%', xa, showPtLbl)
            f_strip(vNd, xq, yHigh - Hh * 0.655, yHigh - Hh * 0.550, cNd, 'NetDebt/EBITDA%', xa, showPtLbl)
 
            // columns: FCF and net working capital (quarterly, shared scale)
            float cLo = 0.0
            float cHi = 0.0
            for i = 0 to kq - 1
                float a1 = vF.get(i)
                float a2 = vN.get(i)
                if not na(a1)
                    cLo := math.min(cLo, a1)
                    cHi := math.max(cHi, a1)
                if not na(a2)
                    cLo := math.min(cLo, a2)
                    cHi := math.max(cHi, a2)
            if cHi == cLo
                cHi := cLo + 1.0
            float cTop = yHigh - Hh * 0.72
            float cBot = yLow + Hh * 0.13
            float y0c  = cBot + (0 - cLo) / (cHi - cLo) * (cTop - cBot)
            float lastF = vF.get(kq - 1)
            float lastN = vN.get(kq - 1)
            lbs.push(label.new(xa + 1, cTop - (cTop - cBot) * 0.12, '■ FCF', style = label.style_label_left, textcolor = cFc, color = color(na), size = lsz, text_formatting = text.format_bold))
            lbs.push(label.new(xa + 1, cTop - (cTop - cBot) * 0.30, 'Last: ' + f_fmt(lastF), style = label.style_label_left, textcolor = chart.fg_color, color = color(na), size = lsz, text_formatting = text.format_bold))
            lbs.push(label.new(xa + 1, cBot + (cTop - cBot) * 0.30, '■ Work.Cap.', style = label.style_label_left, textcolor = cNw, color = color(na), size = lsz, text_formatting = text.format_bold))
            lbs.push(label.new(xa + 1, cBot + (cTop - cBot) * 0.12, 'Last: ' + f_fmt(lastN), style = label.style_label_left, textcolor = chart.fg_color, color = color(na), size = lsz, text_formatting = text.format_bold))
            glines.push(line.new(xa + mLft, y0c, xb, y0c, color = color.new(chart.fg_color, 60), width = 1))
            for i = 0 to kq - 1
                int xcq = xq.get(i)
                for k2 = 0 to 1
                    float v2 = k2 == 0 ? vF.get(i) : vN.get(i)
                    if not na(v2)
                        float yv = cBot + (v2 - cLo) / (cHi - cLo) * (cTop - cBot)
                        int   xl = k2 == 0 ? xcq - bwC : xcq
                        int   xr = xl + bwC - 1
                        color bcl = v2 < 0 ? cNeg : (k2 == 0 ? cFc : cNw)
                        bxs.push(box.new(left = xl, top = math.max(yv, y0c), right = xr, bottom = math.min(yv, y0c), border_color = color(na), bgcolor = bcl))
                        float yo = k2 == 0 ? 0.0 : Hh * 0.05          // the working capital label is shifted slightly up / down (to avoid overlap)
                        int   xlc = xl + int(math.round((bwC - 1) / 2.0))
                        if showPtLbl
                            if v2 >= 0
                                lbs.push(label.new(xlc, yv + yo, f_fmt(v2), style = label.style_label_down, textcolor = chart.fg_color, color = color(na), size = lsz))
                            else
                                lbs.push(label.new(xlc, yv - yo, f_fmt(v2), style = label.style_label_up, textcolor = chart.fg_color, color = color(na), size = lsz))
                lbs.push(label.new(xcq, yLow + Hh * 0.055, ql.get(i), style = label.style_none, textcolor = chart.fg_color, size = lsz))

← 返回列表