Splurge vs Invest: What a Purchase Would Be Worth Invested

JSCastellano · study · 985 行 · 点赞 13 · TradingView 原页

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

Pine Script

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © 2026 J. Stephen Castellano (JSCastellano)
//@version=6
// Hypothetical daily-chart calculator. No orders or alerts.
// Start values and monthly contributions remain provisional until their bars close.
// CPI is a calendar-month deflator; historical month values are not publication-time signals.
indicator("Splurge vs Invest: What a Purchase Would Be Worth Invested", shorttitle = "Splurge vs Invest", overlay = true, max_labels_count = 500, behind_chart = false)
 
// 1. ENUMS AND INPUTS
 
enum Cat
    all = "All (headline items)"
    food = "Food & drink"
    habits = "Daily habits (per year)"
    tech = "Gaming & tech"
    style = "Style"
    events = "Concerts & sports"
    fitness = "Fitness & golf"
    pets = "Pets"
    travel = "Travel"
    love = "Love & weddings"
    opportunity = "Opportunity costs"
    housing = "Housing"
    cars = "Cars"
    over = "Over the top"
 
enum StartMode
    years5 = "5 years ago"
    years10 = "10 years ago"
    years20 = "20 years ago"
    firstBar = "First bar on the chart"
    pickDate = "Pick a date"
 
enum ItemType
    oneTime = "One-time"
    perYear = "Per year"
 
enum TableFormat
    detailed = "Detailed"
    compact = "Compact"
 
enum TextSize
    small = "Small"
    medium = "Medium"
    large = "Large"
 
enum MaType
    sma = "SMA"
    ema = "EMA"
    wma = "WMA"
    rma = "RMA"
    vwma = "VWMA"
 
enum CandleColors
    pastel = "Pastel mint and pink"
    whiteGrey = "White and grey"
    ink = "Ink"
    money = "Money green and gold"
    classic = "TradingView classic"
    tealCoral = "Soft teal and coral"
    blackGold = "Black and gold"
    neon = "Neon (dark charts)"
 
enum TableColors
    pastel = "Pastel mint and pink"
    money = "Money green and gold"
    fadeGrey = "Fade VWAP grey"
    midnight = "Midnight blue"
    light = "Light card"
    blackGold = "Black and gold"
    purple = "Purple and pink"
 
enum TablePos
    topRight = "Top right"
    middleRight = "Middle right"
    bottomRight = "Bottom right"
    topLeft = "Top left"
    bottomLeft = "Bottom left"
 
enum FoodPick
    dunkin_donut = "Dunkin' donut"
    egg_mcmuffin = "Egg McMuffin"
    grande_latte = "Grande latte"
    big_mac_meal = "Big Mac meal"
    nyc_avocado_toast = "NYC avocado toast"
    chain_steakhouse_dinner_for_two = "Chain steakhouse dinner for two"
    nyc_steakhouse_dinner_for_two = "NYC steakhouse dinner for two"
    nyc_club_bottle_service = "NYC club bottle service"
 
enum HabitsPick
    powerball_every_drawing = "Powerball, every drawing"
    four_streaming_services = "Four streaming services"
    a_latte_every_workday = "A latte every workday"
    lunch_out_every_workday = "Lunch out every workday"
    line_sitter_cronuts_weekly = "Line-sitter Cronuts, weekly"
    food_delivery_twice_a_week = "Food delivery twice a week"
 
enum TechPick
    apple_polishing_cloth = "Apple Polishing Cloth"
    gta_vi_ultimate_edition = "GTA VI Ultimate edition"
    item_10_hours_of_fortnite_coaching = "10 hours of Fortnite coaching"
    nintendo_switch_2 = "Nintendo Switch 2"
    xbox_series_x_1tb = "Xbox Series X 1TB"
    iphone_18_pro_max = "iPhone 18 Pro Max"
    rtx_5090_gaming_pc = "RTX 5090 gaming PC"
 
enum StylePick
    labubu_blind_box = "Labubu blind box"
    lululemon_align_leggings = "lululemon Align leggings"
    air_jordan_1_retro_high_og = "Air Jordan 1 Retro High OG"
    sneaker_drop_line_sitter = "Sneaker-drop line-sitter"
    canada_goose_parka = "Canada Goose parka"
    louis_vuitton_neverfull_mm = "Louis Vuitton Neverfull MM"
    rolex_submariner = "Rolex Submariner"
    hermes_birkin_25 = "Hermès Birkin 25"
 
enum EventsPick
    priciest_nfl_stadium_beer = "Priciest NFL stadium beer"
    stadium_tour_ticket = "Stadium tour ticket"
    broadway_for_two = "Broadway for two"
    coachella_weekend_pass = "Coachella weekend pass"
    yankees_fantasy_camp_week = "Yankees Fantasy Camp week"
    super_bowl_ticket = "Super Bowl ticket"
    knicks_courtside_seat = "Knicks courtside seat"
 
enum FitnessPick
    goat_yoga_class = "Goat yoga class"
    dozen_pro_v1_golf_balls = "Dozen Pro V1 golf balls"
    topgolf_night_for_four = "Topgolf night for four"
    peloton_bike = "Peloton Bike"
    round_at_pebble_beach = "Round at Pebble Beach"
    custom_fitted_golf_clubs = "Custom-fitted golf clubs"
    equinox_membership = "Equinox membership"
 
enum PetsPick
    pumpkin_dog_costume = "Pumpkin dog costume"
    pet_psychic_session = "Pet psychic session"
    french_bulldog_puppy = "French bulldog puppy"
    nyc_dog_walker = "NYC dog walker"
 
enum TravelPick
    item_27_airport_beer = "$27 airport beer"
    big_idaho_potato_hotel_night = "Big Idaho Potato Hotel night"
    camping_week_in_maine = "Camping week in Maine"
    bachelor_ette_weekend = "Bachelor(ette) weekend"
    bali_week_for_two = "Bali week for two"
    disney_world_week_for_four = "Disney World week for four"
    europe_for_two_two_weeks = "Europe for two, two weeks"
    business_class_to_tokyo_for_two = "Business class to Tokyo for two"
    vail_ski_week_for_two = "Vail ski week for two"
    luxury_cruise_week_for_two = "Luxury cruise week for two"
    luxury_disney_week_for_four = "Luxury Disney week for four"
 
enum LovePick
    dozen_red_roses_delivered = "Dozen red roses, delivered"
    elvis_wedding_in_vegas = "Elvis wedding in Vegas"
    wedding_dress_worn_once = "Wedding dress worn once"
    mikimoto_pearl_necklace = "Mikimoto pearl necklace"
    backyard_wedding = "Backyard wedding"
    item_2_carat_engagement_ring = "2-carat engagement ring"
    average_us_wedding = "Average US wedding"
    ny_botanical_garden_wedding = "NY Botanical Garden wedding"
 
enum OpportunityPick
    binge_the_office_twice = "Binge The Office twice"
    tiktok_47_minutes_a_day = "TikTok, 47 minutes a day"
    a_year_of_fortnite_not_work = "A year of Fortnite, not work"
    startup_equity_that_busts = "Startup equity that busts"
 
enum HousingPick
    closet_organizer_5_hours = "Closet organizer, 5 hours"
    storage_unit = "Storage unit"
    ues_1_bedroom_a_year_s_rent = "UES 1-bedroom, a year's rent"
    ues_3_bedroom_a_year_s_rent = "UES 3-bedroom, a year's rent"
 
enum CarsPick
    getting_towed_in_manhattan = "Getting towed in Manhattan"
    manhattan_garage_parking = "Manhattan garage parking"
    toyota_camry = "Toyota Camry"
    bmw_m2_fully_loaded = "BMW M2, fully loaded"
    porsche_911_carrera = "Porsche 911 Carrera"
    lamborghini_revuelto = "Lamborghini Revuelto"
 
enum OverPick
    times_square_billboard_photo = "Times Square billboard photo"
    private_jet_nyc_to_miami = "Private jet NYC to Miami"
    superyacht_week = "Superyacht week"
    virgin_galactic_seat = "Virgin Galactic seat"
    duct_taped_banana_artwork = "Duct-taped banana artwork"
 
const string G_MAIN = "Splurge"
const string G_SHOW = "Show lines"
const string G_PICKS = "Headline items"
const string G_MA = "Moving averages"
const string G_DISPLAY = "Other Display Options"
 
const string CAT_TIP = "Default: Food & drink, with NYC Avocado Toast as its headline item. Which purchases the table shows. All: one headline item per category (choose them under Headline items), cheapest first. A category: all its items, its headline item first. The selected item (highlighted) is Your item when it has a cost, otherwise the category's headline item; All has none unless Your item has a cost. Compact rows show the price at the start date → what that money would be worth now. Per-year items (/yr) are invested a twelfth each month from the start."
 
const string START_TIP = "The day the money would have been invested instead, at that day's close. 5, 10 or 20 years ago count back from today's date, so the start moves forward a day each day. First bar on the chart: the oldest bar loaded. Pick a date: the date on this row (greyed out otherwise). If the chart's history starts later, its first bar is used and the Warnings row says so."
 
const string ADJ_TIP = "Adjust prices for inflation: each price is today's price scaled back to the start month with the US consumer price index (CPI-U, FRED:CPIAUCNS), so it has the same buying power then. That isn't what the exact item cost then; some didn't exist. Off: today's price is invested on the start date. Reinvest dividends: on, dividends are reinvested on their ex-dates (the script reads dividend-adjusted prices, whatever the chart's ADJ setting); off, price change only. The candles show prices without dividends unless the chart's ADJ button is on, so the table can show more growth than the candles."
 
const string MINE_TIP = "Your own purchase: a name, today's cost in US dollars, and One-time or Per year (a yearly cost, invested a twelfth each month from the start). With a cost above 0 it becomes the selected item: shown first and highlighted, or on its own with Show all items off. Its cost is scaled with the latest CPI, not the list's September 2026 anchor."
 
const string PICK_TIP = "This category's headline item. The All view lists the 13 headline items, and the Detailed format draws its examples from them. It's also the selected item (highlighted) when this category is chosen and Your item has no cost. Prices are US prices from October 2026, carried forward with CPI."
 
const string SHOW_TIP = "Start line: a flat line at the start day's close, with a START marker. Inflation line: where the price would be if it had only kept up with inflation since the start; candles above it are ahead of inflation, below it behind. MA lines: the moving averages set under Moving averages. Candles: paints the candles in the scheme chosen under Candle colors, over the chart's own; off shows the chart's candles. Info table: the results table."
 
const string LABEL_TIP = "Names each line at its right end in the line's default color. A line recolored in the Style tab keeps its default-colored label. With prices adds the value, e.g. \"Start 201.02\"."
 
const string OFFSET_TIP = "How many bars to the right of each line's end its name label sits."
 
const string SIZE_TIP = "Text size for the table, the line labels and the START marker. Small, Medium (default) or Large; the title row is always one size larger than the rest."
 
const string TABLE_TIP = "Where the table sits on the chart. Disclaimer adds a last row: \"Hypothetical, before taxes and costs. Educational tool, not investment advice.\""
 
const string FORMAT_TIP = "Detailed (default): a sentence each for three examples, cheapest first, item names in bold: the selected item on a highlighted row, plus the cheapest, a middle-priced and the priciest headline item (the selected item takes the place nearest its cost). Compact: one row per item: the price at the start date → what it would be worth now · that worth as a multiple of the item's price today (per-year items: how many years of it that would pay for); the selected item's row is bold. With Show all items off, either format shows only the selected item."
const string ALL_TIP = "On: every item in the view (Compact), or three examples from cheapest to priciest (Detailed). Off: only the selected item: Your item when it has a cost, otherwise the chosen category's headline item. With Category All and no Your item, there's no selected item, so the table stays as it is with this on."
const string CANDLE_TIP = "Colors for the painted candles: Pastel mint and pink, White and grey, Ink (white up, black down), Money green and gold, TradingView classic, Soft teal and coral, Black and gold, or Neon (made for dark charts). Each scheme has its own Candles entry in the Style tab, where its colors can be changed."
const string COLORS_TIP = "The table's colors: Pastel mint and pink, Money green and gold, Fade VWAP grey, Midnight blue, Light card (made for white charts), Black and gold, or Purple and pink."
const string MA_TIP = "A moving average of the close, drawn when MA lines is on (Show lines) and this box is ticked: length in bars, then type (SMA simple, EMA exponential, WMA weighted, RMA Wilder's, VWMA volume-weighted). Defaults: the 21 SMA (green), 50 SMA (blue) and 200 SMA (black) on; the 9 EMA off. On a dark chart, recolor the black 200 SMA in the Style tab."
 
Cat category = input.enum(Cat.food, "Category", group = G_MAIN, tooltip = CAT_TIP)
TableFormat tableFormat = input.enum(TableFormat.detailed, "Table format", group = G_MAIN, tooltip = FORMAT_TIP)
StartMode startMode = input.enum(StartMode.years10, "Start", inline = "start", group = G_MAIN)
int pickedDate = input.time(timestamp("04 Jan 2016 00:00 -0500"), "", inline = "start", active = startMode == StartMode.pickDate, group = G_MAIN, tooltip = START_TIP)
bool adjustInflation = input.bool(true, "Adjust prices for inflation", inline = "adjust", group = G_MAIN)
bool reinvestDivs = input.bool(true, "Reinvest dividends", inline = "adjust", group = G_MAIN, tooltip = ADJ_TIP)
 
bool showStartLine = input.bool(true, "Start line", inline = "show", group = G_SHOW)
bool showInflLine = input.bool(true, "Inflation line", inline = "show", group = G_SHOW)
bool showMaLines = input.bool(true, "MA lines", inline = "show", group = G_SHOW)
bool showCandles = input.bool(true, "Candles", inline = "show", group = G_SHOW)
bool showInfo = input.bool(true, "Info table", inline = "show", group = G_SHOW, tooltip = SHOW_TIP)
 
bool showAllItems = input.bool(true, "Show all items", group = G_PICKS, tooltip = ALL_TIP)
string myName = input.string("My splurge", "Your item", inline = "mine", group = G_PICKS)
float myPrice = input.float(0.0, "Cost $", minval = 0, step = 1, inline = "mine", group = G_PICKS)
ItemType myType = input.enum(ItemType.oneTime, "", inline = "mine", group = G_PICKS, tooltip = MINE_TIP)
 
FoodPick foodPick = input.enum(FoodPick.nyc_avocado_toast, "Food & drink", group = G_PICKS, tooltip = PICK_TIP)
 
HabitsPick habitsPick = input.enum(HabitsPick.a_latte_every_workday, "Daily habits", group = G_PICKS, tooltip = PICK_TIP)
 
TechPick techPick = input.enum(TechPick.iphone_18_pro_max, "Gaming & tech", group = G_PICKS, tooltip = PICK_TIP)
 
StylePick stylePick = input.enum(StylePick.air_jordan_1_retro_high_og, "Style", group = G_PICKS, tooltip = PICK_TIP)
 
EventsPick eventsPick = input.enum(EventsPick.coachella_weekend_pass, "Concerts & sports", group = G_PICKS, tooltip = PICK_TIP)
 
FitnessPick fitnessPick = input.enum(FitnessPick.peloton_bike, "Fitness & golf", group = G_PICKS, tooltip = PICK_TIP)
 
PetsPick petsPick = input.enum(PetsPick.french_bulldog_puppy, "Pets", group = G_PICKS, tooltip = PICK_TIP)
 
TravelPick travelPick = input.enum(TravelPick.luxury_disney_week_for_four, "Travel", group = G_PICKS, tooltip = PICK_TIP)
 
LovePick lovePick = input.enum(LovePick.item_2_carat_engagement_ring, "Love & weddings", group = G_PICKS, tooltip = PICK_TIP)
 
OpportunityPick opportunityPick = input.enum(OpportunityPick.a_year_of_fortnite_not_work, "Opportunity costs", group = G_PICKS, tooltip = PICK_TIP)
 
HousingPick housingPick = input.enum(HousingPick.ues_1_bedroom_a_year_s_rent, "Housing", group = G_PICKS, tooltip = PICK_TIP)
 
CarsPick carsPick = input.enum(CarsPick.bmw_m2_fully_loaded, "Cars", group = G_PICKS, tooltip = PICK_TIP)
 
OverPick overPick = input.enum(OverPick.duct_taped_banana_artwork, "Over the top", group = G_PICKS, tooltip = PICK_TIP)
 
bool ma1Show = input.bool(false, "MA1", inline = "ma1", active = showMaLines, group = G_MA)
int ma1Len = input.int(9, "", minval = 1, inline = "ma1", active = showMaLines and ma1Show, group = G_MA)
MaType ma1Type = input.enum(MaType.ema, "", inline = "ma1", active = showMaLines and ma1Show, group = G_MA, tooltip = MA_TIP)
 
bool ma2Show = input.bool(true, "MA2", inline = "ma2", active = showMaLines, group = G_MA)
int ma2Len = input.int(21, "", minval = 1, inline = "ma2", active = showMaLines and ma2Show, group = G_MA)
MaType ma2Type = input.enum(MaType.sma, "", inline = "ma2", active = showMaLines and ma2Show, group = G_MA, tooltip = MA_TIP)
 
bool ma3Show = input.bool(true, "MA3", inline = "ma3", active = showMaLines, group = G_MA)
int ma3Len = input.int(50, "", minval = 1, inline = "ma3", active = showMaLines and ma3Show, group = G_MA)
MaType ma3Type = input.enum(MaType.sma, "", inline = "ma3", active = showMaLines and ma3Show, group = G_MA, tooltip = MA_TIP)
 
bool ma4Show = input.bool(true, "MA4", inline = "ma4", active = showMaLines, group = G_MA)
int ma4Len = input.int(200, "", minval = 1, inline = "ma4", active = showMaLines and ma4Show, group = G_MA)
MaType ma4Type = input.enum(MaType.sma, "", inline = "ma4", active = showMaLines and ma4Show, group = G_MA, tooltip = MA_TIP)
 
bool showLineLabels = input.bool(true, "Line labels", inline = "labels", group = G_DISPLAY)
bool labelPrices = input.bool(false, "with prices", inline = "labels", active = showLineLabels, group = G_DISPLAY, tooltip = LABEL_TIP)
int labelOffset = input.int(3, "Label offset (bars)", minval = 0, maxval = 50, active = showLineLabels, group = G_DISPLAY, tooltip = OFFSET_TIP)
TextSize textSize = input.enum(TextSize.medium, "Text size", group = G_DISPLAY, tooltip = SIZE_TIP)
CandleColors candleColors = input.enum(CandleColors.pastel, "Candle colors", group = G_DISPLAY, tooltip = CANDLE_TIP)
TableColors tableColors = input.enum(TableColors.pastel, "Table colors", group = G_DISPLAY, tooltip = COLORS_TIP)
TablePos tablePos = input.enum(TablePos.topRight, "Table position", inline = "table", group = G_DISPLAY)
bool showDisclaimer = input.bool(true, "Disclaimer", inline = "table", group = G_DISPLAY, tooltip = TABLE_TIP)
 
const color C_PASTEL_UP = #B7F0D8
const color C_PASTEL_DOWN = #F9C6DC
const color C_PASTEL_UP_BORDER = #12A37A
const color C_PASTEL_DOWN_BORDER = #D6336C
const color C_PASTEL_WICK = #8A8D96
const color C_WHITE_GREY_UP = #FFFFFF
const color C_WHITE_GREY_DOWN = #B2B5BE
const color C_WHITE_GREY_UP_BORDER = #5D606B
const color C_WHITE_GREY_DOWN_BORDER = #5D606B
const color C_WHITE_GREY_WICK = #5D606B
const color C_INK_UP = #FFFFFF
const color C_INK_DOWN = #131722
const color C_INK_UP_BORDER = #131722
const color C_INK_DOWN_BORDER = #131722
const color C_INK_WICK = #131722
const color C_MONEY_UP = #0F7B55
const color C_MONEY_DOWN = #E0A82E
const color C_MONEY_UP_BORDER = #0B3D2E
const color C_MONEY_DOWN_BORDER = #8A6414
const color C_MONEY_WICK = #0B3D2E
const color C_CLASSIC_UP = #089981
const color C_CLASSIC_DOWN = #F23645
const color C_CLASSIC_UP_BORDER = #089981
const color C_CLASSIC_DOWN_BORDER = #F23645
const color C_CLASSIC_WICK = #787B86
const color C_TEAL_CORAL_UP = #26A69A
const color C_TEAL_CORAL_DOWN = #EF5350
const color C_TEAL_CORAL_UP_BORDER = #1B7A70
const color C_TEAL_CORAL_DOWN_BORDER = #B23A37
const color C_TEAL_CORAL_WICK = #5D606B
const color C_BLACK_GOLD_UP = #D4AF37
const color C_BLACK_GOLD_DOWN = #1A1A1A
const color C_BLACK_GOLD_UP_BORDER = #8C6D1F
const color C_BLACK_GOLD_DOWN_BORDER = #1A1A1A
const color C_BLACK_GOLD_WICK = #6B5A2E
const color C_NEON_UP = #00E5FF
const color C_NEON_DOWN = #FF2E88
const color C_NEON_UP_BORDER = #00E5FF
const color C_NEON_DOWN_BORDER = #FF2E88
const color C_NEON_WICK = #5B6478
const color START_COLOR = color.rgb(201, 162, 39)
const color INFL_COLOR = color.rgb(103, 58, 183)
const color MA1_COLOR = color.rgb(255, 152, 0)
const color MA2_COLOR = color.rgb(76, 175, 80)
const color MA3_COLOR = color.rgb(41, 98, 255)
const color MA4_COLOR = color.black
const color GAIN_COLOR = color.rgb(8, 153, 129)
const color LOSS_COLOR = color.rgb(242, 54, 69)
string tableTextSize = textSize == TextSize.small ? size.small : textSize == TextSize.large ? size.large : size.normal
string labelTextSize = tableTextSize
string titleTextSize = textSize == TextSize.small ? size.normal : textSize == TextSize.large ? size.huge : size.large
 
type Theme
    color titleBg
    color titleText
    color gainBg
    color gainText
    color lossBg
    color lossText
    color headerBg
    color headerText
    color rowBg
    color captionText
    color valueText
    color selBg
    color selText
    color footBg
    color footCaption
    color footValue
    color warnText
 
var Theme th = switch tableColors
    TableColors.fadeGrey => Theme.new(color.new(color.black, 15), color.white, #089981, color.white, #F23645, color.white, color.new(color.black, 15), color.silver, color.new(color.black, 15), color.silver, color.white, color.new(color.black, 15), color.white, color.new(color.black, 15), color.silver, color.white, color.orange)
    TableColors.midnight => Theme.new(#2962FF, color.white, #089981, color.white, #F23645, color.white, #1E222D, #787B86, #131722, #B2B5BE, color.white, #131722, #FFCA28, #1E222D, #B2B5BE, color.white, #FF9800)
    TableColors.light => Theme.new(#131722, color.white, #089981, color.white, #F23645, color.white, #F0F3FA, #5D606B, color.white, #5D606B, #131722, #E3EFFD, #0C3299, #F0F3FA, #5D606B, #131722, #E65100)
    TableColors.blackGold => Theme.new(#C9A227, #111111, #1B5E20, color.white, #B71C1C, color.white, #111111, #8A8A8A, #111111, #BDBDBD, #F5F5F5, #1C1C1C, #FFD54F, #111111, #BDBDBD, #F5F5F5, #FFB74D)
    TableColors.purple => Theme.new(#5B21B6, color.white, #059669, color.white, #F23645, color.white, #2A1B4A, #A78BFA, #1E1433, #DDD6FE, color.white, #DB2777, color.white, #2A1B4A, #DDD6FE, color.white, #FDBA74)
    TableColors.money => Theme.new(#0B3D2E, #F5C451, #F5C451, #0B3D2E, #C62828, color.white, #124C3A, #9CC9B5, #124C3A, #CFE8DC, color.white, #0F5A43, color.white, #0B3D2E, #CFE8DC, #F5C451, #FFB74D)
    => Theme.new(#F9C6DC, #8C1D47, #0E8A66, color.white, #D6336C, color.white, #E8FBF3, #0E7A5C, color.white, #5D606B, #1F2937, #B7F0D8, #0B5F47, #FFF5F9, #8A8D96, #1F2937, #C2410C)
 
// 2. ITEM CATALOG AND VIEW ORDER
// Parallel arrays: identical index = identical item. List prices are anchored to LIST_CPI.
 
var array<string> ITEM_NAME = array.from(
    "Dunkin' donut", "Egg McMuffin", "Grande latte", "Big Mac meal", "NYC avocado toast", "Chain steakhouse dinner for two",
    "NYC steakhouse dinner for two", "NYC club bottle service", "Powerball, every drawing", "Four streaming services", "A latte every workday", "Lunch out every workday",
    "Line-sitter Cronuts, weekly", "Food delivery twice a week", "Apple Polishing Cloth", "GTA VI Ultimate edition", "10 hours of Fortnite coaching", "Nintendo Switch 2",
    "Xbox Series X 1TB", "iPhone 18 Pro Max", "RTX 5090 gaming PC", "Labubu blind box", "lululemon Align leggings", "Air Jordan 1 Retro High OG",
    "Sneaker-drop line-sitter", "Canada Goose parka", "Louis Vuitton Neverfull MM", "Rolex Submariner", "Hermès Birkin 25", "Priciest NFL stadium beer",
    "Stadium tour ticket", "Broadway for two", "Coachella weekend pass", "Yankees Fantasy Camp week", "Super Bowl ticket", "Knicks courtside seat",
    "Goat yoga class", "Dozen Pro V1 golf balls", "Topgolf night for four", "Peloton Bike", "Round at Pebble Beach", "Custom-fitted golf clubs",
    "Equinox membership", "Pumpkin dog costume", "Pet psychic session", "French bulldog puppy", "NYC dog walker", "$27 airport beer",
    "Big Idaho Potato Hotel night", "Camping week in Maine", "Bachelor(ette) weekend", "Bali week for two", "Disney World week for four", "Europe for two, two weeks",
    "Business class to Tokyo for two", "Vail ski week for two", "Luxury cruise week for two", "Luxury Disney week for four", "Dozen red roses, delivered", "Elvis wedding in Vegas",
    "Wedding dress worn once", "Mikimoto pearl necklace", "Backyard wedding", "2-carat engagement ring", "Average US wedding", "NY Botanical Garden wedding",
    "Binge The Office twice", "TikTok, 47 minutes a day", "A year of Fortnite, not work", "Startup equity that busts", "Closet organizer, 5 hours", "Storage unit",
    "UES 1-bedroom, a year's rent", "UES 3-bedroom, a year's rent", "Getting towed in Manhattan", "Manhattan garage parking", "Toyota Camry", "BMW M2, fully loaded",
    "Porsche 911 Carrera", "Lamborghini Revuelto", "Times Square billboard photo", "Private jet NYC to Miami", "Superyacht week", "Virgin Galactic seat",
    "Duct-taped banana artwork")
 
var array<float> ITEM_PRICE = array.from(
    2.0, 4.29, 6.0, 9.45, 16.0, 90.0,
    200.0, 1950.0, 312.0, 864.0, 1490.0, 3350.0,
    3380.0, 3640.0, 9.0, 100.0, 200.0, 500.0,
    899.0, 1299.0, 5500.0, 28.0, 108.0, 185.0,
    315.0, 1800.0, 2240.0, 10050.0, 13500.0, 16.49,
    250.0, 262.0, 650.0, 5600.0, 7400.0, 34000.0,
    40.0, 58.0, 200.0, 1695.0, 2355.0, 3500.0,
    4200.0, 25.0, 165.0, 4000.0, 6250.0, 27.85,
    200.0, 1000.0, 2000.0, 6000.0, 6500.0, 9000.0,
    9000.0, 11000.0, 12400.0, 21500.0, 125.0, 199.0,
    2100.0, 6900.0, 15000.0, 22000.0, 34200.0, 120000.0,
    4300.0, 8300.0, 60300.0, 216000.0, 250.0, 1428.0,
    50400.0, 144000.0, 205.0, 11400.0, 29600.0, 100600.0,
    135500.0, 612900.0, 150.0, 24000.0, 283000.0, 750000.0,
    6200000.0)
 
var array<int> ITEM_CAT = array.from(
    1, 1, 1, 1, 1, 1,
    1, 1, 2, 2, 2, 2,
    2, 2, 3, 3, 3, 3,
    3, 3, 3, 4, 4, 4,
    4, 4, 4, 4, 4, 5,
    5, 5, 5, 5, 5, 5,
    6, 6, 6, 6, 6, 6,
    6, 7, 7, 7, 7, 8,
    8, 8, 8, 8, 8, 8,
    8, 8, 8, 8, 9, 9,
    9, 9, 9, 9, 9, 9,
    10, 10, 10, 10, 11, 11,
    11, 11, 12, 12, 12, 12,
    12, 12, 13, 13, 13, 13,
    13)
 
var array<bool> ITEM_PER_YEAR = array.from(
    false, false, false, false, false, false,
    false, false, true, true, true, true,
    true, true, false, false, false, false,
    false, false, false, false, false, false,
    false, false, false, false, false, false,
    false, false, false, false, false, false,
    false, false, false, false, false, false,
    true, false, false, false, true, false,
    false, false, false, false, false, false,
    false, false, false, false, false, false,
    false, false, false, false, false, false,
    false, true, false, false, false, true,
    false, false, false, true, false, false,
    false, false, false, false, false, false,
    false)
 
var array<string> ITEM_PHRASE = array.from(
    "a Dunkin' donut", "an Egg McMuffin", "a grande latte", "a Big Mac meal", "avocado toast at an NYC cafe", "a chain steakhouse dinner for two",
    "an NYC steakhouse dinner for two", "bottle service at an NYC club", "a Powerball ticket for every drawing", "four streaming services", "a latte every workday", "lunch out every workday",
    "a line-sitter fetching Cronuts every weekend", "food delivery twice a week", "Apple's Polishing Cloth", "GTA VI Ultimate edition", "10 hours of Fortnite coaching", "a Nintendo Switch 2",
    "an Xbox Series X", "an iPhone 18 Pro Max", "an RTX 5090 gaming PC", "a Labubu blind box", "lululemon Align leggings", "Air Jordan 1s",
    "a line-sitter for a sneaker drop", "a Canada Goose parka", "a Louis Vuitton Neverfull bag", "a Rolex Submariner", "a Hermès Birkin bag", "a beer at the NFL's priciest stadium",
    "a stadium tour ticket", "Broadway for two", "a Coachella weekend pass", "a week at Yankees Fantasy Camp", "a Super Bowl ticket", "a courtside seat at the Knicks",
    "a goat yoga class", "a dozen Pro V1 golf balls", "a Topgolf night for four", "a Peloton Bike", "a round at Pebble Beach", "custom-fitted golf clubs",
    "an Equinox membership", "a pumpkin costume for the dog", "a session with a pet psychic", "a French bulldog puppy", "an NYC dog walker", "a $27 airport beer",
    "a night in the Big Idaho Potato Hotel", "a camping week in Maine", "a bachelor or bachelorette weekend", "a week in Bali for two", "a Disney World week for four", "two weeks in Europe for two",
    "business class to Tokyo for two", "a ski week in Vail for two", "a luxury cruise for two", "a luxury Disney week for four", "a dozen red roses", "an Elvis wedding in Vegas",
    "a wedding dress worn once", "a Mikimoto pearl necklace", "a backyard wedding", "a 2-carat engagement ring", "an average US wedding", "a wedding at the NY Botanical Garden",
    "binge-watching The Office twice", "spending 47 minutes a day on TikTok", "playing Fortnite for a year instead of working", "taking startup equity that went bust", "a closet organizer", "a storage unit",
    "a year's rent on a UES 1-bedroom", "a year's rent on a UES 3-bedroom", "getting towed in Manhattan", "Manhattan garage parking", "a Toyota Camry", "a fully loaded BMW M2",
    "a Porsche 911 Carrera", "a Lamborghini Revuelto", "a photo on a Times Square billboard", "a private jet to Miami", "a week on a superyacht", "a seat on Virgin Galactic",
    "a banana duct-taped to a wall")
 
var int foodIdx = array.indexof(ITEM_NAME, str.tostring(foodPick))
 
var int habitsIdx = array.indexof(ITEM_NAME, str.tostring(habitsPick))
 
var int techIdx = array.indexof(ITEM_NAME, str.tostring(techPick))
 
var int styleIdx = array.indexof(ITEM_NAME, str.tostring(stylePick))
 
var int eventsIdx = array.indexof(ITEM_NAME, str.tostring(eventsPick))
 
var int fitnessIdx = array.indexof(ITEM_NAME, str.tostring(fitnessPick))
 
var int petsIdx = array.indexof(ITEM_NAME, str.tostring(petsPick))
 
var int travelIdx = array.indexof(ITEM_NAME, str.tostring(travelPick))
 
var int loveIdx = array.indexof(ITEM_NAME, str.tostring(lovePick))
 
var int opportunityIdx = array.indexof(ITEM_NAME, str.tostring(opportunityPick))
 
var int housingIdx = array.indexof(ITEM_NAME, str.tostring(housingPick))
 
var int carsIdx = array.indexof(ITEM_NAME, str.tostring(carsPick))
 
var int overIdx = array.indexof(ITEM_NAME, str.tostring(overPick))
 
var array<int> HEADLINE_IDX = array.from(foodIdx, habitsIdx, techIdx, styleIdx, eventsIdx, fitnessIdx, petsIdx, travelIdx, loveIdx, opportunityIdx, housingIdx, carsIdx, overIdx)
 
int categoryId = switch category
    Cat.food => 1
    Cat.habits => 2
    Cat.tech => 3
    Cat.style => 4
    Cat.events => 5
    Cat.fitness => 6
    Cat.pets => 7
    Cat.travel => 8
    Cat.love => 9
    Cat.opportunity => 10
    Cat.housing => 11
    Cat.cars => 12
    Cat.over => 13
    => 0
var array<int> VIEW_IDX = array.new<int>()
if barstate.isfirst
    if categoryId == 0
        array<float> headlinePrices = array.new<float>()
        for itemIdx in HEADLINE_IDX
            array.push(headlinePrices, array.get(ITEM_PRICE, itemIdx))
        array<int> sortedPicks = array.sort_indices(headlinePrices, order.ascending)
        for pickIdx in sortedPicks
            array.push(VIEW_IDX, array.get(HEADLINE_IDX, pickIdx))
    else
        int headlineIdx = array.get(HEADLINE_IDX, categoryId - 1)
        array.push(VIEW_IDX, headlineIdx)
        for itemIdx = 0 to array.size(ITEM_NAME) - 1
            if array.get(ITEM_CAT, itemIdx) == categoryId and itemIdx != headlineIdx
                array.push(VIEW_IDX, itemIdx)
 
const int CUSTOM_IDX = -1
const int NO_SELECTION = -2
int selectedIdx = myPrice > 0 ? CUSTOM_IDX : categoryId != 0 ? array.get(HEADLINE_IDX, categoryId - 1) : NO_SELECTION
f_itemCost(int itemIdx) =>
    itemIdx == CUSTOM_IDX ? myPrice : array.get(ITEM_PRICE, itemIdx)
 
var array<int> COMPACT_IDX = array.new<int>()
var array<int> EXAMPLE_IDX = array.new<int>()
if barstate.isfirst
    bool selectedOnly = not showAllItems and selectedIdx != NO_SELECTION
    if selectedOnly
        array.push(COMPACT_IDX, selectedIdx)
        array.push(EXAMPLE_IDX, selectedIdx)
    else
        if myPrice > 0
            array.push(COMPACT_IDX, CUSTOM_IDX)
        for itemIdx in VIEW_IDX
            array.push(COMPACT_IDX, itemIdx)
        int lowIdx = array.get(HEADLINE_IDX, 0)
        int highIdx = lowIdx
        for itemIdx in HEADLINE_IDX
            if f_itemCost(itemIdx) < f_itemCost(lowIdx)
                lowIdx := itemIdx
            if f_itemCost(itemIdx) > f_itemCost(highIdx)
                highIdx := itemIdx
        float geometricMean = math.sqrt(f_itemCost(lowIdx) * f_itemCost(highIdx))
        int middleIdx = NO_SELECTION
        float middleDistance = na
        for itemIdx in HEADLINE_IDX
            if itemIdx != lowIdx and itemIdx != highIdx
                float distance = math.abs(math.log(f_itemCost(itemIdx) / geometricMean))
                if na(middleDistance) or distance < middleDistance
                    middleIdx := itemIdx
                    middleDistance := distance
        array.push(EXAMPLE_IDX, lowIdx)
        array.push(EXAMPLE_IDX, middleIdx)
        array.push(EXAMPLE_IDX, highIdx)
        if selectedIdx != NO_SELECTION and not array.includes(EXAMPLE_IDX, selectedIdx)
            int nearestSlot = 0
            float nearestDistance = na
            for slot = 0 to array.size(EXAMPLE_IDX) - 1
                float distance = math.abs(math.log(f_itemCost(array.get(EXAMPLE_IDX, slot)) / f_itemCost(selectedIdx)))
                if na(nearestDistance) or distance < nearestDistance
                    nearestSlot := slot
                    nearestDistance := distance
            array.set(EXAMPLE_IDX, nearestSlot, selectedIdx)
        array<float> examplePrices = array.new<float>()
        for itemIdx in EXAMPLE_IDX
            array.push(examplePrices, f_itemCost(itemIdx))
        array<int> sortedExamples = array.sort_indices(examplePrices, order.ascending)
        array<int> unsortedExamples = array.copy(EXAMPLE_IDX)
        array.clear(EXAMPLE_IDX)
        for slot in sortedExamples
            array.push(EXAMPLE_IDX, array.get(unsortedExamples, slot))
 
// 3. DATA AND START STATE
const string CPI_SYMBOL = "FRED:CPIAUCNS"
const float LIST_CPI = 336.940
const string LIST_CPI_MONTH = "Sep 2026"
// Chart timeframe and lookahead_off intentionally preserve the calendar-month deflator.
[cpiRaw, cpiTime] = request.security(CPI_SYMBOL, timeframe.period, [close, time], gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off, ignore_invalid_symbol = true)
string mathTicker = reinvestDivs ? ticker.modify(syminfo.tickerid, adjustment = adjustment.dividends) : ticker.modify(syminfo.tickerid, adjustment = adjustment.splits)
float px = request.security(mathTicker, timeframe.period, close, gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off, currency = currency.USD)
var int firstBarTime = time
var int firstBarDate = timestamp(syminfo.timezone, year(time_close, syminfo.timezone), month(time_close, syminfo.timezone), dayofmonth(time_close, syminfo.timezone), 0, 0)
int yearsBack = switch startMode
    StartMode.years5 => 5
    StartMode.years20 => 20
    => 10
int startTime = switch startMode
    StartMode.firstBar => firstBarTime
    StartMode.pickDate => pickedDate
    => timestamp(syminfo.timezone, year(timenow, syminfo.timezone) - yearsBack, month(timenow, syminfo.timezone), dayofmonth(timenow, syminfo.timezone), 0, 0)
var bool started = false
var int startBarTime = na
var string startDateText = ""
var float startClose = na
var float pxStart = na
var float cpiStart = na
var string cpiStartMonth = ""
var bool adjOn = false
var bool startBeforeHistory = false
var int months = 0
var float sumPaid = 0.0
var float sumUnits = 0.0
bool newStart = not started and time_close >= startTime and not na(px)
bool newMonth = timeframe.change("1M")
if newStart
    started := true
    startBarTime := time
    startDateText := str.format_time(time_close, "MMM d, yyyy", syminfo.timezone)
    startClose := close
    pxStart := px
    cpiStart := cpiRaw
    cpiStartMonth := not na(cpiTime) ? str.format_time(cpiTime, "MMM yyyy", "UTC") : "n/a"
    adjOn := adjustInflation and not na(cpiStart)
    startBeforeHistory := barstate.isfirst and startMode != StartMode.firstBar and startTime < firstBarDate
// One contribution even when the start bar is also the first bar of its month.
// Ordinary var state rolls back on each realtime tick; no intrabar persistence.
if started and (newStart or newMonth)
    float f = adjOn ? cpiRaw : 1.0
    sumPaid += f / 12.0
    sumUnits += (f / 12.0) / px
    months += 1
 
// 4. FORMATTING AND DISPLAY HELPERS
 
f_group(float x) =>
    string digits = str.tostring(math.abs(x), "0")
    int n = str.length(digits)
    string out = ""
    for i = 0 to n - 1
        if i > 0 and (n - i) % 3 == 0
            out += ","
        out += str.substring(digits, i, i + 1)
    out
 
// Title Case: capitalizes the first letter of each word and of each part of a hyphenated word ("Duct-Taped", "1-Bedroom"),
// keeps small words lowercase (except the first word), and leaves a part unchanged when it already has a capital
// or starts with a non-letter ("iPhone", "NYC", "$27").
var array<string> SMALL_WORDS = array.from("a", "an", "the", "and", "or", "for", "of", "on", "in", "at", "to", "with", "per")
f_titleCase(string s) =>
    array<string> words = str.split(s, " ")
    array<string> out = array.new<string>()
    for [i, w] in words
        string result = w
        bool small = i > 0 and array.includes(SMALL_WORDS, w)
        if str.length(w) > 0 and not small
            array<string> parts = str.split(w, "-")
            array<string> fixed = array.new<string>()
            for p in parts
                string q = p
                if str.length(p) > 0
                    string first = str.substring(p, 0, 1)
                    if str.contains("abcdefghijklmnopqrstuvwxyz", first) and str.lower(p) == p
                        q := str.upper(first) + str.substring(p, 1)
                array.push(fixed, q)
            result := array.join(fixed, "-")
        array.push(out, result)
    array.join(out, " ")
 
// Bold letters inside regular text (Unicode sans-serif bold): A–Z, a–z and 0–9 change; everything else stays as it is.
var string PLAIN_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
var array<string> BOLD_CHARS = array.from("𝗔", "𝗕", "𝗖", "𝗗", "𝗘", "𝗙", "𝗚", "𝗛", "𝗜", "𝗝", "𝗞", "𝗟", "𝗠", "𝗡", "𝗢", "𝗣", "𝗤", "𝗥", "𝗦", "𝗧", "𝗨", "𝗩", "𝗪", "𝗫", "𝗬", "𝗭", "𝗮", "𝗯", "𝗰", "𝗱", "𝗲", "𝗳", "𝗴", "𝗵", "𝗶", "𝗷", "𝗸", "𝗹", "𝗺", "𝗻", "𝗼", "𝗽", "𝗾", "𝗿", "𝘀", "𝘁", "𝘂", "𝘃", "𝘄", "𝘅", "𝘆", "𝘇", "𝟬", "𝟭", "𝟮", "𝟯", "𝟰", "𝟱", "𝟲", "𝟳", "𝟴", "𝟵")
f_boldText(string s) =>
    string out = ""
    int n = str.length(s)
    if n > 0
        for i = 0 to n - 1
            string ch = str.substring(s, i, i + 1)
            int k = str.pos(PLAIN_CHARS, ch)
            out += na(k) ? ch : array.get(BOLD_CHARS, k)
    out
 
// An item's name in a Detailed sentence: a leading "a " / "an " stays plain and lowercase, the rest is Title Case,
// in bold letters when bold is true. "a Dunkin' donut" → "a Dunkin' Donut", or "a 𝗗𝘂𝗻𝗸𝗶𝗻' 𝗗𝗼𝗻𝘂𝘁" when selected. Your item: its whole name.
f_highlight(string phrase, bool isCustom, bool bold) =>
    string article = ""
    string rest = phrase
    if not isCustom
        if str.startswith(phrase, "a ")
            article := "a "
            rest := str.substring(phrase, 2)
        else if str.startswith(phrase, "an ")
            article := "an "
            rest := str.substring(phrase, 3)
    string titled = f_titleCase(rest)
    article + (bold ? f_boldText(titled) : titled)
 
// The ticker in bold letters, built once.
var string tickerBold = f_boldText(syminfo.ticker)
 
var array<int> PLURAL_IDX = array.from(9, 16, 22, 23, 41, 53)
 
f_usd(float amount) =>
    string result = "n/a"
    if not na(amount)
        float a = math.abs(amount)
        string body = a >= 100 ? f_group(a) : math.abs(a - math.round(a)) < 0.005 ? str.tostring(a, "0") : str.tostring(a, "0.00")
        result := (amount < 0 ? "−$" : "$") + body
    result
 
f_count(float x) =>
    na(x) ? "n/a" : x < 1 ? str.tostring(x, "0.00") : x < 100 ? str.tostring(x, "0.0") : str.tostring(x, "0")
 
f_mult(float x) =>
    na(x) ? "n/a" : x < 1 ? str.tostring(x, "0.00") + "x" : x < 100 ? str.tostring(x, "0.0") + "x" : f_group(x) + "x"
 
f_pct(float multiple) =>
    string result = "n/a"
    if not na(multiple)
        float p = (multiple - 1) * 100
        string body = math.abs(p) < 10 ? str.tostring(math.abs(p), "0.0") : f_group(p)
        result := (p >= 0 ? "+" : "−") + body + "%"
    result
 
f_pair(table panel, int rowIndex, string caption, string value, color bg, color captionColor, color valueColor, bool bold, string textSize) =>
    table.cell(panel, 0, rowIndex, caption, text_color = captionColor, bgcolor = bg, text_size = textSize, text_halign = text.align_left, text_formatting = bold ? text.format_bold : text.format_none)
    table.cell(panel, 1, rowIndex, value, text_color = valueColor, bgcolor = bg, text_size = textSize, text_halign = text.align_left, text_formatting = bold ? text.format_bold : text.format_none)
 
// Clearing contents preserves merges. Merge each subtitle, example and spacer row only on its first render.
f_mergedRow(table panel, int rowIndex, string sentence, color bg, color valueColor, bool bold, string textSize, bool firstMerge, string textAlign = text.align_left) =>
    table.cell(panel, 0, rowIndex, sentence, text_color = valueColor, bgcolor = bg, text_size = textSize, text_halign = textAlign, text_formatting = bold ? text.format_bold : text.format_none)
    if firstMerge
        table.cell(panel, 1, rowIndex, "", text_color = valueColor, bgcolor = bg, text_size = textSize, text_halign = textAlign)
        table.merge_cells(panel, 0, rowIndex, 1, rowIndex)
 
f_lineLabel(label lbl, float value, string caption, color lineColor, bool lineVisible) =>
    label.set_xy(lbl, bar_index + labelOffset, value)
    label.set_textcolor(lbl, lineColor)
    label.set_text(lbl, showLineLabels and lineVisible and not na(value) ? caption + (labelPrices ? " " + str.tostring(value, format.mintick) : "") : "")
 
// Compact formatter: one call site handles both custom and list items.
f_item(string itemName, float price, bool perYear, float anchor, float pxLast, float cpiLast) =>
    float a = adjOn ? anchor : 1.0
    float startFactor = adjOn ? cpiStart : 1.0
    float lastFactor = adjOn ? cpiLast : 1.0
    float todayPrice = price * lastFactor / a
    float paid = perYear ? price * sumPaid / a : price * startFactor / a
    float worth = perYear ? price * sumUnits / a * pxLast : paid * pxLast / pxStart
    float count = todayPrice != 0 ? worth / todayPrice : na
    string caption = itemName + " " + f_usd(todayPrice) + (perYear ? "/yr" : "")
    string value = f_usd(paid) + " → " + f_usd(worth) + " · " + (perYear ? f_count(count) + " yrs of it" : f_count(count) + "x today's price")
    [caption, value]
 
f_detail(int itemIdx, float pxLast, float cpiLast, float growth, float real) =>
    bool isCustom = itemIdx == CUSTOM_IDX
    float price = f_itemCost(itemIdx)
    bool perYear = isCustom ? myType == ItemType.perYear : array.get(ITEM_PER_YEAR, itemIdx)
    float anchor = isCustom ? cpiLast : LIST_CPI
    float a = adjOn ? anchor : 1.0
    float startFactor = adjOn ? cpiStart : 1.0
    float lastFactor = adjOn ? cpiLast : 1.0
    float todayPrice = price * lastFactor / a
    float paid = perYear ? price * sumPaid / a : price * startFactor / a
    float worth = perYear ? price * sumUnits / a * pxLast : paid * pxLast / pxStart
    bool behind = perYear ? worth < todayPrice * months / 12.0 : worth < todayPrice
    bool shrunk = worth < paid
    float years = todayPrice != 0 ? worth / todayPrice : na
    string phrase = isCustom ? myName : array.get(ITEM_PHRASE, itemIdx)
    bool opportunity = isCustom ? false : array.get(ITEM_CAT, itemIdx) == 10
    string opener = opportunity ? "Earning and investing " : "Investing "
    string link = (opportunity ? " instead of " : " instead of spending it on ") + f_highlight(phrase, isCustom, true)
    string line1 = opener + (perYear ? "about " + f_usd(months > 0 ? paid / float(months) : na) + " a month" : f_usd(paid)) + " in " + tickerBold + link
    string line2 = ""
    if perYear
        if not behind
            line2 := "(" + f_usd(paid) + " in all) would be worth " + f_usd(worth) + " today: " + f_mult(paid != 0 ? worth / paid : na) + " the money paid, or " + f_count(years) + " years of it at today's price."
        else if shrunk
            line2 := "(" + f_usd(paid) + " in all) would have shrunk to " + f_usd(worth) + " today: just " + f_mult(paid != 0 ? worth / paid : na) + " the money paid, or " + f_count(years) + " years of it at today's price."
        else
            line2 := "(" + f_usd(paid) + " in all) would be worth " + f_usd(worth) + " today: " + f_mult(paid != 0 ? worth / paid : na) + " the money paid, but just " + f_count(years) + " years of it at today's price."
    else if not na(real)
        if real >= 1
            line2 := "would be worth " + f_usd(worth) + " today: a " + f_pct(growth) + " return, " + f_pct(real) + " after inflation, or " + f_mult(real) + " the money in today's dollars."
        else if growth >= 1
            line2 := "would be worth " + f_usd(worth) + " today: a " + f_pct(growth) + " return, but " + f_pct(real) + " after inflation, so just " + f_mult(real) + " the money in today's dollars."
        else
            line2 := "would have shrunk to " + f_usd(worth) + " today: a " + f_pct(growth) + " return, " + f_pct(real) + " after inflation, or just " + f_mult(real) + " the money in today's dollars."
    else if growth < 1
        line2 := "would have shrunk to " + f_usd(worth) + " today: a " + f_pct(growth) + " return (just " + f_mult(growth) + " the money)."
    else
        line2 := "would be worth " + f_usd(worth) + " today: a " + f_pct(growth) + " return (" + f_mult(growth) + " the money)."
    line1 + "\n" + line2
 
// The subtitle uses the same paid/worth expressions as the item formatters.
f_subtitle(int itemIdx, float pxLast, float cpiLast) =>
    bool isCustom = itemIdx == CUSTOM_IDX
    float price = f_itemCost(itemIdx)
    bool perYear = isCustom ? myType == ItemType.perYear : array.get(ITEM_PER_YEAR, itemIdx)
    float anchor = isCustom ? cpiLast : LIST_CPI
    float a = adjOn ? anchor : 1.0
    float startFactor = adjOn ? cpiStart : 1.0
    float lastFactor = adjOn ? cpiLast : 1.0
    float todayPrice = price * lastFactor / a
    float paid = perYear ? price * sumPaid / a : price * startFactor / a
    float worth = perYear ? price * sumUnits / a * pxLast : paid * pxLast / pxStart
    bool behind = perYear ? worth < todayPrice * months / 12.0 : worth < todayPrice
    bool shrunk = worth < paid
    string phrase = isCustom ? myName : array.get(ITEM_PHRASE, itemIdx)
    array<string> words = str.split(phrase, " ")
    string firstWord = array.size(words) > 0 ? array.get(words, 0) : ""
    string opener = "Is that "
    string middle = "enjoying that "
    if not isCustom
        if str.endswith(str.lower(firstWord), "ing")
            opener := "Is "
            middle := ""
        else if array.includes(PLURAL_IDX, itemIdx)
            opener := "Are those "
            middle := "enjoying those "
        else if str.startswith(phrase, "a ")
            phrase := str.substring(phrase, 2)
        else if str.startswith(phrase, "an ")
            phrase := str.substring(phrase, 3)
    string itemText = f_titleCase(phrase)
    behind ? "You'd have been better off " + middle + itemText + "!" : opener + itemText + " really worth " + f_usd(worth) + "?"
 
f_ma(simple string maType, simple int len) =>
    float result = switch maType
        "SMA" => ta.sma(close, len)
        "EMA" => ta.ema(close, len)
        "WMA" => ta.wma(close, len)
        "RMA" => ta.rma(close, len)
        => ta.vwma(close, len)
    result
 
// 5. CANDLES, LINES AND DATA WINDOW
// Plot budget: candles 46 (six at 6, two at 5), plus ten line/Data Window plots = 56 of 64.
bool paintPastel = showCandles and candleColors == CandleColors.pastel
plotcandle(paintPastel ? open : na, paintPastel ? high : na, paintPastel ? low : na, paintPastel ? close : na, title = "Candles: Pastel mint and pink", color = close >= open ? C_PASTEL_UP : C_PASTEL_DOWN, wickcolor = C_PASTEL_WICK, bordercolor = close >= open ? C_PASTEL_UP_BORDER : C_PASTEL_DOWN_BORDER)
 
bool paintWhiteGrey = showCandles and candleColors == CandleColors.whiteGrey
plotcandle(paintWhiteGrey ? open : na, paintWhiteGrey ? high : na, paintWhiteGrey ? low : na, paintWhiteGrey ? close : na, title = "Candles: White and grey", color = close >= open ? C_WHITE_GREY_UP : C_WHITE_GREY_DOWN, wickcolor = C_WHITE_GREY_WICK, bordercolor = C_WHITE_GREY_UP_BORDER)
 
bool paintInk = showCandles and candleColors == CandleColors.ink
plotcandle(paintInk ? open : na, paintInk ? high : na, paintInk ? low : na, paintInk ? close : na, title = "Candles: Ink", color = close >= open ? C_INK_UP : C_INK_DOWN, wickcolor = C_INK_WICK, bordercolor = C_INK_UP_BORDER)
 
bool paintMoney = showCandles and candleColors == CandleColors.money
plotcandle(paintMoney ? open : na, paintMoney ? high : na, paintMoney ? low : na, paintMoney ? close : na, title = "Candles: Money green and gold", color = close >= open ? C_MONEY_UP : C_MONEY_DOWN, wickcolor = C_MONEY_WICK, bordercolor = close >= open ? C_MONEY_UP_BORDER : C_MONEY_DOWN_BORDER)
 
bool paintClassic = showCandles and candleColors == CandleColors.classic
plotcandle(paintClassic ? open : na, paintClassic ? high : na, paintClassic ? low : na, paintClassic ? close : na, title = "Candles: TradingView classic", color = close >= open ? C_CLASSIC_UP : C_CLASSIC_DOWN, wickcolor = C_CLASSIC_WICK, bordercolor = close >= open ? C_CLASSIC_UP_BORDER : C_CLASSIC_DOWN_BORDER)
 
bool paintTealCoral = showCandles and candleColors == CandleColors.tealCoral
plotcandle(paintTealCoral ? open : na, paintTealCoral ? high : na, paintTealCoral ? low : na, paintTealCoral ? close : na, title = "Candles: Soft teal and coral", color = close >= open ? C_TEAL_CORAL_UP : C_TEAL_CORAL_DOWN, wickcolor = C_TEAL_CORAL_WICK, bordercolor = close >= open ? C_TEAL_CORAL_UP_BORDER : C_TEAL_CORAL_DOWN_BORDER)
 
bool paintBlackGold = showCandles and candleColors == CandleColors.blackGold
plotcandle(paintBlackGold ? open : na, paintBlackGold ? high : na, paintBlackGold ? low : na, paintBlackGold ? close : na, title = "Candles: Black and gold", color = close >= open ? C_BLACK_GOLD_UP : C_BLACK_GOLD_DOWN, wickcolor = C_BLACK_GOLD_WICK, bordercolor = close >= open ? C_BLACK_GOLD_UP_BORDER : C_BLACK_GOLD_DOWN_BORDER)
 
bool paintNeon = showCandles and candleColors == CandleColors.neon
plotcandle(paintNeon ? open : na, paintNeon ? high : na, paintNeon ? low : na, paintNeon ? close : na, title = "Candles: Neon (dark charts)", color = close >= open ? C_NEON_UP : C_NEON_DOWN, wickcolor = C_NEON_WICK, bordercolor = close >= open ? C_NEON_UP_BORDER : C_NEON_DOWN_BORDER)
// Start and Inflation lines stay in the chart's own currency, using chart close to sit on its candles.
float startLineV = showStartLine and started ? startClose : na
float inflLineV = showInflLine and started and not na(cpiStart) ? startClose * cpiRaw / cpiStart : na
plot(startLineV, "Start price", color = START_COLOR, linewidth = 2, style = plot.style_linebr, linestyle = plot.linestyle_solid)
plot(inflLineV, "Inflation only", color = INFL_COLOR, linewidth = 4, style = plot.style_linebr, linestyle = plot.linestyle_solid)
float growthV = started ? px / pxStart : na
float realV = started and not na(cpiStart) and not na(cpiRaw) ? growthV * cpiStart / cpiRaw : na
plot(cpiRaw, "CPI", color = INFL_COLOR, linewidth = 1, style = plot.style_line, linestyle = plot.linestyle_solid, display = display.data_window, precision = 3)
plot(px, "Price used", color = START_COLOR, linewidth = 1, style = plot.style_line, linestyle = plot.linestyle_solid, display = display.data_window, precision = 6)
plot(growthV, "Growth", color = GAIN_COLOR, linewidth = 1, style = plot.style_line, linestyle = plot.linestyle_solid, display = display.data_window, precision = 6)
plot(realV, "Growth after inflation", color = GAIN_COLOR, linewidth = 1, style = plot.style_line, linestyle = plot.linestyle_solid, display = display.data_window, precision = 6)
 
float ma1 = f_ma(str.tostring(ma1Type), ma1Len)
float ma1V = showMaLines and ma1Show ? ma1 : na
plot(ma1V, "MA1", color = MA1_COLOR, linewidth = 4, style = plot.style_line, linestyle = plot.linestyle_solid)
float ma2 = f_ma(str.tostring(ma2Type), ma2Len)
float ma2V = showMaLines and ma2Show ? ma2 : na
plot(ma2V, "MA2", color = MA2_COLOR, linewidth = 4, style = plot.style_line, linestyle = plot.linestyle_solid)
float ma3 = f_ma(str.tostring(ma3Type), ma3Len)
float ma3V = showMaLines and ma3Show ? ma3 : na
plot(ma3V, "MA3", color = MA3_COLOR, linewidth = 4, style = plot.style_line, linestyle = plot.linestyle_solid)
float ma4 = f_ma(str.tostring(ma4Type), ma4Len)
float ma4V = showMaLines and ma4Show ? ma4 : na
plot(ma4V, "MA4", color = MA4_COLOR, linewidth = 4, style = plot.style_line, linestyle = plot.linestyle_solid)
 
// 6. LAST-BAR LABELS AND DASHBOARD
var label startLabel = label.new(na, na, "", xloc = xloc.bar_index, style = label.style_label_left, color = color.new(color.white, 100), size = size.small)
var label inflLabel = label.new(na, na, "", xloc = xloc.bar_index, style = label.style_label_left, color = color.new(color.white, 100), size = size.small)
var label ma1Label = label.new(na, na, "", xloc = xloc.bar_index, style = label.style_label_left, color = color.new(color.white, 100), size = size.small)
var label ma2Label = label.new(na, na, "", xloc = xloc.bar_index, style = label.style_label_left, color = color.new(color.white, 100), size = size.small)
var label ma3Label = label.new(na, na, "", xloc = xloc.bar_index, style = label.style_label_left, color = color.new(color.white, 100), size = size.small)
var label ma4Label = label.new(na, na, "", xloc = xloc.bar_index, style = label.style_label_left, color = color.new(color.white, 100), size = size.small)
var label startMarker = label.new(na, na, "", xloc = xloc.bar_time, yloc = yloc.belowbar, style = label.style_triangleup, color = GAIN_COLOR, textcolor = GAIN_COLOR, text_formatting = text.format_bold, size = size.small)
string panelPosition = switch tablePos
    TablePos.middleRight => position.middle_right
    TablePos.bottomRight => position.bottom_right
    TablePos.topLeft => position.top_left
    TablePos.bottomLeft => position.bottom_left
    => position.top_right
var table panel = table.new(panelPosition, 2, 24, border_width = 1)
var bool exampleRowsMerged = false
if barstate.islast
    float pxLast = px
    float cpiLast = cpiRaw
    string cpiLastMonth = not na(cpiTime) ? str.format_time(cpiTime, "MMM yyyy", "UTC") : "n/a"
    float growth = started ? pxLast / pxStart : na
    float real = started and not na(cpiStart) and not na(cpiLast) ? growth * cpiStart / cpiLast : na
    f_lineLabel(startLabel, startLineV, "Start", START_COLOR, showStartLine)
    f_lineLabel(inflLabel, inflLineV, "Inflation only", INFL_COLOR, showInflLine)
    f_lineLabel(ma1Label, ma1V, "MA1 " + str.tostring(ma1Len) + " " + str.tostring(ma1Type), MA1_COLOR, showMaLines and ma1Show)
    label.set_size(ma1Label, labelTextSize)
    f_lineLabel(ma2Label, ma2V, "MA2 " + str.tostring(ma2Len) + " " + str.tostring(ma2Type), MA2_COLOR, showMaLines and ma2Show)
    label.set_size(ma2Label, labelTextSize)
    f_lineLabel(ma3Label, ma3V, "MA3 " + str.tostring(ma3Len) + " " + str.tostring(ma3Type), MA3_COLOR, showMaLines and ma3Show)
    label.set_size(ma3Label, labelTextSize)
    f_lineLabel(ma4Label, ma4V, "MA4 " + str.tostring(ma4Len) + " " + str.tostring(ma4Type), MA4_COLOR, showMaLines and ma4Show)
    label.set_size(ma4Label, labelTextSize)
    label.set_size(startLabel, labelTextSize)
    label.set_size(inflLabel, labelTextSize)
    label.set_xy(startMarker, showStartLine and started ? startBarTime : na, startClose)
    label.set_text(startMarker, showStartLine and started ? "START" : "")
    label.set_size(startMarker, labelTextSize)
    array<string> warningMessages = array.new<string>()
    if timeframe.isintraday
        array.push(warningMessages, "Built for daily charts; intraday history is too short.")
    if startBeforeHistory
        array.push(warningMessages, "Start is before the chart's history; starting " + startDateText + ".")
    if not started
        array.push(warningMessages, "The start date is after the last bar.")
    if syminfo.currency != "USD"
        array.push(warningMessages, syminfo.ticker + " prices converted from " + syminfo.currency + " to US dollars; returns include currency moves.")
    if adjustInflation and na(cpiStart)
        array.push(warningMessages, "No CPI for the start month; prices aren't adjusted for inflation.")
    bool hasWarnings = array.size(warningMessages) > 0
    string warnings = hasWarnings ? array.join(warningMessages, "\n") : "None"
    table.clear(panel, 0, 0, 1, 23)
    if showInfo
        string titleValue = syminfo.ticker + (started ? " FROM " + startDateText + " · " + (reinvestDivs ? "DIVIDENDS REINVESTED" : "PRICE ONLY") : " · NO START BAR")
        f_pair(panel, 0, "SPLURGE VS INVEST", str.upper(titleValue), th.titleBg, th.titleText, th.titleText, true, titleTextSize)
        int rowIndex = 1
        if started
            float shadeGrowth = not na(real) ? real : growth
            bool gain = shadeGrowth >= 1.0
            string returnText = f_pct(growth) + " / " + f_pct(real) + " (" + f_mult(growth) + " / " + f_mult(real) + ")"
            f_pair(panel, rowIndex, "Return / after inflation", returnText, gain ? th.gainBg : th.lossBg, gain ? th.gainText : th.lossText, gain ? th.gainText : th.lossText, true, tableTextSize)
            rowIndex += 1
            int subtitleIdx = selectedIdx != NO_SELECTION ? selectedIdx : tableFormat == TableFormat.compact ? array.get(COMPACT_IDX, 0) : array.get(EXAMPLE_IDX, 0)
            string subtitle = f_subtitle(subtitleIdx, pxLast, cpiLast)
            if tableFormat == TableFormat.detailed
                f_mergedRow(panel, rowIndex, "", th.rowBg, th.valueText, false, size.tiny, not exampleRowsMerged)
                rowIndex += 1
            f_mergedRow(panel, rowIndex, subtitle, th.headerBg, th.headerText, true, tableTextSize, not exampleRowsMerged, text.align_center)
            rowIndex += 1
            if tableFormat == TableFormat.compact
                string header = categoryId == 0 ? "HEADLINE ITEMS" : str.upper(str.tostring(category))
                f_pair(panel, rowIndex, header, "paid then → worth today", th.headerBg, th.headerText, th.headerText, false, tableTextSize)
                rowIndex += 1
                for itemIdx in COMPACT_IDX
                    bool isCustom = itemIdx == CUSTOM_IDX
                    string itemName = isCustom ? myName : array.get(ITEM_NAME, itemIdx)
                    bool perYear = isCustom ? myType == ItemType.perYear : array.get(ITEM_PER_YEAR, itemIdx)
                    [caption, value] = f_item(f_titleCase(itemName), f_itemCost(itemIdx), perYear, isCustom ? cpiLast : LIST_CPI, pxLast, cpiLast)
                    bool selected = itemIdx == selectedIdx
                    f_pair(panel, rowIndex, caption, value, selected ? th.selBg : th.rowBg, selected ? th.selText : th.captionText, selected ? th.selText : th.valueText, selected, tableTextSize)
                    rowIndex += 1
            else
                // The subtitle's lower spacer is also the first example's upper spacer.
                f_mergedRow(panel, rowIndex, "", th.rowBg, th.valueText, false, size.tiny, not exampleRowsMerged)
                rowIndex += 1
                for itemIdx in EXAMPLE_IDX
                    bool selected = itemIdx == selectedIdx
                    string sentence = f_detail(itemIdx, pxLast, cpiLast, growth, real)
                    f_mergedRow(panel, rowIndex, sentence, selected ? th.selBg : th.rowBg, selected ? th.selText : th.valueText, false, tableTextSize, not exampleRowsMerged)
                    rowIndex += 1
                    f_mergedRow(panel, rowIndex, "", th.rowBg, th.valueText, false, size.tiny, not exampleRowsMerged)
                    rowIndex += 1
            exampleRowsMerged := true
            bool hasCpi = not na(cpiStart) and not na(cpiLast)
            string cpiText = "n/a"
            if hasCpi
                float priceChange = (cpiLast / cpiStart - 1.0) * 100.0
                string changeText = (priceChange >= 0 ? "+" : "−") + str.tostring(math.abs(priceChange), "0.0") + "%"
                cpiText := cpiStartMonth + " " + str.tostring(cpiStart, "0.0") + " / " + cpiLastMonth + " " + str.tostring(cpiLast, "0.0") + " (prices " + changeText + (adjOn ? "" : ", not applied") + ")"
            float dollarWorth = hasCpi ? real : growth
            string dollarText = na(dollarWorth) ? "n/a" : dollarWorth < 1000 ? "$" + str.tostring(dollarWorth, "0.00") : f_usd(dollarWorth)
            cpiText += "\n$1.00 invested in " + tickerBold + " then would be worth " + (dollarWorth < 1 ? "only " : "") + dollarText + " today, " + (hasCpi ? "after inflation" : "before inflation")
            if hasCpi
                float cash = cpiStart / cpiLast
                cpiText += "\n$1.00 kept in cash would be worth " + (cash < 1 ? "only " : "") + "$" + str.tostring(cash, "0.00") + " today, after inflation"
            f_pair(panel, rowIndex, "CPI start / latest", cpiText, th.footBg, th.footCaption, th.footValue, false, tableTextSize)
            rowIndex += 1
        f_pair(panel, rowIndex, "Warnings", warnings, th.footBg, th.footCaption, hasWarnings ? th.warnText : th.footCaption, false, tableTextSize)
        rowIndex += 1
        if showDisclaimer
            f_pair(panel, rowIndex, "Disclaimer", "Hypothetical, before taxes and costs. Educational tool, not investment advice.", th.footBg, th.footCaption, th.footCaption, false, tableTextSize)

← 返回列表