本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Original code written from scratch to analyze how global markets react to the 4-year US Presidential Election Cycle.
//@version=6
indicator(
title = "Global Market Reaction to the US Presidential Cycle",
overlay = true,
behind_chart = true,
max_lines_count = 500,
max_labels_count = 500,
max_boxes_count = 500
)
// ============================================================================
// 1. CONSTANTS & INPUT SETTINGS
// ============================================================================
const string GRP_MARKET = "A. Market Selection"
const string GRP_BG = "B. Background Colors"
const string GRP_MARKERS = "C. Election Markers"
const string GRP_LABELS = "D. Performance Labels"
const string GRP_HIST = "E. Historical Settings"
const string GRP_CONFIRM = "F. Wait for Candle Close Confirmation"
const string GRP_DASH = "G. Historical Cycle Dashboard"
const string GRP_PARTY = "H. Presidential Party Labels"
const string MODE_AUTO = "Automatic (Chart Symbol)"
const string MODE_CUSTOM = "Custom Symbol"
const string DASH_BOTH = "Summary + Cycle Ledger"
const string DASH_SUM = "Summary Statistics Only"
const string DASH_LEDGER = "Cycle Ledger Only"
// --- A. Market Selection ---
string calcMode = input.string(
defval = MODE_AUTO,
title = "Calculation Mode",
options = [MODE_AUTO, MODE_CUSTOM],
group = GRP_MARKET,
tooltip = "Automatic (Chart Symbol): Calculates annual returns from the global instrument currently shown on the chart.\nCustom Symbol: Calculates annual returns from the Custom Calculation Symbol below (default: S&P 500) and overlays them onto the current chart.",
display = display.data_window
)
string customSymbol = input.symbol(
defval = "SP:SPX",
title = "Custom Calculation Symbol",
group = GRP_MARKET,
tooltip = "Used when Calculation Mode is set to Custom Symbol. Default is S&P 500 (SP:SPX). Compatible with global indices, crypto, commodities, FX, and stocks worldwide (e.g., SP:SPX, NASDAQ:NDX, DJ:DJI, XETR:DAX, TVC:UKX, TVC:NI225, HKEX:HSI, NSE:NIFTY, BTCUSD, XAUUSD).",
display = display.data_window
)
// --- B. Background Colors ---
color posBgColor = input.color(
defval = #00C853,
title = "Positive Performance Color",
group = GRP_BG,
tooltip = "Background zone color when the selected market finished the year (or current YTD) with a positive return.",
display = display.none
)
color negBgColor = input.color(
defval = #FF0000,
title = "Negative Performance Color",
group = GRP_BG,
tooltip = "Background zone color when the selected market finished the year (or current YTD) with a negative return (default: #FF0000).",
display = display.none
)
int bgTransparency = input.int(
defval = 70,
title = "Background Transparency (0–100)",
minval = 0,
maxval = 100,
group = GRP_BG,
tooltip = "0 = fully opaque, 100 = fully transparent. Default is 70.",
display = display.data_window
)
bool showYearDividers = input.bool(
defval = true,
title = "Show Annual Zone Divider Lines",
group = GRP_BG,
tooltip = "Draws a subtle boundary line between consecutive calendar years so adjacent all-green or all-red years remain visually distinct.",
display = display.none
)
color yearDividerColor = input.color(
defval = color.new(#787B86, 65),
title = "Annual Divider Line Color",
group = GRP_BG,
tooltip = "Color used for the subtle boundary between adjacent annual background zones.",
display = display.none
)
// --- C. Election Markers ---
bool showPresMarker = input.bool(
defval = true,
title = "Show Presidential Election Marker (Year 0)",
group = GRP_MARKERS,
tooltip = "Displays a vertical line on the US Presidential Election date in Year 0.",
display = display.none
)
bool showMidMarker = input.bool(
defval = true,
title = "Show Midterm Election Marker (Year 2)",
group = GRP_MARKERS,
tooltip = "Displays a distinct vertical line on the US Midterm Election date in Year 2.",
display = display.none
)
color presMarkerColor = input.color(
defval = #FFFFFF,
title = "Presidential Marker Color",
group = GRP_MARKERS,
tooltip = "Color of the Year 0 Presidential Election vertical line and label background (default: #FFFFFF white).",
display = display.none
)
color presMarkerTextColor = input.color(
defval = #000000,
title = "Presidential Marker Text Color",
group = GRP_MARKERS,
tooltip = "Text color for the 'YEAR 0 – PRESIDENTIAL ELECTION' label (default: #000000 black).",
display = display.none
)
string presLineStyleIn = input.string(
defval = "Solid",
title = "Presidential Marker Line Style",
options = ["Solid", "Dashed", "Dotted"],
group = GRP_MARKERS,
tooltip = "Selects the line pattern used for Presidential Year 0 election markers.",
display = display.data_window
)
int presLineWidth = input.int(
defval = 2,
title = "Presidential Marker Line Width",
minval = 1,
maxval = 4,
group = GRP_MARKERS,
tooltip = "Sets the thickness of Presidential Year 0 vertical marker lines.",
display = display.data_window
)
color midMarkerColor = input.color(
defval = #000000,
title = "Midterm Marker Color",
group = GRP_MARKERS,
tooltip = "Color of the Year 2 Midterm Election vertical line and label background (default: #000000 black).",
display = display.none
)
color midMarkerTextColor = input.color(
defval = #FFFFFF,
title = "Midterm Marker Text Color",
group = GRP_MARKERS,
tooltip = "Text color for the 'YEAR 2 – MIDTERM ELECTION' label (default: #FFFFFF white).",
display = display.none
)
string midLineStyleIn = input.string(
defval = "Dashed",
title = "Midterm Marker Line Style",
options = ["Solid", "Dashed", "Dotted"],
group = GRP_MARKERS,
tooltip = "Selects the line pattern used for Midterm Year 2 election markers.",
display = display.data_window
)
int midLineWidth = input.int(
defval = 2,
title = "Midterm Marker Line Width",
minval = 1,
maxval = 4,
group = GRP_MARKERS,
tooltip = "Sets the thickness of Midterm Year 2 vertical marker lines.",
display = display.data_window
)
bool showMarkerLabels = input.bool(
defval = true,
title = "Show Election & Midterm Marker Labels",
group = GRP_MARKERS,
tooltip = "Shows 'YEAR 0 – PRESIDENTIAL ELECTION' and 'YEAR 2 – MIDTERM ELECTION' labels on the election markers.",
display = display.none
)
string markerLabelPos = input.string(
defval = "Bottom",
title = "Marker Label Position",
options = ["Bottom", "Top"],
group = GRP_MARKERS,
tooltip = "Places event marker labels below the year's low or above the year's high so candlesticks remain unobstructed.",
display = display.data_window
)
string markerTextSizeIn = input.string(
defval = "Small",
title = "Marker Label Text Size",
options = ["Tiny", "Small", "Normal", "Large"],
group = GRP_MARKERS,
tooltip = "Controls the text size of Presidential and Midterm election marker labels.",
display = display.data_window
)
// --- D. Performance Labels ---
bool showPerfLabels = input.bool(
defval = true,
title = "Show Annual Percentage",
group = GRP_LABELS,
tooltip = "Displays the presidential-cycle year and percentage return for each annual zone.",
display = display.none
)
string perfLabelPos = input.string(
defval = "Top",
title = "Label Position",
options = ["Top", "Bottom", "Middle"],
group = GRP_LABELS,
tooltip = "Top places the label above the year's highest candle; Bottom places it below the year's lowest candle; Middle places it at the midpoint of the year's price range.",
display = display.data_window
)
string perfTextSizeIn = input.string(
defval = "Small",
title = "Text Size",
options = ["Tiny", "Small", "Normal", "Large", "Huge"],
group = GRP_LABELS,
tooltip = "Controls the text size of annual performance labels displayed in each year zone.",
display = display.data_window
)
color posTextColor = input.color(
defval = #1FF500,
title = "Positive Return Text Color",
group = GRP_LABELS,
tooltip = "Text color for positive annual returns (default: #1FF500).",
display = display.none
)
color negTextColor = input.color(
defval = #FF0000,
title = "Negative Return Text Color",
group = GRP_LABELS,
tooltip = "Text color for negative annual returns (default: #FF0000).",
display = display.none
)
color perfBadgeBgColor = input.color(
defval = color.new(#131722, 15),
title = "Performance Label Background",
group = GRP_LABELS,
tooltip = "Backdrop color and opacity for performance labels to maintain readability on both dark and light chart themes.",
display = display.none
)
bool showCalYearInLbl = input.bool(
defval = false,
title = "Include Calendar Year Prefix",
group = GRP_LABELS,
tooltip = "Optional: prefixes each label with the four-digit calendar year (e.g., '2024 | YEAR 0 – ELECTION: +23.31%').",
display = display.none
)
// --- E. Historical Settings ---
bool autoHistDates = input.bool(
defval = true,
title = "Automatic Historical Election Dates",
group = GRP_HIST,
tooltip = "Automatically computes the statutory US election date (first Tuesday after the first Monday in November) for every historical and upcoming Presidential (Year 0) and Midterm (Year 2) year.",
display = display.none
)
bool enableManualDates = input.bool(
defval = false,
title = "Optional Manual Date Override",
group = GRP_HIST,
tooltip = "When enabled, any YYYY-MM-DD dates entered below override the automatic election or midterm date for their corresponding calendar year.",
display = display.none
)
string manualDatesInput = input.string(
defval = "2024-11-05, 2026-11-03",
title = "Manual Override Dates (YYYY-MM-DD)",
group = GRP_HIST,
tooltip = "Comma-separated list of custom election or midterm dates in YYYY-MM-DD format (e.g., 2020-11-03, 2022-11-08, 2024-11-05, 2026-11-03). Used when Optional Manual Date Override is enabled.",
display = display.data_window
)
bool showHistZones = input.bool(
defval = true,
title = "Historical Zone Visibility",
group = GRP_HIST,
tooltip = "Enables or disables the green/red annual performance background zones across historical cycles.",
display = display.none
)
int maxHistYears = input.int(
defval = 120,
title = "Maximum Historical Years Displayed",
minval = 1,
maxval = 250,
group = GRP_HIST,
tooltip = "Maximum number of calendar years rendered from the latest chart year backwards (subject to symbol history and Pine drawing limits).",
display = display.data_window
)
// --- F. Wait for Candle Close Confirmation ---
bool waitForClose = input.bool(
defval = true,
title = "Wait for Candle Close Confirmation",
group = GRP_CONFIRM,
tooltip = "ENABLED (Default): Non-repainting behaviour. Annual/YTD calculations update only after each daily candle closes.\nDISABLED: Allows current-year YTD calculations to update dynamically before daily candle close.\nCompleted historical annual returns always remain permanently stable.",
display = display.none
)
// --- G. Historical Cycle Dashboard ---
bool showDashboard = input.bool(
defval = false,
title = "Show Historical Cycle Dashboard",
group = GRP_DASH,
tooltip = "OFF by default. Aggregates the full 1D historical dataset of the selected symbol across 4-year US Presidential Cycles into a single table—no manual chart scrolling required.\n\nTip: Click More (...) on the indicator status line -> 'Move tables to bottom' to open a full-width, scrollable, copyable bottom panel.",
display = display.none
)
string dashViewMode = input.string(
defval = DASH_BOTH,
title = "Dashboard View Mode",
options = [DASH_BOTH, DASH_SUM, DASH_LEDGER],
group = GRP_DASH,
tooltip = "Summary + Cycle Ledger: Shows aggregated statistics per cycle year (Year 0–3 vs All-Years Baseline) plus individual 4-year cycle rows.\nSummary Statistics Only: Compact statistical summary card.\nCycle Ledger Only: Shows only the 4-year historical cycle matrix.",
display = display.data_window
)
color dashBgColor = input.color(
defval = #000000,
title = "Dashboard Background Color",
group = GRP_DASH,
tooltip = "Background color of the Historical Cycle Dashboard (default: #000000 black).",
display = display.none
)
color dashTextColor = input.color(
defval = #FFFFFF,
title = "Dashboard Text Color",
group = GRP_DASH,
tooltip = "Text color for dashboard headers, cycle spans, labels, and standard cells (default: #FFFFFF white).",
display = display.none
)
color dashBorderColor = input.color(
defval = #2E2E2E,
title = "Dashboard Grid Border Color",
group = GRP_DASH,
tooltip = "Color of the grid lines separating dashboard rows and columns.",
display = display.none
)
int dashBgTransp = input.int(
defval = 0,
title = "Dashboard Background Transparency (0–100)",
minval = 0,
maxval = 100,
group = GRP_DASH,
tooltip = "0 = solid opaque background (default #000000 black), 100 = fully transparent.",
display = display.data_window
)
bool dashColorizeReturns = input.bool(
defval = true,
title = "Colorize Positive / Negative Return Text",
group = GRP_DASH,
tooltip = "ENABLED (Default): Colors positive and negative percentage figures using Positive (#1FF500) and Negative (#FF0000) Return Text Colors.\nDISABLED: Displays all figures in the Dashboard Text Color (#FFFFFF).",
display = display.none
)
bool dashTintCells = input.bool(
defval = true,
title = "Colored Return Cell Backgrounds (On/Off)",
group = GRP_DASH,
tooltip = "ON (Default): Applies a shaded green/red background tint to cells displaying positive or negative returns.\nOFF: Uses the Dashboard Background Color for all return cells, while keeping the colored return text unchanged.",
display = display.none
)
int dashStartYear = input.int(
defval = 0,
title = "Filter Start Year (0 = Full 1D History)",
minval = 0,
maxval = 2100,
group = GRP_DASH,
tooltip = "0 evaluates the entire available 1D history of the selected symbol (up to 100,000 daily bars). Set a specific year (e.g., 1928, 1950, 1971, or 2000) to isolate a specific historical regime.",
display = display.data_window
)
int dashMaxCycles = input.int(
defval = 30,
title = "Max 4-Year Cycles Listed in Ledger",
minval = 1,
maxval = 65,
group = GRP_DASH,
tooltip = "Maximum number of 4-year Presidential Cycles shown in the Cycle Ledger (30 cycles = 120 years; 65 cycles = 260 years). Summary Statistics always include all years matching the Filter Start Year.",
display = display.data_window
)
string dashSortOrder = input.string(
defval = "Newest First",
title = "Cycle Ledger Order",
options = ["Newest First", "Oldest First"],
group = GRP_DASH,
tooltip = "Controls whether the Cycle Ledger lists the most recent 4-year cycle at the top or starts from the earliest cycle.",
display = display.data_window
)
bool dashIncludeYtd = input.bool(
defval = false,
title = "Include Unfinished Current Year (YTD) in Summary Stats",
group = GRP_DASH,
tooltip = "OFF by default so Average, Median, and Positive Rate statistics reflect strictly completed calendar years. The active YTD return is still shown in the Cycle Ledger marked with '*'.",
display = display.none
)
string dashPositionIn = input.string(
defval = "Top Right",
title = "Dashboard Chart Position",
options = ["Top Right", "Top Left", "Top Center", "Middle Right", "Middle Left", "Middle Center", "Bottom Right", "Bottom Left", "Bottom Center"],
group = GRP_DASH,
tooltip = "Anchor location on the chart pane (ignored when moved to TradingView's scrollable bottom panel via More -> 'Move tables to bottom').",
display = display.data_window
)
string dashTextSizeIn = input.string(
defval = "Small",
title = "Dashboard Text Size",
options = ["Tiny", "Small", "Normal", "Large"],
group = GRP_DASH,
tooltip = "Controls the text size of labels and values in the Historical Cycle Dashboard.",
display = display.data_window
)
bool showPartyLabels = input.bool(
defval = true,
title = "Show Presidential Party Labels",
group = GRP_PARTY,
tooltip = "ON (Default): Adds a party badge to the first available chart bar of each calendar year. The badge identifies the party of the President in office for most of that calendar year, not control of Congress. Republican years use a red badge and Democratic years use a blue badge. Years outside the mapped Republican and Democratic periods are left unlabeled. The current mapping runs through 2028.",
display = display.none
)
// ============================================================================
// 2. DATA STRUCTURES & HELPER FUNCTIONS
// ============================================================================
//@type Stores annual opening and closing prices computed on the 1D timeframe of the selected calculation symbol.
type AnnualLedger
array<int> years
array<float> opens
array<float> closes
array<bool> confirmed
//@type Holds aggregated summary statistics for one cycle-year bucket (Year 0..3) or the All-Years baseline.
type BucketStats
int count
int posCount
int negCount
int flatCount
float avgRet
float medRet
float posRate
float bestRet
int bestYear
float worstRet
int worstYear
//@function Maps cycle year remainder (0..3): Year 0 = Presidential Election (e.g., 2024), Year 1 = Post-Election (2025), Year 2 = Midterm (2026), Year 3 = Pre-Election (2027).
f_getCycleYear(int calYear) =>
int rem = calYear % 4
rem < 0 ? rem + 4 : rem
//@function Returns 1 for Republican, 2 for Democratic, or 0 when no mapped two-party label applies.
// Calendar-year transitions follow the President in office for most of the year.
f_getPresidentParty(int calYear) =>
bool isDemocratic = (
(calYear >= 1829 and calYear <= 1840) or
(calYear >= 1845 and calYear <= 1848) or
(calYear >= 1853 and calYear <= 1860) or
(calYear >= 1865 and calYear <= 1868) or
(calYear >= 1885 and calYear <= 1888) or
(calYear >= 1893 and calYear <= 1896) or
(calYear >= 1913 and calYear <= 1920) or
(calYear >= 1933 and calYear <= 1952) or
(calYear >= 1961 and calYear <= 1968) or
(calYear >= 1977 and calYear <= 1980) or
(calYear >= 1993 and calYear <= 2000) or
(calYear >= 2009 and calYear <= 2016) or
(calYear >= 2021 and calYear <= 2024)
)
bool isRepublican = (
(calYear >= 1861 and calYear <= 1864) or
(calYear >= 1869 and calYear <= 1884) or
(calYear >= 1889 and calYear <= 1892) or
(calYear >= 1897 and calYear <= 1912) or
(calYear >= 1921 and calYear <= 1932) or
(calYear >= 1953 and calYear <= 1960) or
(calYear >= 1969 and calYear <= 1976) or
(calYear >= 1981 and calYear <= 1992) or
(calYear >= 2001 and calYear <= 2008) or
(calYear >= 2017 and calYear <= 2020) or
(calYear >= 2025 and calYear <= 2028)
)
isDemocratic ? 2 : (isRepublican ? 1 : 0)
//@function Converts string size option to Pine built-in size constant.
f_getTextSize(string sizeOpt) =>
switch sizeOpt
"Tiny" => size.tiny
"Small" => size.small
"Normal" => size.normal
"Large" => size.large
"Huge" => size.huge
=> size.small
//@function Converts string style option to Pine built-in line style constant.
f_getLineStyle(string styleOpt) =>
switch styleOpt
"Solid" => line.style_solid
"Dashed" => line.style_dashed
"Dotted" => line.style_dotted
=> line.style_solid
//@function Converts string position option to Pine built-in table position constant.
f_getTablePosition(string posOpt) =>
switch posOpt
"Top Right" => position.top_right
"Top Left" => position.top_left
"Top Center" => position.top_center
"Middle Right" => position.middle_right
"Middle Left" => position.middle_left
"Middle Center" => position.middle_center
"Bottom Right" => position.bottom_right
"Bottom Left" => position.bottom_left
"Bottom Center" => position.bottom_center
=> position.top_right
//@function Formats a percentage float with an explicit '+' sign for non-negative values (2 decimal places).
f_fmtSignedPct(float val) =>
val >= 0.0 ? "+" + str.tostring(val, "0.00") + "%" : str.tostring(val, "0.00") + "%"
//@function Formats a compact percentage float with an explicit '+' sign (1 decimal place, for Best/Worst summary pairs).
f_fmtCompactPct(float val) =>
val >= 0.0 ? "+" + str.tostring(val, "0.0") + "%" : str.tostring(val, "0.0") + "%"
//@function Computes sample size, average, median, positive rate, positive/negative counts, and best/worst years for a return bucket.
f_computeBucketStats(array<float> rets, array<int> yrs) =>
int n = rets.size()
int posC = 0
int negC = 0
int fltC = 0
float avgV = float(na)
float medV = float(na)
float winR = float(na)
float bstV = float(na)
int bstY = int(na)
float wstV = float(na)
int wstY = int(na)
if n > 0
avgV := array.avg(rets)
medV := array.median(rets)
int lastIdx = n - 1
for i = 0 to lastIdx
float r = rets.get(i)
int y = yrs.get(i)
if r > 0.0
posC += 1
else if r < 0.0
negC += 1
else
fltC += 1
if na(bstV) or r > bstV
bstV := r
bstY := y
if na(wstV) or r < wstV
wstV := r
wstY := y
winR := (float(posC) / float(n)) * 100.0
BucketStats.new(n, posC, negC, fltC, avgV, medV, winR, bstV, bstY, wstV, wstY)
//@function Computes the statutory US general/midterm election date (00:00 UTC) for a given calendar year:
// First Tuesday after the first Monday in November (always falls between Nov 2 and Nov 8).
f_calcStatutoryElectionUtc(int calYear) =>
int nov1NoonUtc = timestamp("UTC", calYear, 11, 1, 12, 0, 0)
int dowNov1 = dayofweek(nov1NoonUtc, "UTC")
int electDay = switch dowNov1
dayofweek.monday => 2
dayofweek.tuesday => 8
dayofweek.wednesday => 7
dayofweek.thursday => 6
dayofweek.friday => 5
dayofweek.saturday => 4
=> 3
timestamp("UTC", calYear, 11, electDay, 0, 0, 0)
//@function Searches the comma-separated YYYY-MM-DD manual override string for a date matching `targetYear`.
f_findManualOverrideUtc(int targetYear, string rawDates) =>
int matchedTs = int(na)
string cleaned = str.trim(rawDates)
if str.length(cleaned) > 0
array<string> tokens = str.split(cleaned, ",")
int tokenCount = tokens.size()
if tokenCount > 0
int lastToken = tokenCount - 1
for i = 0 to lastToken
string entry = str.trim(tokens.get(i))
if str.length(entry) >= 8
array<string> ymd = str.split(entry, "-")
if ymd.size() == 3
float yNum = str.tonumber(str.trim(ymd.get(0)))
float mNum = str.tonumber(str.trim(ymd.get(1)))
float dNum = str.tonumber(str.trim(ymd.get(2)))
if not na(yNum) and not na(mNum) and not na(dNum)
int yi = int(yNum)
int mi = int(mNum)
int di = int(dNum)
if yi == targetYear and mi >= 1 and mi <= 12 and di >= 1 and di <= 31
matchedTs := timestamp("UTC", yi, mi, di, 0, 0, 0)
matchedTs
//@function Resolves the election/midterm UTC timestamp for `calYear` (Year 0, Year 2, or explicit manual override).
f_resolveElectionDateUtc(int calYear, bool useAuto, bool useManual, string manualStr) =>
int cyc = f_getCycleYear(calYear)
int resultTs = int(na)
if useManual
resultTs := f_findManualOverrideUtc(calYear, manualStr)
if na(resultTs) and useAuto and (cyc == 0 or cyc == 2) and calYear >= 1845
resultTs := f_calcStatutoryElectionUtc(calYear)
resultTs
//@function Formats the cycle year prefix for annual performance labels per specification.
f_formatPerfHeader(int calYear, int cycYear, bool includeCalYr) =>
string cycTitle = switch cycYear
0 => "YEAR 0 – ELECTION"
1 => "YEAR 1"
2 => "YEAR 2 – MIDTERM"
=> "YEAR 3"
includeCalYr ? str.tostring(calYear) + " | " + cycTitle : cycTitle
//@function Executes inside the 1D security context of the selected calculation symbol.
// Records the first available trading session open and last available trading session close for every calendar year.
f_buildAnnualLedger(bool requireConfirmedClose) =>
var array<int> yrList = array.new<int>(0)
var array<float> opnList = array.new<float>(0)
var array<float> clsList = array.new<float>(0)
var array<bool> cnfList = array.new<bool>(0)
if not na(open) and not na(close) and open != 0.0
// `time_tradingday` (00:00 UTC of the session's trading date) accurately assigns overnight sessions
// (e.g., futures/FX opening Dec 31 evening for the Jan 2 trading day) as well as 24/7 crypto and global exchanges.
int sessYear = not na(time_tradingday) ? year(time_tradingday, "UTC") : year(time)
bool isReplayFeed = str.contains(syminfo.tickerid, "replay")
bool isUnclosedLoadedLast = barstate.ishistory and barstate.islast and not isReplayFeed and not na(time_close) and time_close > timenow
bool isDailyBarConfirmed = barstate.isconfirmed and not isUnclosedLoadedLast
bool canUpdatePrice = not requireConfirmedClose or isDailyBarConfirmed
int count = yrList.size()
int prevYear = count > 0 ? yrList.get(count - 1) : int(na)
if count == 0 or sessYear > prevYear
if canUpdatePrice
yrList.push(sessYear)
opnList.push(open)
clsList.push(close)
cnfList.push(true)
else
// First session of a new calendar year is currently open and waiting for daily candle close confirmation.
yrList.push(sessYear)
opnList.push(open)
clsList.push(open)
cnfList.push(false)
else if sessYear == prevYear
if canUpdatePrice
int lastIdx = count - 1
if not cnfList.get(lastIdx)
opnList.set(lastIdx, open)
cnfList.set(lastIdx, true)
clsList.set(lastIdx, close)
// Emit copies only near the end of the 1D dataset to keep memory usage negligible across century-long histories,
// while guaranteeing availability on intraday (lookahead_off), daily, weekly, and monthly charts.
bool shouldEmit = barstate.islast or barstate.islastconfirmedhistory or (last_bar_index - bar_index <= 10)
AnnualLedger snapshot = shouldEmit ? AnnualLedger.new(yrList.copy(), opnList.copy(), clsList.copy(), cnfList.copy()) : na
snapshot
// ============================================================================
// 3. UNIVERSAL DAILY (1D) SYMBOL PERFORMANCE REQUEST
// ============================================================================
string trimmedCustom = str.trim(customSymbol)
string targetSymbol = (calcMode == MODE_CUSTOM and str.length(trimmedCustom) > 0) ? trimmedCustom : syminfo.tickerid
AnnualLedger requestedLedger = request.security(
symbol = targetSymbol,
timeframe = "1D",
expression = f_buildAnnualLedger(waitForClose),
gaps = barmerge.gaps_off,
lookahead = barmerge.lookahead_off,
ignore_invalid_symbol = true,
calc_bars_count = 100000
)
// Live quote on the active timeframe for instant intra-candle YTD responsiveness on intraday charts when Wait for Close is disabled.
[liveSymPrice, liveSymYear] = request.security(
symbol = targetSymbol,
timeframe = timeframe.period,
expression = [close, not na(time_tradingday) ? year(time_tradingday, "UTC") : year(time)],
gaps = barmerge.gaps_off,
lookahead = barmerge.lookahead_off,
ignore_invalid_symbol = true
)
var AnnualLedger latestLedger = na
if not na(requestedLedger)
latestLedger := requestedLedger
// ============================================================================
// 4. MAIN CHART ANNUAL ZONE & ELECTION BAR TRACKING
// ============================================================================
// Determine the calendar year of each main-chart bar cleanly across intraday, daily, weekly, and monthly charts.
int tradingDayYear = not na(time_tradingday) ? year(time_tradingday, "UTC") : year(time)
int chartBarYear = (timeframe.isintraday or timeframe.isdaily) ? tradingDayYear : year(time)
// Presidential party badges are separate from, and do not alter, annual return colors.
int partyCode = f_getPresidentParty(chartBarYear)
bool firstChartBarOfYear = barstate.isfirst or chartBarYear != chartBarYear[1]
plotshape(
series = showPartyLabels and firstChartBarOfYear and partyCode == 1,
title = "Republican Presidential Party",
style = shape.labeldown,
location = location.top,
color = #FF0000,
text = "REPUBLICAN",
textcolor = #FFFFFF,
size = size.tiny,
editable = false,
display = display.pane
)
plotshape(
series = showPartyLabels and firstChartBarOfYear and partyCode == 2,
title = "Democratic Presidential Party",
style = shape.labeldown,
location = location.top,
color = #2962FF,
text = "DEMOCRATIC",
textcolor = #FFFFFF,
size = size.tiny,
editable = false,
display = display.pane
)
// UTC start-of-day and end-of-bar-session timestamps for accurate Election Day matching across all timeframes and holiday schedules.
int barStartUtc = timestamp("UTC", year(time), month(time), dayofmonth(time), 0, 0, 0)
int barEndUtc = not na(time_tradingday) ? time_tradingday : nz(time_close, time)
// Election-date alerts are informational calendar events, not trading signals.
// The seven-day window matches marker handling for weekends, holidays, and non-US sessions.
int electionAlertUtc = f_resolveElectionDateUtc(chartBarYear, autoHistDates, enableManualDates, manualDatesInput)
bool electionDateBar = not na(electionAlertUtc) and barEndUtc >= electionAlertUtc and barStartUtc <= electionAlertUtc + 7 * 86400000
bool firstElectionDateBar = electionDateBar and not electionDateBar[1] and barstate.isconfirmed
bool presidentialElectionAlert = firstElectionDateBar and f_getCycleYear(chartBarYear) == 0
bool midtermElectionAlert = firstElectionDateBar and f_getCycleYear(chartBarYear) == 2
alertcondition(presidentialElectionAlert, "Presidential Election Date (Year 0)", "Presidential Election (Year 0) calendar event on {{ticker}} ({{interval}}). Informational only; not a buy or sell signal.")
alertcondition(midtermElectionAlert, "Midterm Election Date (Year 2)", "Midterm Election (Year 2) calendar event on {{ticker}} ({{interval}}). Informational only; not a buy or sell signal.")
var array<int> chartYears = array.new<int>(0)
var array<int> chartStartTimes = array.new<int>(0)
var array<int> chartMidTimes = array.new<int>(0)
var array<float> chartStartLows = array.new<float>(0)
var array<float> chartStartHighs = array.new<float>(0)
var array<float> chartYearHighs = array.new<float>(0)
var array<float> chartYearLows = array.new<float>(0)
var array<int> chartElectTimes = array.new<int>(0)
var array<float> chartElectHighs = array.new<float>(0)
var array<float> chartElectLows = array.new<float>(0)
var array<int> currYrBarTimes = array.new<int>(0)
int trackedCount = chartYears.size()
int lastTrackedYear = trackedCount > 0 ? chartYears.get(trackedCount - 1) : int(na)
if trackedCount == 0 or chartBarYear > lastTrackedYear
currYrBarTimes.clear()
currYrBarTimes.push(time)
chartYears.push(chartBarYear)
chartStartTimes.push(time)
chartMidTimes.push(time)
chartStartLows.push(low)
chartStartHighs.push(high)
chartYearHighs.push(high)
chartYearLows.push(low)
int targetElectUtc = f_resolveElectionDateUtc(chartBarYear, autoHistDates, enableManualDates, manualDatesInput)
bool hitsElectOnFirstBar = not na(targetElectUtc) and barEndUtc >= targetElectUtc and barStartUtc <= targetElectUtc + 7 * 86400000
chartElectTimes.push(hitsElectOnFirstBar ? time : int(na))
chartElectHighs.push(hitsElectOnFirstBar ? high : float(na))
chartElectLows.push(hitsElectOnFirstBar ? low : float(na))
else if chartBarYear == lastTrackedYear
int idx = trackedCount - 1
currYrBarTimes.push(time)
int midBarPos = int(math.floor((currYrBarTimes.size() - 1) * 0.5))
chartMidTimes.set(idx, currYrBarTimes.get(midBarPos))
if high > chartYearHighs.get(idx)
chartYearHighs.set(idx, high)
if low < chartYearLows.get(idx)
chartYearLows.set(idx, low)
if na(chartElectTimes.get(idx))
int targetElectUtc = f_resolveElectionDateUtc(chartBarYear, autoHistDates, enableManualDates, manualDatesInput)
if not na(targetElectUtc) and barEndUtc >= targetElectUtc and barStartUtc <= targetElectUtc + 7 * 86400000
chartElectTimes.set(idx, time)
chartElectHighs.set(idx, high)
chartElectLows.set(idx, low)
// ============================================================================
// 5. VISUAL RENDERING (OVERLAY ZONES, ELECTION MARKERS & PERFORMANCE LABELS)
// ============================================================================
var array<line> poolZoneLines = array.new<line>(0)
var array<linefill> poolZoneFills = array.new<linefill>(0)
var array<line> poolElectLines = array.new<line>(0)
var array<label> poolElectLabels = array.new<label>(0)
var array<label> poolPerfLabels = array.new<label>(0)
var table dashTable = na
if barstate.islast
// Clean up prior last-bar drawings to prevent object accumulation across realtime bar transitions.
int nZoneLines = poolZoneLines.size()
if nZoneLines > 0
int lastZL = nZoneLines - 1
for i = 0 to lastZL
line.delete(poolZoneLines.get(i))
poolZoneLines.clear()
int nZoneFills = poolZoneFills.size()
if nZoneFills > 0
int lastZF = nZoneFills - 1
for i = 0 to lastZF
linefill.delete(poolZoneFills.get(i))
poolZoneFills.clear()
int nElectLines = poolElectLines.size()
if nElectLines > 0
int lastEL = nElectLines - 1
for i = 0 to lastEL
line.delete(poolElectLines.get(i))
poolElectLines.clear()
int nElectLabels = poolElectLabels.size()
if nElectLabels > 0
int lastELb = nElectLabels - 1
for i = 0 to lastELb
label.delete(poolElectLabels.get(i))
poolElectLabels.clear()
int nPerfLabels = poolPerfLabels.size()
if nPerfLabels > 0
int lastPLb = nPerfLabels - 1
for i = 0 to lastPLb
label.delete(poolPerfLabels.get(i))
poolPerfLabels.clear()
int totalYears = chartYears.size()
if totalYears > 0
int startIdx = math.max(0, totalYears - maxHistYears)
int endIdx = totalYears - 1
int spanCnt = endIdx - startIdx + 1
// Resolve visual styles once before the rendering loop.
color posZoneFill = color.new(posBgColor, bgTransparency)
color negZoneFill = color.new(negBgColor, bgTransparency)
color flatZoneFill = color.new(#787B86, math.min(95, bgTransparency + 5))
color dividerCol = showYearDividers ? yearDividerColor : color.new(yearDividerColor, 100)
presStyle = f_getLineStyle(presLineStyleIn)
midStyle = f_getLineStyle(midLineStyleIn)
perfSize = f_getTextSize(perfTextSizeIn)
markerSize = f_getTextSize(markerTextSizeIn)
// Build (spanCnt + 1) shared vertical boundary lines using local candle high/low + `extend.both`
// so background fills span 100% of chart height without ever compressing price auto-scaling.
array<line> boundaryLines = array.new<line>(0)
for k = startIdx to endIdx
int bTime = chartStartTimes.get(k)
float bLow = chartStartLows.get(k) - syminfo.mintick
float bHigh = chartStartHighs.get(k) + syminfo.mintick
line bLine = line.new(
x1 = bTime,
y1 = bLow,
x2 = bTime,
y2 = bHigh,
xloc = xloc.bar_time,
extend = extend.both,
color = dividerCol,
style = line.style_solid,
width = 1
)
poolZoneLines.push(bLine)
boundaryLines.push(bLine)
// Rightmost boundary at the closing edge of the latest bar on the chart.
int tfSeconds = int(nz(timeframe.in_seconds(), 86400))
int fallbackStepMs = math.max(60000, tfSeconds * 1000)
int lastStartTime = chartStartTimes.get(endIdx)
int barCloseEdge = nz(time_close, time + fallbackStepMs)
int rightEdgeTime = math.max(barCloseEdge, lastStartTime + fallbackStepMs)
line rightEdgeLine = line.new(
x1 = rightEdgeTime,
y1 = low - syminfo.mintick,
x2 = rightEdgeTime,
y2 = high + syminfo.mintick,
xloc = xloc.bar_time,
extend = extend.both,
color = dividerCol,
style = line.style_solid,
width = 1
)
poolZoneLines.push(rightEdgeLine)
boundaryLines.push(rightEdgeLine)
bool hasLedger = not na(latestLedger)
int currentYear = chartYears.get(endIdx)
int lastOffset = spanCnt - 1
if not hasLedger
label warnLbl = label.new(
x = time,
y = high,
text = "No 1D data available for symbol: " + targetSymbol,
xloc = xloc.bar_time,
yloc = yloc.abovebar,
color = color.new(#FF0000, 15),
style = label.style_label_down,
textcolor = color.white,
size = size.small
)
poolPerfLabels.push(warnLbl)
// Render each annual background zone, performance label, and Presidential/Midterm marker.
for offset = 0 to lastOffset
int k = startIdx + offset
int calYear = chartYears.get(k)
int cycYear = f_getCycleYear(calYear)
bool isYtd = calYear == currentYear
float yrHigh = chartYearHighs.get(k)
float yrLow = chartYearLows.get(k)
float yrRange = math.max(yrHigh - yrLow, syminfo.mintick * 10.0)
// Look up exact 1D annual return for `calYear` from the selected calculation symbol.
int ledgerPos = hasLedger ? array.indexof(latestLedger.years, calYear) : -1
bool foundSymbolYr = ledgerPos != -1
bool isReady = foundSymbolYr ? latestLedger.confirmed.get(ledgerPos) : false
float yrOpen = foundSymbolYr ? latestLedger.opens.get(ledgerPos) : float(na)
float yrClose = foundSymbolYr ? latestLedger.closes.get(ledgerPos) : float(na)
// On intraday charts with Wait for Close disabled, reflect the latest intraday quote for the active year.
if isYtd and not waitForClose and timeframe.isintraday and foundSymbolYr and not na(liveSymPrice) and liveSymYear == calYear
yrClose := liveSymPrice
isReady := true
bool validPrices = foundSymbolYr and isReady and not na(yrOpen) and yrOpen != 0.0 and not na(yrClose)
float annualRetPct = validPrices ? ((yrClose / yrOpen) - 1.0) * 100.0 : float(na)
// 1) Annual Performance Background Zone
if showHistZones and foundSymbolYr
color perfFill = validPrices ? (annualRetPct > 0.0 ? posZoneFill : (annualRetPct < 0.0 ? negZoneFill : flatZoneFill)) : flatZoneFill
linefill zf = linefill.new(boundaryLines.get(offset), boundaryLines.get(offset + 1), perfFill)
poolZoneFills.push(zf)
// 2) Annual Performance Percentage Label
if showPerfLabels and foundSymbolYr
string headerStr = f_formatPerfHeader(calYear, cycYear, showCalYearInLbl)
string retStr = validPrices ? f_fmtSignedPct(annualRetPct) : "Awaiting Close"
string fullPerfText = headerStr + ": " + retStr
string statusNote = isYtd ? (waitForClose ? "Year-to-Date (Confirmed 1D Close)" : "Year-to-Date (Live)") : "Completed Calendar Year"
string closeLabel = isYtd ? "Latest Close: " : "Year-End Close: "
string tipBody = validPrices ? ("\nYear-Start Open: " + str.tostring(yrOpen, "#.####") + "\n" + closeLabel + str.tostring(yrClose, "#.####") + "\nAnnual Return: " + retStr) : "\nWaiting for first daily candle of the year to close."
string tipText = "Calendar Year: " + str.tostring(calYear) + "\nCycle Phase: " + headerStr + "\nCalculation Symbol: " + targetSymbol + " (1D)\nPeriod Status: " + statusNote + tipBody
float bottomSafeY = yrLow > 0.0 ? math.max(yrLow * 0.85, yrLow - yrRange * 0.03) : (yrLow - yrRange * 0.03)
float perfY = switch perfLabelPos
"Top" => yrHigh + yrRange * 0.03
"Bottom" => bottomSafeY
=> (yrHigh + yrLow) * 0.5
perfStyle = switch perfLabelPos
"Top" => label.style_label_down
"Bottom" => label.style_label_up
=> label.style_label_center
color txtCol = validPrices ? (annualRetPct >= 0.0 ? posTextColor : negTextColor) : #B2B5BE
label perfLbl = label.new(
x = chartMidTimes.get(k),
y = perfY,
text = fullPerfText,
xloc = xloc.bar_time,
yloc = yloc.price,
color = perfBadgeBgColor,
style = perfStyle,
textcolor = txtCol,
size = perfSize,
textalign = text.align_center,
tooltip = tipText
)
poolPerfLabels.push(perfLbl)
// 3) Presidential Election (Year 0) & Midterm Election (Year 2) Distinct Markers
int electBarTime = chartElectTimes.get(k)
if not na(electBarTime)
bool isPresYear = cycYear == 0
bool isMidYear = cycYear == 2
bool isCustomOtherYr = not isPresYear and not isMidYear and enableManualDates
bool shouldDrawMarker = (isPresYear and showPresMarker) or (isMidYear and showMidMarker) or isCustomOtherYr
if shouldDrawMarker
color mCol = isPresYear ? presMarkerColor : midMarkerColor
color mTxtCol = isPresYear ? presMarkerTextColor : midMarkerTextColor
int mWidth = isPresYear ? presLineWidth : midLineWidth
mStyle = isPresYear ? presStyle : midStyle
float eLow = nz(chartElectLows.get(k), yrLow) - syminfo.mintick
float eHigh = nz(chartElectHighs.get(k), yrHigh) + syminfo.mintick
line eLine = line.new(
x1 = electBarTime,
y1 = eLow,
x2 = electBarTime,
y2 = eHigh,
xloc = xloc.bar_time,
extend = extend.both,
color = mCol,
style = mStyle,
width = mWidth
)
poolElectLines.push(eLine)
if showMarkerLabels
string midOrCustomTxt = isMidYear ? "YEAR 2 – MIDTERM ELECTION" : "MANUAL ELECTION OVERRIDE"
string markerText = isPresYear ? "YEAR 0 – PRESIDENTIAL ELECTION" : midOrCustomTxt
int resolvedElectTs = f_resolveElectionDateUtc(calYear, autoHistDates, enableManualDates, manualDatesInput)
string dateFormatted = not na(resolvedElectTs) ? str.format_time(resolvedElectTs, "yyyy-MM-dd", "UTC") : str.tostring(calYear)
// Offset slightly further if both performance and marker labels share the same vertical side.
bool sameSide = showPerfLabels and (markerLabelPos == perfLabelPos)
float padMult = sameSide ? 0.14 : 0.03
float mTopY = yrHigh + yrRange * padMult
float mBotY = yrLow > 0.0 ? math.max(yrLow * 0.80, yrLow - yrRange * padMult) : (yrLow - yrRange * padMult)
float markerY = markerLabelPos == "Top" ? mTopY : mBotY
mLblStyle = markerLabelPos == "Top" ? label.style_label_down : label.style_label_up
label eLbl = label.new(
x = electBarTime,
y = markerY,
text = markerText,
xloc = xloc.bar_time,
yloc = yloc.price,
color = mCol,
style = mLblStyle,
textcolor = mTxtCol,
size = markerSize,
textalign = text.align_center,
tooltip = markerText + "\nReference Date: " + dateFormatted
)
poolElectLabels.push(eLbl)
// ========================================================================
// 6. HISTORICAL CYCLE DASHBOARD RENDERING (SECTION G — OFF BY DEFAULT)
// ========================================================================
if not na(dashTable)
table.delete(dashTable)
dashTable := na
if showDashboard
dashPos = f_getTablePosition(dashPositionIn)
dashSize = f_getTextSize(dashTextSizeIn)
color tblBgCol = color.new(dashBgColor, dashBgTransp)
color tblBorderCol = color.new(dashBorderColor, math.min(85, int(dashBgTransp * 0.5)))
int cellTintTrsp = math.min(92, math.max(55, 72 + int(dashBgTransp * 0.2)))
color posCellBg = dashTintCells ? color.new(posBgColor, cellTintTrsp) : tblBgCol
color negCellBg = dashTintCells ? color.new(negBgColor, cellTintTrsp) : tblBgCol
color dashPosFg = dashColorizeReturns ? posTextColor : dashTextColor
color dashNegFg = dashColorizeReturns ? negTextColor : dashTextColor
bool hasLedgerData = not na(latestLedger) and latestLedger.years.size() > 0
if not hasLedgerData
dashTable := table.new(
position = dashPos,
columns = 1,
rows = 2,
bgcolor = tblBgCol,
frame_color = tblBorderCol,
frame_width = 1,
border_color = tblBorderCol,
border_width = 1
)
table.cell(dashTable, 0, 0, "GLOBAL MARKET × US PRESIDENTIAL CYCLE", text_color = dashTextColor, text_halign = text.align_center, text_size = dashSize, bgcolor = tblBgCol)
table.cell(dashTable, 0, 1, "No 1D historical data available for: " + targetSymbol, text_color = dashNegFg, text_halign = text.align_center, text_size = dashSize, bgcolor = tblBgCol)
else
array<int> dYears = array.new<int>(0)
array<float> dOpens = array.new<float>(0)
array<float> dCloses = array.new<float>(0)
array<float> dRets = array.new<float>(0)
array<bool> dValid = array.new<bool>(0)
array<bool> dIsYtd = array.new<bool>(0)
int rawLen = latestLedger.years.size()
int lastRawIdx = rawLen - 1
int chartLastYr = chartYears.size() > 0 ? chartYears.get(chartYears.size() - 1) : year(time)
int activeRefYear = str.contains(syminfo.tickerid, "replay") ? chartLastYr : year(timenow, "UTC")
for m = 0 to lastRawIdx
int yr = latestLedger.years.get(m)
if yr >= dashStartYear
bool isYtdYr = yr >= activeRefYear
bool rdy = latestLedger.confirmed.get(m)
float opn = latestLedger.opens.get(m)
float cls = latestLedger.closes.get(m)
if isYtdYr and not waitForClose and timeframe.isintraday and not na(liveSymPrice) and liveSymYear == yr
cls := liveSymPrice
rdy := true
bool vld = rdy and not na(opn) and opn != 0.0 and not na(cls)
float ret = vld ? ((cls / opn) - 1.0) * 100.0 : float(na)
dYears.push(yr)
dOpens.push(opn)
dCloses.push(cls)
dRets.push(ret)
dValid.push(vld)
dIsYtd.push(isYtdYr)
int dCount = dYears.size()
if dCount == 0
dashTable := table.new(
position = dashPos,
columns = 1,
rows = 2,
bgcolor = tblBgCol,
frame_color = tblBorderCol,
frame_width = 1,
border_color = tblBorderCol,
border_width = 1
)
table.cell(dashTable, 0, 0, "GLOBAL MARKET × US PRESIDENTIAL CYCLE", text_color = dashTextColor, text_halign = text.align_center, text_size = dashSize, bgcolor = tblBgCol)
table.cell(dashTable, 0, 1, "No 1D history on or after " + str.tostring(dashStartYear) + " for " + targetSymbol, text_color = dashTextColor, text_halign = text.align_center, text_size = dashSize, bgcolor = tblBgCol)
else
// Build summary buckets: Year 0, Year 1, Year 2, Year 3, and All Years Baseline.
array<float> r0 = array.new<float>(0)
array<int> y0 = array.new<int>(0)
array<float> r1 = array.new<float>(0)
array<int> y1 = array.new<int>(0)
array<float> r2 = array.new<float>(0)
array<int> y2 = array.new<int>(0)
array<float> r3 = array.new<float>(0)
array<int> y3 = array.new<int>(0)
array<float> rA = array.new<float>(0)
array<int> yA = array.new<int>(0)
int lastD = dCount - 1
for m = 0 to lastD
bool vld = dValid.get(m)
bool ytdFlag = dIsYtd.get(m)
if vld and (not ytdFlag or dashIncludeYtd)
int yr = dYears.get(m)
float ret = dRets.get(m)
int cyc = f_getCycleYear(yr)
rA.push(ret)
yA.push(yr)
if cyc == 0
r0.push(ret)
y0.push(yr)
else if cyc == 1
r1.push(ret)
y1.push(yr)
else if cyc == 2
r2.push(ret)
y2.push(yr)
else
r3.push(ret)
y3.push(yr)
array<BucketStats> statsArr = array.new<BucketStats>(0)
statsArr.push(f_computeBucketStats(r0, y0))
statsArr.push(f_computeBucketStats(r1, y1))
statsArr.push(f_computeBucketStats(r2, y2))
statsArr.push(f_computeBucketStats(r3, y3))
statsArr.push(f_computeBucketStats(rA, yA))
int minYr = dYears.get(0)
int maxYr = dYears.get(lastD)
int firstCycleBase = minYr - f_getCycleYear(minYr)
int lastCycleBase = maxYr - f_getCycleYear(maxYr)
int totalCycles = int((lastCycleBase - firstCycleBase) / 4) + 1
bool showSummarySec = dashViewMode == DASH_BOTH or dashViewMode == DASH_SUM
bool showLedgerSec = dashViewMode == DASH_BOTH or dashViewMode == DASH_LEDGER
int cyclesToShow = showLedgerSec ? math.min(totalCycles, dashMaxCycles) : 0
int startCycleBase = lastCycleBase - (cyclesToShow - 1) * 4
int summaryRowCnt = showSummarySec ? 7 : 0
int ledgerRowCnt = cyclesToShow > 0 ? (1 + cyclesToShow) : 0
int totalTableRows = 1 + summaryRowCnt + ledgerRowCnt + 1
dashTable := table.new(
position = dashPos,
columns = 6,
rows = totalTableRows,
bgcolor = tblBgCol,
frame_color = tblBorderCol,
frame_width = 1,
border_color = tblBorderCol,
border_width = 1
)
int curRow = 0
// --- Row 0: Merged Title Banner ---
string confirmTag = waitForClose ? "Confirmed 1D" : "Live YTD"
string bannerTitle = "GLOBAL MARKET REACTION • US PRESIDENTIAL CYCLE • " + targetSymbol + " (1D) • " + str.tostring(minYr) + "–" + str.tostring(maxYr) + " (" + str.tostring(dCount) + " Yrs | " + confirmTag + ")"
table.cell(dashTable, 0, curRow, bannerTitle, text_color = dashTextColor, text_halign = text.align_center, text_size = dashSize, bgcolor = tblBgCol)
table.merge_cells(dashTable, 0, curRow, 5, curRow)
curRow += 1
// --- Section 1: Cycle Phase Summary Statistics ---
if showSummarySec
table.cell(dashTable, 0, curRow, "SUMMARY METRIC", text_color = dashTextColor, text_halign = text.align_left, text_size = dashSize, bgcolor = tblBgCol)
table.cell(dashTable, 1, curRow, "YEAR 0\nPres. Election", text_color = dashTextColor, text_halign = text.align_center, text_size = dashSize, bgcolor = tblBgCol)
table.cell(dashTable, 2, curRow, "YEAR 1\nPost-Election", text_color = dashTextColor, text_halign = text.align_center, text_size = dashSize, bgcolor = tblBgCol)
table.cell(dashTable, 3, curRow, "YEAR 2\nMidterm", text_color = dashTextColor, text_halign = text.align_center, text_size = dashSize, bgcolor = tblBgCol)
table.cell(dashTable, 4, curRow, "YEAR 3\nPre-Election", text_color = dashTextColor, text_halign = text.align_center, text_size = dashSize, bgcolor = tblBgCol)
table.cell(dashTable, 5, curRow, "ALL YEARS\nBaseline", text_color = dashTextColor, text_halign = text.align_center, text_size = dashSize, bgcolor = tblBgCol)
curRow += 1
int rowSample = curRow
int rowAvg = curRow + 1
int rowMed = curRow + 2
int rowPosRate = curRow + 3
int rowPosNeg = curRow + 4
int rowBestWst = curRow + 5
table.cell(dashTable, 0, rowSample, "Sample Size (N)", text_color = dashTextColor, text_halign = text.align_left, text_size = dashSize, bgcolor = tblBgCol, tooltip = "Number of historical calendar years included in each column.")
table.cell(dashTable, 0, rowAvg, "Average Return", text_color = dashTextColor, text_halign = text.align_left, text_size = dashSize, bgcolor = tblBgCol, tooltip = "Arithmetic mean annual return (%) across all included years in this phase.")
table.cell(dashTable, 0, rowMed, "Median Return", text_color = dashTextColor, text_halign = text.align_left, text_size = dashSize, bgcolor = tblBgCol, tooltip = "Median annual return (%) across all included years—resistant to single-year extreme outliers.")
table.cell(dashTable, 0, rowPosRate, "Positive Years (%)", text_color = dashTextColor, text_halign = text.align_left, text_size = dashSize, bgcolor = tblBgCol, tooltip = "Percentage of years in this cycle phase that closed with a strictly positive (> 0%) annual return.")
table.cell(dashTable, 0, rowPosNeg, "Pos / Neg Count", text_color = dashTextColor, text_halign = text.align_left, text_size = dashSize, bgcolor = tblBgCol, tooltip = "Count of positive (+) vs negative (-) calendar years.")
table.cell(dashTable, 0, rowBestWst, "Best / Worst Yr", text_color = dashTextColor, text_halign = text.align_left, text_size = dashSize, bgcolor = tblBgCol, tooltip = "Highest and lowest annual returns recorded in this cycle phase (hover cells for exact calendar years).")
for b = 0 to 4
int col = b + 1
BucketStats st = statsArr.get(b)
if st.count == 0
table.cell(dashTable, col, rowSample, "0 yrs", text_color = dashTextColor, text_halign = text.align_center, text_size = dashSize, bgcolor = tblBgCol)
table.cell(dashTable, col, rowAvg, "—", text_color = dashTextColor, text_halign = text.align_center, text_size = dashSize, bgcolor = tblBgCol)
table.cell(dashTable, col, rowMed, "—", text_color = dashTextColor, text_halign = text.align_center, text_size = dashSize, bgcolor = tblBgCol)
table.cell(dashTable, col, rowPosRate, "—", text_color = dashTextColor, text_halign = text.align_center, text_size = dashSize, bgcolor = tblBgCol)
table.cell(dashTable, col, rowPosNeg, "0+ / 0-", text_color = dashTextColor, text_halign = text.align_center, text_size = dashSize, bgcolor = tblBgCol)
table.cell(dashTable, col, rowBestWst, "—", text_color = dashTextColor, text_halign = text.align_center, text_size = dashSize, bgcolor = tblBgCol)
else
color avgBg = st.avgRet > 0.0 ? posCellBg : (st.avgRet < 0.0 ? negCellBg : tblBgCol)
color avgFg = st.avgRet > 0.0 ? dashPosFg : (st.avgRet < 0.0 ? dashNegFg : dashTextColor)
color medBg = st.medRet > 0.0 ? posCellBg : (st.medRet < 0.0 ? negCellBg : tblBgCol)
color medFg = st.medRet > 0.0 ? dashPosFg : (st.medRet < 0.0 ? dashNegFg : dashTextColor)
color wrBg = st.posRate >= 50.0 ? posCellBg : negCellBg
color wrFg = st.posRate >= 50.0 ? dashPosFg : dashNegFg
string posNegTxt = str.tostring(st.posCount) + "+ / " + str.tostring(st.negCount) + "-"
string flatNote = st.flatCount > 0 ? ("\nFlat (0.00%): " + str.tostring(st.flatCount)) : ""
string posNegTip = "Positive Years: " + str.tostring(st.posCount) + "\nNegative Years: " + str.tostring(st.negCount) + flatNote + "\nTotal Sample: " + str.tostring(st.count)
string bwTxt = f_fmtCompactPct(st.bestRet) + " / " + f_fmtCompactPct(st.worstRet)
string bwTip = "Best Year: " + str.tostring(st.bestYear) + " (" + f_fmtSignedPct(st.bestRet) + ")\nWorst Year: " + str.tostring(st.worstYear) + " (" + f_fmtSignedPct(st.worstRet) + ")"
table.cell(dashTable, col, rowSample, str.tostring(st.count) + " yrs", text_color = dashTextColor, text_halign = text.align_center, text_size = dashSize, bgcolor = tblBgCol)
table.cell(dashTable, col, rowAvg, f_fmtSignedPct(st.avgRet), text_color = avgFg, text_halign = text.align_center, text_size = dashSize, bgcolor = avgBg)
table.cell(dashTable, col, rowMed, f_fmtSignedPct(st.medRet), text_color = medFg, text_halign = text.align_center, text_size = dashSize, bgcolor = medBg)
table.cell(dashTable, col, rowPosRate, str.tostring(st.posRate, "0.0") + "%", text_color = wrFg, text_halign = text.align_center, text_size = dashSize, bgcolor = wrBg, tooltip = posNegTip)
table.cell(dashTable, col, rowPosNeg, posNegTxt, text_color = dashTextColor, text_halign = text.align_center, text_size = dashSize, bgcolor = tblBgCol, tooltip = posNegTip)
table.cell(dashTable, col, rowBestWst, bwTxt, text_color = dashTextColor, text_halign = text.align_center, text_size = dashSize, bgcolor = tblBgCol, tooltip = bwTip)
curRow += 6
// --- Section 2: 4-Year Presidential Cycle Historical Ledger ---
if cyclesToShow > 0
table.cell(dashTable, 0, curRow, "4-YR CYCLE", text_color = dashTextColor, text_halign = text.align_left, text_size = dashSize, bgcolor = tblBgCol, tooltip = "Four-year US Presidential Cycle span (Year 0 through Year 3).")
table.cell(dashTable, 1, curRow, "YEAR 0 (Elect)", text_color = dashTextColor, text_halign = text.align_center, text_size = dashSize, bgcolor = tblBgCol)
table.cell(dashTable, 2, curRow, "YEAR 1 (Post)", text_color = dashTextColor, text_halign = text.align_center, text_size = dashSize, bgcolor = tblBgCol)
table.cell(dashTable, 3, curRow, "YEAR 2 (Mid)", text_color = dashTextColor, text_halign = text.align_center, text_size = dashSize, bgcolor = tblBgCol)
table.cell(dashTable, 4, curRow, "YEAR 3 (Pre)", text_color = dashTextColor, text_halign = text.align_center, text_size = dashSize, bgcolor = tblBgCol)
table.cell(dashTable, 5, curRow, "CYCLE TOTAL", text_color = dashTextColor, text_halign = text.align_center, text_size = dashSize, bgcolor = tblBgCol, tooltip = "Compounded cumulative return across the available years in each 4-year cycle.")
curRow += 1
int lastCycIdx = cyclesToShow - 1
for cIdx = 0 to lastCycIdx
int baseYr = dashSortOrder == "Newest First" ? (lastCycleBase - cIdx * 4) : (startCycleBase + cIdx * 4)
string spanLbl = str.tostring(baseYr) + "–" + str.tostring(baseYr + 3)
table.cell(dashTable, 0, curRow, spanLbl, text_color = dashTextColor, text_halign = text.align_left, text_size = dashSize, bgcolor = tblBgCol)
float compFactor = 1.0
int validPhaseCnt = 0
bool cycleHasYtd = false
for phase = 0 to 3
int targetYr = baseYr + phase
int col = phase + 1
int pos = array.indexof(dYears, targetYr)
if pos == -1
string missReason = targetYr > maxYr ? "Upcoming future cycle year." : "Prior to available/filtered 1D symbol history."
table.cell(dashTable, col, curRow, "—", text_color = dashTextColor, text_halign = text.align_center, text_size = dashSize, bgcolor = tblBgCol, tooltip = str.tostring(targetYr) + ": " + missReason)
else
bool vld = dValid.get(pos)
bool ytd = dIsYtd.get(pos)
if not vld
table.cell(dashTable, col, curRow, "Wait", text_color = dashTextColor, text_halign = text.align_center, text_size = dashSize, bgcolor = tblBgCol, tooltip = str.tostring(targetYr) + ": Waiting for first daily candle close.")
else
float ret = dRets.get(pos)
float opn = dOpens.get(pos)
float cls = dCloses.get(pos)
string suffix = ytd ? "*" : ""
string cTxt = f_fmtSignedPct(ret) + suffix
color cBg = ret > 0.0 ? posCellBg : (ret < 0.0 ? negCellBg : tblBgCol)
color cFg = ret > 0.0 ? dashPosFg : (ret < 0.0 ? dashNegFg : dashTextColor)
string pHead = f_formatPerfHeader(targetYr, phase, true)
string stNote = ytd ? "Unfinished YTD" : "Completed Year"
string cTip = pHead + " (" + stNote + ")\nSymbol: " + targetSymbol + " (1D)\nOpen: " + str.tostring(opn, "#.####") + " | Close: " + str.tostring(cls, "#.####") + "\nReturn: " + f_fmtSignedPct(ret)
table.cell(dashTable, col, curRow, cTxt, text_color = cFg, text_halign = text.align_center, text_size = dashSize, bgcolor = cBg, tooltip = cTip)
compFactor := compFactor * (1.0 + ret / 100.0)
validPhaseCnt += 1
if ytd
cycleHasYtd := true
if validPhaseCnt == 0
table.cell(dashTable, 5, curRow, "—", text_color = dashTextColor, text_halign = text.align_center, text_size = dashSize, bgcolor = tblBgCol)
else
float cycTotalPct = (compFactor - 1.0) * 100.0
bool isPartial = validPhaseCnt < 4 or cycleHasYtd
string totSuffix = isPartial ? "*" : ""
string totTxt = f_fmtSignedPct(cycTotalPct) + totSuffix
color totBg = cycTotalPct > 0.0 ? posCellBg : (cycTotalPct < 0.0 ? negCellBg : tblBgCol)
color totFg = cycTotalPct > 0.0 ? dashPosFg : (cycTotalPct < 0.0 ? dashNegFg : dashTextColor)
string ytdPartNote = cycleHasYtd ? " (includes active YTD)" : ""
string totTip = "Cycle: " + spanLbl + "\nCompounded Return: " + f_fmtSignedPct(cycTotalPct) + "\nIncluded Years: " + str.tostring(validPhaseCnt) + " of 4" + ytdPartNote
table.cell(dashTable, 5, curRow, totTxt, text_color = totFg, text_halign = text.align_center, text_size = dashSize, bgcolor = totBg, tooltip = totTip)
curRow += 1
// --- Bottom Footer Row ---
string truncNote = (showLedgerSec and totalCycles > cyclesToShow) ? ("Showing " + str.tostring(cyclesToShow) + " of " + str.tostring(totalCycles) + " cycles | ") : ""
string footerText = truncNote + "* = Unfinished YTD / Partial 4-Yr Cycle | Tip: Indicator '...' Menu -> 'Move tables to bottom' for full-width scroll & copy"
table.cell(dashTable, 0, curRow, footerText, text_color = dashTextColor, text_halign = text.align_center, text_size = size.tiny, bgcolor = tblBgCol)
table.merge_cells(dashTable, 0, curRow, 5, curRow)
curRow += 1