本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This script is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
// https://creativecommons.org/licenses/by-nc-sa/4.0/
// © QuantAlgo
//@version=6
indicator("Return Distribution Profile [QuantAlgo]", overlay = false, precision = 0, max_boxes_count = 500, max_labels_count = 50, max_polylines_count = 5)
// ╔════════════════════════════════╗ //
// ║ USER-DEFINED SETTINGS ║ //
// ╚════════════════════════════════╝ //
var string distribution_settings = "════════ Distribution Settings ════════"
var string statistics_settings = "════════ Statistics Settings ════════"
var string histogram_settings = "════════ Histogram Settings ════════"
var string visual_settings = "════════ Visualization Settings ════════"
tooltip_horizon = "Number of bars each return spans, measured in percent from the close that many bars back to the current close, as set by Return Type. A horizon of 1 measures bar-to-bar moves, such as daily returns on a daily chart. Longer horizons measure multi-bar swings, such as 5 or 20 for weekly or monthly moves on a daily chart, or 1440 for daily moves measured on a 1-minute chart. Above a horizon of 1, each return shares most of its bars with the returns beside it, so the sample holds fewer independent moves than its count suggests and larger samples suit longer horizons."
tooltip_return_type = "How each return is measured. Log takes the natural logarithm of the price ratio, so returns add up across bars, a gain and a loss of the same size in log terms cancel out, and the Mean equals the compounded growth per bar, the basis most statistical work on returns uses. Simple takes the percentage change in price, so each return reads as the actual price move, such as a 10% drop reading as -10% rather than -10.54%, tail figures such as VaR and CVaR read directly as price moves, and the Mean is the average move, which runs above the compounded growth when returns are volatile. The two nearly match for small moves and drift apart for large ones, with log returns always reading lower than simple returns, so the gap shows mostly in the tails and the range labels. The selected type applies to the histogram, every dashboard figure, and the tail alerts."
tooltip_sample = "Number of most recent returns that form the histogram, the dashboard statistics, and the tail levels. Each return joins the sample once its bar closes, and once the sample is full the oldest return drops out as each new one joins, while under Live bar data the forming bar's return also counts as it develops. Larger samples (1000-5000) span more market conditions and give steadier tail estimates, while smaller samples (100-300) follow the recent regime more closely. Below about 100 returns, VaR 99% rests on the one or two worst returns, and skewness and kurtosis shift noticeably with each new return. The sample can only hold the returns of the bars loaded on the chart, which depend on the symbol's history, the chart timeframe, and the TradingView plan, so when fewer returns are available every available return is used and the Observations row in the dashboard shows the actual count. The Lower Tail Return and Upper Tail Return alerts compare each bar's return with the tail levels set by Tail Level, measured on the closed sample as it stood before that bar, and the Any alert() function call option carries the return and the tail level it crossed in its message."
tooltip_bins = "Number of bins the histogram range is divided into, as set by Histogram Range. Bin edges are aligned to 0%, so every bin holds either returns at or below 0% or returns above 0%, never both, and the share of returns in the columns above zero matches the Positive figure in the dashboard when Positive Share is set to All Returns. More bins (50-200) show finer detail with fewer returns per bin, which suits large samples. Fewer bins (10-20) give a smoother outline, which suits small samples. When the tallest column holds only a handful of returns, such as with many bins on a small sample, the scale beside the pane can repeat whole numbers, which a higher Precision in this indicator's Style tab avoids."
tooltip_range_mode = "How far the histogram's bins span. Full Range runs from the lowest to the highest return in the sample, so every column covers an equal slice of everything, while a few extreme returns can stretch the bins wide enough to squeeze most returns into a handful of columns. Percentile spans the returns between the Percentile Trim at each end, such as the 0.5th to the 99.5th percentile, and Std Dev spans the Mean plus and minus the Std Dev Range, so the bins resolve the body of the distribution in finer detail. Under both, the end columns collect every return beyond the span and are drawn with a dashed outline, so no return is left out of the histogram, and the span never reaches past the lowest or highest return. The range changes the display only, while every dashboard figure and alert still uses the full sample."
tooltip_trim = "Share of the sample trimmed from each end of the histogram's span when Histogram Range is set to Percentile, such as 0.5 for a span from the 0.5th to the 99.5th percentile. The trimmed returns are not dropped, since the dashed end columns collect them. Lower values (0.1-0.5) keep more of the tails inside the regular columns, and 0 matches Full Range. Higher values (1-5) zoom further into the body of the distribution. Only used when Histogram Range is set to Percentile."
tooltip_sd_range = "Number of standard deviations on each side of the Mean that the histogram spans when Histogram Range is set to Std Dev, such as 4 for a span from 4 Std Dev below the Mean to 4 above it. Returns beyond the span are collected in the dashed end columns. Lower values (2-3) zoom into the body of the distribution. Higher values (5-8) keep more of the tails inside the regular columns, which suits fat-tailed markets where extreme returns sit many standard deviations from the Mean. Only used when Histogram Range is set to Std Dev."
tooltip_data = "Which bar data the histogram, the dashboard, and the tail alerts work from. Confirmed uses closed bars only, so the histogram and every figure hold steady while a bar forms and update once it closes, the latest return reads the most recent closed bar, and the tail alerts fire at the close. Live also counts the forming bar as price develops, adding its return to the sample in place of the oldest return once the sample is full and marking it as the latest return, so the histogram and the dashboard update with each price change and the tail alerts can fire as soon as the forming return crosses a tail level. The forming bar's return covers only the part of that bar elapsed so far, and it joins the sample for good once its bar closes. Under both options the tail levels come from closed bars, so each return is judged against the sample as it stood before its bar."
tooltip_basis = "How Std Dev, Skewness, and Kurtosis are calculated from the sample. Population treats the sample as the complete set of returns and divides by the number of observations, the same basis as TradingView's built-in standard deviation. Sample Adjusted treats it as a sample drawn from a longer history and applies the standard small-sample corrections, dividing the variance by one less than the number of observations and adjusting skewness and kurtosis to match, the basis used by spreadsheet functions such as STDEV.S, SKEW, and KURT and by most statistical software. The two converge as the sample grows, differing by about 1% or less at 500 observations, while on small samples the Sample Adjusted figures read larger, most noticeably for kurtosis in fat-tailed returns. The normal curve, the Std Dev histogram range, and Annualized Vol use the Std Dev of the selected basis."
tooltip_kurt_type = "How kurtosis is expressed. Excess subtracts 3, the kurtosis of a normal distribution, so a normal shape reads zero and positive values show tails fatter than normal, the convention behind spreadsheet KURT functions and most statistical software. Raw reports kurtosis without that subtraction, so a normal shape reads 3 and values above 3 show fatter tails, the convention used in many textbooks and risk reports. Both describe the same tails, with Raw always reading exactly 3 higher, and the dashboard row is named Excess Kurtosis or Kurtosis to match."
tooltip_pct_method = "How percentiles are read from the sample, which sets VaR 95%, VaR 99%, the 95th Percentile, the Median, the tail levels behind the alerts and markers, and the span of the Percentile histogram range. Linear Interpolation blends the two returns on either side of the exact percentile position, giving smooth values that shift gradually as returns enter and leave the sample, and reads the Median as the average of the two middle returns when the count is even. Nearest Rank picks the actual return at the percentile's rank, so every percentile figure, including the Median, matches a real past move. The two differ little on large samples and most in the far tails of small samples, where VaR 99% rests on only a few returns. CVaR 95% averages the returns at or below the VaR 95% of the selected method."
tooltip_var_display = "How VaR 95%, VaR 99%, and CVaR 95% are signed in the dashboard. Return shows them as the returns at those levels, so a loss reads negative, such as -3.25%, in line with every other return figure. Loss shows the same figures as the size of the loss, so a loss reads positive, such as 3.25%, the convention common in risk reporting, where VaR is quoted as the amount at risk. Only the sign changes between the two, and in either case the figure takes the negative return color whenever it marks a loss."
tooltip_pos_share = "How the Positive figure in the dashboard treats returns of exactly 0%, which come from bars that close unchanged from the close a horizon earlier. All Returns divides the returns above 0% by every return in the sample, so unchanged closes count against the share, in line with the histogram, where they sit in the column just below zero. Non-Zero Returns leaves unchanged closes out of the count, so the figure reads as the share of up moves among the bars that moved, the way a win rate that ignores flat outcomes is read. The two match whenever no return is exactly 0%, and drift apart on markets and timeframes where unchanged closes are common, such as low timeframes or thinly traded symbols."
tooltip_rank = "How Latest Percentile ranks the latest return within the sample, which matters when other returns in the sample equal it exactly. At or Below counts every return less than or equal to the latest return, so the latest return counts itself and the lowest possible reading is one return's share of the sample. Below counts only the returns strictly less than it, so the lowest return in the sample reads 0%. Midpoint counts the returns below it plus half of those equal to it, splitting ties evenly, the mid-rank convention used in statistics. The three differ by about one return's share when values are distinct, and drift apart when many returns are identical, such as runs of unchanged closes on low timeframes."
tooltip_tail = "Share of the sample at each end that marks a tail return, setting the levels the tail alerts and the tail markers work from. At 5, the lower tail level is the 5th percentile and the upper tail level the 95th percentile, so about one return in twenty lands beyond each level. Lower values (0.1-2.5) reserve the alerts for rarer, more extreme moves. Higher values (10-25) flag moderate moves more often. The levels are read as set by Percentile Method, and for the alerts from the closed sample as it stood before each bar."
tooltip_annual = "How Annualized Vol in the dashboard converts Std Dev to a yearly figure, by scaling it with the square root of the number of returns per year, the standard convention that treats returns as independent from bar to bar and reads most precisely on log returns. Auto works out the bars per year from the chart itself. Daily, weekly, and monthly bars use 365.25 trading days a year for symbols that trade every day of the week and 252 for symbols with weekly closures. Intraday bars multiply the bars in a trading day by those same day counts, taking the bars per day from the timeframe for round-the-clock markets and from the complete trading days on the chart for markets with sessions, so extended hours and short sessions count as they are. Whether a symbol trades every day of the week is read from its bars once the chart covers a full week, and from the symbol type before that. Custom uses the Bars per Year value instead, for a specific convention such as 260 trading days a year on forex. Hovering over the Annualized Vol figure shows the bars per year in use."
tooltip_bpy = "Number of chart bars in a year, used for Annualized Vol when Annualization is set to Custom, such as 252 for daily bars on a stock, 365 for daily bars on a crypto pair, or 252 times the bars in one session for intraday bars on a stock. The figure is divided by the Return Horizon to count returns per year, so multi-bar returns annualize on the same basis. Only used when Annualization is set to Custom."
tooltip_offset = "Position of the histogram's right edge relative to the latest bar, in bars. At zero the right edge lines up with the latest bar and the histogram extends to the left across the most recent bars, so it is in view as soon as the indicator loads and follows the latest bar as new bars print. Negative values shift it further back to the left. Positive values shift it forward into the space to the right of the latest bar, up to 500 bars, the furthest a drawing can be placed ahead of the latest bar. A value equal to the histogram width, such as 60 for 30 bins at a width of 2, places its left edge on the latest bar so the whole histogram sits ahead of price, and larger values can place it beyond the visible range until the chart is scrolled to the right."
tooltip_bin_width = "Horizontal width of each bin in bars, which sets the total width of the histogram to Histogram Bins times this value, such as 60 bars for 30 bins at a width of 2. Wider bins (3-10) spread the histogram across more of the pane for a closer look at its shape. Narrower bins (1-2) keep it compact, so it stays in full view when the chart is zoomed in. On charts with fewer bars than the histogram needs, the bins narrow automatically so the histogram still fits."
tooltip_height = "How the height of each column is measured. Count shows the number of returns in each bin, so the scale reads in returns. Percent of Sample shows each bin's share of the sample, so the columns add up to 100% and histograms built from different sample sizes, timeframes, or symbols can be compared on the same scale. The normal curve and the tail markers follow the same measure. The scale beside the pane shows whole numbers by default, and finer steps for small percentages are available through the Precision option in this indicator's Style tab."
tooltip_opacity = "Fill strength of the histogram columns, from 0 for outlines only to 100 for solid columns. The highlighted column holding the latest return is filled 40 points stronger, up to solid, so it stays distinct at any setting, and every column keeps its outline, so the columns stay separate even at 0."
tooltip_normal = "Enable/disable the normal curve, a line joining the count each regular bin would hold if the returns followed a normal distribution with the same mean and standard deviation as the sample, with each point placed over the center of its column. Each count comes from the share of that normal distribution falling between the bin's edges, so the line and the columns compare like for like at any bin width. The line spans the regular columns and leaves out any dashed end column, since those collect returns of every size beyond the histogram range. Columns rising above the line at the center and in the far tails, with shortfalls in between, mark the fat tails measured by Kurtosis, while a longer run of columns on one side of the center marks the lopsidedness measured by Skewness. The line is drawn in the Highlight Color."
tooltip_curve_width = "Line thickness of the normal curve, from 1 for a fine line to 10 for a heavy one. Only applies when Show Normal Curve is turned on."
tooltip_markers = "Enable/disable the tail markers, dashed vertical lines across the histogram at the lower and upper tail levels set by Tail Level, each labeled at its top with its percentile and return, such as P5 -3.25% and P95 +3.44%, the lower label reading outward to the left and the upper label to the right. The lower marker takes the negative return color and the upper marker the positive return color, so the columns beyond each line show the returns the tail alerts respond to. A marker that falls inside a dashed end column is left out, since that column has no fixed position for it."
tooltip_highlight = "Enable/disable the highlight on the column holding the latest return, which fills that column in the Highlight Color so the current move can be placed within the distribution at a glance. Under Live bar data the latest return is the forming bar's return, so the highlight can move between columns as price develops until the bar closes. Under Confirmed it marks the return of the most recent closed bar and moves only when a new bar closes. When disabled, the column keeps its positive or negative return color."
tooltip_latest_label = "Enable/disable the label above the column holding the latest return. The label points down at that column, reads the latest return, and is filled in the Highlight Color, and hovering over it shows where the latest return ranks within the sample, as set by Latest Percentile Rank. It follows the same latest return as Highlight Latest Return, so it can mark the column with or without the highlight."
tooltip_range = "Enable/disable the range labels beneath the histogram. The labels under the end columns read the lowest and highest return in the sample, or, when an end column collects the returns beyond a trimmed Histogram Range, the edge it collects from, such as ≤ -8.25%, with hovering showing how many returns it holds and the most extreme of them. A 0% mark sits at the boundary between the negative and positive columns whenever that boundary sits clear of both ends."
tooltip_caption = "Enable/disable the caption beneath the histogram, which names the symbol, the chart timeframe, the return horizon and type, the number of observations, and the bar data in use, so the histogram carries its own context in a screenshot. Hovering over the caption explains the column colors, the dashed end columns, and the lines. When the range labels are shown, the caption sits on the line below them."
tooltip_color_preset = "Pre-configured color schemes for different chart themes and visual preferences. Classic uses traditional green and red. Aqua provides ocean-inspired blue and orange. Cosmic offers futuristic cyan and purple. Cyber features cool cyan and warm orange contrast. Neon delivers high-contrast yellow and magenta for maximum visibility. Each preset sets the positive and negative return colors, while Custom uses the Positive Return Color and Negative Return Color set below. The Highlight Color applies under every preset. On light chart backgrounds, colors too bright to stand out are darkened automatically, more for text and marker lines than for columns, and on dark backgrounds colors too dark to stand out are lightened, so every preset and custom color stays readable on either theme."
tooltip_pos_color = "Color applied to the columns holding returns above 0%, the upper tail marker, the Mean and Median figures in the dashboard when they are above zero, and the 95th Percentile figure when it sits above zero. Use a vibrant color to set gains apart from losses. Its shade adapts to light and dark chart backgrounds as described under Color Preset. Only used when Color Preset is set to Custom."
tooltip_neg_color = "Color applied to the columns holding returns at or below 0%, the lower tail marker, the Mean and Median figures in the dashboard when they are below zero, and the VaR 95%, VaR 99%, and CVaR 95% figures whenever they mark a loss. Use a warning color to highlight losses and tail risk. Its shade adapts to light and dark chart backgrounds as described under Color Preset. Only used when Color Preset is set to Custom."
tooltip_accent_color = "Color applied to the normal curve, the highlighted column holding the latest return, the label above it, and the Latest Return figure in the dashboard. It applies under every Color Preset, so the latest return and the normal curve keep one consistent color while the column and figure colors follow the preset. Its shade adapts to light and dark chart backgrounds as described under Color Preset."
tooltip_dashboard = "Enable/disable the dashboard, which lists the statistics of the returns in the sample, headed by the return horizon and type, the chart timeframe, and the bar data in use. Observations is the number of returns in the sample. Mean is the average return and Median is the middle return, with half of the sample below it, so a Mean below the Median points to large losses pulling the average down and a Mean above it to large gains pulling it up. Std Dev measures the typical spread of returns around the Mean, and Annualized Vol scales it to a yearly figure as set by Annualization. Skewness measures lopsidedness, reading negative when large losses stretch further than large gains and positive when large gains stretch further. Kurtosis compares the tails with a normal distribution, reading higher when extreme returns occur more often than a normal distribution implies, expressed as set by Kurtosis Type. VaR 95% and VaR 99% are the 5th and 1st percentiles of the sample, the returns that 5% and 1% of returns fell below, and CVaR 95% averages the returns at or below VaR 95%, so it reads how deep the worst 5% of returns go on average, all three signed as set by VaR Display. 95th Percentile is the return that 95% of the sample fell below, the upside counterpart of VaR 95%. Positive is the share of returns above 0%, counted as set by Positive Share. Latest Return is the return of the forming bar under Live bar data and of the most recent closed bar under Confirmed, and Latest Percentile ranks it within the sample as set by Latest Percentile Rank. Std Dev, Skewness, and Kurtosis follow Statistics Basis, and every percentile figure follows Percentile Method."
tooltip_layout = "How many rows the dashboard lists. Full shows every statistic. Compact keeps the core rows, Observations, Mean, Std Dev, Annualized Vol, VaR 95%, CVaR 95%, Positive, Latest Return, and Latest Percentile, for smaller screens and cleaner screenshots. Only applies when Show Dashboard is turned on."
tooltip_dash_pos = "Position in the indicator pane where the dashboard is anchored, covering every corner, the middle of each edge, and the center. Tables from other indicators placed in the same pane at the same position overlap with it. Only applies when Show Dashboard is turned on."
tooltip_decimals = "Number of decimal places shown for the return figures in the dashboard, the range labels, the latest return label, the tail marker labels, and the alert messages. Auto adds decimal places as returns get smaller, showing at least three on returns and two on Annualized Vol, so figures stay readable from monthly charts down to second charts, and drops trailing zeros. A fixed value from 0 to 8 shows exactly that many decimal places on every return figure, keeping trailing zeros so the dashboard values line up. Counts and shares such as Positive and Latest Percentile keep their own format, and the decimal places of the scale beside the pane are set by the Precision option in this indicator's Style tab."
tooltip_text_size = "Text size for the range labels, the caption, the latest return label, the tail marker labels, and every row and figure in the dashboard. Tiny and Small keep them compact beside the histogram, while Normal and Large suit presentation and screen recording."
int horizonInput = input.int(1, "Return Horizon (Bars)", group = distribution_settings, minval = 1, maxval = 5000, tooltip = tooltip_horizon)
string returnTypeInput = input.string("Log", "Return Type", group = distribution_settings, options = ["Log", "Simple"], tooltip = tooltip_return_type)
int lookbackInput = input.int(500, "Sample Size (Bars)", group = distribution_settings, minval = 10, maxval = 100000, tooltip = tooltip_sample)
int binsInput = input.int(30, "Histogram Bins", group = distribution_settings, minval = 3, maxval = 500, tooltip = tooltip_bins)
string rangeModeInput = input.string("Percentile", "Histogram Range", group = distribution_settings, options = ["Full Range", "Percentile", "Std Dev"], tooltip = tooltip_range_mode)
float trimInput = input.float(0.5, "Percentile Trim (%)", group = distribution_settings, minval = 0.0, maxval = 25.0, step = 0.1, tooltip = tooltip_trim)
float sdRangeInput = input.float(4.0, "Std Dev Range", group = distribution_settings, minval = 0.5, maxval = 50.0, step = 0.5, tooltip = tooltip_sd_range)
string dataInput = input.string("Confirmed", "Bar Data", group = distribution_settings, options = ["Confirmed", "Live"], tooltip = tooltip_data)
string basisInput = input.string("Population", "Statistics Basis", group = statistics_settings, options = ["Population", "Sample Adjusted"], tooltip = tooltip_basis)
string kurtTypeInput = input.string("Excess", "Kurtosis Type", group = statistics_settings, options = ["Excess", "Raw"], tooltip = tooltip_kurt_type)
string pctMethodInput = input.string("Linear Interpolation", "Percentile Method", group = statistics_settings, options = ["Linear Interpolation", "Nearest Rank"], tooltip = tooltip_pct_method)
string varDisplayInput = input.string("Return", "VaR Display", group = statistics_settings, options = ["Return", "Loss"], tooltip = tooltip_var_display)
string posShareInput = input.string("All Returns", "Positive Share", group = statistics_settings, options = ["All Returns", "Non-Zero Returns"], tooltip = tooltip_pos_share)
string rankInput = input.string("At or Below", "Latest Percentile Rank", group = statistics_settings, options = ["At or Below", "Below", "Midpoint"], tooltip = tooltip_rank)
float tailInput = input.float(5.0, "Tail Level (%)", group = statistics_settings, minval = 0.1, maxval = 49.0, step = 0.1, tooltip = tooltip_tail)
string annualInput = input.string("Auto", "Annualization", group = statistics_settings, options = ["Auto", "Custom"], tooltip = tooltip_annual)
float bpyInput = input.float(252.0, "Bars per Year", group = statistics_settings, minval = 1.0, step = 1.0, tooltip = tooltip_bpy)
int offsetInput = input.int(0, "Histogram Offset (Bars)", group = histogram_settings, minval = -500, maxval = 500, tooltip = tooltip_offset)
int binWidthInput = input.int(2, "Bin Width (Bars)", group = histogram_settings, minval = 1, maxval = 50, tooltip = tooltip_bin_width)
string heightInput = input.string("Count", "Column Height", group = histogram_settings, options = ["Count", "Percent of Sample"], tooltip = tooltip_height)
int opacityInput = input.int(40, "Column Opacity (%)", group = histogram_settings, minval = 0, maxval = 100, tooltip = tooltip_opacity)
bool normalInput = input.bool(true, "Show Normal Curve", group = histogram_settings, tooltip = tooltip_normal)
int curveWidthInput = input.int(2, "Curve Width", group = histogram_settings, minval = 1, maxval = 10, tooltip = tooltip_curve_width)
bool markersInput = input.bool(true, "Show Tail Markers", group = histogram_settings, tooltip = tooltip_markers)
bool highlightInput = input.bool(true, "Highlight Latest Return", group = histogram_settings, tooltip = tooltip_highlight)
bool latestLabelInput = input.bool(true, "Show Latest Return Label", group = histogram_settings, tooltip = tooltip_latest_label)
bool rangeInput = input.bool(true, "Show Range Labels", group = histogram_settings, tooltip = tooltip_range)
bool captionInput = input.bool(true, "Show Caption", group = histogram_settings, tooltip = tooltip_caption)
string colorPreset = input.string("Custom", "Color Preset", group = visual_settings, options = ["Custom", "Classic", "Aqua", "Cosmic", "Cyber", "Neon"], tooltip = tooltip_color_preset)
color posColorInput = input.color(#00ffaa, "Positive Return Color", group = visual_settings, tooltip = tooltip_pos_color)
color negColorInput = input.color(#ff0000, "Negative Return Color", group = visual_settings, tooltip = tooltip_neg_color)
color accentColorInput = input.color(#f0b90b, "Highlight Color", group = visual_settings, tooltip = tooltip_accent_color)
bool tableInput = input.bool(true, "Show Dashboard", group = visual_settings, tooltip = tooltip_dashboard)
string layoutInput = input.string("Full", "Dashboard Layout", group = visual_settings, options = ["Full", "Compact"], tooltip = tooltip_layout)
string tablePosInput = input.string("Top Right", "Dashboard Position", group = visual_settings, options = ["Top Left", "Top Center", "Top Right", "Middle Left", "Middle Center", "Middle Right", "Bottom Left", "Bottom Center", "Bottom Right"], tooltip = tooltip_dash_pos)
string decimalsInput = input.string("Auto", "Decimals", group = visual_settings, options = ["Auto", "0", "1", "2", "3", "4", "5", "6", "7", "8"], tooltip = tooltip_decimals)
string textSizeInput = input.string("Small", "Text Size", group = visual_settings, options = ["Tiny", "Small", "Normal", "Large"], tooltip = tooltip_text_size)
// ╔════════════════════════════════╗ //
// ║ PRESET CONFIGURATION ║ //
// ╚════════════════════════════════╝ //
[posCol, negCol] = switch colorPreset
"Classic" => [#00ff00, #ff0000]
"Aqua" => [#00d4ff, #ff8c00]
"Cosmic" => [#49ffce, #9932cc]
"Cyber" => [#00cccc, #ff6600]
"Neon" => [#ffff00, #ff00ff]
=> [posColorInput, negColorInput]
string textSize = switch textSizeInput
"Tiny" => size.tiny
"Normal" => size.normal
"Large" => size.large
=> size.small
float bgBright = (color.r(chart.bg_color) * 299.0 + color.g(chart.bg_color) * 587.0 + color.b(chart.bg_color) * 114.0) / 1000.0
bool lightBg = bgBright >= 128.0
themed(color c, float lightCap, float darkFloor) =>
float cB = (color.r(c) * 299.0 + color.g(c) * 587.0 + color.b(c) * 114.0) / 1000.0
if lightBg and cB > lightCap
color.rgb(color.r(c) * lightCap / cB, color.g(c) * lightCap / cB, color.b(c) * lightCap / cB)
else if not lightBg and cB < darkFloor
float t = (darkFloor - cB) / (255.0 - cB)
color.rgb(color.r(c) + (255.0 - color.r(c)) * t, color.g(c) + (255.0 - color.g(c)) * t, color.b(c) + (255.0 - color.b(c)) * t)
else
c
color posText = themed(posCol, 100.0, 70.0)
color negText = themed(negCol, 100.0, 70.0)
color accentText = themed(accentColorInput, 100.0, 70.0)
color posFill = themed(posCol, 150.0, 50.0)
color negFill = themed(negCol, 150.0, 50.0)
color accentFill = themed(accentColorInput, 150.0, 50.0)
// ╔════════════════════════════════╗ //
// ║ DISTRIBUTION ENGINE ║ //
// ╚════════════════════════════════╝ //
bool useLive = dataInput == "Live"
bool useSimple = returnTypeInput == "Simple"
bool sampleBasis = basisInput == "Sample Adjusted"
bool rawKurt = kurtTypeInput == "Raw"
bool nearestRank = pctMethodInput == "Nearest Rank"
bool lossView = varDisplayInput == "Loss"
bool nonZeroBase = posShareInput == "Non-Zero Returns"
bool pctHeight = heightInput == "Percent of Sample"
bool compact = layoutInput == "Compact"
float tieWeight = rankInput == "Below" ? 0.0 : rankInput == "Midpoint" ? 0.5 : 1.0
string tailText = str.tostring(tailInput, "#.##")
string upperText = str.tostring(100.0 - tailInput, "#.##")
pctOf(array<float> src, float p) =>
nearestRank ? array.percentile_nearest_rank(src, p) : array.percentile_linear_interpolation(src, p)
float priceRatio = close / close[horizonInput]
float ret = useSimple ? (priceRatio - 1.0) * 100.0 : math.log(priceRatio) * 100.0
bool hasRet = not na(ret)
var array<float> rets = array.new<float>()
float lowerCut = na
float upperCut = na
if barstate.isrealtime and (useLive or barstate.isconfirmed) and array.size(rets) >= 10
lowerCut := pctOf(rets, tailInput)
upperCut := pctOf(rets, 100.0 - tailInput)
if barstate.isconfirmed and hasRet
if array.size(rets) >= lookbackInput
array.shift(rets)
array.push(rets, ret)
array<float> sample = rets
if useLive and barstate.islast and not barstate.isconfirmed and hasRet
sample := array.copy(rets)
if array.size(sample) >= lookbackInput
array.shift(sample)
array.push(sample, ret)
float latest = useLive or barstate.isconfirmed ? ret : ret[1]
bool hasLatest = not na(latest)
// ╔════════════════════════════════╗ //
// ║ STATISTICS ENGINE ║ //
// ╚════════════════════════════════╝ //
var int firstTime = time
var bool satSeen = false
var bool sunSeen = false
var int dayCount = 0
var int dayBars = 0
var float fullBars = 0.0
var float fullDays = 0.0
int tdDow = dayofweek(time_tradingday + 43200000, syminfo.timezone)
if tdDow == dayofweek.saturday
satSeen := true
if tdDow == dayofweek.sunday
sunSeen := true
if bar_index == 0 or time_tradingday != time_tradingday[1]
if dayCount >= 2
fullBars += dayBars
fullDays += 1
dayCount += 1
dayBars := 0
dayBars += 1
int n = array.size(sample)
bool hasData = barstate.islast and n >= 10
float meanV = na
float medianV = na
float sdV = na
float lo = na
float hi = na
float var95 = na
float var99 = na
float cvar = na
float p95V = na
float tailLoV = na
float tailHiV = na
float skewV = na
float kurtV = na
float posPct = na
float pctV = na
if hasData
meanV := array.avg(sample)
medianV := nearestRank ? array.percentile_nearest_rank(sample, 50) : array.median(sample)
lo := array.min(sample)
hi := array.max(sample)
var95 := pctOf(sample, 5)
var99 := pctOf(sample, 1)
p95V := pctOf(sample, 95)
tailLoV := pctOf(sample, tailInput)
tailHiV := pctOf(sample, 100.0 - tailInput)
float sdPop = array.stdev(sample)
bool hasSd = sdPop > 0
float m3 = 0.0
float m4 = 0.0
float tailSum = 0.0
float tailN = 0.0
float posN = 0.0
float zeroN = 0.0
float belowN = 0.0
float equalN = 0.0
for x in sample
if hasSd
float d = (x - meanV) / sdPop
m3 += d * d * d
m4 += d * d * d * d
if x <= var95
tailSum += x
tailN += 1
if x > 0
posN += 1
else if x == 0
zeroN += 1
if hasLatest
if x < latest
belowN += 1
else if x == latest
equalN += 1
float g1 = hasSd ? m3 / n : na
float g2 = hasSd ? m4 / n - 3.0 : na
float posBase = nonZeroBase ? n - zeroN : n
sdV := sampleBasis ? array.stdev(sample, false) : sdPop
skewV := sampleBasis ? g1 * math.sqrt(n * (n - 1.0)) / (n - 2.0) : g1
kurtV := (sampleBasis ? ((n + 1.0) * g2 + 6.0) * (n - 1.0) / ((n - 2.0) * (n - 3.0)) : g2) + (rawKurt ? 3.0 : 0.0)
cvar := tailN > 0 ? tailSum / tailN : na
posPct := posBase > 0 ? posN / posBase * 100.0 : na
pctV := hasLatest ? (belowN + tieWeight * equalN) / n * 100.0 : na
bool allWeek = time - firstTime >= 604800000 ? satSeen and sunSeen : syminfo.type == "crypto"
float tradingDays = allWeek ? 365.25 : 252.0
float barsPerDay = allWeek ? 86400.0 / timeframe.in_seconds() : fullDays > 0 ? fullBars / fullDays : (bar_index + 1.0) / math.max(dayCount, 1)
float autoBpy = timeframe.isticks ? na : timeframe.ismonthly ? 12.0 / timeframe.multiplier : timeframe.isweekly ? 52.1775 / timeframe.multiplier : timeframe.isdaily ? tradingDays / timeframe.multiplier : barsPerDay * tradingDays
float barsPerYear = annualInput == "Custom" ? bpyInput : autoBpy
float annVol = sdV * math.sqrt(barsPerYear / horizonInput)
int autoDec = sdV > 0 ? math.max(3, math.ceil(-math.log10(sdV)) + 2) : 3
bool fixedDec = decimalsInput != "Auto"
int fixedN = fixedDec ? int(str.tonumber(decimalsInput)) : 0
string fixedFmt = fixedN == 0 ? "0" : "0." + str.repeat("0", fixedN)
string numFmt = fixedDec ? fixedFmt : "#." + str.repeat("#", autoDec)
string axisFmt = fixedDec ? fixedFmt : "#." + str.repeat("#", autoDec - 1)
string volFmt = fixedDec ? fixedFmt : "#.##"
// ╔════════════════════════════════╗ //
// ║ VISUALIZATION ║ //
// ╚════════════════════════════════╝ //
readoutTextColor(color fillColor) =>
float brightness = (color.r(fillColor) * 299.0 + color.g(fillColor) * 587.0 + color.b(fillColor) * 114.0) / 1000.0
brightness >= 128.0 ? color.black : color.white
normCdf(float z) =>
float t = 1.0 / (1.0 + 0.2316419 * math.abs(z))
float poly = t * (0.319381530 + t * (-0.356563782 + t * (1.781477937 + t * (-1.821255978 + t * 1.330274429))))
float tail = math.exp(-0.5 * z * z) / math.sqrt(2.0 * math.pi) * poly
z >= 0 ? 1.0 - tail : tail
fmtPct(float v) =>
na(v) ? "n/a" : (v > 0 ? "+" : "") + str.tostring(v, numFmt) + "%"
fmtTail(float v) =>
na(v) ? "n/a" : lossView ? str.tostring(-v, numFmt) + "%" : fmtPct(v)
tfLabel() =>
string mult = str.tostring(timeframe.multiplier)
timeframe.isseconds ? mult + "s" : timeframe.isminutes ? (timeframe.multiplier % 60 == 0 ? str.tostring(timeframe.multiplier / 60, "#") + "h" : mult + "m") : timeframe.isdaily ? mult + "D" : timeframe.isweekly ? mult + "W" : timeframe.ismonthly ? mult + "M" : timeframe.period
hline(0.0, "Baseline", color.new(chart.fg_color, 50), hline.style_solid)
var array<box> histBoxes = array.new<box>()
var array<line> histLines = array.new<line>()
var array<label> histLabels = array.new<label>()
var polyline normalLine = na
if barstate.islast
for b in histBoxes
box.delete(b)
array.clear(histBoxes)
for ln in histLines
line.delete(ln)
array.clear(histLines)
for l in histLabels
label.delete(l)
array.clear(histLabels)
polyline.delete(normalLine)
normalLine := na
if hasData
float loR = rangeModeInput == "Percentile" ? pctOf(sample, trimInput) : rangeModeInput == "Std Dev" ? math.max(meanV - sdRangeInput * sdV, lo) : lo
float hiR = rangeModeInput == "Percentile" ? pctOf(sample, 100.0 - trimInput) : rangeModeInput == "Std Dev" ? math.min(meanV + sdRangeInput * sdV, hi) : hi
if hiR <= loR
loR := lo
hiR := hi
float binW = (hiR - loR) / (binsInput - 1)
if binW > 0
int kLo = math.ceil(loR / binW) - 1
int rightEdge = bar_index + offsetInput
int binWide = math.max(1, math.min(binWidthInput, math.floor(rightEdge / (binsInput * 1.0))))
int histWidth = binsInput * binWide
int leftEdge = math.max(rightEdge - histWidth, 0)
int halfW = math.floor(binWide / 2.0)
int fillTransp = 100 - opacityInput
int curTransp = 100 - math.min(100, opacityInput + 40)
float hScale = pctHeight ? 100.0 / n : 1.0
bool lowOver = lo <= kLo * binW
bool highOver = hi > (kLo + binsInput) * binW
bool drawCurve = normalInput and sdV > 0
color clearBg = color.new(chart.bg_color, 100)
array<float> counts = array.new<float>(binsInput, 0.0)
for x in sample
int bi = math.max(math.min(math.ceil(x / binW) - 1 - kLo, binsInput - 1), 0)
array.set(counts, bi, array.get(counts, bi) + 1)
int curBin = hasLatest ? math.max(math.min(math.ceil(latest / binW) - 1 - kLo, binsInput - 1), 0) : -1
array<chart.point> pts = array.new<chart.point>()
for i = 0 to binsInput - 1
int left = leftEdge + i * binWide
bool isCur = highlightInput and i == curBin
bool isOver = (i == 0 and lowOver) or (i == binsInput - 1 and highOver)
color c = isCur ? accentFill : kLo + i >= 0 ? posFill : negFill
if array.get(counts, i) > 0
array.push(histBoxes, box.new(left, array.get(counts, i) * hScale, left + binWide, 0.0, border_color = color.new(c, 30), border_style = isOver ? line.style_dashed : line.style_solid, bgcolor = color.new(c, isCur ? curTransp : fillTransp)))
if drawCurve and not isOver
float pLow = normCdf(((kLo + i) * binW - meanV) / sdV)
float pHigh = normCdf(((kLo + i + 1) * binW - meanV) / sdV)
array.push(pts, chart.point.from_index(left + halfW, n * (pHigh - pLow) * hScale))
if drawCurve and array.size(pts) >= 2
normalLine := polyline.new(pts, curved = false, closed = false, xloc = xloc.bar_index, line_color = accentFill, line_width = curveWidthInput)
if markersInput
float maxHeight = array.max(counts) * hScale
for side = 0 to 1
float v = side == 0 ? tailLoV : tailHiV
float u = v / binW - kLo
bool fits = not na(v) and u >= (lowOver ? 1.0 : 0.0) and u <= binsInput - (highOver ? 1.0 : 0.0)
if fits
int mx = leftEdge + math.round(u * binWide)
color mc = v > 0 ? posText : negText
array.push(histLines, line.new(mx, 0.0, mx, maxHeight, xloc = xloc.bar_index, color = mc, style = line.style_dashed, width = 1))
array.push(histLabels, label.new(mx, maxHeight, "P" + (side == 0 ? tailText : upperText) + " " + fmtPct(v), style = side == 0 ? label.style_label_right : label.style_label_left, color = clearBg, textcolor = mc, size = textSize))
if rangeInput
float loEdge = (kLo + 1) * binW
float hiEdge = (kLo + binsInput - 1) * binW
string loText = lowOver ? "≤ " + str.tostring(loEdge, axisFmt) + "%" : "Min " + str.tostring(lo, axisFmt) + "%"
string hiText = highOver ? "> " + str.tostring(hiEdge, axisFmt) + "%" : "Max " + str.tostring(hi, axisFmt) + "%"
string loTip = lowOver ? "This column collects every return at or below " + str.tostring(loEdge, axisFmt) + "%, " + str.tostring(array.get(counts, 0)) + " in all, reaching down to the lowest return in the sample at " + str.tostring(lo, axisFmt) + "%." : "Lowest return in the sample."
string hiTip = highOver ? "This column collects every return above " + str.tostring(hiEdge, axisFmt) + "%, " + str.tostring(array.get(counts, binsInput - 1)) + " in all, reaching up to the highest return in the sample at " + str.tostring(hi, axisFmt) + "%." : "Highest return in the sample."
array.push(histLabels, label.new(leftEdge + halfW, 0.0, loText, style = label.style_label_up, color = clearBg, textcolor = chart.fg_color, size = textSize, tooltip = loTip))
array.push(histLabels, label.new(leftEdge + histWidth - binWide + halfW, 0.0, hiText, style = label.style_label_up, color = clearBg, textcolor = chart.fg_color, size = textSize, tooltip = hiTip))
if -kLo >= 3 and -kLo <= binsInput - 3
array.push(histLabels, label.new(leftEdge - kLo * binWide, 0.0, "0%", style = label.style_label_up, color = clearBg, textcolor = chart.fg_color, size = textSize))
if captionInput
string captionTip = (pctHeight ? "Each column shows the share of the sample that falls in its bin." : "Each column counts the returns that fall in its bin.") + " Columns in the negative return color hold returns at or below 0% and columns in the positive return color hold returns above 0%." + (highlightInput and curBin >= 0 ? " The highlighted column holds the latest return." : "") + (lowOver or highOver ? " A column with a dashed outline collects every return beyond the histogram range at its end." : "") + (drawCurve ? " The solid line traces the " + (pctHeight ? "shares" : "counts") + " a normal distribution with the same mean and standard deviation would produce across the regular columns." : "") + (markersInput ? " The dashed vertical lines mark the tail levels the tail alerts work from." : "")
array.push(histLabels, label.new(leftEdge + math.round(histWidth / 2.0), 0.0, (rangeInput ? "\n" : "") + syminfo.ticker + " · " + tfLabel() + " · " + str.tostring(horizonInput) + "-bar " + (useSimple ? "simple" : "log") + " returns · " + str.tostring(n) + " observations · " + (useLive ? "live" : "confirmed bars"), style = label.style_label_up, color = clearBg, textcolor = chart.fg_color, size = textSize, tooltip = captionTip))
if latestLabelInput and curBin >= 0
string rankText = rankInput == "Below" ? "% of the sample is below the latest return." : rankInput == "Midpoint" ? "% of the sample ranks below the latest return, with returns equal to it counted as half." : "% of the sample is at or below the latest return."
array.push(histLabels, label.new(leftEdge + curBin * binWide + halfW, array.get(counts, curBin) * hScale, " Latest " + fmtPct(latest) + " ", style = label.style_label_down, color = accentFill, textcolor = readoutTextColor(accentFill), size = textSize, tooltip = str.tostring(pctV, "#.#") + rankText))
// ╔════════════════════════════════╗ //
// ║ DASHBOARD ║ //
// ╚════════════════════════════════╝ //
string tablePos = switch tablePosInput
"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
=> position.top_left
color hdrBg = color.new(chart.fg_color, 85)
color cellBg = color.new(chart.bg_color, 10)
color txt = chart.fg_color
string kurtLabel = rawKurt ? "Kurtosis" : "Excess Kurtosis"
string volTip = na(barsPerYear) ? "Annualization needs a time-based chart." : "Std Dev scaled by the square root of " + str.tostring(barsPerYear / horizonInput, "#,###.##") + " returns per year, from " + str.tostring(barsPerYear, "#,###.##") + " bars per year" + (annualInput == "Custom" ? " set by Bars per Year." : timeframe.isweekly or timeframe.ismonthly ? "." : ", based on " + (allWeek ? "365.25" : "252") + " trading days a year.")
signCol(float v) =>
na(v) or v == 0 ? txt : v > 0 ? posText : negText
addRow(array<string> names, array<string> values, array<color> colors, array<string> tips, string name, string value, color col, string tip) =>
array.push(names, name)
array.push(values, value)
array.push(colors, col)
array.push(tips, tip)
var table dash = tableInput ? table.new(tablePos, 2, 15, border_width = 1, border_color = color.new(chart.fg_color, 85), frame_width = 1, frame_color = color.new(chart.fg_color, 70)) : na
if barstate.islast and not na(dash)
array<string> names = array.new<string>()
array<string> values = array.new<string>()
array<color> colors = array.new<color>()
array<string> tips = array.new<string>()
addRow(names, values, colors, tips, "Observations", str.tostring(n), txt, "")
addRow(names, values, colors, tips, "Mean", fmtPct(meanV), signCol(meanV), "")
if not compact
addRow(names, values, colors, tips, "Median", fmtPct(medianV), signCol(medianV), "")
addRow(names, values, colors, tips, "Std Dev", na(sdV) ? "n/a" : str.tostring(sdV, numFmt) + "%", txt, "")
addRow(names, values, colors, tips, "Annualized Vol", na(annVol) ? "n/a" : str.tostring(annVol, volFmt) + "%", txt, volTip)
if not compact
addRow(names, values, colors, tips, "Skewness", na(skewV) ? "n/a" : str.tostring(skewV, "#.##"), txt, "")
addRow(names, values, colors, tips, kurtLabel, na(kurtV) ? "n/a" : str.tostring(kurtV, "#.##"), txt, "")
addRow(names, values, colors, tips, "VaR 95%", fmtTail(var95), var95 < 0 ? negText : txt, "")
if not compact
addRow(names, values, colors, tips, "VaR 99%", fmtTail(var99), var99 < 0 ? negText : txt, "")
addRow(names, values, colors, tips, "CVaR 95%", fmtTail(cvar), cvar < 0 ? negText : txt, "")
if not compact
addRow(names, values, colors, tips, "95th Percentile", fmtPct(p95V), p95V > 0 ? posText : txt, "")
addRow(names, values, colors, tips, "Positive", na(posPct) ? "n/a" : str.tostring(posPct, "#.#") + "%", txt, "")
addRow(names, values, colors, tips, "Latest Return", fmtPct(latest), accentText, "")
addRow(names, values, colors, tips, "Latest Percentile", na(pctV) ? "n/a" : str.tostring(pctV, "#.#") + "%", txt, "")
table.cell(dash, 0, 0, str.tostring(horizonInput) + "-Bar " + returnTypeInput + " Returns", text_color = txt, bgcolor = hdrBg, text_size = textSize, text_halign = text.align_left)
table.cell(dash, 1, 0, tfLabel() + " · " + dataInput, text_color = txt, bgcolor = hdrBg, text_size = textSize)
int rowCount = array.size(names)
for r = 0 to rowCount - 1
color rowBg = r == rowCount - 1 ? hdrBg : cellBg
table.cell(dash, 0, r + 1, array.get(names, r), text_color = txt, bgcolor = rowBg, text_size = textSize, text_halign = text.align_left)
table.cell(dash, 1, r + 1, array.get(values, r), text_color = array.get(colors, r), bgcolor = rowBg, text_size = textSize, tooltip = array.get(tips, r))
// ╔════════════════════════════════╗ //
// ║ ALERTS ║ //
// ╚════════════════════════════════╝ //
bool lowerTail = not na(lowerCut) and ret < lowerCut
bool upperTail = not na(upperCut) and ret > upperCut
string symbolText = syminfo.prefix + ":" + syminfo.ticker
string alertFreq = useLive ? alert.freq_once_per_bar : alert.freq_once_per_bar_close
alertcondition(lowerTail, title = "Lower Tail Return", message = "Return Distribution Profile: LOWER tail return below the lower tail level of the sample on {{exchange}}:{{ticker}} - {{interval}}")
alertcondition(upperTail, title = "Upper Tail Return", message = "Return Distribution Profile: UPPER tail return above the upper tail level of the sample on {{exchange}}:{{ticker}} - {{interval}}")
alertcondition(lowerTail or upperTail, title = "Any Tail Return", message = "Return Distribution Profile: TAIL return beyond the lower or upper tail level of the sample on {{exchange}}:{{ticker}} - {{interval}}")
if lowerTail
alert("Return Distribution Profile: lower tail return of " + fmtPct(ret) + " on " + symbolText + ", within the lowest " + tailText + "% of the sample, below " + fmtPct(lowerCut), alertFreq)
if upperTail
alert("Return Distribution Profile: upper tail return of " + fmtPct(ret) + " on " + symbolText + ", within the highest " + tailText + "% of the sample, above " + fmtPct(upperCut), alertFreq)
// ╔════════════════════════════════╗ //
// ║ CREATED BY ║ //
// ╚════════════════════════════════╝ //
// ██████╗ ██╗ ██╗ █████╗ ███╗ ██╗████████╗ █████╗ ██╗ ██████╗ ██████╗
//██╔═══██╗██║ ██║██╔══██╗████╗ ██║╚══██╔══╝ ██╔══██╗██║ ██╔════╝ ██╔═══██╗
//██║ ██║██║ ██║███████║██╔██╗ ██║ ██║ ███████║██║ ██║ ███╗██║ ██║
//██║▄▄ ██║██║ ██║██╔══██║██║╚██╗██║ ██║ ██╔══██║██║ ██║ ██║██║ ██║
//╚██████╔╝╚██████╔╝██║ ██║██║ ╚████║ ██║ ██║ ██║███████╗╚██████╔╝╚██████╔╝
// ╚══▀▀═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═╝ ╚═╝ ╚═╝╚══════╝ ╚═════╝ ╚═════╝