Holding-Period Outcomes

EnzoBlack · study · 151 行 · 点赞 17 · TradingView 原页

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

Pine Script

//@version=6
// Holding-Period Outcomes
// For every day in a symbol's history, buy at that day's close and hold for a fixed number of calendar days. This
// indicator counts how those holds ended: how many ended lower than they started, the median outcome, the worst and
// the best, and how long the worst start took to get back to even. It answers a plain question about any symbol: if
// someone had bought on any day and waited, how often were they down at the end, and for how long?
//
// It reads only the chart's own prices and draws its table on the last bar from confirmed bars. The bars in the pane
// use only prices up to the bar they are drawn on, so nothing repaints: the current day's bar moves with the price
// until the day closes, and past bars never change.
//
// Made for a daily (1D) chart. Each day is dated by time_tradingday, 00:00 UTC of its trading day on every symbol: a
// futures daily bar's time is its session open the evening before, so it would show one day early. On weekly or
// monthly bars there is one start per bar, so the worst and best holds of any day are missed, and on intraday bars a
// day has many bars. On any timeframe but 1D it shows one row and nothing else.
indicator("Holding-Period Outcomes", overlay=false)
 
// ---------- inputs ----------
src      = input.source(close, "Price", tooltip="The price each hold is bought and sold at. The close by default: buy at a day's close, sell at the close of the first day on which the holding length has passed.")
fromDate = input.time(timestamp("1970-01-01T00:00:00"), "Count starts from", tooltip="Only holds that start on or after this date are counted. Use it to leave out an early period, or to compare two eras of the same symbol.")
GRP      = "Holding lengths, in calendar days (0 = off)"
h1 = input.int(30,   "Length 1", minval=0, group=GRP, tooltip="The first holding length, in calendar days. 30 is about one month. Set 0 to hide this row.")
h2 = input.int(91,   "Length 2", minval=0, group=GRP, tooltip="The second holding length, in calendar days. 91 is about three months. Set 0 to hide this row.")
h3 = input.int(182,  "Length 3", minval=0, group=GRP, tooltip="The third holding length, in calendar days. 182 is about six months. Set 0 to hide this row.")
h4 = input.int(365,  "Length 4", minval=0, group=GRP, tooltip="The fourth holding length, in calendar days. 365 is one year. Set 0 to hide this row.")
h5 = input.int(730,  "Length 5", minval=0, group=GRP, tooltip="The fifth holding length, in calendar days. 730 is two years. Set 0 to hide this row.")
h6 = input.int(1460, "Length 6", minval=0, group=GRP, tooltip="The sixth holding length, in calendar days. 1460 is four years. Set 0 to hide this row.")
plotSel  = input.int(4, "Bars show the holds of length", options=[1, 2, 3, 4, 5, 6], group="Display", tooltip="Which holding length the bars in the pane show. Each bar is the outcome of the hold of that length that ends on it, in percent.")
showPlot = input.bool(true, "Show the bars", group="Display", tooltip="Turn the bars off to keep only the table.")
tblPos   = input.string("Top right", "Table position", options=["Top right", "Top left", "Bottom right", "Bottom left", "Middle right"], group="Display", tooltip="Where the table sits in the pane.")
tblSize  = input.string("Small", "Table text size", options=["Tiny", "Small", "Normal"], group="Display", tooltip="The text size of the table.")
 
DAY_MS = 86400000
// daily (1D) only: on any other timeframe the table shows one row and the pane draws nothing
okTf  = timeframe.isdaily and timeframe.multiplier == 1
 
lenOf(int k) =>
    k == 1 ? h1 : k == 2 ? h2 : k == 3 ? h3 : k == 4 ? h4 : k == 5 ? h5 : h6
 
// ---------- the price history, confirmed bars only ----------
var float[] pxA = array.new_float()
var int[]   tmA = array.new_int()
if okTf and barstate.isconfirmed and not na(src) and src > 0
    array.push(pxA, src)
    array.push(tmA, time_tradingday)
 
// ---------- the bars: the outcome of the hold that ends on this bar ----------
// It started on the last recorded day at or before this bar's trading day minus the holding length. Only past prices.
plotLen = lenOf(plotSel)
var int ptr = 0
float endRet = na
if okTf and plotLen > 0 and array.size(tmA) > 0 and not na(src)
    target = time_tradingday - plotLen * DAY_MS
    while ptr + 1 < array.size(tmA) and array.get(tmA, ptr + 1) <= target
        ptr += 1
    t0 = array.get(tmA, ptr)
    if t0 <= target and t0 >= fromDate
        endRet := src / array.get(pxA, ptr) - 1.0
plot(showPlot ? endRet * 100.0 : na, "Outcome of the hold that ends here (%)", style=plot.style_columns, color=endRet >= 0 ? color.new(color.teal, 35) : color.new(color.red, 35))
hline(0, "Even", color=color.new(color.gray, 40), linestyle=hline.style_dotted)
 
// ---------- the statistics for one holding length ----------
// Every start on or after fromDate whose hold has finished: bought at the start's price, sold at the first recorded bar
// at or after start time plus H days. Returns the count, how many ended lower, the median, the worst and the best with
// their start times, and the days from the worst start until the price closed at or above its starting price
// again, looking only after that hold ended (na: not yet). Looking from the start itself would count a bounce the
// next day, before the fall the hold went through.
stats(int H) =>
    n = array.size(tmA)
    rets = array.new_float()
    lower = 0
    float worst = na
    float best = na
    int worstAt = na
    int bestAt = na
    int worstIdx = na
    int worstEnd = na
    if H > 0 and n > 1
        j = 0
        for i = 0 to n - 1
            ti = array.get(tmA, i)
            if ti < fromDate
                continue
            tgt = ti + H * DAY_MS
            while j < n and array.get(tmA, j) < tgt
                j += 1
            if j >= n
                break
            r = array.get(pxA, j) / array.get(pxA, i) - 1.0
            array.push(rets, r)
            if r < 0
                lower += 1
            if na(worst) or r < worst
                worst := r
                worstAt := ti
                worstIdx := i
                worstEnd := j
            if na(best) or r > best
                best := r
                bestAt := ti
    float backDays = na
    if not na(worstIdx)
        p0 = array.get(pxA, worstIdx)
        for k = worstEnd to n - 1
            if array.get(pxA, k) >= p0
                backDays := (array.get(tmA, k) - array.get(tmA, worstIdx)) / DAY_MS
                break
    cnt = array.size(rets)
    med = cnt > 0 ? array.median(rets) : na
    [cnt, lower, med, worst, worstAt, best, bestAt, backDays]
 
// ---------- the table ----------
pctS(float x) => na(x) ? "-" : (x >= 0 ? "+" : "") + str.tostring(x * 100.0, "#,##0") + "%"
dateS(int t) => na(t) ? "-" : str.format_time(t, "yyyy-MM-dd", "UTC")
lenS(int d) => d % 365 == 0 ? str.tostring(d / 365) + (d == 365 ? " year" : " years") : str.tostring(d) + " days"
pos = tblPos == "Top left" ? position.top_left : tblPos == "Bottom right" ? position.bottom_right : tblPos == "Bottom left" ? position.bottom_left : tblPos == "Middle right" ? position.middle_right : position.top_right
tsz = tblSize == "Tiny" ? size.tiny : tblSize == "Normal" ? size.normal : size.small
var table tb = table.new(pos, 7, 9, border_width=1, frame_width=1, frame_color=color.new(color.gray, 50))
if barstate.islast and not okTf
    table.clear(tb, 0, 0, 6, 8)
    table.cell(tb, 0, 0, "Made for a daily chart", text_color=chart.fg_color, bgcolor=color.new(color.gray, 75), text_size=tsz)
else if barstate.islast
    table.clear(tb, 0, 0, 6, 8)
    fg = chart.fg_color
    hdrBg = color.new(color.gray, 75)
    nAll = array.size(tmA)
    firstStart = na(fromDate) or nAll == 0 ? na : math.max(fromDate, array.get(tmA, 0))
    table.cell(tb, 0, 0, "Bought on any day since " + dateS(firstStart) + " and held for:", text_color=fg, bgcolor=hdrBg, text_size=tsz, text_halign=text.align_left)
    table.merge_cells(tb, 0, 0, 6, 0)
    heads = array.from("Holding length", "Holds counted", "Ended lower", "Median", "Worst (start)", "Best (start)", "Worst start: back to even")
    for c = 0 to 6
        table.cell(tb, c, 1, array.get(heads, c), text_color=fg, bgcolor=hdrBg, text_size=tsz)
    row = 2
    for k = 1 to 6
        H = lenOf(k)
        if H > 0
            [cnt, lower, med, worst, worstAt, best, bestAt, backDays] = stats(H)
            table.cell(tb, 0, row, lenS(H), text_color=fg, text_size=tsz, text_halign=text.align_left)
            if cnt == 0
                table.cell(tb, 1, row, "not enough history", text_color=color.gray, text_size=tsz)
                table.merge_cells(tb, 1, row, 6, row)
            else
                table.cell(tb, 1, row, str.tostring(cnt, "#,##0"), text_color=fg, text_size=tsz)
                table.cell(tb, 2, row, str.tostring(lower * 100.0 / cnt, "0") + "%", text_color=lower * 2 > cnt ? color.red : fg, text_size=tsz)
                table.cell(tb, 3, row, pctS(med), text_color=med < 0 ? color.red : fg, text_size=tsz)
                table.cell(tb, 4, row, pctS(worst) + " (" + dateS(worstAt) + ")", text_color=worst < 0 ? color.red : fg, text_size=tsz)
                table.cell(tb, 5, row, pctS(best) + " (" + dateS(bestAt) + ")", text_color=fg, text_size=tsz)
                table.cell(tb, 6, row, worst >= 0 ? "none ended lower" : na(backDays) ? "not yet" : str.tostring(backDays, "#,##0") + " days", text_color=fg, text_size=tsz)
            row += 1
    table.cell(tb, 0, row, "Past outcomes of this symbol only. Holds overlap, so they are not independent. Not a forecast.", text_color=color.gray, text_size=size.tiny, text_halign=text.align_left)
    table.merge_cells(tb, 0, row, 6, row)

← 返回列表