Skip to Main Content
Back to website
Indicator Disclaimer | Report this indicator

What's Priced In: Peer Premium, Implied Growth & Risk

Every stock price is a set of assumptions. This indicator makes them visible. It compares the stock's valuation and fundamentals with the companies that trade on the same story, solves for the growth rate the current price requires, and lists the risks that would break the thesis. All of it fits in one on-chart panel that refreshes with each earnings report.

How it works. The indicator picks a peer group automatically: first from curated narrative groups (memory and storage, neoclouds, betting and gaming, regional banks, shale producers, and about fifty more), then from the company's industry classification, then its sector, with a manual override for anything else. It pulls twenty fundamental metrics for the stock and each peer, aligns them point-in-time so no report is used before it was public, and compares the stock with the peer median.

What it shows. The headline is P/E against the peer median, in percent and as a multiple. Below it, a reverse DCF solves for the average free-cash-flow growth the price implies over the next ten years, using the live 10-year Treasury yield plus an equity risk premium as the discount rate, and sets that against the company's recent growth, consensus EPS estimates and analyst price targets, so you see what the market is paying for next to what the company is delivering. A fundamentals score ranks growth, quality and balance sheet against the peers on a 0 to 100 percentile scale and produces a plain-language verdict: a premium backed by stronger fundamentals, a premium that isn't, a discount that reflects weaker fundamentals, or a discount despite stronger ones. Seven key metrics follow in a stock-versus-median layout, then the "Why" section lists the metrics where the company beats or trails most peers, and the risk flags line reports absolute checks: leverage, interest cover, Altman Z, liquidity, negative free cash flow, shrinking revenue, unprofitability, share and stock-based dilution, unsupported premium, and peak-cycle margins.

For scanning and alerts. Every conclusion is also registered as a signal, so the Market Scanner and Alerts can find stocks trading at a premium or discount to their industry, priced for a slowdown or an acceleration, carrying three or more risk flags, or adding a new flag this quarter.

Inputs. Peer override, table size and position, the premium threshold and fundamentals weights, every risk-flag threshold, the discount-rate assumptions, forecast horizon and growth path for the reverse DCF.

#TSBuild26

/*
	What's Priced In: Peer Premium, Implied Growth & Risk
	-----------------------------------------------------
	Overlay-only indicator (nothing painted on the price scale). Compares the current stock
	against the MEDIAN of an industry peer set and answers three questions:

		1. Is it trading at a premium or discount to its industry, and on which multiples?
		2. Do its growth, quality and balance sheet justify that premium (and which metrics)?
		3. How much risk is in the premium you are paying?

	PEER SET (the "industry median" is the median of these tickers, subject excluded)
		Order of precedence: "Peers override" input  >  FMP stock-peers lookup (if API key given)
		>  narrative group containing the ticker  >  industry map keyed by current.industry  >  sector fallback.
		The title row of the table shows which peers were used.

	PREMIUM
		Headline:      P/E ttm vs the industry median P/E, shown as a percentage and as a multiple
		               (77x vs 42x = +83%, 1.8x). Falls back to EV/Sales when there are no earnings.
		Implied growth: the EPS growth rate the P/E is paying for at peer growth pricing, next to
		               trailing growth, so "market expects slowdown / acceleration" is explicit.
		Support:       weighted blend of Growth, Quality and Safety percentiles vs the peer set
		               (0-100; Value excluded because valuation is the thing being explained).
		Premium risk:  de-rating exposure (premium / (1 + premium)) x (100 - support) / 100.
		Why:           growth / quality / balance-sheet metrics where the stock beats most peers
		               (up) or trails most peers (down), with the actual numbers.

	FORWARD DATA (subject only, from request.earnings; snapshot as of today)
		Forward EPS = sum of the next 4 quarterly consensus estimates (annualised if fewer).
		Forward P/E = last close / forward EPS.  PEG (fwd) = forward P/E / forward EPS growth %.
		Surprise avg = mean EPS surprise % over the last 4 reports.

	ABSOLUTE RISK FLAGS (thresholds are inputs)
		Leverage, interest cover, Altman Z, liquidity, negative TTM FCF, shrinking revenue,
		unprofitable, SBC dilution, share dilution, weak F-score, unsupported premium.

	Point-in-time discipline for the historical series behind the scanner signals: reportdate on
	fundamentals is the FISCAL PERIOD END, not the release date, so every record is pushed forward
	by "Report lag (days)" (default 45, roughly the 10-Q filing lag) before it is used or landed
	onto candles. A peer's metric is its latest lagged report on or before the subject's (max 200
	days old).
*/

describe_indicator("What's Priced In: Peer Premium, Implied Growth & Risk", 'price', { shortName: "What's Priced In" });

// ---------------------------------------------------------------------------
// Inputs
// ---------------------------------------------------------------------------

const peerGroup = input.group('Peer set');
const peersOverrideText = peerGroup.text('Peers override', '', { hide_in_legend: true });
const fmpApiKey = peerGroup.text('FMP API key', '', { hide_in_legend: true });
const maxPeers = peerGroup.number('Max peers', 8, { min: 3, max: 12 });

const tableGroup = input.group('Table');
const tableDetail = tableGroup.select('Table detail', 'Compact', ['Compact', 'Standard', 'Full']);
const compactTable = tableDetail === 'Compact';
const tablePosition = tableGroup.select('Table position', 'top_right', ['top_left', 'center_left', 'bottom_left', 'top_right', 'center_right', 'bottom_right']);
const tableOffsetY = tableGroup.number('Table offset Y (px)', 40, { min: 0, max: 600 });
const tableOffsetX = tableGroup.number('Table offset X (px)', -40, { min: -1000, max: 1000 });

const premiumGroup = input.group('Premium analysis');
const premiumThresholdPct = premiumGroup.number('Premium threshold (%)', 15, { min: 0, max: 200 });
const supportStrongAt = premiumGroup.number('Strong support >=', 60, { min: 0, max: 100 });
const supportWeakBelow = premiumGroup.number('Weak support <', 45, { min: 0, max: 100 });
const premiumRiskFlagAt = premiumGroup.number('Flag premium risk >=', 20, { min: 0, max: 100 });
const growthFloorPct = premiumGroup.number('Growth floor (%)', 5, { min: 0, max: 30 });
const growthCapPct = premiumGroup.number('Growth cap (%)', 50, { min: 10, max: 300 });

const weightsGroup = input.group('Fundamentals score weights');
const weightGrowth = weightsGroup.number('Growth', 35, { min: 0, max: 100 });
const weightQuality = weightsGroup.number('Quality', 40, { min: 0, max: 100 });
const weightSafety = weightsGroup.number('Balance sheet', 25, { min: 0, max: 100 });

const riskGroup = input.group('Absolute risk thresholds');
const maxNetDebtEbitda = riskGroup.number('Net debt/EBITDA >', 3, { min: 0, max: 20 });
const minInterestCoverage = riskGroup.number('EBIT / interest <', 3, { min: 0, max: 50 });
const minAltmanZ = riskGroup.number('Altman Z <', 1.81, { min: 0, max: 10 });
const minCurrentRatio = riskGroup.number('Current ratio <', 1, { min: 0, max: 5 });
const maxSbcPercent = riskGroup.number('SBC / revenue > (%)', 10, { min: 0, max: 100 });
const maxDilutionPct = riskGroup.number('Share dilution > (%)', 3, { min: 0, max: 50 });
const maxPiotroski = riskGroup.number('Piotroski F <=', 3, { min: 0, max: 9 });

const dcfGroup = input.group('Reverse DCF');
const equityRiskPremiumPct = dcfGroup.number('Equity risk premium (%)', 5.5, { min: 2, max: 12 });
const riskFreeFallbackPct = dcfGroup.number('Risk-free fallback (%)', 4.2, { min: 0, max: 15 });
const dcfFadeYears = dcfGroup.number('Forecast years', 10, { min: 5, max: 20 });
const dcfGrowthPath = dcfGroup.select('Growth path', 'Flat', ['Flat', 'Fade']);
const dcfTerminalPct = dcfGroup.number('Terminal growth (%)', 3, { min: 0, max: 5 });

const dataGroup = input.group('Data');
const quartersOfHistory = dataGroup.number('Quarters of history', 16, { min: 8, max: 40 });
const reportLagDays = dataGroup.number('Report lag (days)', 45, { min: 0, max: 120 });

const MAX_STALENESS_SECONDS = 200 * 86400;
const WORST_MULTIPLE = 1e12;
const DASH = '-';
const DAY = 86400;

// ---------------------------------------------------------------------------
// Peer set resolution
// ---------------------------------------------------------------------------

// Keys are TrendSpider industry ids (current.industry) normalised to lowercase alphanumerics.
// Matching is exact, then prefix either way, so truncated ids like "computersoftwareprogrammi"
// still match "computersoftware". Verify membership against your own view of the industry;
// the lists are representative large caps, not an exhaustive classification.
const INDUSTRY_PEERS = {
	semiconductors: ['NVDA', 'AMD', 'AVGO', 'QCOM', 'TXN', 'MU', 'INTC', 'ADI', 'MRVL', 'LRCX', 'AMAT', 'KLAC'],
	computersoftware: ['MSFT', 'ORCL', 'CRM', 'ADBE', 'NOW', 'INTU', 'PLTR', 'PANW', 'SNOW', 'WDAY', 'CRWD', 'DDOG'],
	internetandinformationser: ['GOOGL', 'META', 'NFLX', 'UBER', 'ABNB', 'BKNG', 'PINS', 'SNAP', 'SPOT', 'DASH'],
	computermanufacturing: ['AAPL', 'DELL', 'HPQ', 'SMCI', 'NTAP', 'PSTG', 'WDC'],
	computercommunicationsequ: ['CSCO', 'ANET', 'MSI', 'UI', 'CIEN', 'FFIV'],
	computerperipheralequipme: ['AAPL', 'DELL', 'HPQ', 'NTAP', 'WDC', 'STX'],
	edpservices: ['ACN', 'IBM', 'CTSH', 'EPAM', 'IT', 'GDDY'],
	businessservices: ['ACN', 'ADP', 'PAYX', 'FI', 'FIS', 'GPN', 'BR', 'VRSK'],
	electroniccomponents: ['APH', 'TEL', 'GLW', 'JBL', 'FLEX', 'CDW'],
	telecommunicationsequipm: ['CSCO', 'ANET', 'MSI', 'CIEN', 'JNPR'],
	telecommunications: ['T', 'VZ', 'TMUS', 'CMCSA', 'CHTR'],
	majorbanks: ['JPM', 'BAC', 'WFC', 'C', 'USB', 'PNC', 'TFC', 'GS', 'MS'],
	commercialbanks: ['PNC', 'USB', 'TFC', 'FITB', 'KEY', 'RF', 'MTB', 'HBAN', 'CFG'],
	savingsinstitutions: ['NYCB', 'WAL', 'ZION', 'CMA', 'FHN', 'SNV'],
	investmentbankersbrokers: ['GS', 'MS', 'SCHW', 'RJF', 'LPLA', 'IBKR', 'HOOD'],
	investmentmanagers: ['BLK', 'BX', 'KKR', 'APO', 'TROW', 'BEN', 'IVZ', 'ARES'],
	financecompanies: ['AXP', 'COF', 'SYF', 'ALLY', 'SOFI', 'OMF'],
	financeconsumerservices: ['AXP', 'COF', 'SYF', 'ALLY', 'SOFI'],
	diversifiedfinancialservi: ['V', 'MA', 'PYPL', 'FI', 'GPN', 'AFRM', 'TOST'],
	lifeinsurance: ['MET', 'PRU', 'AFL', 'PFG', 'GL', 'UNM'],
	propertycasualtyinsurers: ['PGR', 'ALL', 'TRV', 'CB', 'AIG', 'HIG', 'CINF', 'WRB'],
	accidenthealthinsurance: ['AFL', 'UNM', 'GL', 'CNO'],
	realestate: ['PLD', 'AMT', 'EQIX', 'SPG', 'O', 'PSA', 'WELL', 'DLR', 'VICI', 'AVB'],
	realestateinvestmenttrust: ['PLD', 'AMT', 'EQIX', 'SPG', 'O', 'PSA', 'WELL', 'DLR', 'VICI', 'AVB'],
	biotechnologypharmaceutic: ['LLY', 'JNJ', 'ABBV', 'MRK', 'PFE', 'BMY', 'AMGN', 'GILD'],
	majorpharmaceuticals: ['LLY', 'JNJ', 'ABBV', 'MRK', 'PFE', 'BMY', 'AMGN', 'GILD'],
	biotechnologybiologicalpr: ['AMGN', 'GILD', 'REGN', 'VRTX', 'BIIB', 'MRNA', 'ALNY', 'INCY'],
	biotechnologycommercialph: ['AMGN', 'GILD', 'REGN', 'VRTX', 'BIIB', 'MRNA', 'ALNY', 'INCY'],
	medicaldentalinstruments: ['MDT', 'SYK', 'BSX', 'ISRG', 'EW', 'ZBH', 'ABT', 'BDX'],
	medicalelectronics: ['ISRG', 'BSX', 'MDT', 'DXCM', 'PODD', 'GEHC'],
	medicalspecialities: ['TMO', 'DHR', 'A', 'IQV', 'RMD', 'HOLX'],
	managedhealthcare: ['UNH', 'ELV', 'CI', 'HUM', 'CVS', 'CNC', 'MOH'],
	hospitalnursingmanagement: ['HCA', 'UHS', 'THC', 'CYH', 'ENSG'],
	medicalnursingservices: ['HCA', 'UHS', 'THC', 'DVA', 'ENSG'],
	oilgasproduction: ['EOG', 'COP', 'OXY', 'DVN', 'FANG', 'APA', 'CTRA', 'EQT'],
	integratedoilcompanies: ['XOM', 'CVX', 'COP', 'OXY'],
	oilrefiningmarketing: ['VLO', 'MPC', 'PSX', 'DK', 'PBF'],
	oilfieldservicesequipment: ['SLB', 'HAL', 'BKR', 'NOV', 'FTI', 'CHX'],
	naturalgasdistribution: ['KMI', 'WMB', 'OKE', 'LNG', 'TRGP', 'ATO'],
	electricutilitiescentral: ['NEE', 'DUK', 'SO', 'D', 'AEP', 'EXC', 'SRE', 'XEL'],
	powergeneration: ['NEE', 'CEG', 'VST', 'NRG', 'AES', 'PEG'],
	industrialmachinerycompon: ['CAT', 'DE', 'PH', 'ITW', 'DOV', 'CMI', 'ETN', 'EMR'],
	constructionagequipment: ['CAT', 'DE', 'PCAR', 'CMI', 'AGCO', 'OSK'],
	militarygovernmenttechnic: ['LMT', 'RTX', 'NOC', 'GD', 'LHX', 'HII', 'LDOS'],
	aerospace: ['BA', 'RTX', 'LMT', 'GE', 'NOC', 'GD', 'HWM', 'TDG'],
	electricalproducts: ['ETN', 'EMR', 'ROK', 'AME', 'HUBB', 'VRT'],
	buildingproducts: ['MAS', 'CARR', 'TT', 'JCI', 'LII', 'BLDR'],
	homebuilding: ['DHI', 'LEN', 'PHM', 'NVR', 'TOL', 'KBH'],
	motorvehicles: ['TSLA', 'F', 'GM', 'RIVN', 'LCID', 'HOG'],
	autopartsoem: ['APTV', 'BWA', 'LEA', 'GNTX', 'ALV', 'DAN'],
	automotiveaftermarket: ['AZO', 'ORLY', 'GPC', 'AAP', 'LKQ'],
	packagedfoods: ['GIS', 'HSY', 'MDLZ', 'CPB', 'CAG', 'KHC', 'SJM', 'HRL'],
	softdrinks: ['KO', 'PEP', 'MNST', 'KDP', 'CELH'],
	beveragesproductiondistrib: ['KO', 'PEP', 'STZ', 'TAP', 'BF.B'],
	packagegoodscosmetics: ['PG', 'CL', 'EL', 'KMB', 'CHD', 'CLX', 'COTY'],
	apparel: ['NKE', 'LULU', 'VFC', 'RL', 'PVH', 'TPR', 'UAA'],
	shoemanufacturing: ['NKE', 'DECK', 'SKX', 'CROX', 'ONON'],
	restaurants: ['MCD', 'SBUX', 'CMG', 'YUM', 'DRI', 'QSR', 'DPZ', 'WING'],
	departmentspecialtyretail: ['AMZN', 'WMT', 'COST', 'TGT', 'TJX', 'ROST', 'BBY', 'M'],
	catalogspecialtydistribut: ['AMZN', 'EBAY', 'ETSY', 'W', 'CHWY'],
	foodchains: ['WMT', 'COST', 'KR', 'ACI', 'DG', 'DLTR', 'SFM'],
	retailbuildingmaterials: ['HD', 'LOW', 'FND', 'TSCO'],
	hotelsresorts: ['MAR', 'HLT', 'H', 'LVS', 'WYNN', 'MGM', 'RCL', 'CCL'],
	moviesentertainment: ['DIS', 'NFLX', 'WBD', 'LYV', 'EA', 'TTWO', 'RBLX'],
	televisionservices: ['CMCSA', 'CHTR', 'FOX', 'PARA', 'WBD'],
	broadcasting: ['CMCSA', 'FOX', 'NXST', 'SIRI', 'IHRT'],
	airlines: ['DAL', 'UAL', 'AAL', 'LUV', 'ALK', 'JBLU'],
	railroads: ['UNP', 'CSX', 'NSC'],
	truckingfreightcourierser: ['UPS', 'FDX', 'ODFL', 'JBHT', 'XPO', 'SAIA', 'KNX'],
	marinetransportation: ['KEX', 'MATX', 'ZIM', 'GOGL'],
	majorchemicals: ['DOW', 'LYB', 'DD', 'EMN', 'OLN', 'HUN'],
	specialtychemicals: ['LIN', 'APD', 'SHW', 'PPG', 'ECL', 'IFF', 'ALB', 'RPM'],
	agriculturalchemicals: ['CTVA', 'NTR', 'MOS', 'CF', 'FMC'],
	steelironore: ['NUE', 'STLD', 'CLF', 'CMC', 'RS'],
	metalmining: ['FCX', 'NEM', 'SCCO', 'AA', 'MP'],
	preciousmetals: ['NEM', 'GOLD', 'AEM', 'FNV', 'WPM', 'RGLD'],
	containerspackaging: ['BALL', 'IP', 'PKG', 'AMCR', 'CCK', 'SW', 'BERY'],
	paper: ['IP', 'PKG', 'SW', 'GPK'],
	forestproducts: ['WY', 'PCH', 'RYN', 'LPX'],
	environmentalservices: ['WM', 'RSG', 'WCN', 'CLH', 'CWST'],
	watersewerpipelinecommpow: ['AWK', 'WTRG', 'AWR', 'CWT'],
	otherpharmaceuticals: ['ZTS', 'ELAN', 'PRGO', 'TEVA', 'VTRS'],
	consumerelectronicsvideoc: ['BBY', 'GME', 'WSM', 'RH', 'DKS', 'ULTA', 'FIVE', 'BBWI'],
	consumerelectronicsappli: ['WHR', 'GRMN', 'SONO', 'LOGI', 'IRBT', 'GPRO', 'HELE'],
	otherspecialtystores: ['ULTA', 'DKS', 'WSM', 'RH', 'FIVE', 'TSCO', 'BBWI', 'AZO'],
	clothingshoeaccessorysto: ['TJX', 'ROST', 'BURL', 'GPS', 'ANF', 'URBN', 'AEO'],
	diversifiedcommercialserv: ['CTAS', 'CPRT', 'FAST', 'PAYX', 'ROL', 'ARMK'],
	otherconsumerservices: ['CTAS', 'ROL', 'SCI', 'BFAM', 'ABNB', 'BKNG'],
	recreationalproductstoys: ['HAS', 'MAT', 'POOL', 'BC', 'PII', 'FNKO'],
	servicesmiscamusementrecr: ['LYV', 'PLNT', 'SIX', 'FUN', 'RCL', 'CCL', 'NCLH'],
	toolshardware: ['SWK', 'SNA', 'TTC', 'MIDD'],
	homefurnishings: ['WSM', 'RH', 'LZB', 'ETD', 'SNBR', 'TPX'],
	miscellaneousmanufacturin: ['MMM', 'ITW', 'DOV', 'GE', 'ROP', 'IEX'],
	electronicsdistribution: ['ARW', 'AVT', 'SNX', 'TDSY'],
	semiconductorequipment: ['AMAT', 'LRCX', 'KLAC', 'ASML', 'TER', 'ENTG'],
	consumerspecialties: ['NWL', 'SPB', 'YETI', 'ELF', 'COTY'],
	packagegoods: ['PG', 'CL', 'KMB', 'CHD', 'CLX', 'EL']
};

const SECTOR_PEERS = {
	technology: ['AAPL', 'MSFT', 'NVDA', 'GOOGL', 'META', 'AVGO', 'ORCL', 'CRM', 'ADBE', 'CSCO'],
	finance: ['JPM', 'BAC', 'WFC', 'C', 'GS', 'MS', 'BLK', 'AXP', 'V', 'MA'],
	healthcare: ['LLY', 'JNJ', 'UNH', 'ABBV', 'MRK', 'PFE', 'TMO', 'ABT', 'AMGN', 'ISRG'],
	energy: ['XOM', 'CVX', 'COP', 'EOG', 'SLB', 'OXY', 'MPC', 'PSX', 'KMI', 'WMB'],
	capitalgoods: ['CAT', 'DE', 'HON', 'GE', 'ETN', 'EMR', 'LMT', 'RTX', 'ITW', 'PH'],
	basicindustries: ['LIN', 'SHW', 'APD', 'DOW', 'NUE', 'FCX', 'NEM', 'ECL', 'DD', 'PPG'],
	consumerdurables: ['TSLA', 'F', 'GM', 'APTV', 'WHR', 'LEN', 'DHI', 'MHK'],
	consumernondurables: ['PG', 'KO', 'PEP', 'PM', 'MO', 'CL', 'MDLZ', 'NKE', 'EL', 'KMB'],
	consumerservices: ['AMZN', 'WMT', 'COST', 'HD', 'MCD', 'DIS', 'NFLX', 'SBUX', 'TJX', 'LOW'],
	transportation: ['UNP', 'UPS', 'FDX', 'DAL', 'UAL', 'CSX', 'NSC', 'ODFL', 'LUV', 'JBHT'],
	publicutilities: ['NEE', 'DUK', 'SO', 'D', 'AEP', 'EXC', 'SRE', 'T', 'VZ', 'TMUS'],
	miscellaneous: ['BRK.B', 'HON', 'MMM', 'GE', 'DHR', 'ACN', 'ADP', 'WM'],
	// GICS-style sector ids
	informationtechnology: ['AAPL', 'MSFT', 'NVDA', 'AVGO', 'ORCL', 'CRM', 'ADBE', 'CSCO', 'AMD', 'ACN'],
	communicationservices: ['GOOGL', 'META', 'NFLX', 'DIS', 'CMCSA', 'T', 'VZ', 'TMUS', 'CHTR', 'EA'],
	consumerdiscretionary: ['AMZN', 'TSLA', 'HD', 'MCD', 'NKE', 'LOW', 'SBUX', 'TJX', 'BKNG', 'CMG'],
	consumerstaples: ['PG', 'KO', 'PEP', 'COST', 'WMT', 'PM', 'MDLZ', 'CL', 'MO', 'KMB'],
	financials: ['JPM', 'BAC', 'WFC', 'C', 'GS', 'MS', 'BLK', 'AXP', 'V', 'MA'],
	industrials: ['CAT', 'DE', 'HON', 'GE', 'ETN', 'UNP', 'UPS', 'LMT', 'RTX', 'BA'],
	materials: ['LIN', 'SHW', 'APD', 'DOW', 'NUE', 'FCX', 'NEM', 'ECL', 'DD', 'PPG'],
	utilities: ['NEE', 'DUK', 'SO', 'D', 'AEP', 'EXC', 'SRE', 'XEL', 'ED', 'PEG'],
	realestate: ['PLD', 'AMT', 'EQIX', 'SPG', 'O', 'PSA', 'WELL', 'DLR', 'VICI', 'AVB']
};

// Narrative groups: finer than industry, for names that trade on a specific story. A ticker in a
// group gets the other members as peers before the industry map is consulted. Edit freely.
const NARRATIVE_GROUPS = {
	memory_storage: ['MU', 'SNDK', 'WDC', 'STX', 'PSTG', 'NTAP', 'SMCI'],
	ai_accelerators: ['NVDA', 'AMD', 'AVGO', 'MRVL', 'ARM', 'INTC'],
	analog_mixed_signal: ['TXN', 'ADI', 'MCHP', 'NXPI', 'ON', 'STM', 'SWKS', 'QRVO'],
	semi_equipment: ['AMAT', 'LRCX', 'KLAC', 'TER', 'ENTG', 'ONTO', 'ASML'],
	eda_ip: ['SNPS', 'CDNS', 'ARM', 'CEVA'],
	datacenter_infra: ['VRT', 'SMCI', 'DELL', 'ANET', 'CIEN', 'COHR', 'LITE'],
	hyperscalers: ['MSFT', 'AMZN', 'GOOGL', 'META', 'ORCL'],
	cybersecurity: ['PANW', 'CRWD', 'ZS', 'FTNT', 'S', 'OKTA', 'CYBR', 'NET'],
	ecommerce_platforms: ['SHOP', 'MELI', 'ETSY', 'GDDY', 'WIX', 'XYZ', 'TOST', 'BILL'],
	app_software: ['CRM', 'NOW', 'ADBE', 'INTU', 'WDAY', 'HUBS', 'TEAM', 'DDOG', 'SNOW'],
	payments: ['V', 'MA', 'PYPL', 'AFRM', 'XYZ', 'TOST', 'FI', 'GPN'],
	streaming_media: ['NFLX', 'DIS', 'WBD', 'SPOT', 'ROKU', 'PARA'],
	gig_delivery: ['UBER', 'LYFT', 'DASH', 'CART'],
	online_travel: ['BKNG', 'EXPE', 'ABNB', 'TRIP'],
	cruise_lines: ['RCL', 'CCL', 'NCLH', 'VIK'],
	airlines: ['DAL', 'UAL', 'AAL', 'LUV', 'ALK', 'JBLU'],
	ev_makers: ['TSLA', 'RIVN', 'LCID', 'F', 'GM'],
	homebuilders: ['DHI', 'LEN', 'PHM', 'NVR', 'TOL', 'KBH', 'MTH'],
	regional_banks: ['PNC', 'USB', 'TFC', 'FITB', 'KEY', 'RF', 'MTB', 'HBAN', 'CFG', 'ZION', 'CMA', 'WAL'],
	money_center_banks: ['JPM', 'BAC', 'WFC', 'C'],
	alt_managers: ['BX', 'KKR', 'APO', 'ARES', 'CG', 'TPG', 'BAM'],
	glp1_pharma: ['LLY', 'NVO', 'AMGN', 'PFE', 'VKTX'],
	medtech_robotics: ['ISRG', 'SYK', 'MDT', 'BSX', 'EW', 'PODD', 'DXCM'],
	managed_care: ['UNH', 'ELV', 'CI', 'HUM', 'CVS', 'CNC', 'MOH'],
	oil_majors: ['XOM', 'CVX', 'COP', 'OXY', 'SHEL', 'BP'],
	shale_ep: ['EOG', 'DVN', 'FANG', 'APA', 'CTRA', 'EQT', 'PR', 'MTDR'],
	refiners: ['VLO', 'MPC', 'PSX', 'DK', 'PBF'],
	midstream: ['KMI', 'WMB', 'OKE', 'LNG', 'TRGP', 'ET'],
	uranium_nuclear: ['CCJ', 'UEC', 'LEU', 'OKLO', 'SMR', 'NNE'],
	solar: ['FSLR', 'ENPH', 'RUN', 'NXT', 'ARRY'],
	defense_primes: ['LMT', 'RTX', 'NOC', 'GD', 'LHX', 'HII'],
	rails: ['UNP', 'CSX', 'NSC'],
	parcel_ltl: ['UPS', 'FDX', 'ODFL', 'SAIA', 'XPO'],
	discount_retail: ['WMT', 'COST', 'TGT', 'DG', 'DLTR', 'BJ'],
	off_price_apparel: ['TJX', 'ROST', 'BURL'],
	home_improvement: ['HD', 'LOW', 'FND', 'TSCO'],
	athletic_apparel: ['NKE', 'LULU', 'DECK', 'ONON', 'UAA', 'SKX'],
	restaurants_qsr: ['MCD', 'YUM', 'QSR', 'DPZ', 'WING', 'CMG', 'SBUX', 'CAVA'],
	consumer_electronics_retail: ['BBY', 'GME'],
	telecom_carriers: ['T', 'VZ', 'TMUS', 'CMCSA', 'CHTR'],
	gold_miners: ['NEM', 'GOLD', 'AEM', 'KGC', 'AU', 'FNV', 'WPM'],
	copper_miners: ['FCX', 'SCCO', 'TECK'],
	steel: ['NUE', 'STLD', 'CLF', 'CMC'],
	waste: ['WM', 'RSG', 'WCN', 'CLH'],
	crypto_proxies: ['COIN', 'MSTR', 'MARA', 'RIOT', 'HOOD', 'CLSK'],
	ai_cloud_neoclouds: ['NBIS', 'CRWV', 'IREN', 'APLD', 'CORZ', 'WULF', 'CIFR', 'ORCL'],
	betting_gaming: ['FLUT', 'DKNG', 'MGM', 'CZR', 'PENN', 'LVS', 'WYNN', 'CHDN', 'RSI'],
	quantum_computing: ['IONQ', 'RGTI', 'QBTS', 'QUBT', 'ARQQ', 'IBM']
};

function lookupNarrativePeers(ticker) {
	const symbol = String(ticker || '').toUpperCase();
	const keys = Object.keys(NARRATIVE_GROUPS);

	for (let i = 0; i < keys.length; i += 1) {
		if (NARRATIVE_GROUPS[keys[i]].indexOf(symbol) >= 0) {
			return { key: keys[i], peers: NARRATIVE_GROUPS[keys[i]] };
		}
	}

	return null;
}

const MARKET_PEERS = ['AAPL', 'MSFT', 'AMZN', 'GOOGL', 'JPM', 'UNH', 'XOM', 'PG', 'HD', 'CAT', 'LIN', 'NEE'];

function normalizeId(value) {
	return String(value || '').toLowerCase().replace(/[^a-z0-9]/g, '');
}

function parseTickerList(text) {
	return String(text || '')
		.split(',')
		.map(symbol => symbol.trim().toUpperCase())
		.filter(symbol => symbol.length > 0 && symbol !== current.ticker)
		.filter((symbol, index, all) => all.indexOf(symbol) === index);
}

function lookupIndustryPeers(industryId) {
	const id = normalizeId(industryId);

	if (id.length === 0) {
		return null;
	}

	if (INDUSTRY_PEERS[id]) {
		return { key: id, peers: INDUSTRY_PEERS[id] };
	}

	const keys = Object.keys(INDUSTRY_PEERS);

	for (let i = 0; i < keys.length; i += 1) {
		const key = keys[i];
		const shared = Math.min(key.length, id.length);

		if (shared >= 8 && (key.indexOf(id) === 0 || id.indexOf(key) === 0)) {
			return { key, peers: INDUSTRY_PEERS[key] };
		}
	}

	return null;
}

async function fetchFmpPeers() {
	if (!fmpApiKey) {
		return null;
	}

	try {
		const url = `https://financialmodelingprep.com/stable/stock-peers?symbol=${current.ticker}&apikey=${fmpApiKey}`;
		const data = await request.http(url, 3600);

		if (!Array.isArray(data) || data.length === 0) {
			return null;
		}

		// v4-style payload: [{ symbol, peersList: [...] }]; stable-style payload: [{ symbol, companyName, ... }, ...]
		if (Array.isArray(data[0].peersList)) {
			return data[0].peersList;
		}

		return data.map(item => item && item.symbol).filter(symbol => typeof symbol === 'string');
	}
	catch (error) {
		console.log(`FMP peers lookup failed: ${error && error.message ? error.message : error}`);
		return null;
	}
}

async function resolvePeers() {
	const override = parseTickerList(peersOverrideText);

	if (override.length > 0) {
		return { peers: override.slice(0, maxPeers), source: 'manual list' };
	}

	const fmpPeers = await fetchFmpPeers();

	if (fmpPeers) {
		const cleaned = parseTickerList(fmpPeers.join(','));

		if (cleaned.length >= 3) {
			return { peers: cleaned.slice(0, maxPeers), source: 'FMP peers' };
		}
	}

	const narrative = lookupNarrativePeers(current.ticker);

	if (narrative) {
		const cleaned = parseTickerList(narrative.peers.join(','));

		if (cleaned.length >= 3) {
			return { peers: cleaned.slice(0, maxPeers), source: `group: ${narrative.key}` };
		}
	}

	const industry = lookupIndustryPeers(current.industry);

	if (industry) {
		const cleaned = parseTickerList(industry.peers.join(','));

		if (cleaned.length >= 3) {
			return { peers: cleaned.slice(0, maxPeers), source: `industry: ${industry.key}` };
		}
	}

	const sectorId = normalizeId(current.sector);
	const sectorKeys = Object.keys(SECTOR_PEERS);

	for (let i = 0; i < sectorKeys.length; i += 1) {
		const key = sectorKeys[i];
		const shared = Math.min(key.length, sectorId.length);

		if (key === sectorId || (shared >= 6 && (key.indexOf(sectorId) === 0 || sectorId.indexOf(key) === 0))) {
			const cleaned = parseTickerList(SECTOR_PEERS[key].join(','));
			return { peers: cleaned.slice(0, maxPeers), source: `sector: ${key}` };
		}
	}

	// No classification at all (relistings, recent IPOs, some foreign-domiciled names): compare
	// against a broad market set rather than fail, and say so in the table.
	const marketPeers = parseTickerList(MARKET_PEERS.join(','));
	return { peers: marketPeers.slice(0, maxPeers), source: 'market (no classification)' };
}

const peerSet = await resolvePeers();
const peers = peerSet.peers;

console.log(`sector=${current.sector} industry=${current.industry} peers(${peerSet.source})=${peers.join(',')}`);
assert(peers.length >= 3, 'Peer set has fewer than 3 tickers. Enter more in "Peers override".');

const tickers = [current.ticker].concat(peers);

// ---------------------------------------------------------------------------
// Data
// ---------------------------------------------------------------------------

const METRIC_IDS = [
	'pe_ratio_ttm', 'ev_ebitda', 'ev_sales', 'pfcf_ratio_ttm',
	'gross_profit_margin', 'operating_margin', 'fcf_margin', 'return_on_invested_capital', 'ocf_to_net_income',
	'revenue', 'eps_diluted', 'free_cash_flow', 'ebitda', 'shares_diluted_is',
	'net_debt_ebitda', 'ebit_to_interest_expense', 'altman_z_score', 'current_ratio',
	'sbc_to_revenue', 'piotroski_f_score'
];

async function fetchFundamentals(ticker) {
	try {
		const response = await request.fundamental(ticker, METRIC_IDS, quartersOfHistory + 12);
		return response || { error: 'empty response' };
	}
	catch (error) {
		return { error: (error && error.message) ? error.message : String(error) };
	}
}

async function fetchSubjectEarnings() {
	// reportdate on fundamentals is the fiscal period end, so actual release dates and consensus
	// estimates come from request.earnings. Future records are trimmed unless a timestamp filter is
	// set; the docs do not say which unit the filter expects, so try seconds, then milliseconds,
	// then no filter (which still returns history plus ~3 days ahead).
	const since = current.now - 400 * DAY;
	const until = current.now + 400 * DAY;
	const attempts = [
		{ filters: [{ field: 'timestamp', filter: 'greater', value: since }, { field: 'timestamp', filter: 'less', value: until }] },
		{ filters: [{ field: 'timestamp', filter: 'greater', value: since * 1000 }, { field: 'timestamp', filter: 'less', value: until * 1000 }] },
		{ filters: [{ field: 'timestamp', filter: 'greater', value: since }] },
		{ filters: [{ field: 'timestamp', filter: 'greater', value: since * 1000 }] },
		null
	];
	let bestRecords = [];

	for (let i = 0; i < attempts.length; i += 1) {
		try {
			const data = attempts[i] ? await request.earnings(current.ticker, attempts[i]) : await request.earnings(current.ticker);

			let records = data;

			if (records && !Array.isArray(records) && typeof records === 'object') {
				const arrayKey = Object.keys(records).find(key => Array.isArray(records[key]));
				records = arrayKey ? records[arrayKey] : null;
			}

			if (Array.isArray(records) && records.length > 0) {
				const futureCount = records.filter(record => record && (record.isFuture === true || Number(record.timestamp) > current.now * (Number(record.timestamp) > 1e11 ? 1000 : 1))).length;
				console.log(`Earnings: attempt ${i + 1} returned ${records.length} records (${futureCount} future). First record keys: ${Object.keys(records[0]).join(', ')}`);

				if (futureCount > 0) {
					return records;
				}

				if (records.length > bestRecords.length) {
					bestRecords = records;
				}

				continue;
			}

			console.log(`Earnings: attempt ${i + 1} returned ${data && data.error ? data.error : 'no records'}`);
		}
		catch (error) {
			console.log(`Earnings: attempt ${i + 1} failed: ${error && error.message ? error.message : error}`);
		}
	}

	return bestRecords;
}

// Analyst price targets: an observed market expectation, not a solved one
async function fetchAnalystRatings() {
	try {
		const data = await request.analyst_ratings(current.ticker);
		if (Array.isArray(data)) {
			console.log(`Analysts: ${data.length} records${data.length > 0 ? `. First record keys: ${Object.keys(data[0]).join(', ')}` : ''}`);
			return data;
		}
		console.log(`Analysts: ${data && data.error ? data.error : 'no array returned'}`);
		return [];
	}
	catch (error) {
		console.log(`Analyst ratings lookup failed: ${error && error.message ? error.message : error}`);
		return [];
	}
}

const fetched = await Promise.all(tickers.map(fetchFundamentals).concat([fetchSubjectEarnings(), fetchAnalystRatings()]));
const analystRecords = fetched[tickers.length + 1];
const responses = fetched.slice(0, tickers.length);
const earningsRecords = fetched[tickers.length];

function normalizeRecords(records) {
	if (!Array.isArray(records)) {
		return [];
	}

	return records
		.filter(record => record && Number.isFinite(record.value) && Number.isFinite(record.reportdate))
		.map(record => ({ t: record.reportdate + reportLagDays * DAY, v: record.value }))
		.sort((a, b) => a.t - b.t);
}

const companies = responses.map((response, index) => {
	const company = { ticker: tickers[index], ok: !(response && response.error) };

	METRIC_IDS.forEach(id => {
		company[id] = company.ok ? normalizeRecords(response[id]) : [];
	});

	return company;
});

const subject = companies[0];
assert(subject.ok, `Could not load fundamentals for ${current.ticker}: ${responses[0] && responses[0].error}`);
assert(subject.revenue.length > 0, `No revenue reports returned for ${current.ticker}.`);

const usablePeers = companies.slice(1).filter(company => company.ok && company.revenue.length > 0);
companies.slice(1).forEach(company => {
	if (!company.ok) {
		console.log(`Peer ${company.ticker}: fundamentals unavailable, excluded.`);
	}
});
assert(usablePeers.length >= 2, 'Fewer than 2 peers returned fundamentals; widen the peer set.');

// ---------------------------------------------------------------------------
// Point-in-time accessors
// ---------------------------------------------------------------------------

function latestIndexAt(records, t) {
	let index = -1;

	for (let i = 0; i < records.length; i += 1) {
		if (records[i].t <= t) {
			index = i;
		}
		else {
			break;
		}
	}

	if (index >= 0 && t - records[index].t > MAX_STALENESS_SECONDS) {
		return -1;
	}

	return index;
}

function valueAt(company, id, t) {
	const records = company[id] || [];
	const index = latestIndexAt(records, t);
	return index >= 0 ? records[index].v : null;
}

function ttmAt(company, id, t) {
	const records = company[id] || [];
	const index = latestIndexAt(records, t);

	if (index < 3) {
		return null;
	}

	return records[index].v + records[index - 1].v + records[index - 2].v + records[index - 3].v;
}

function ttmAtOffset(company, id, t, quartersBack) {
	const records = company[id] || [];
	const index = latestIndexAt(records, t) - quartersBack;

	if (index < 3) {
		return null;
	}

	return records[index].v + records[index - 1].v + records[index - 2].v + records[index - 3].v;
}

// YoY growth on trailing-twelve-month sums: (TTM now / TTM four quarters earlier) - 1
function yoyAt(company, id, t) {
	const now = ttmAt(company, id, t);
	const base = ttmAtOffset(company, id, t, 4);

	if (now === null || base === null || base === 0) {
		return null;
	}

	return (now - base) / Math.abs(base);
}

// Three-year compound growth on TTM sums; needs 16 quarters
function cagr3At(company, id, t) {
	const now = ttmAt(company, id, t);
	const base = ttmAtOffset(company, id, t, 12);

	if (now === null || base === null || base <= 0 || now <= 0) {
		return null;
	}

	return Math.pow(now / base, 1 / 3) - 1;
}

// Share of the last 8 quarters where diluted EPS grew vs the same quarter a year earlier
function epsConsistencyAt(company, t) {
	const records = company.eps_diluted || [];
	const index = latestIndexAt(records, t);

	if (index < 11) {
		return null;
	}

	let up = 0;

	for (let q = 0; q < 8; q += 1) {
		if (records[index - q].v > records[index - q - 4].v) {
			up += 1;
		}
	}

	return up / 8;
}

// Diluted share count change vs a year earlier: positive = dilution, negative = buybacks
function dilutionAt(company, t) {
	const records = company.shares_diluted_is || [];
	const index = latestIndexAt(records, t);

	if (index < 4 || !records[index - 4].v) {
		return null;
	}

	return records[index].v / records[index - 4].v - 1;
}

// Through-cycle P/E: price (backed out of the platform's trailing P/E) divided by the average annual
// diluted EPS of the last 12 quarters. At a cyclical peak this sits far above the trailing P/E.
function normalizedPeAt(company, t) {
	const peTtm = valueAt(company, 'pe_ratio_ttm', t);
	const epsTtm = ttmAt(company, 'eps_diluted', t);
	const records = company.eps_diluted || [];
	const index = latestIndexAt(records, t);

	if (peTtm === null || peTtm <= 0 || epsTtm === null || epsTtm <= 0 || index < 11) {
		return null;
	}

	let sum12 = 0;
	for (let q = 0; q < 12; q += 1) {
		sum12 += records[index - q].v;
	}

	const averageAnnualEps = sum12 / 3;
	return averageAnnualEps > 0 ? (peTtm * epsTtm) / averageAnnualEps : null;
}

// Where the current operating margin sits inside its own last-12-quarter range: 1 = at the peak, 0 = at the trough
function marginCyclePositionAt(company, t) {
	const records = company.operating_margin || [];
	const index = latestIndexAt(records, t);

	if (index < 7) {
		return null;
	}

	const marginWindow = records.slice(Math.max(0, index - 11), index + 1).map(record => record.v);
	const windowHigh = Math.max.apply(null, marginWindow);
	const windowLow = Math.min.apply(null, marginWindow);

	return windowHigh === windowLow ? null : (records[index].v - windowLow) / (windowHigh - windowLow);
}

function positiveOrWorst(value) {
	if (value === null) {
		return null;
	}

	return value <= 0 ? WORST_MULTIPLE : value;
}

function identity(value) {
	return value;
}

function mean(values) {
	return values.reduce((sum, value) => sum + value, 0) / values.length;
}

function median(values) {
	const sorted = values.filter(value => value !== null && Number.isFinite(value)).slice().sort((a, b) => a - b);

	if (sorted.length === 0) {
		return null;
	}

	const middle = Math.floor(sorted.length / 2);
	return sorted.length % 2 === 1 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2;
}

// Ratio metrics may arrive as fractions (0.42) or percents (42). Detect once from gross margin.
const latestGrossMargin = valueAt(subject, 'gross_profit_margin', subject.revenue[subject.revenue.length - 1].t);
const ratiosArePercent = latestGrossMargin !== null && Math.abs(latestGrossMargin) > 1.5;
const toPercent = value => value === null ? null : (ratiosArePercent ? value : value * 100);

// ---------------------------------------------------------------------------
// Formatting
// ---------------------------------------------------------------------------

const fmtMultiple = value => value === null ? DASH : (value <= 0 ? 'neg' : `${value.toFixed(1)}x`);
const fmtPctComputed = value => value === null ? DASH : `${(value * 100).toFixed(1)}%`;
const fmtPctReported = value => value === null ? DASH : `${toPercent(value).toFixed(1)}%`;
const fmtRatio = value => value === null ? DASH : value.toFixed(2);
const fmtInt = value => value === null ? DASH : value.toFixed(0);
const fmtSignedPct = value => value === null ? DASH : `${value >= 0 ? '+' : ''}${(value * 100).toFixed(0)}%`;
const fmtSignedPts = value => value === null ? DASH : `${value >= 0 ? '+' : ''}${value.toFixed(1)}pts`;
const fmtSignedRatio = value => value === null ? DASH : `${value >= 0 ? '+' : ''}${value.toFixed(2)}`;

// "vs median" column: relative % for multiples, point difference for percentages, raw difference for ratios
const diffMultiple = (own, med) => (own === null || med === null || own <= 0 || med <= 0) ? null : own / med - 1;
const diffPctComputed = (own, med) => (own === null || med === null) ? null : (own - med) * 100;
const diffPctReported = (own, med) => (own === null || med === null) ? null : toPercent(own) - toPercent(med);
const diffRatio = (own, med) => (own === null || med === null) ? null : own - med;

// ---------------------------------------------------------------------------
// Metric definitions
// ---------------------------------------------------------------------------

const CATEGORIES = {
	Value: [
		{ label: 'P/E ttm', multipleLabel: 'P/E', higherBetter: false, rankValue: positiveOrWorst, fmt: fmtMultiple, diff: diffMultiple, fmtDiff: fmtSignedPct, compact: false, get: (c, t) => valueAt(c, 'pe_ratio_ttm', t) },
		{ label: 'P/E on 3y avg EPS', multipleLabel: 'P/E 3y', higherBetter: false, rankValue: positiveOrWorst, fmt: fmtMultiple, diff: diffMultiple, fmtDiff: fmtSignedPct, compact: true, get: (c, t) => normalizedPeAt(c, t) },
		{ label: 'EV/EBITDA', multipleLabel: 'EV/EBITDA', higherBetter: false, rankValue: positiveOrWorst, fmt: fmtMultiple, diff: diffMultiple, fmtDiff: fmtSignedPct, compact: true, get: (c, t) => valueAt(c, 'ev_ebitda', t) },
		{ label: 'EV/Sales', multipleLabel: 'EV/Sales', higherBetter: false, rankValue: positiveOrWorst, fmt: fmtMultiple, diff: diffMultiple, fmtDiff: fmtSignedPct, compact: false, get: (c, t) => valueAt(c, 'ev_sales', t) },
		{ label: 'P/FCF ttm', multipleLabel: 'P/FCF', higherBetter: false, rankValue: positiveOrWorst, fmt: fmtMultiple, diff: diffMultiple, fmtDiff: fmtSignedPct, compact: false, get: (c, t) => valueAt(c, 'pfcf_ratio_ttm', t) }
	],
	Growth: [
		{ label: 'Revenue YoY (ttm)', higherBetter: true, rankValue: identity, fmt: fmtPctComputed, diff: diffPctComputed, fmtDiff: fmtSignedPts, compact: true, get: (c, t) => yoyAt(c, 'revenue', t) },
		{ label: 'Revenue 3y CAGR', higherBetter: true, rankValue: identity, fmt: fmtPctComputed, diff: diffPctComputed, fmtDiff: fmtSignedPts, compact: false, get: (c, t) => cagr3At(c, 'revenue', t) },
		{ label: 'EPS YoY (ttm)', higherBetter: true, rankValue: identity, fmt: fmtPctComputed, diff: diffPctComputed, fmtDiff: fmtSignedPts, compact: false, get: (c, t) => yoyAt(c, 'eps_diluted', t) },
		{ label: 'FCF YoY (ttm)', higherBetter: true, rankValue: identity, fmt: fmtPctComputed, diff: diffPctComputed, fmtDiff: fmtSignedPts, compact: false, get: (c, t) => yoyAt(c, 'free_cash_flow', t) },
		{ label: 'EPS consistency (8q)', higherBetter: true, rankValue: identity, fmt: fmtPctComputed, diff: diffPctComputed, fmtDiff: fmtSignedPts, compact: false, get: (c, t) => epsConsistencyAt(c, t) }
	],
	Quality: [
		{ label: 'Gross margin', higherBetter: true, rankValue: identity, fmt: fmtPctReported, diff: diffPctReported, fmtDiff: fmtSignedPts, compact: false, get: (c, t) => valueAt(c, 'gross_profit_margin', t) },
		{ label: 'Operating margin', higherBetter: true, rankValue: identity, fmt: fmtPctReported, diff: diffPctReported, fmtDiff: fmtSignedPts, compact: true, get: (c, t) => valueAt(c, 'operating_margin', t) },
		{ label: 'FCF margin', higherBetter: true, rankValue: identity, fmt: fmtPctReported, diff: diffPctReported, fmtDiff: fmtSignedPts, compact: false, get: (c, t) => valueAt(c, 'fcf_margin', t) },
		{ label: 'Op margin vs own 3y range', higherBetter: null, rankValue: identity, fmt: fmtPctComputed, diff: diffPctComputed, fmtDiff: fmtSignedPts, compact: false, get: (c, t) => marginCyclePositionAt(c, t) },
		{ label: 'ROIC', higherBetter: true, rankValue: identity, fmt: fmtPctReported, diff: diffPctReported, fmtDiff: fmtSignedPts, compact: true, get: (c, t) => valueAt(c, 'return_on_invested_capital', t) },
		{ label: 'OCF / net income', higherBetter: true, rankValue: identity, fmt: fmtRatio, diff: diffRatio, fmtDiff: fmtSignedRatio, compact: false, get: (c, t) => valueAt(c, 'ocf_to_net_income', t) }
	],
	Safety: [
		{ label: 'Net debt / EBITDA', higherBetter: false, rankValue: identity, fmt: fmtRatio, diff: diffRatio, fmtDiff: fmtSignedRatio, compact: true, get: (c, t) => valueAt(c, 'net_debt_ebitda', t) },
		{ label: 'EBIT / interest', higherBetter: true, rankValue: identity, fmt: fmtRatio, diff: diffRatio, fmtDiff: fmtSignedRatio, compact: false, get: (c, t) => valueAt(c, 'ebit_to_interest_expense', t) },
		{ label: 'Altman Z', higherBetter: true, rankValue: identity, fmt: fmtRatio, diff: diffRatio, fmtDiff: fmtSignedRatio, compact: false, get: (c, t) => valueAt(c, 'altman_z_score', t) },
		{ label: 'Current ratio', higherBetter: true, rankValue: identity, fmt: fmtRatio, diff: diffRatio, fmtDiff: fmtSignedRatio, compact: false, get: (c, t) => valueAt(c, 'current_ratio', t) },
		{ label: 'Piotroski F', higherBetter: true, rankValue: identity, fmt: fmtInt, diff: diffRatio, fmtDiff: fmtSignedRatio, compact: false, get: (c, t) => valueAt(c, 'piotroski_f_score', t) },
		{ label: 'Share count YoY (+ = dilution)', higherBetter: false, rankValue: identity, fmt: fmtPctComputed, diff: diffPctComputed, fmtDiff: fmtSignedPts, compact: false, get: (c, t) => dilutionAt(c, t) },
		{ label: 'SBC / revenue', higherBetter: false, rankValue: identity, fmt: fmtPctReported, diff: diffPctReported, fmtDiff: fmtSignedPts, compact: false, get: (c, t) => valueAt(c, 'sbc_to_revenue', t) }
	]
};

const CATEGORY_NAMES = ['Value', 'Growth', 'Quality', 'Safety'];
const SUPPORT_CATEGORIES = ['Growth', 'Quality', 'Safety'];
const SUPPORT_WEIGHTS = { Growth: weightGrowth, Quality: weightQuality, Safety: weightSafety };

// 100 = beats every peer on this metric, 0 = every peer is better
function percentileRank(subjectValue, otherValues, higherBetter) {
	let better = 0;
	let ties = 0;

	otherValues.forEach(other => {
		if (other === subjectValue) {
			ties += 1;
		}
		else if (higherBetter ? subjectValue > other : subjectValue < other) {
			better += 1;
		}
	});

	return 100 * (better + 0.5 * ties) / otherValues.length;
}

function metricRankAt(metric, companyIndex, t) {
	if (metric.higherBetter === null) {
		return null;
	}

	const values = companies.map(company => metric.rankValue(metric.get(company, t)));
	const own = values[companyIndex];

	if (own === null) {
		return null;
	}

	const others = values.filter((value, index) => index !== companyIndex && value !== null);
	return others.length >= 2 ? percentileRank(own, others, metric.higherBetter) : null;
}

function scoreCompany(companyIndex, t) {
	const result = {};

CATEGORY_NAMES.forEach(category => {
		const ranks = CATEGORIES[category]
			.map(metric => metricRankAt(metric, companyIndex, t))
			.filter(rank => rank !== null);

		result[category] = ranks.length > 0 ? mean(ranks) : null;
	});

	let supportSum = 0;
	let supportWeight = 0;

	SUPPORT_CATEGORIES.forEach(category => {
		const weight = SUPPORT_WEIGHTS[category] > 0 ? SUPPORT_WEIGHTS[category] : 0;

		if (result[category] !== null && weight > 0) {
			supportSum += result[category] * weight;
			supportWeight += weight;
		}
	});

	result.Support = supportWeight > 0 ? supportSum / supportWeight : null;
	return result;
}

// ---------------------------------------------------------------------------
// Premium vs industry median
// ---------------------------------------------------------------------------

const VALUATION_MULTIPLES = [
	{ id: 'pe_ratio_ttm', label: 'P/E', growthId: 'eps_diluted', growthLabel: 'EPS' },
	{ id: 'ev_ebitda', label: 'EV/EBITDA', growthId: 'ebitda', growthLabel: 'EBITDA' },
	{ id: 'ev_sales', label: 'EV/Sales', growthId: 'revenue', growthLabel: 'revenue' },
	{ id: 'pfcf_ratio_ttm', label: 'P/FCF', growthId: 'free_cash_flow', growthLabel: 'FCF' },
	{ id: 'normalized_pe', label: 'P/E 3y', growthId: null, growthLabel: null }
];

// Growth used for the adjustment is clamped to [floor, cap]: negative or near-zero growth would
// make a PEG explode, and cyclical-peak growth (+167%) is not a rate anyone pays for.
function clampGrowth(growth) {
	if (growth === null) {
		return null;
	}

	return Math.min(growthCapPct / 100, Math.max(growthFloorPct / 100, growth));
}

function premiumAt(companyIndex, t) {
	const own = companies[companyIndex];
	const perMultiple = [];

	const multipleValue = (company, multiple) => multiple.id === 'normalized_pe' ? normalizedPeAt(company, t) : valueAt(company, multiple.id, t);

	VALUATION_MULTIPLES.forEach(multiple => {
		const ownValue = multipleValue(own, multiple);
		const peerRows = companies
			.filter((company, index) => index !== companyIndex)
			.map(company => ({ value: multipleValue(company, multiple), growth: multiple.growthId ? clampGrowth(yoyAt(company, multiple.growthId, t)) : null }))
			.filter(peer => peer.value !== null && peer.value > 0);

		if (ownValue === null || ownValue <= 0 || peerRows.length < 2) {
			return;
		}

		const peerMedian = median(peerRows.map(peer => peer.value));
		const item = { label: multiple.label, growthLabel: multiple.growthLabel, ownValue, peerMedian, premium: ownValue / peerMedian - 1, adjusted: null, implied: null, growthUsed: null, growthRaw: multiple.growthId ? yoyAt(own, multiple.growthId, t) : null };

		// "Multiple per point of growth" (PEG-style) for the subject vs the peer median of the same
		const ownGrowth = clampGrowth(item.growthRaw);
		const peerPerGrowth = peerRows.filter(peer => peer.growth !== null).map(peer => peer.value / (peer.growth * 100));

		if (ownGrowth !== null && peerPerGrowth.length >= 2) {
			const medianPeerPerGrowth = median(peerPerGrowth);
			const ownPerGrowth = ownValue / (ownGrowth * 100);
			item.growthUsed = ownGrowth;
			item.adjusted = ownPerGrowth / medianPeerPerGrowth - 1;								// premium after paying for (clamped trailing) growth
			item.implied = ownValue / medianPeerPerGrowth / 100;								// growth the subject is priced for at peer growth pricing
		}

		perMultiple.push(item);
	});

	// Headline = P/E vs industry median P/E. Falls back to EV/Sales only when the company has no
	// positive earnings, where P/E is meaningless.
	const peItem = perMultiple.find(item => item.label === 'P/E') || null;
	const salesItem = perMultiple.find(item => item.label === 'EV/Sales') || null;
	const headline = peItem || salesItem;
	const ownPe = valueAt(own, 'pe_ratio_ttm', t);

	return {
		premium: headline ? headline.premium : null,
		basis: headline ? (headline === peItem ? 'P/E' : 'EV/Sales') : null,
		basisReason: headline === salesItem ? (ownPe !== null && ownPe <= 0 ? 'no positive earnings' : 'P/E unavailable') : null,
		ownMultiple: headline ? headline.ownValue : null,
		peerMultiple: headline ? headline.peerMedian : null,
		adjustedPremium: headline ? headline.adjusted : null,
		impliedGrowth: headline ? headline.implied : null,
		perMultiple
	};
}

function growthVerdict(implied, trailing) {
	if (implied === null || trailing === null) {
		return { text: 'Growth pricing n/a (insufficient growth data)', color: '#9aa4b2' };
	}

	const impliedText = `${(implied * 100).toFixed(0)}%`;
	const trailingText = `${(trailing * 100).toFixed(0)}%`;

	if (trailing > 0 && implied < trailing * 0.7) {
		return { text: `Priced for ~${impliedText} growth vs ${trailingText} trailing: market expects slowdown`, color: '#ffb74d' };
	}

	if (implied > Math.max(trailing, 0) * 1.3 + 0.02) {
		return { text: `Priced for ~${impliedText} growth vs ${trailingText} trailing: market expects acceleration`, color: '#ffb74d' };
	}

	return { text: `Priced for ~${impliedText} growth, in line with ${trailingText} trailing`, color: '#d0d0d0' };
}

function premiumRiskOf(premium, support) {
	if (premium === null || support === null) {
		return null;
	}

	// Exposure = drawdown to peer-median valuation = premium / (1 + premium); a 274% premium is a 73%
	// de-rating, not 274%. Weighted by how little the fundamentals argue against a re-rating.
	const exposure = premium > 0 ? premium / (1 + premium) : 0;
	return Math.min(100, exposure * 100 * (1 - support / 100));
}

function deratingOf(premium) {
	return premium === null || premium <= 0 ? null : -(premium / (1 + premium));
}

function premiumVerdict(premium, support) {
	if (premium === null) {
		return { text: 'Premium n/a (negative earnings or no peer data)', color: '#9aa4b2' };
	}

	const threshold = premiumThresholdPct / 100;
	const strong = support !== null && support >= supportStrongAt;
	const weak = support !== null && support < supportWeakBelow;

	if (premium >= threshold) {
		if (strong) {
			return { text: 'Premium, backed by fundamentals', color: '#4caf50' };
		}
		if (weak) {
			return { text: 'Premium not backed by fundamentals', color: '#ef5350' };
		}
		return { text: 'Premium, partly backed', color: '#ffb74d' };
	}

	if (premium <= -threshold) {
		if (strong) {
			return { text: 'Discount, fundamentals stronger', color: '#4caf50' };
		}
		if (weak) {
			return { text: 'Discount, fundamentals weaker', color: '#ef5350' };
		}
		return { text: 'Discount, fundamentals mixed', color: '#ffb74d' };
	}

	return { text: 'Priced in line with peers', color: '#d0d0d0' };
}

// ---------------------------------------------------------------------------
// Absolute risk flags
// ---------------------------------------------------------------------------

function riskFlagsAt(companyIndex, t, scores, premiumInfo) {
	const company = companies[companyIndex];
	const flags = [];

	const netDebtEbitda = valueAt(company, 'net_debt_ebitda', t);
	if (netDebtEbitda !== null && netDebtEbitda > maxNetDebtEbitda) {
		flags.push('Leverage');
	}

	const coverage = valueAt(company, 'ebit_to_interest_expense', t);
	if (coverage !== null && coverage < minInterestCoverage) {
		flags.push('Interest cover');
	}

	const altman = valueAt(company, 'altman_z_score', t);
	if (altman !== null && altman < minAltmanZ) {
		flags.push('Altman Z');
	}

	const currentRatio = valueAt(company, 'current_ratio', t);
	if (currentRatio !== null && currentRatio < minCurrentRatio) {
		flags.push('Liquidity');
	}

	const fcfTtm = ttmAt(company, 'free_cash_flow', t);
	if (fcfTtm !== null && fcfTtm < 0) {
		flags.push('Negative FCF');
	}

	const revenueYoy = yoyAt(company, 'revenue', t);
	if (revenueYoy !== null && revenueYoy < 0) {
		flags.push('Revenue shrinking');
	}

	const epsTtm = ttmAt(company, 'eps_diluted', t);
	if (epsTtm !== null && epsTtm <= 0) {
		flags.push('Unprofitable');
	}

	const sbcPercent = toPercent(valueAt(company, 'sbc_to_revenue', t));
	if (sbcPercent !== null && sbcPercent > maxSbcPercent) {
		flags.push('SBC dilution');
	}

	const dilution = dilutionAt(company, t);
	if (dilution !== null && dilution * 100 > maxDilutionPct) {
		flags.push('Share dilution');
	}

	const piotroski = valueAt(company, 'piotroski_f_score', t);
	if (piotroski !== null && piotroski <= maxPiotroski) {
		flags.push('Weak F-score');
	}

	const premiumRisk = premiumRiskOf(premiumInfo.premium, scores.Support);
	if (premiumRisk !== null && premiumRisk >= premiumRiskFlagAt) {
		flags.push('Unsupported premium');
	}

	const cyclePosition = marginCyclePositionAt(company, t);
	if (cyclePosition !== null && cyclePosition >= 0.95) {
		flags.push('Peak margins');
	}

	return flags;
}

function evaluateSubjectAt(t) {
	const scores = scoreCompany(0, t);
	const premiumInfo = premiumAt(0, t);
	const flags = riskFlagsAt(0, t, scores, premiumInfo);

	return Object.assign({
		t,
		premium: premiumInfo.premium,
		adjustedPremium: premiumInfo.adjustedPremium,
		impliedGrowth: premiumInfo.impliedGrowth,
		basis: premiumInfo.basis,
		basisReason: premiumInfo.basisReason,
		ownMultiple: premiumInfo.ownMultiple,
		peerMultiple: premiumInfo.peerMultiple,
		perMultiple: premiumInfo.perMultiple,
		premiumRisk: premiumRiskOf(premiumInfo.premium, scores.Support),
		flags
	}, scores);
}

// ---------------------------------------------------------------------------
// History (one row per subject report) and latest snapshot
// ---------------------------------------------------------------------------

const reportTimes = subject.revenue.map(record => record.t);
const history = reportTimes.map(evaluateSubjectAt);
const latest = history[history.length - 1];
const verdict = premiumVerdict(latest.premium, latest.Support);
const trailingRevenueGrowth = yoyAt(subject, 'revenue', latest.t);
const growthView = growthVerdict(latest.impliedGrowth, trailingRevenueGrowth);
const marginCycle = marginCyclePositionAt(subject, latest.t);

// ---------------------------------------------------------------------------
// Forward estimates for the subject (snapshot as of now)
// ---------------------------------------------------------------------------

const lastClose = close[close.length - 1];
const num = value => {
	const parsed = Number(value);
	return Number.isFinite(parsed) ? parsed : null;
};
const toSeconds = value => value > 1e11 ? Math.round(value / 1000) : value;
const earningsNormalized = earningsRecords
	.map(record => record ? {
		timestamp: num(record.timestamp) !== null ? toSeconds(num(record.timestamp)) : (num(record.date) !== null ? toSeconds(num(record.date)) : null),
		isFuture: record.isFuture === true,
		eps: num(record.eps),
		eps_est: num(record.eps_est !== undefined ? record.eps_est : record.epsEstimate),
		eps_surprise_percent: num(record.eps_surprise_percent !== undefined ? record.eps_surprise_percent : record.epsSurprisePercent)
	} : null)
	.filter(record => record && record.timestamp !== null)
	.map(record => Object.assign(record, { isFuture: record.isFuture || record.timestamp > current.now }))
	.sort((a, b) => a.timestamp - b.timestamp);
console.log(`Earnings: ${earningsNormalized.length} usable records, ${earningsNormalized.filter(record => record.isFuture).length} future`);
const pastEarnings = earningsNormalized.filter(record => !record.isFuture);
const futureEarnings = earningsNormalized.filter(record => record.isFuture);

const futureEstimates = futureEarnings.map(record => record.eps_est).filter(value => value !== null).slice(0, 4);
const forwardEps = futureEstimates.length >= 2 ? mean(futureEstimates) * 4 : null;
const ttmEps = ttmAt(subject, 'eps_diluted', latest.t);
const forwardPe = forwardEps !== null && forwardEps > 0 && lastClose > 0 ? lastClose / forwardEps : null;
const forwardEpsGrowth = forwardEps !== null && ttmEps !== null && ttmEps > 0 ? forwardEps / ttmEps - 1 : null;
const forwardPeg = forwardPe !== null && forwardEpsGrowth !== null && forwardEpsGrowth > 0 ? forwardPe / (forwardEpsGrowth * 100) : null;
const trailingPe = ttmEps !== null && ttmEps > 0 ? lastClose / ttmEps : null;

const recentSurprises = pastEarnings.slice(-4).map(record => record.eps_surprise_percent).filter(value => value !== null);
const surpriseAvg = recentSurprises.length > 0 ? mean(recentSurprises) : null;
const surpriseBeats = recentSurprises.filter(value => value > 0).length;

const nextEarnings = futureEarnings.length > 0 ? futureEarnings[0] : null;
const twoDigits = value => (value < 10 ? '0' : '') + String(value);
const dateText = timestamp => {
	const parts = time_of(timestamp);
	return `${parts.year}-${twoDigits(parts.month + 1)}-${twoDigits(parts.dayOfMonth)}`;
};
// Latest target per analyst firm within 90 days, then the median
const analystSince = current.now - 90 * DAY;
const latestTargetByFirm = {};
analystRecords
	.filter(record => record && Number.isFinite(Number(record.timestamp)) && Number(record.pTarget) > 0)
	.map(record => Object.assign({}, record, { timestamp: Number(record.timestamp) > 1e11 ? Number(record.timestamp) / 1000 : Number(record.timestamp) }))
	.filter(record => record.timestamp >= analystSince)
	.sort((a, b) => a.timestamp - b.timestamp)
	.forEach(record => { latestTargetByFirm[record.analystCompany || record.analystPerson || String(record.timestamp)] = record; });
const recentTargets = Object.keys(latestTargetByFirm).map(key => latestTargetByFirm[key]);
const medianTarget = recentTargets.length > 0 ? median(recentTargets.map(record => Number(record.pTarget))) : null;
const ratingCounts = { buy: 0, hold: 0, sell: 0 };
recentTargets.forEach(record => {
	const rating = String(record.ratingCurrent || '').toLowerCase();
	if (ratingCounts[rating] !== undefined) {
		ratingCounts[rating] += 1;
	}
});

const nextEarningsText = nextEarnings
	? `${dateText(nextEarnings.timestamp)} (${Math.max(0, Math.round((nextEarnings.timestamp - current.now) / DAY))}d)`
	: DASH;

// ---------------------------------------------------------------------------
// Reverse DCF: the FCF growth path the price implies, at a live discount rate
// ---------------------------------------------------------------------------

// Risk-free rate: 10-year Treasury from FRED (series name per TrendSpider's FRED list), else fallback input
async function fetchRiskFreeRate() {
	const candidates = [
		'Market Yield on U.S. Treasury Securities at 10-Year Constant Maturity, Quoted on an Investment Basis, DGS10 d',
		'Market Yield on U.S. Treasury Securities at 10-Year Constant Maturity, DGS10 d',
		'10-Year Treasury Constant Maturity Rate, DGS10 d',
		'10-Year Treasury Constant Maturity Rate, DGS10 mo',
		'10-Year Treasury Constant Maturity Rate, DGS10 d',
		'DGS10'
	];

	for (let i = 0; i < candidates.length; i += 1) {
		try {
			const data = await request.fred_series(candidates[i]);
			const series = data && Array.isArray(data.series) ? data.series.filter(point => Array.isArray(point) && Number.isFinite(point[1])) : [];

			if (series.length > 0) {
				return { rate: series[series.length - 1][1] / 100, source: 'FRED 10y' };
			}
		}
		catch (error) {
			// try the next name
		}
	}

	return { rate: riskFreeFallbackPct / 100, source: 'fallback' };
}

const riskFree = await fetchRiskFreeRate();
const discountRate = riskFree.rate + equityRiskPremiumPct / 100;
const terminalGrowth = dcfTerminalPct / 100;

// Growth in a given forecast year: constant (Flat) or fading linearly to terminal by year N (Fade)
function growthInYear(startGrowth, year) {
	if (dcfGrowthPath === 'Flat' || dcfFadeYears <= 1) {
		return startGrowth;
	}

	return startGrowth + (terminalGrowth - startGrowth) * (year - 1) / (dcfFadeYears - 1);
}

// Value per share of FCF that starts at fcfPerShare, follows growthInYear for N years,
// then grows at terminal forever, discounted at r.
function fadingDcfValue(fcfPerShare, startGrowth) {
	if (fcfPerShare === null || fcfPerShare <= 0 || discountRate <= terminalGrowth) {
		return null;
	}

	let value = 0;
	let fcf = fcfPerShare;

	for (let year = 1; year <= dcfFadeYears; year += 1) {
		fcf *= 1 + growthInYear(startGrowth, year);
		value += fcf / Math.pow(1 + discountRate, year);
	}

	value += (fcf * (1 + terminalGrowth) / (discountRate - terminalGrowth)) / Math.pow(1 + discountRate, dcfFadeYears);
	return value;
}

// Share of DCF value that comes from beyond the fade period (the terminal value)
function terminalShare(fcfPerShare, startGrowth) {
	const total = fadingDcfValue(fcfPerShare, startGrowth);

	if (total === null || total <= 0) {
		return null;
	}

	let fcf = fcfPerShare;

	for (let year = 1; year <= dcfFadeYears; year += 1) {
		fcf *= 1 + growthInYear(startGrowth, year);
	}

	const terminal = (fcf * (1 + terminalGrowth) / (discountRate - terminalGrowth)) / Math.pow(1 + discountRate, dcfFadeYears);
	return terminal / total;
}

// Solve for the starting growth that makes the DCF equal the price. Returns null when there is no
// positive cash flow to discount; +/-Infinity when the price sits outside the search band.
function impliedStartGrowth(fcfPerShare, price) {
	if (fcfPerShare === null || fcfPerShare <= 0 || !(price > 0)) {
		return null;
	}

	let lowGrowth = -0.5;
	let highGrowth = 1.5;

	if (fadingDcfValue(fcfPerShare, highGrowth) < price) {
		return Infinity;
	}

	if (fadingDcfValue(fcfPerShare, lowGrowth) > price) {
		return -Infinity;
	}

	for (let step = 0; step < 60; step += 1) {
		const midGrowth = (lowGrowth + highGrowth) / 2;
		if (fadingDcfValue(fcfPerShare, midGrowth) < price) {
			lowGrowth = midGrowth;
		}
		else {
			highGrowth = midGrowth;
		}
	}

	return (lowGrowth + highGrowth) / 2;
}

// First candle after t; the last candle when t is beyond the chart (a report lagged past today)
function candleIndexAfter(t) {
	for (let i = 0; i < time.length; i += 1) {
		if (time[i] > t) {
			return i;
		}
	}

	return time.length - 1;
}

// FCF per share from the platform's own P/FCF ratio and the price at that report date, which
// avoids any units mismatch between raw FCF and share counts.
function fcfPerShareAt(t) {
	const pfcf = valueAt(subject, 'pfcf_ratio_ttm', t);
	const candleIndex = candleIndexAfter(t);

	if (pfcf === null || pfcf <= 0 || candleIndex < 0) {
		return null;
	}

	return close[candleIndex] / pfcf;
}

const fcfPerShareNow = (() => {
	const pfcf = valueAt(subject, 'pfcf_ratio_ttm', latest.t);
	const reportIndex = candleIndexAfter(latest.t);
	return pfcf !== null && pfcf > 0 && reportIndex >= 0 ? close[reportIndex] / pfcf : null;
})();
const priceNow = close[close.length - 1];
const impliedGrowthNow = impliedStartGrowth(fcfPerShareNow, priceNow);
const valueAtRecentGrowth = trailingRevenueGrowth === null ? null : fadingDcfValue(fcfPerShareNow, Math.min(growthCapPct / 100, Math.max(-0.5, trailingRevenueGrowth)));

function impliedGrowthText(value) {
	if (value === null) {
		return 'n/a';
	}
	if (value === Infinity) {
		return '>150%';
	}
	if (value === -Infinity) {
		return '<-50%';
	}
	return fmtPctComputed(value);
}

function reverseDcfVerdict(implied, recent) {
	if (implied === null) {
		return { text: 'Not priced on current cash flow (no positive FCF)', color: '#9aa4b2' };
	}

	if (!Number.isFinite(implied)) {
		return { text: `Priced for ${impliedGrowthText(implied)} FCF growth`, color: '#d0d0d0' };
	}

	const impliedAverage = dcfGrowthPath === 'Flat' ? implied : (implied + terminalGrowth) / 2;

	if (recent === null) {
		return { text: `Priced for ~${fmtPctComputed(impliedAverage)} avg FCF growth over ${dcfFadeYears}y`, color: '#d0d0d0' };
	}

	const recentClamped = Math.min(growthCapPct / 100, Math.max(-0.5, recent));
	const recentAverage = dcfGrowthPath === 'Flat' ? recentClamped : (recentClamped + terminalGrowth) / 2;
	const gap = impliedAverage - recentAverage;
	const pct0 = value => `${(value * 100).toFixed(0)}%`;
	const pair = `${pct0(impliedAverage)} vs ${pct0(recentAverage)} recent`;

	const threshold = dcfGrowthPath === 'Flat' ? 0.05 : 0.025;

	if (gap <= -threshold) {
		return { text: `Market expects slowdown: ${pair}`, color: '#4caf50' };
	}

	if (gap >= threshold) {
		return { text: `Price needs acceleration: ${pair}`, color: '#ef5350' };
	}

	return { text: `Priced for current growth: ${pair}`, color: '#d0d0d0' };
}

// Average growth over the fade period (linear fade from start to terminal): the number people think in
const averageFadeGrowth = start => (start === null || !Number.isFinite(start)) ? null : (dcfGrowthPath === 'Flat' ? start : (start + terminalGrowth) / 2);
const impliedAverageNow = averageFadeGrowth(impliedGrowthNow);
const terminalShareNow = impliedGrowthNow !== null && Number.isFinite(impliedGrowthNow) ? terminalShare(fcfPerShareNow, impliedGrowthNow) : null;
const recentForDcf = trailingRevenueGrowth === null ? null : Math.min(growthCapPct / 100, Math.max(-0.5, trailingRevenueGrowth));
const recentAverageNow = recentForDcf === null ? null : averageFadeGrowth(recentForDcf);
const reverseDcfView = reverseDcfVerdict(impliedGrowthNow, trailingRevenueGrowth);

// History for scanner signals: implied growth at each report date, at that date's price
const impliedGrowthHistory = reportTimes.map(t => {
	const candleIndex = candleIndexAfter(t);
	const implied = candleIndex >= 0 ? impliedStartGrowth(fcfPerShareAt(t), close[candleIndex]) : null;
	const recent = yoyAt(subject, 'revenue', t);
	return implied === null || !Number.isFinite(implied) || recent === null ? null : implied - recent;
});

// ---------------------------------------------------------------------------
// Drivers: why the stock deserves (or does not deserve) its premium
// ---------------------------------------------------------------------------

const drivers = [];

SUPPORT_CATEGORIES.forEach(category => {
	CATEGORIES[category].forEach(metric => {
		const own = metric.get(subject, latest.t);
		const rank = metricRankAt(metric, 0, latest.t);

		if (own === null || rank === null) {
			return;
		}

		const peerMedian = median(companies.slice(1).map(company => metric.get(company, latest.t)));
		drivers.push({ rank, text: `${metric.label} ${metric.fmt(own)} vs ${metric.fmt(peerMedian)}` });
	});
});

const driverCount = tableDetail === 'Compact' ? 2 : 3;
const supports = drivers.filter(driver => driver.rank >= 75).sort((a, b) => b.rank - a.rank).slice(0, driverCount);
const detractors = drivers.filter(driver => driver.rank <= 25).sort((a, b) => a.rank - b.rank).slice(0, driverCount);

// ---------------------------------------------------------------------------
// Signals for Scanner / Alerts / Strategy Tester (historical, point-in-time)
// ---------------------------------------------------------------------------

function landSeries(values) {
	return interpolate_sparse_series(land_points_onto_series(reportTimes, values, time, 'gt'), 'constant');
}

const premiumPctSeries = landSeries(history.map(row => row.premium === null ? null : row.premium * 100));
const supportSeries = landSeries(history.map(row => row.Support));
const premiumRiskSeries = landSeries(history.map(row => row.premiumRisk));
const flagCountSeries = landSeries(history.map(row => row.flags.length));

const impliedGapSeries = landSeries(impliedGrowthHistory);
register_signal(for_every(impliedGapSeries, gap => gap !== null && gap <= -0.05), 'Priced for slowdown (reverse DCF)');
register_signal(for_every(impliedGapSeries, gap => gap !== null && gap >= 0.05), 'Priced for acceleration (reverse DCF)');
register_signal(for_every(premiumPctSeries, value => value !== null && value >= premiumThresholdPct), 'Premium to industry');
register_signal(for_every(premiumPctSeries, value => value !== null && value <= -premiumThresholdPct), 'Discount to industry');
register_signal(for_every(premiumRiskSeries, risk => risk !== null && risk >= premiumRiskFlagAt), 'Unsupported premium');
const adjustedPctSeries = landSeries(history.map(row => row.adjustedPremium === null ? null : row.adjustedPremium * 100));
register_signal(for_every(adjustedPctSeries, value => value !== null && value >= premiumThresholdPct), 'Overpriced for growth');
register_signal(for_every(adjustedPctSeries, value => value !== null && value <= -premiumThresholdPct), 'Underpriced for growth');
register_signal(
	for_every(premiumPctSeries, supportSeries, (value, support) => value !== null && support !== null && value <= -premiumThresholdPct && support >= supportStrongAt),
	'Discount with strong support'
);
register_signal(for_every(supportSeries, support => support !== null && support >= supportStrongAt), 'Strong fundamentals vs industry');
register_signal(for_every(flagCountSeries, count => count !== null && count >= 3), 'Risk flags >= 3');

// Peer-set provenance as scanner signals: run the Market Scanner on these across an index to list
// the names whose comparison rests on a fallback or on TrendSpider's industry label alone.
const peerSourceKind = peerSet.source.indexOf('group:') === 0 ? 'group' : (peerSet.source.indexOf('industry:') === 0 ? 'industry' : (peerSet.source === 'manual list' || peerSet.source === 'FMP peers' ? 'custom' : 'fallback'));
register_signal(for_every(close, () => peerSourceKind === 'fallback'), 'Peers: fallback used');
register_signal(for_every(close, () => peerSourceKind === 'industry'), 'Peers: industry map');
register_signal(for_every(close, () => peerSourceKind === 'group'), 'Peers: narrative group');
register_signal(
	for_every(flagCountSeries, shift(flagCountSeries, 1), (count, prev) => count !== null && prev !== null && count > prev),
	'New risk flag added'
);

// One hidden, empty series so the indicator always has a painted line and never touches the price scale
// One hidden, empty series so the indicator always has a painted line and never touches the price scale
paint(constants.empty_series, { name: 'Industry premium', hidden: true, hideInLegend: true, editorHidden: true });

// ---------------------------------------------------------------------------
// On-chart table (4 columns: metric | subject | industry median | difference)
// ---------------------------------------------------------------------------

const TABLE = {
	title: '#ffd600',
	titleBg: 'rgba(255,214,0,0.10)',
	header: '#ffffff',
	label: '#aab4c2',
	value: '#eef1f5',
	median: '#c3cbd6',
	muted: '#7d8794',
	section: '#8fc9f9',
	sectionBg: 'rgba(143,201,249,0.10)',
	headerBg: 'rgba(255,255,255,0.08)',
	stripeBg: 'rgba(255,255,255,0.035)',
	good: '#4caf50',
	bad: '#ef5350',
	warn: '#ffb74d',
	subjectBg: 'rgba(35,135,228,0.14)',
	subjectHeaderBg: 'rgba(35,135,228,0.32)'
};

const COLUMNS = 4;

function cell(text, color, background) {
	return {
		text: String(text === null || text === undefined ? '' : text),
		color: color || TABLE.value,
		background: background || 'transparent',
		paddingTop: 1,
		paddingBottom: 1,
		paddingLeft: 6,
		paddingRight: 6
	};
}

function row(cells) {
	while (cells.length < COLUMNS) {
		cells.push(cell(''));
	}
	return { cells };
}

function textRow(text, color, background) {
	return row([cell(text, color, background)]);
}

// Overlay cells do not wrap, so long lines are split at word boundaries into continuation rows
// (indented) to keep the first column, and therefore the table, narrow.
const WRAP_AT = 34;

function wrappedRows(text, color, background) {
	// parenthetical groups stay together so "(premium risk 28)" never splits across lines
	const words = String(text).match(/([^)]*)|S+/g) || [];
	const wrappedLines = [];
	let lineText = '';

	words.forEach(word => {
		if (lineText.length > 0 && lineText.length + 1 + word.length > WRAP_AT) {
			wrappedLines.push(lineText);
			lineText = '  ' + word;
		}
		else {
			lineText = lineText.length > 0 ? `${lineText} ${word}` : word;
		}
	});

	if (lineText.length > 0) {
		wrappedLines.push(lineText);
	}

	return wrappedLines.map(part => textRow(part, color, background));
}

function pushWrapped(text, color, background) {
	wrappedRows(text, color, background).forEach(item => rows.push(item));
}

function sectionRow(text) {
	return row([cell(text, TABLE.section, TABLE.sectionBg), cell('', TABLE.value, TABLE.sectionBg), cell('', TABLE.value, TABLE.sectionBg), cell('', TABLE.value, TABLE.sectionBg)]);
}

function rankColor(rank) {
	if (rank === null) {
		return TABLE.value;
	}
	return rank >= 75 ? TABLE.good : (rank <= 25 ? TABLE.bad : TABLE.value);
}

let metricRowCount = 0;

function metricRow(metric) {
	metricRowCount += 1;
	const stripe = metricRowCount % 2 === 0 ? TABLE.stripeBg : null;
	const own = metric.get(subject, latest.t);
	const peerMedian = median(companies.slice(1).map(company => metric.get(company, latest.t)));
	const rank = metricRankAt(metric, 0, latest.t);
	const diff = metric.diff(own, peerMedian);
	const color = rankColor(rank);
	const multipleItem = metric.multipleLabel ? latest.perMultiple.find(item => item.label === metric.multipleLabel) : null;
	const adjustedText = !compactTable && multipleItem && multipleItem.adjusted !== null ? ` (adj ${fmtSignedPct(multipleItem.adjusted)})` : '';

	return row([
		cell(metric.label, TABLE.label, stripe),
		cell(metric.fmt(own), own === null ? TABLE.muted : color, TABLE.subjectBg),
		cell(metric.fmt(peerMedian), peerMedian === null ? TABLE.muted : TABLE.median, stripe),
		cell(diff === null ? DASH : `${metric.fmtDiff(diff)}${adjustedText}`, diff === null ? TABLE.muted : color, stripe)
	]);
}

const scoreColor = score => score === null ? TABLE.muted : (score >= supportStrongAt ? TABLE.good : (score < supportWeakBelow ? TABLE.bad : TABLE.value));
const riskColor = risk => risk === null ? TABLE.muted : (risk >= premiumRiskFlagAt ? TABLE.bad : (risk >= premiumRiskFlagAt / 2 ? TABLE.warn : TABLE.good));
const flagColor = count => count >= 3 ? TABLE.bad : (count >= 1 ? TABLE.warn : TABLE.good);
const premiumColor = premium => premium === null ? TABLE.muted : (premium >= premiumThresholdPct / 100 ? TABLE.bad : (premium <= -premiumThresholdPct / 100 ? TABLE.good : TABLE.value));

const usedPeerTickers = usablePeers.map(company => company.ticker);
const rows = [];

const comparisonLabel = peerSet.source.indexOf('group:') === 0
	? peerSet.source.slice(7).replace(/_/g, ' ').replace(/ and /g, ' & ')
	: (peerSet.source.indexOf('industry:') === 0 ? 'industry' : (peerSet.source.indexOf('sector:') === 0 ? 'sector' : (peerSet.source === 'manual list' ? 'chosen peers' : (peerSet.source === 'FMP peers' ? 'FMP peers' : 'market'))));
rows.push(textRow(`${subject.ticker} vs ${comparisonLabel} | Q ${dateText(latest.t - reportLagDays * DAY)}`, TABLE.title, TABLE.titleBg));
if (nextEarnings) {
	rows.push(textRow(`Next earnings ${nextEarningsText}`, TABLE.median));
}
pushWrapped(`vs ${usedPeerTickers.join(' ')}`, TABLE.median);
rows.push(row([cell('', TABLE.label, TABLE.headerBg), cell(subject.ticker, TABLE.header, TABLE.subjectHeaderBg), cell('Peer median', TABLE.median, TABLE.headerBg), cell('vs median', TABLE.median, TABLE.headerBg)]));

if (!compactTable) {
	rows.push(sectionRow('Premium to industry'));
}
const multipleRatio = latest.premium === null ? DASH : `${(1 + latest.premium).toFixed(1)}x`;
const basisLabel = latest.basis === 'EV/Sales' ? `EV/Sales vs peers (${latest.basisReason})` : 'P/E vs peers';
rows.push(row([
	cell(basisLabel, TABLE.label),
	cell(fmtMultiple(latest.ownMultiple), premiumColor(latest.premium), TABLE.subjectBg),
	cell(fmtMultiple(latest.peerMultiple), TABLE.median),
	cell(latest.premium === null ? DASH : `${fmtSignedPct(latest.premium)} (${multipleRatio})`, premiumColor(latest.premium))
]));
if (!compactTable) {
	rows.push(row([cell('De-rating to peer median', TABLE.label), cell(fmtSignedPct(deratingOf(latest.premium)), deratingOf(latest.premium) === null ? TABLE.muted : TABLE.bad, TABLE.subjectBg), cell(''), cell('')]));
	rows.push(row([cell('Premium after growth', TABLE.label), cell(fmtSignedPct(latest.adjustedPremium), premiumColor(latest.adjustedPremium), TABLE.subjectBg), cell('vs clamped trailing', TABLE.muted), cell('')]));
}
if (!compactTable) {
	rows.push(sectionRow('What the price implies (reverse DCF)'));
}
rows.push(row([cell(`Priced for avg growth (${dcfFadeYears}y)`, TABLE.label), cell(impliedAverageNow === null ? impliedGrowthText(impliedGrowthNow) : fmtPctComputed(impliedAverageNow), impliedGrowthNow === null ? TABLE.muted : reverseDcfView.color, TABLE.subjectBg), cell(impliedAverageNow === null ? '' : (dcfGrowthPath === 'Flat' ? `${(discountRate * 100).toFixed(1)}% disc` : `from ~${impliedGrowthText(impliedGrowthNow)}`), TABLE.median), cell('')]));
rows.push(row([cell(recentForDcf === null ? 'If recent growth holds' : `If ${(recentForDcf * 100).toFixed(0)}%${recentForDcf < trailingRevenueGrowth - 1e-9 ? ' (capped)' : ''} holds ${dcfFadeYears}y`, TABLE.label), cell(recentAverageNow === null ? DASH : `${fmtPctComputed(recentAverageNow)} avg`, TABLE.value, TABLE.subjectBg), cell(valueAtRecentGrowth === null ? '' : `$${valueAtRecentGrowth.toFixed(0)}, ${fmtSignedPct(valueAtRecentGrowth / priceNow - 1)}`, valueAtRecentGrowth === null ? TABLE.muted : (valueAtRecentGrowth >= priceNow ? TABLE.good : TABLE.bad)), cell('')]));
if (!compactTable || forwardEpsGrowth !== null) {
	rows.push(row([cell('Consensus EPS growth (4q)', TABLE.label), cell(forwardEpsGrowth === null ? 'no estimates in feed' : fmtPctComputed(forwardEpsGrowth), forwardEpsGrowth === null ? TABLE.muted : TABLE.value, TABLE.subjectBg), cell(forwardPe === null ? '' : `fwd P/E ${fmtMultiple(forwardPe)}`, TABLE.median), cell('')]));
}
if (!compactTable || medianTarget !== null) {
	rows.push(row([cell('Analyst target (median)', TABLE.label), cell(medianTarget === null ? 'none in 90d' : medianTarget.toFixed(2), medianTarget === null ? TABLE.muted : (medianTarget >= priceNow ? TABLE.good : TABLE.bad), TABLE.subjectBg), cell(medianTarget === null ? '' : `${fmtSignedPct(medianTarget / priceNow - 1)}; ${ratingCounts.buy}B/${ratingCounts.hold}H/${ratingCounts.sell}S`, TABLE.median), cell('')]));
}
if (!compactTable) {
	rows.push(row([cell('Discount rate', TABLE.label), cell(`${(discountRate * 100).toFixed(1)}%`, TABLE.value, TABLE.subjectBg), cell(`10y ${(riskFree.rate * 100).toFixed(2)}% (${riskFree.source}) + ${equityRiskPremiumPct}% ERP`, TABLE.median), cell('')]));
}
pushWrapped(reverseDcfView.text, reverseDcfView.color);
rows.push(row([cell('Fundamentals vs peers', TABLE.label), cell(fmtInt(latest.Support), scoreColor(latest.Support), TABLE.subjectBg), cell(`G${fmtInt(latest.Growth)} Q${fmtInt(latest.Quality)} B${fmtInt(latest.Safety)}`, TABLE.median), cell('')]));
if (compactTable) {
	pushWrapped(`${verdict.text} (risk ${fmtInt(latest.premiumRisk)})`, verdict.color);
}
else {
	rows.push(row([cell('Premium risk', TABLE.label), cell(fmtInt(latest.premiumRisk), riskColor(latest.premiumRisk), TABLE.subjectBg), cell('', TABLE.muted), cell('')]));
	pushWrapped(verdict.text, verdict.color);
}

const growthUsedItems = latest.perMultiple.filter(item => item.growthUsed !== null);

if (!compactTable && growthUsedItems.length > 0) {
	const clampedAny = growthUsedItems.some(item => item.growthRaw !== null && Math.abs(item.growthRaw - item.growthUsed) > 1e-9);
	const revItem = growthUsedItems.find(item => item.growthLabel === 'revenue');
	const epsItem = growthUsedItems.find(item => item.growthLabel === 'EPS');
	const parts = [];
	if (revItem) {
		parts.push(`rev ${(revItem.growthUsed * 100).toFixed(0)}%`);
	}
	if (epsItem) {
		parts.push(`EPS ${(epsItem.growthUsed * 100).toFixed(0)}%`);
	}
	rows.push(row([cell(`Growth used${clampedAny ? ' (clamped)' : ''}`, TABLE.label), cell(parts.join(' '), TABLE.muted, TABLE.subjectBg), cell(`cap ${growthFloorPct}-${growthCapPct}%`, TABLE.muted), cell('')]));
}

const hasForwardData = forwardPe !== null || surpriseAvg !== null || nextEarnings !== null;

if (hasForwardData && !compactTable) {
	rows.push(sectionRow('Forward (consensus, today)'));
	rows.push(row([cell('Forward P/E', TABLE.label), cell(fmtMultiple(forwardPe), TABLE.value, TABLE.subjectBg), cell(trailingPe === null ? DASH : `now ${fmtMultiple(trailingPe)}`, TABLE.median), cell('')]));

	if (!compactTable) {
		rows.push(row([cell('Fwd EPS growth', TABLE.label), cell(fmtPctComputed(forwardEpsGrowth), forwardEpsGrowth === null ? TABLE.muted : (forwardEpsGrowth > 0 ? TABLE.good : TABLE.bad), TABLE.subjectBg), cell(forwardEps === null ? DASH : `fwd EPS ${forwardEps.toFixed(2)}`, TABLE.muted), cell('')]));
		rows.push(row([cell('PEG (fwd)', TABLE.label), cell(fmtRatio(forwardPeg), forwardPeg === null ? TABLE.muted : (forwardPeg <= 1 ? TABLE.good : (forwardPeg >= 2 ? TABLE.bad : TABLE.value)), TABLE.subjectBg), cell(''), cell('')]));
	}

	rows.push(row([cell('EPS surprise avg (4q)', TABLE.label), cell(surpriseAvg === null ? DASH : `${surpriseAvg >= 0 ? '+' : ''}${surpriseAvg.toFixed(1)}%`, surpriseAvg === null ? TABLE.muted : (surpriseAvg > 0 ? TABLE.good : TABLE.bad), TABLE.subjectBg), cell(recentSurprises.length > 0 ? `${surpriseBeats}/${recentSurprises.length} beats` : DASH, TABLE.muted), cell('')]));
	rows.push(row([cell('Next earnings', TABLE.label), cell(nextEarningsText, TABLE.value, TABLE.subjectBg), cell(''), cell('')]));
}

const sectionTitles = { Value: 'Valuation', Growth: 'Growth', Quality: 'Quality', Safety: 'Balance sheet' };


CATEGORY_NAMES.forEach(category => {
	const metrics = CATEGORIES[category].filter(metric => tableDetail === 'Full' || (tableDetail === 'Standard' && metric.compact !== null) || (tableDetail === 'Compact' && metric.compact));

	if (metrics.length === 0) {
		return;
	}

	if (tableDetail !== 'Compact') {
		rows.push(sectionRow(`${sectionTitles[category]}  (score ${fmtInt(latest[category])})`));
	}

	metrics.forEach(metric => rows.push(metricRow(metric)));
});

if (tableDetail === 'Compact') {
	rows.push(sectionRow('Why (vs peers)'));
}
else {
	rows.push(sectionRow('Why (vs peers)'));
}

supports.forEach(driver => pushWrapped(`▲ ${driver.text}`, TABLE.good));

if (marginCycle !== null && marginCycle >= 0.9) {
	pushWrapped('⚠ Op margin at 3y high: earnings flattered', TABLE.warn);
}
detractors.forEach(driver => pushWrapped(`▼ ${driver.text}`, TABLE.bad));

if (supports.length === 0 && detractors.length === 0) {
	rows.push(textRow('No metric stands out vs industry', TABLE.label));
}

pushWrapped(`Risk flags (${latest.flags.length}): ${latest.flags.length > 0 ? latest.flags.join(', ') : 'none'}`, flagColor(latest.flags.length));

paint_overlay('IndustryPremium', {
	position: tablePosition,
	offset_x: tableOffsetX,
	offset_y: tableOffsetY,
	order: 'above_all'
}, {
	background: 'rgba(10,10,20,0.88)',
	rows
});

// ---------------------------------------------------------------------------
// Console summary
// ---------------------------------------------------------------------------

console.log(`${subject.ticker}: premium ${fmtSignedPct(latest.premium)}, support ${fmtInt(latest.Support)}, premium risk ${fmtInt(latest.premiumRisk)}. ${verdict.text}. Ratio units: ${ratiosArePercent ? 'percent' : 'fraction'}.`);
console.log(`Forward P/E ${fmtMultiple(forwardPe)} (fwd EPS ${forwardEps === null ? DASH : forwardEps.toFixed(2)}, ttm EPS ${ttmEps === null ? DASH : ttmEps.toFixed(2)}), next earnings ${nextEarningsText}`);
console.log(`Flags: ${latest.flags.join(', ') || 'none'}`);