本页源码来自 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/
// © Quantum-Edge-Capital
//@version=6
indicator(title = "Historical Data Heatmap [Quantum Edge]", overlay = true, max_boxes_count = 500)
// ╔════════════════════════════════╗ //
// ║ USER-DEFINED SETTINGS ║ //
// ╚════════════════════════════════╝ //
var string date_settings = "════════ Date Range Settings ════════"
var string display_settings = "════════ Display Settings ════════"
var string monthly_settings = "═══════ Monthly Heatmap Settings ═══════"
var string daily_settings = "══════ Day-of-Week Heatmap Settings ══════"
var string timing_settings = "══════ Optimal Timing Table Settings ══════"
tooltip_from_date = "Starting date for seasonality calculations. Historical data from this date onwards will be included in the analysis. Earlier start dates provide more data points for statistical significance but may include less relevant historical patterns. Recommended: Use at least 5-10 years of data for meaningful seasonality insights."
tooltip_to_date = "Ending date for seasonality calculations. Setting a specific end date allows you to analyze historical periods or exclude recent anomalous market conditions. Use this to backtest seasonality patterns across different time periods."
tooltip_price_source = "Select which price data to use for calculations. Close: Most common, reflects end-of-period prices. Open: Shows opening gaps and initial sentiment. High: Captures peak bullish momentum. Low: Reveals maximum bearish pressure. Close price is recommended for most seasonality analysis as it represents the market's final verdict for each period."
tooltip_color_preset = "Pre-configured color schemes optimized for different chart backgrounds and visual preferences. Classic uses traditional green/red for intuitive interpretation. Aqua offers blue/orange combination for reduced eye strain. Cosmic provides vibrant aqua/purple theme for dark mode users. Custom allows full personalization of positive and negative colors."
tooltip_positive_color = "The base color for table cells displaying positive percentage changes. This color represents profitable periods, bullish months, or days with gains. Choose a color that stands out against your chart background. Green tones are traditional, but any high-contrast color works well for quick visual pattern recognition."
tooltip_negative_color = "The base color for table cells displaying negative percentage changes. This color represents loss periods, bearish months, or days with declines. Red tones are conventional for losses, but customize based on your preference. Ensure good contrast with positive color for instant differentiation of bullish vs bearish patterns."
tooltip_border_color = "Color for both the outer table frame and internal cell borders. This creates visual separation between data cells and defines table structure. Black or dark gray works well for light backgrounds. Light gray or white is better for dark chart themes. Use subtle colors to avoid visual clutter while maintaining clear table organization."
tooltip_text_size = "Text size for all tables in the indicator. Auto: TradingView automatically scales text based on chart size. Tiny/Small: Fit more data in limited space. Normal: Balanced readability. Large/Huge: Enhanced visibility on high-resolution displays. Recommended: Start with Normal and adjust based on your screen size and number of visible tables."
tooltip_show_monthly = "Toggle visibility of the monthly seasonality heatmap table. This table displays percentage changes for each month across multiple years, revealing which months historically show strength or weakness. Essential for identifying seasonal entry/exit patterns and understanding annual cyclical behavior in your asset."
tooltip_monthly_position = "Screen position for the monthly seasonality heatmap. Choose a location that doesn't obscure important price action or other indicators. Bottom Center is default as monthly data is typically less time-sensitive than daily data. Consider your chart layout and which tables you're displaying simultaneously."
tooltip_show_averages = "Toggles the 'Avg %' row, which displays the average percentage change for each month across all years. This is the most important metric for identifying consistent seasonal patterns. Positive averages suggest months that typically trend upward, while negative averages indicate historically weak months. Use this to time entries and exits."
tooltip_show_months_up = "Toggles the 'Months Up %' row, which shows what percentage of historical months closed positive. Values above 50% indicate bullish bias, below 50% bearish bias. A month with 70%+ win rate suggests strong seasonal tendency. Combine with average return to identify the most reliable seasonal opportunities."
tooltip_show_consistency = "Toggles the 'Consistency' row, which rates how reliable returns are for each month on a 1-10 scale. High scores (8-10, shown in green) indicate the month consistently moves in the same direction with predictable magnitude. Medium scores (5-7, shown in gray) suggest moderate reliability. Low scores (1-4, shown in red) indicate high variability and less reliable patterns. Focus on high-consistency months (green) for seasonal trading strategies."
tooltip_show_best = "Toggles the 'Best' row, showing the strongest historical return for each month along with the year it occurred. This reveals the maximum upside potential for each month and helps identify which years had exceptional performance. Useful for understanding the range of outcomes and spotting outlier years that may skew averages."
tooltip_show_worst = "Toggles the 'Worst' row, showing the most negative historical return for each month along with the year it occurred. This reveals maximum downside risk for each month and helps with risk management. Knowing the worst-case scenario for typically strong months provides realistic expectations and position sizing guidance."
tooltip_show_daily = "Toggle visibility of the day-of-week seasonality heatmap table. This table displays average percentage changes for each day of the week within each month, revealing intraweek patterns. Useful for optimizing entry/exit timing within the monthly seasonal window and identifying which days typically show strength or weakness."
tooltip_daily_position = "Screen position for the day-of-week seasonality heatmap. Middle Right is default to avoid overlap with the monthly table. Choose a position that provides clear visibility without obscuring price action. Consider stacking tables vertically or horizontally based on your monitor orientation and chart layout preferences."
tooltip_daily_averages = "Toggles the 'Avg %' row in the day-of-week table, showing average daily changes across all months. This identifies which weekdays historically perform best or worst. For example, 'Monday Effect' or 'Friday strength' patterns. Use this to fine-tune entry timing within favorable seasonal months."
tooltip_days_up = "Toggles the 'Days Up %' row, showing percentage of days that closed higher than they opened for each weekday. Values above 50% indicate bullish intraday bias, below 50% bearish bias. Combine with average returns to identify days with both strong directional bias and reliable follow-through for intraday or swing strategies."
tooltip_daily_consistency = "Toggles the 'Consistency' row in the day-of-week table, rating reliability of each weekday's returns on a 1-10 scale. High scores (8-10, shown in green) indicate the weekday consistently behaves similarly across different months with predictable patterns. Medium scores (5-7, shown in gray) suggest moderate reliability. Low scores (1-4, shown in red) indicate high variability. Prioritize high-consistency weekdays (green) for tactical trade timing."
tooltip_daily_best = "Toggles the 'Best' row in the day-of-week table, showing which month had the strongest performance for each weekday. Helps identify optimal combinations of month and weekday for maximum seasonal edge. For instance, if Wednesdays are best in April, target Wednesday entries during the April seasonal window."
tooltip_daily_worst = "Toggles the 'Worst' row in the day-of-week table, showing which month had the weakest performance for each weekday. Useful for avoiding unfavorable day-month combinations and understanding downside risks. If Mondays are weakest in September, consider delaying entries until later in the week during that month."
tooltip_show_timing = "Toggle visibility of the optimal timing summary table. This table synthesizes all seasonality data to identify the single best and second-best months and weekdays for buying (entering at lows) and selling (exiting at highs). This is the quick-reference guide for seasonal trading decisions, displaying the most actionable insights from the complete dataset."
tooltip_timing_position = "Screen position for the optimal timing summary table. Middle Left is default as this table contains critical actionable information that benefits from central positioning. Place it where you'll naturally look first when planning trades. This table's recommendations are based on historical averages, so keep it prominently visible."
tooltip_show_second_best = "Toggle visibility of the '2nd Best' rows in the Optimal Timing table. When enabled, shows alternative months and days that also have favorable historical performance. Useful for backup timing options when the primary best periods are not suitable for your strategy or when you want multiple entry/exit opportunities."
int startDate = input.time(timestamp("01 Jan 2015 00:00 +0000"), "From Date", tooltip = tooltip_from_date, group = date_settings)
int endDate = input.time(timestamp("04 Apr 4444 00:00 +0000"), "To Date", tooltip = tooltip_to_date, group = date_settings)
string priceType = input.string("Close", "Price Source", options = ["Open", "Close", "High", "Low"], tooltip = tooltip_price_source, group = date_settings)
colorScheme = input.string("Custom", "Color Preset", options = ["Classic", "Aqua", "Cosmic", "Custom"], group = display_settings, tooltip = tooltip_color_preset)
bullishColorInput = input.color(#00ffaa, "Positive Color", group = display_settings, tooltip = tooltip_positive_color)
bearishColorInput = input.color(#ff0000, "Negative Color", group = display_settings, tooltip = tooltip_negative_color)
color frameColor = input.color(color.rgb(0, 0, 0), "Table Border Color", group = display_settings, tooltip = tooltip_border_color)
string fontSize = input.string("Small", "Text Size", options = ["Auto", "Tiny", "Small", "Normal", "Large", "Huge"], group = display_settings, tooltip = tooltip_text_size)
bool displayMonthlyHeatmap = input.bool(true, "Show Monthly Heatmap", group = monthly_settings, tooltip = tooltip_show_monthly)
string monthlyLocation = "Top Left"
bool displayMean = input.bool(true, "Show Averages", group = monthly_settings, tooltip = tooltip_show_averages)
bool displayWinRate = input.bool(true, "Show Months Up %", group = monthly_settings, tooltip = tooltip_show_months_up)
bool displayReliability = input.bool(true, "Show Consistency", group = monthly_settings, tooltip = tooltip_show_consistency)
bool displayPeak = input.bool(true, "Show Best", group = monthly_settings, tooltip = tooltip_show_best)
bool displayTrough = input.bool(true, "Show Worst", group = monthly_settings, tooltip = tooltip_show_worst)
bool hasMonthlyStats = displayMean or displayPeak or displayTrough or displayReliability or displayWinRate
bool displayDailyHeatmap = input.bool(true, "Show Day-of-Week Heatmap", group = daily_settings, tooltip = tooltip_show_daily)
string dailyLocation = "Top Right"
bool displayDailyMean = input.bool(true, "Show Averages", group = daily_settings, tooltip = tooltip_daily_averages)
bool displayDailyWinRate = input.bool(true, "Show Days Up %", group = daily_settings, tooltip = tooltip_days_up)
bool displayDailyReliability = input.bool(true, "Show Consistency", group = daily_settings, tooltip = tooltip_daily_consistency)
bool displayDailyPeak = input.bool(true, "Show Best", group = daily_settings, tooltip = tooltip_daily_best)
bool displayDailyTrough = input.bool(true, "Show Worst", group = daily_settings, tooltip = tooltip_daily_worst)
bool hasDailyStats = displayDailyMean or displayDailyPeak or displayDailyTrough or displayDailyReliability or displayDailyWinRate
bool displayTimingMatrix = input.bool(true, "Show Optimal Timing Table", group = timing_settings, tooltip = tooltip_show_timing)
string timingLocation = "Bottom Right"
bool showSecondBest = input.bool(true, "Show 2nd Best Options", group = timing_settings, tooltip = tooltip_show_second_best)
// ╔════════════════════════════════╗ //
// ║ COLOR PROCESSING ║ //
// ╚════════════════════════════════╝ //
[bullishColor, bearishColor] = switch colorScheme
"Classic" => [#00ff00, #ff0000]
"Aqua" => [#00bfff, #ff8c00]
"Cosmic" => [#49ffce, #9932cc]
"Custom" => [bullishColorInput, bearishColorInput]
bullishColor := color.new(bullishColor, 0)
bearishColor := color.new(bearishColor, 0)
// ╔════════════════════════════════╗ //
// ║ HELPER FUNCTIONS ║ //
// ╚════════════════════════════════╝ //
pct(float x) =>
na(x) ? "—" : str.tostring(x, format.percent)
parseTextSize(string s) =>
switch s
"Auto" => 12
"Tiny" => 8
"Small" => 12
"Normal" => 14
"Large" => 20
"Huge" => 36
=> 12
fetchPrice(string src, int lag) =>
switch src
"Open" => open[lag]
"Close" => close[lag]
"High" => high[lag]
"Low" => low[lag]
=> close[lag]
generateHeatColor(float val, int maxIntensity = na) =>
float dimOpacity = 90
float brightOpacity = 50
bool isPositive = val >= 0
color baseHue = isPositive ? bullishColor : bearishColor
if na(val)
color.gray
else if na(maxIntensity)
baseHue
else
color dimShade = color.new(baseHue, dimOpacity)
color brightShade = color.new(baseHue, brightOpacity)
color.from_gradient(math.abs(val), 0, maxIntensity, dimShade, brightShade)
percentageMove(float current, float prior) =>
100.0 * (current - prior) / prior
method ratioPositive(array<float> arr) =>
int totalItems = 0
int totalPositive = 0
for item in arr
if not na(item)
totalItems += 1
totalPositive += item >= 0 ? 1 : 0
totalItems > 0 ? (totalPositive * 100.0 / totalItems) : na
computeReliabilityMetric(array<float> dataset) =>
float metric = na
int n = dataset.size()
if n > 0
float mean = dataset.avg()
float stdDev = dataset.stdev(false)
if not na(mean) and not na(stdDev) and math.abs(mean) > 0.01
float coeffVar = stdDev / math.abs(mean)
metric := math.max(1, math.min(10, 10 - (coeffVar * 1.8)))
else if not na(stdDev)
metric := stdDev < 1 ? 10 : math.max(1, math.min(10, 10 - stdDev))
metric
mapReliabilityColor(float rating) =>
color shade = color.new(color.gray, 80)
if not na(rating)
if rating < 5
shade := color.new(bearishColor, 70)
else if rating >= 8
shade := color.new(bullishColor, 70)
shade
validateTimeRange(int barTimestamp, int rangeStart, int rangeEnd) =>
barTimestamp >= rangeStart and (rangeEnd == 0 or barTimestamp <= rangeEnd)
// ╔════════════════════════════════╗ //
// ║ CALCULATION FUNCTIONS ║ //
// ╚════════════════════════════════╝ //
aggregateMonthlyReturns(int rangeStart, int rangeEnd, string src) =>
var matrix<float> returnMatrix = matrix.new<float>(0, 13)
var array<int> yearRegistry = array.new<int>()
int prevTimeClose = time_close[1] - 1
int prevBarYear = year(prevTimeClose)
int prevBarMonth = month(prevTimeClose)
float priorPrice = fetchPrice(src, 2)
float currentPrice = fetchPrice(src, 1)
float returnPct = percentageMove(currentPrice, priorPrice)
if prevBarYear >= year(rangeStart) and validateTimeRange(prevTimeClose, rangeStart, rangeEnd)
if prevBarYear != prevBarYear[1] or returnMatrix.rows() == 0
returnMatrix.add_row()
yearRegistry.push(prevBarYear)
returnMatrix.set(returnMatrix.rows() - 1, prevBarMonth, returnPct)
[yearRegistry, returnMatrix]
aggregateDailyByMonth(int rangeStart, int rangeEnd, string src) =>
var matrix<float> totalReturnMatrix = matrix.new<float>(12, 8, 0.0)
var matrix<int> observationMatrix = matrix.new<int>(12, 8, 0)
var matrix<float> squaredReturnMatrix = matrix.new<float>(12, 8, 0.0)
var matrix<int> positiveCountMatrix = matrix.new<int>(12, 8, 0)
int barMonth = month(time_tradingday, "UTC")
int barWeekday = dayofweek(time_tradingday, "UTC")
float priorClose = close[1]
float currentVal = fetchPrice(src, 0)
float dailyMove = percentageMove(currentVal, priorClose)
if validateTimeRange(time_tradingday, rangeStart, rangeEnd) and not na(dailyMove)
int monthIdx = barMonth - 1
float existingTotal = totalReturnMatrix.get(monthIdx, barWeekday)
int existingObs = observationMatrix.get(monthIdx, barWeekday)
float existingSq = squaredReturnMatrix.get(monthIdx, barWeekday)
int existingPos = positiveCountMatrix.get(monthIdx, barWeekday)
totalReturnMatrix.set(monthIdx, barWeekday, existingTotal + dailyMove)
observationMatrix.set(monthIdx, barWeekday, existingObs + 1)
squaredReturnMatrix.set(monthIdx, barWeekday, existingSq + (dailyMove * dailyMove))
if dailyMove >= 0
positiveCountMatrix.set(monthIdx, barWeekday, existingPos + 1)
[totalReturnMatrix, observationMatrix, squaredReturnMatrix, positiveCountMatrix]
// ╔════════════════════════════════╗ //
// ║ DATA COLLECTION ║ //
// ╚════════════════════════════════╝ //
[yearRegistry, returnsMatrix] = request.security(
syminfo.tickerid, "1M",
aggregateMonthlyReturns(startDate, endDate, priceType),
lookahead = barmerge.lookahead_on
)
[dailyTotals, dailyObs, dailySq, dailyPositives] = request.security(
syminfo.tickerid, "1D",
aggregateDailyByMonth(startDate, endDate, priceType),
lookahead = barmerge.lookahead_on
)
// ╔════════════════════════════════╗ //
// ║ TABLE RENDERING ║ //
// ╚════════════════════════════════╝ //
var monthLabels = array.from("Year", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
var weekdayLabels = array.from("Month", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat")
var monthShort = array.from("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
var weekdayShort = array.from("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat")
if barstate.islast and not na(returnsMatrix) and displayMonthlyHeatmap
pos = switch monthlyLocation
"Top Left" => position.top_left
"Top Center" => position.top_center
"Top Right" => position.top_right
"Middle Left" => position.middle_left
"Middle Center" => position.middle_center
"Middle Right" => position.middle_right
"Bottom Left" => position.bottom_left
"Bottom Center" => position.bottom_center
"Bottom Right" => position.bottom_right
int totalRows = returnsMatrix.rows() + 2 + (displayMean ? 1 : 0) + (displayWinRate ? 1 : 0) + (displayReliability ? 1 : 0) + (displayPeak ? 1 : 0) + (displayTrough ? 1 : 0)
table heatmap = table.new(pos, 13, totalRows, bgcolor=color.new(#1a1a1a, 0), border_width=1, border_color=frameColor, frame_color=frameColor, frame_width=1)
color headerBg = color.new(#1a1a1a, 0)
color txtColor = chart.fg_color
heatmap.cell(0, 0, "Monthly Seasonality", bgcolor = color.new(color.gray, 70), text_color = txtColor, text_size = parseTextSize(fontSize), height = math.min(3.05, 72.0 / totalRows))
heatmap.merge_cells(0, 0, 12, 0)
for [idx, label] in monthLabels
heatmap.cell(idx, 1, label, bgcolor = headerBg, text_color = txtColor, text_size = parseTextSize(fontSize), height = math.min(3.05, 72.0 / totalRows), width = idx == 0 ? 6 : 4.35)
for [rowIdx, row] in returnsMatrix
int yr = yearRegistry.get(rowIdx)
for [colIdx, val] in row
if colIdx == 0
heatmap.cell(colIdx, rowIdx + 2, str.tostring(yr), bgcolor = headerBg,
text_color = txtColor, text_size = 11, height = math.min(3.05, 72.0 / totalRows), width = colIdx == 0 ? 6 : 4.35)
else
string txt = pct(val)
color bg = generateHeatColor(val, 10)
heatmap.cell(colIdx, rowIdx + 2, txt, bgcolor = bg, text_color = txtColor, text_size = 11, height = math.min(3.05, 72.0 / totalRows), width = colIdx == 0 ? 6 : 4.35)
if hasMonthlyStats
int row = returnsMatrix.rows() + 2
if displayMean
heatmap.cell(0, row, "Avg %:", bgcolor = headerBg, text_color = txtColor, text_size = 11, height = math.min(3.05, 72.0 / totalRows), width = 0 == 0 ? 6 : 4.35)
for i = 1 to 12
float mean = returnsMatrix.col(i).avg()
heatmap.cell(i, row, pct(mean),
bgcolor = generateHeatColor(mean, 10), text_color = txtColor, text_size = 11, height = math.min(3.05, 72.0 / totalRows), width = i == 0 ? 6 : 4.35)
row += 1
if displayWinRate
heatmap.cell(0, row, "Months Up %:", bgcolor = headerBg, text_color = txtColor, text_size = 11, height = math.min(3.05, 72.0 / totalRows), width = 0 == 0 ? 6 : 4.35)
for i = 1 to 12
float winPct = returnsMatrix.col(i).ratioPositive()
heatmap.cell(i, row, na(winPct) ? "—" : str.tostring(winPct, "#") + "%", bgcolor = generateHeatColor(winPct - 50, 50),
text_color = txtColor, text_size = 11, height = math.min(3.05, 72.0 / totalRows), width = i == 0 ? 6 : 4.35)
row += 1
if displayReliability
heatmap.cell(0, row, "Consistency:", bgcolor = headerBg, text_color = txtColor, text_size = 11, height = math.min(3.05, 72.0 / totalRows), width = 0 == 0 ? 6 : 4.35)
for i = 1 to 12
float rating = computeReliabilityMetric(returnsMatrix.col(i))
float rounded = math.ceil(rating)
string txt = na(rounded) ? "—" : str.tostring(rounded, "#") + "/10"
color bg = mapReliabilityColor(rounded)
heatmap.cell(i, row, txt, bgcolor = bg, text_color = txtColor, text_size = 11, height = math.min(3.05, 72.0 / totalRows), width = i == 0 ? 6 : 4.35)
row += 1
if displayPeak
heatmap.cell(0, row, "Best:", bgcolor = headerBg, text_color = txtColor, text_size = 11, height = math.min(3.05, 72.0 / totalRows), width = 0 == 0 ? 6 : 4.35)
for i = 1 to 12
array<float> colData = returnsMatrix.col(i)
float peak = colData.max()
int peakIdx = colData.indexof(peak)
string yr = peakIdx >= 0 ? str.tostring(yearRegistry.get(peakIdx)) : ""
string txt = na(peak) ? "—" : yr + ": " + pct(peak)
heatmap.cell(i, row, txt, bgcolor = generateHeatColor(peak, 10),
text_color = txtColor, text_size = 11, height = math.min(3.05, 72.0 / totalRows), width = i == 0 ? 6 : 4.35)
row += 1
if displayTrough
heatmap.cell(0, row, "Worst:", bgcolor = headerBg, text_color = txtColor, text_size = 11, height = math.min(3.05, 72.0 / totalRows), width = 0 == 0 ? 6 : 4.35)
for i = 1 to 12
array<float> colData = returnsMatrix.col(i)
float trough = colData.min()
int troughIdx = colData.indexof(trough)
string yr = troughIdx >= 0 ? str.tostring(yearRegistry.get(troughIdx)) : ""
string txt = na(trough) ? "—" : yr + ": " + pct(trough)
heatmap.cell(i, row, txt, bgcolor = generateHeatColor(trough, 10),
text_color = txtColor, text_size = 11, height = math.min(3.05, 72.0 / totalRows), width = i == 0 ? 6 : 4.35)
row += 1
if barstate.islast and not na(dailyTotals) and displayDailyHeatmap
pos = switch dailyLocation
"Top Left" => position.top_left
"Top Center" => position.top_center
"Top Right" => position.top_right
"Middle Left" => position.middle_left
"Middle Center" => position.middle_center
"Middle Right" => position.middle_right
"Bottom Left" => position.bottom_left
"Bottom Center" => position.bottom_center
"Bottom Right" => position.bottom_right
int totalRows = 1 + 1 + 12
if hasDailyStats
totalRows += displayDailyMean ? 1 : 0
totalRows += displayDailyWinRate ? 1 : 0
totalRows += displayDailyReliability ? 1 : 0
totalRows += displayDailyPeak ? 1 : 0
totalRows += displayDailyTrough ? 1 : 0
table weekdayMap = table.new(pos, 8, totalRows, bgcolor=color.new(#1a1a1a, 0), border_width=1, border_color=frameColor, frame_color=frameColor, frame_width=1)
color headerBg = color.new(#1a1a1a, 0)
color txtColor = chart.fg_color
weekdayMap.cell(0, 0, "Day-of-Week Seasonality", bgcolor = color.new(color.gray, 70), text_color = txtColor, text_size = parseTextSize(fontSize), height = 3.15)
weekdayMap.merge_cells(0, 0, 7, 0)
for [idx, label] in weekdayLabels
weekdayMap.cell(idx, 1, label, bgcolor = headerBg, text_color = txtColor, text_size = parseTextSize(fontSize), height = 3.15, width = idx == 0 ? 6 : 4.6)
for mIdx = 0 to 11
string mLabel = monthShort.get(mIdx)
weekdayMap.cell(0, mIdx + 2, mLabel, bgcolor = headerBg, text_color = txtColor, text_size = parseTextSize(fontSize), height = 3.15, width = 0 == 0 ? 6 : 4.6)
for dIdx = 1 to 7
float total = dailyTotals.get(mIdx, dIdx)
int count = dailyObs.get(mIdx, dIdx)
float mean = count > 0 ? total / count : na
string txt = pct(mean)
color bg = generateHeatColor(mean, 1)
weekdayMap.cell(dIdx, mIdx + 2, txt, bgcolor = bg, text_color = txtColor, text_size = parseTextSize(fontSize), height = 3.15, width = dIdx == 0 ? 6 : 4.6)
if hasDailyStats
int row = 14
if displayDailyMean
weekdayMap.cell(0, row, "Avg %:", bgcolor = headerBg, text_color = txtColor, text_size = parseTextSize(fontSize), height = 3.15, width = 0 == 0 ? 6 : 4.6)
for dIdx = 1 to 7
float grandTotal = 0.0
int grandCount = 0
for mIdx = 0 to 11
grandTotal += dailyTotals.get(mIdx, dIdx)
grandCount += dailyObs.get(mIdx, dIdx)
float mean = grandCount > 0 ? grandTotal / grandCount : na
weekdayMap.cell(dIdx, row, pct(mean),
bgcolor = generateHeatColor(mean, 1), text_color = txtColor, text_size = parseTextSize(fontSize), height = 3.15, width = dIdx == 0 ? 6 : 4.6)
row += 1
if displayDailyWinRate
weekdayMap.cell(0, row, "Days Up %:", bgcolor = headerBg, text_color = txtColor, text_size = parseTextSize(fontSize), height = 3.15, width = 0 == 0 ? 6 : 4.6)
for dIdx = 1 to 7
int posTotal = 0
int obsTotal = 0
for mIdx = 0 to 11
posTotal += dailyPositives.get(mIdx, dIdx)
obsTotal += dailyObs.get(mIdx, dIdx)
float winPct = obsTotal > 0 ? 100.0 * posTotal / obsTotal : na
weekdayMap.cell(dIdx, row, na(winPct) ? "—" : str.tostring(winPct, "#") + "%",
bgcolor = generateHeatColor(winPct - 50, 50), text_color = txtColor, text_size = parseTextSize(fontSize), height = 3.15, width = dIdx == 0 ? 6 : 4.6)
row += 1
if displayDailyReliability
weekdayMap.cell(0, row, "Consistency:", bgcolor = headerBg, text_color = txtColor, text_size = parseTextSize(fontSize), height = 3.15, width = 0 == 0 ? 6 : 4.6)
for dIdx = 1 to 7
dataset = array.new<float>()
for mIdx = 0 to 11
float total = dailyTotals.get(mIdx, dIdx)
int count = dailyObs.get(mIdx, dIdx)
if count > 0
dataset.push(total / count)
float rating = computeReliabilityMetric(dataset)
float rounded = math.ceil(rating)
string txt = na(rounded) ? "—" : str.tostring(rounded, "#") + "/10"
color bg = mapReliabilityColor(rounded)
weekdayMap.cell(dIdx, row, txt, bgcolor = bg, text_color = txtColor, text_size = parseTextSize(fontSize), height = 3.15, width = dIdx == 0 ? 6 : 4.6)
row += 1
if displayDailyPeak
weekdayMap.cell(0, row, "Best:", bgcolor = headerBg, text_color = txtColor, text_size = parseTextSize(fontSize), height = 3.15, width = 0 == 0 ? 6 : 4.6)
for dIdx = 1 to 7
float peak = na
int peakMonth = na
for mIdx = 0 to 11
float total = dailyTotals.get(mIdx, dIdx)
int count = dailyObs.get(mIdx, dIdx)
if count > 0
float mean = total / count
if na(peak) or mean > peak
peak := mean
peakMonth := mIdx
string mLabel = not na(peakMonth) ? monthShort.get(peakMonth) : ""
string txt = na(peak) ? "—" : mLabel + ": " + pct(peak)
weekdayMap.cell(dIdx, row, txt, bgcolor = generateHeatColor(peak, 1),
text_color = txtColor, text_size = parseTextSize(fontSize), height = 3.15, width = dIdx == 0 ? 6 : 4.6)
row += 1
if displayDailyTrough
weekdayMap.cell(0, row, "Worst:", bgcolor = headerBg, text_color = txtColor, text_size = parseTextSize(fontSize), height = 3.15, width = 0 == 0 ? 6 : 4.6)
for dIdx = 1 to 7
float trough = na
int troughMonth = na
for mIdx = 0 to 11
float total = dailyTotals.get(mIdx, dIdx)
int count = dailyObs.get(mIdx, dIdx)
if count > 0
float mean = total / count
if na(trough) or mean < trough
trough := mean
troughMonth := mIdx
string mLabel = not na(troughMonth) ? monthShort.get(troughMonth) : ""
string txt = na(trough) ? "—" : mLabel + ": " + pct(trough)
weekdayMap.cell(dIdx, row, txt, bgcolor = generateHeatColor(trough, 1),
text_color = txtColor, text_size = parseTextSize(fontSize), height = 3.15, width = dIdx == 0 ? 6 : 4.6)
row += 1
if barstate.islast and not na(returnsMatrix) and not na(dailyTotals) and displayTimingMatrix
pos = switch timingLocation
"Top Left" => position.top_left
"Top Center" => position.top_center
"Top Right" => position.top_right
"Middle Left" => position.middle_left
"Middle Center" => position.middle_center
"Middle Right" => position.middle_right
"Bottom Left" => position.bottom_left
"Bottom Center" => position.bottom_center
"Bottom Right" => position.bottom_right
float topMonth = na
int topMonthIdx = na
float secondMonth = na
int secondMonthIdx = na
float bottomMonth = na
int bottomMonthIdx = na
float secondBottomMonth = na
int secondBottomMonthIdx = na
for i = 1 to 12
float mean = returnsMatrix.col(i).avg()
if not na(mean)
if na(topMonth) or mean > topMonth
secondMonth := topMonth
secondMonthIdx := topMonthIdx
topMonth := mean
topMonthIdx := i
else if na(secondMonth) or mean > secondMonth
secondMonth := mean
secondMonthIdx := i
if na(bottomMonth) or mean < bottomMonth
secondBottomMonth := bottomMonth
secondBottomMonthIdx := bottomMonthIdx
bottomMonth := mean
bottomMonthIdx := i
else if na(secondBottomMonth) or mean < secondBottomMonth
secondBottomMonth := mean
secondBottomMonthIdx := i
float topDay = na
int topDayIdx = na
float secondDay = na
int secondDayIdx = na
float bottomDay = na
int bottomDayIdx = na
float secondBottomDay = na
int secondBottomDayIdx = na
for dIdx = 1 to 7
float grandTotal = 0.0
int grandCount = 0
for mIdx = 0 to 11
grandTotal += dailyTotals.get(mIdx, dIdx)
grandCount += dailyObs.get(mIdx, dIdx)
float mean = grandCount > 0 ? grandTotal / grandCount : na
if not na(mean)
if na(topDay) or mean > topDay
secondDay := topDay
secondDayIdx := topDayIdx
topDay := mean
topDayIdx := dIdx
else if na(secondDay) or mean > secondDay
secondDay := mean
secondDayIdx := dIdx
if na(bottomDay) or mean < bottomDay
secondBottomDay := bottomDay
secondBottomDayIdx := bottomDayIdx
bottomDay := mean
bottomDayIdx := dIdx
else if na(secondBottomDay) or mean < secondBottomDay
secondBottomDay := mean
secondBottomDayIdx := dIdx
int totalRows = 2
totalRows += 1
totalRows += showSecondBest ? 1 : 0
totalRows += 1
totalRows += showSecondBest ? 1 : 0
totalRows += 1
totalRows += showSecondBest ? 1 : 0
totalRows += 1
totalRows += showSecondBest ? 1 : 0
table summary = table.new(pos, 3, totalRows, bgcolor=color.new(#1a1a1a, 0), border_width=1, border_color=frameColor, frame_color=frameColor, frame_width=1)
color headerBg = color.new(#1a1a1a, 0)
color txtColor = chart.fg_color
string startFmt = str.format("{0,date,yyyy-MM-dd}", startDate)
string endFmt = endDate == 0 or endDate > timenow ? str.format("{0,date,yyyy-MM-dd}", timenow) : str.format("{0,date,yyyy-MM-dd}", endDate)
string title = " Analysis: " + syminfo.ticker + ", from " + startFmt + " to " + endFmt + " "
summary.cell(0, 0, title, bgcolor = color.new(color.gray, 70), text_color = txtColor, text_size = parseTextSize(fontSize), height = 3.05)
summary.merge_cells(0, 0, 2, 0)
summary.cell(0, 1, "Optimal Timing", bgcolor = headerBg, text_color = txtColor, text_size = parseTextSize(fontSize), height = 3.05, width = 0 == 0 ? 16 : 11.1)
summary.cell(1, 1, "Period", bgcolor = headerBg, text_color = txtColor, text_size = parseTextSize(fontSize), height = 3.05, width = 1 == 0 ? 16 : 11.1)
summary.cell(2, 1, "Avg %", bgcolor = headerBg, text_color = txtColor, text_size = parseTextSize(fontSize), height = 3.05, width = 2 == 0 ? 16 : 11.1)
int row = 2
summary.cell(0, row, "Lowest Avg. Month:", bgcolor = headerBg, text_color = txtColor, text_size = parseTextSize(fontSize), height = 3.05, width = 0 == 0 ? 16 : 11.1)
string buyMonth = not na(bottomMonthIdx) ? monthShort.get(bottomMonthIdx - 1) : "N/A"
summary.cell(1, row, buyMonth, bgcolor = generateHeatColor(bottomMonth, 10), text_color = txtColor, text_size = parseTextSize(fontSize), height = 3.05, width = 1 == 0 ? 16 : 11.1)
summary.cell(2, row, pct(bottomMonth), bgcolor = generateHeatColor(bottomMonth, 10), text_color = txtColor, text_size = parseTextSize(fontSize), height = 3.05, width = 2 == 0 ? 16 : 11.1)
row += 1
if showSecondBest
summary.cell(0, row, "2nd Lowest Month:", bgcolor = headerBg, text_color = txtColor, text_size = parseTextSize(fontSize), height = 3.05, width = 0 == 0 ? 16 : 11.1)
string buyMonth2 = not na(secondBottomMonthIdx) ? monthShort.get(secondBottomMonthIdx - 1) : "N/A"
summary.cell(1, row, buyMonth2, bgcolor = generateHeatColor(secondBottomMonth, 10), text_color = txtColor, text_size = parseTextSize(fontSize), height = 3.05, width = 1 == 0 ? 16 : 11.1)
summary.cell(2, row, pct(secondBottomMonth), bgcolor = generateHeatColor(secondBottomMonth, 10), text_color = txtColor, text_size = parseTextSize(fontSize), height = 3.05, width = 2 == 0 ? 16 : 11.1)
row += 1
summary.cell(0, row, "Highest Avg. Month:", bgcolor = headerBg, text_color = txtColor, text_size = parseTextSize(fontSize), height = 3.05, width = 0 == 0 ? 16 : 11.1)
string sellMonth = not na(topMonthIdx) ? monthShort.get(topMonthIdx - 1) : "N/A"
summary.cell(1, row, sellMonth, bgcolor = generateHeatColor(topMonth, 10), text_color = txtColor, text_size = parseTextSize(fontSize), height = 3.05, width = 1 == 0 ? 16 : 11.1)
summary.cell(2, row, pct(topMonth), bgcolor = generateHeatColor(topMonth, 10), text_color = txtColor, text_size = parseTextSize(fontSize), height = 3.05, width = 2 == 0 ? 16 : 11.1)
row += 1
if showSecondBest
summary.cell(0, row, "2nd Highest Month:", bgcolor = headerBg, text_color = txtColor, text_size = parseTextSize(fontSize), height = 3.05, width = 0 == 0 ? 16 : 11.1)
string sellMonth2 = not na(secondMonthIdx) ? monthShort.get(secondMonthIdx - 1) : "N/A"
summary.cell(1, row, sellMonth2, bgcolor = generateHeatColor(secondMonth, 10), text_color = txtColor, text_size = parseTextSize(fontSize), height = 3.05, width = 1 == 0 ? 16 : 11.1)
summary.cell(2, row, pct(secondMonth), bgcolor = generateHeatColor(secondMonth, 10), text_color = txtColor, text_size = parseTextSize(fontSize), height = 3.05, width = 2 == 0 ? 16 : 11.1)
row += 1
summary.cell(0, row, "Lowest Avg. Day:", bgcolor = headerBg, text_color = txtColor, text_size = parseTextSize(fontSize), height = 3.05, width = 0 == 0 ? 16 : 11.1)
string buyDay = not na(bottomDayIdx) ? weekdayShort.get(bottomDayIdx - 1) : "N/A"
summary.cell(1, row, buyDay, bgcolor = generateHeatColor(bottomDay, 1), text_color = txtColor, text_size = parseTextSize(fontSize), height = 3.05, width = 1 == 0 ? 16 : 11.1)
summary.cell(2, row, pct(bottomDay), bgcolor = generateHeatColor(bottomDay, 1), text_color = txtColor, text_size = parseTextSize(fontSize), height = 3.05, width = 2 == 0 ? 16 : 11.1)
row += 1
if showSecondBest
summary.cell(0, row, "2nd Lowest Day:", bgcolor = headerBg, text_color = txtColor, text_size = parseTextSize(fontSize), height = 3.05, width = 0 == 0 ? 16 : 11.1)
string buyDay2 = not na(secondBottomDayIdx) ? weekdayShort.get(secondBottomDayIdx - 1) : "N/A"
summary.cell(1, row, buyDay2, bgcolor = generateHeatColor(secondBottomDay, 1), text_color = txtColor, text_size = parseTextSize(fontSize), height = 3.05, width = 1 == 0 ? 16 : 11.1)
summary.cell(2, row, pct(secondBottomDay), bgcolor = generateHeatColor(secondBottomDay, 1), text_color = txtColor, text_size = parseTextSize(fontSize), height = 3.05, width = 2 == 0 ? 16 : 11.1)
row += 1
summary.cell(0, row, "Highest Avg. Day:", bgcolor = headerBg, text_color = txtColor, text_size = parseTextSize(fontSize), height = 3.05, width = 0 == 0 ? 16 : 11.1)
string sellDay = not na(topDayIdx) ? weekdayShort.get(topDayIdx - 1) : "N/A"
summary.cell(1, row, sellDay, bgcolor = generateHeatColor(topDay, 1), text_color = txtColor, text_size = parseTextSize(fontSize), height = 3.05, width = 1 == 0 ? 16 : 11.1)
summary.cell(2, row, pct(topDay), bgcolor = generateHeatColor(topDay, 1), text_color = txtColor, text_size = parseTextSize(fontSize), height = 3.05, width = 2 == 0 ? 16 : 11.1)
row += 1
if showSecondBest
summary.cell(0, row, "2nd Highest Day:", bgcolor = headerBg, text_color = txtColor, text_size = parseTextSize(fontSize), height = 3.05, width = 0 == 0 ? 16 : 11.1)
string sellDay2 = not na(secondDayIdx) ? weekdayShort.get(secondDayIdx - 1) : "N/A"
summary.cell(1, row, sellDay2, bgcolor = generateHeatColor(secondDay, 1), text_color = txtColor, text_size = parseTextSize(fontSize), height = 3.05, width = 1 == 0 ? 16 : 11.1)
summary.cell(2, row, pct(secondDay), bgcolor = generateHeatColor(secondDay, 1), text_color = txtColor, text_size = parseTextSize(fontSize), height = 3.05, width = 2 == 0 ? 16 : 11.1)
bool weeklyOn = input.bool(true, "Show Weekly Summary", group = display_settings)
[wDate, wClose, wPct, wRange, pDate, pClose, pPct, pRange] = request.security(syminfo.tickerid, "1W", [time_close[1], close[1], 100.0 * (close[1] / close[2] - 1), high[1] - low[1], time_close[2], close[2], 100.0 * (close[2] / close[3] - 1), high[2] - low[2]], lookahead = barmerge.lookahead_on)
if barstate.islast and weeklyOn
table wt = table.new(position.bottom_left, 4, 4, bgcolor = #1a1a1a, border_width = 1, border_color = frameColor, frame_width = 1, frame_color = frameColor)
table.cell(wt, 0, 0, "Weekly Summary | Last 2 Completed Weeks", height = 3.6, bgcolor = #303238, text_color = color.white, text_size = parseTextSize(fontSize))
wt.merge_cells(0, 0, 3, 0)
for c = 0 to 3
string heading = switch c
0 => "Week Ending"
1 => "Close"
2 => "Close-to-Close %"
=> "High − Low"
table.cell(wt, c, 1, heading, width = 14.55, height = 3.6, bgcolor = #303238, text_color = color.white, text_size = parseTextSize(fontSize))
for r = 2 to 3
int ending = r == 2 ? wDate : pDate
float closing = r == 2 ? wClose : pClose
float change = r == 2 ? wPct : pPct
float rng = r == 2 ? wRange : pRange
string value = switch c
0 => na(ending) ? "—" : str.format_time(ending - 1, "yyyy-MM-dd", syminfo.timezone)
1 => na(closing) ? "—" : str.tostring(closing, format.mintick)
2 => pct(change)
=> na(rng) ? "—" : str.tostring(rng, format.mintick)
table.cell(wt, c, r, value, width = 14.55, height = 3.6, bgcolor = c == 2 ? generateHeatColor(change, 5) : #1a1a1a, text_color = color.white, text_size = parseTextSize(fontSize))