Seasonality Columns

ChartingCycles · study · 425 行 · 点赞 27 · TradingView 原页

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

Pine Script

// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ChartingCycles
 
//@version=6
indicator("Seasonality Columns", overlay = false, format = format.percent, precision = 1, max_boxes_count = 500, max_labels_count = 500)
 
// Companion to "Seasonality": the same seasonal composite, shown per bar or per calendar period (week, month,
// quarter). Each bar or period of the current year gets the composite's change across it (what it typically did) and
// this year's actual change. From today to Dec 31 only the seasonal part is drawn, as lighter outlined boxes, because
// a script can't plot into the future. On daily charts single days are small next to daily moves; a Week or Month
// period reads best.
// The calculation between the SHARED markers is copied verbatim from Seasonality.pine (CI checks they match).
 
//#region ———————————————————— Constants
 
const string GP_CALC  = "Seasonal composite"
const string GP_COLS  = "Columns"
 
const string PERIOD_CHART   = "Each chart bar"
const string PERIOD_WEEK    = "Week"
const string PERIOD_MONTH   = "Month"
const string PERIOD_QUARTER = "Quarter"
 
const string CYCLE_ALL      = "All years"
const string CYCLE_POST     = "Post-election (yr 1)"
const string CYCLE_MIDTERM  = "Midterm (yr 2)"
const string CYCLE_PRE      = "Pre-election (yr 3)"
const string CYCLE_ELECTION = "Election (yr 4)"
 
const string AVG_MEAN   = "Mean"
const string AVG_MEDIAN = "Median"
 
const int   DAYS          = 365        // calendar grid; Feb 29 is folded into Feb 28
const int   MS_PER_DAY    = 86400000
// A complete year has data within this many days of Jan 1 and Dec 31 (plus one bar's length) ...
const int   EDGE_DAYS     = 7
// ... no gap between bars longer than this many days (plus one bar's length); long enough for exchange holidays such
// as Lunar New Year or Golden Week, short enough to catch a missing month ...
const int   MAX_GAP_DAYS  = 14
// ... and at least this share of the symbol's typical number of bars per year, taken over its recent years.
const float MIN_BAR_SHARE = 0.9
const int   TYPICAL_YEARS = 3    // recent enough to follow a change in trading days per week
 
//#endregion
 
//#region ———————————————————— Inputs
 
int    yearsInput   = input.int(10, "Years to use", minval = 1, maxval = 100, group = GP_CALC, display = display.none,
     tooltip = "How many past complete calendar years to combine. Years that start late, end early, have gaps or thin data are skipped. With a cycle filter, only matching years count. Set this the same as in Seasonality to compare like with like.")
string cycleInput   = input.string(CYCLE_ALL, "Presidential cycle", options = [CYCLE_ALL, CYCLE_POST, CYCLE_MIDTERM, CYCLE_PRE, CYCLE_ELECTION], group = GP_CALC, display = display.none,
     tooltip = "Use only years at one point in the US presidential cycle. Not set automatically: pick the phase you want (election years are divisible by 4, e.g. 2024, 2028). Keeps 1 year in 4, so 10 years needs about 40 years of history: use a weekly or monthly chart. Mainly relevant to US stocks and indices.")
string avgInput     = input.string(AVG_MEAN, "Average", options = [AVG_MEAN, AVG_MEDIAN], group = GP_CALC, display = display.none,
     tooltip = "Mean: the compounded average of the years, so one huge year can't dominate (nine flat years and one +400% year give +17.5%, not +40%). Median: the middle year on each date; resists outliers even more. Set this the same as in Seasonality (this indicator doesn't smooth).")
 
string periodInput  = input.string(PERIOD_MONTH, "Period", options = [PERIOD_CHART, PERIOD_WEEK, PERIOD_MONTH, PERIOD_QUARTER], group = GP_COLS, display = display.none,
     tooltip = "One column per chart bar, or per calendar week (Mon–Sun), month or quarter. Needs a 1D, 1W or 1M chart and a period longer than the bars; otherwise uses each chart bar. With the mean, a Month column is the compounded average of past years' returns for that month.")
color  seasColInput = input.color(color.new(#ff9800, 0), "Seasonal color", group = GP_COLS, display = display.none,
     tooltip = "The composite's change across each bar or period. Bars or periods to Dec 31 are lighter outlined boxes.")
color  upColInput   = input.color(color.new(#26a69a, 0), "Up color", inline = "yr", group = GP_COLS, display = display.none)
color  dnColInput   = input.color(color.new(#ef5350, 0), "Down color", inline = "yr", group = GP_COLS, display = display.none,
     tooltip = "Colors of this year's actual change on each bar or period. The current one is still forming, so it is partial while the seasonal column covers it in full.")
bool   showValInput = input.bool(true, "Show values", group = GP_COLS, display = display.none,
     tooltip = "Each column's change in %, above or below it. With Week, Month or Quarter only; one label per bar would crowd the pane.")
bool   showKeyInput = input.bool(true, "Show key", group = GP_COLS, display = display.none,
     tooltip = "A small key at the top right of the pane: Seasonal (the seasonal color) and This year (shown in the up color; falls show in the down color). With Week, Month or Quarter (when the chart allows them), the seasonal column is the left half of each period and this year's the right half; otherwise the two overlap on each bar.")
 
//#endregion
 
//#region ———————————————————— Types and functions
 
// SHARED START
//@type One calendar year of data, starting from the prior year's final close.
//@field yr       Calendar year.
//@field complete Data covers the whole year (bar count is checked separately against the typical year).
//@field doys     Calendar day (0-364) of each bar.
//@field rets     Cumulative return (fraction) from the prior year's final close at each bar.
type YearData
    int          yr
    bool         complete = false
    array<int>   doys
    array<float> rets
 
//@function Calendar day (0-364) on which month `m` starts in a non-leap year.
monthStart(int m) =>
    switch m
        1  => 0
        2  => 31
        3  => 59
        4  => 90
        5  => 120
        6  => 151
        7  => 181
        8  => 212
        9  => 243
        10 => 273
        11 => 304
        => 334
 
//@function Day of the year 0-364 for timestamp `t`, with Feb 29 folded into Feb 28 so leap years line up.
dayOfYear(int t) =>
    int m = month(t)
    int d = dayofmonth(t)
    m == 2 and d == 29 ? 58 : monthStart(m) + d - 1
 
//@function Calendar day for a bar ending at `t`. Monthly bars are dated at calendar month-end: their last trading day
// moves from year to year, which would otherwise mix in the previous month.
barDoy(int t) =>
    int m = month(t)
    timeframe.ismonthly ? (m == 12 ? DAYS - 1 : monthStart(m + 1) - 1) : dayOfYear(t)
 
//@function Whether `yr` passes the presidential-cycle filter.
cycleMatch(int yr, string cycle) =>
    switch cycle
        CYCLE_POST     => yr % 4 == 1
        CYCLE_MIDTERM  => yr % 4 == 2
        CYCLE_PRE      => yr % 4 == 3
        CYCLE_ELECTION => yr % 4 == 0
        => true
 
//@function Average of the returns in `values`: the compounded (geometric) mean, or the median; `na` when empty.
// Compounding makes the composite's change between two dates equal the mean of the years' own returns over them.
aggregate(array<float> values, string avgMethod) =>
    float result = na
    int   n      = values.size()
    if n > 0
        if avgMethod == AVG_MEDIAN
            result := values.median()
        else
            float s = 0.0
            for v in values
                s += math.log(1.0 + v)
            result := math.exp(s / n) - 1.0
    result
 
//@function Centered moving average of the returns in `src`, on a compounded basis, over `len` days rounded up to an
// odd count. The window shrinks evenly near the ends, so the first and last values are unchanged.
smoothPath(array<float> src, int len) =>
    int n    = src.size()
    int half = math.floor(len / 2.0)
    array<float> out = array.new<float>()
    if half == 0 or n == 0
        out := src.copy()
    else
        array<float> logs = array.new<float>()
        for v in src
            logs.push(math.log(1.0 + v))
        for k = 0 to n - 1
            int h = math.min(half, k, n - 1 - k)
            out.push(math.exp(logs.slice(k - h, k + h + 1).avg()) - 1.0)
    out
 
//@function Median bar count of the most recent TYPICAL_YEARS complete years before `curYr`; `na` if there are none.
typicalBars(array<YearData> years, int curYr) =>
    array<float> sizes = array.new<float>()
    int i = years.size() - 1
    while i >= 0 and sizes.size() < TYPICAL_YEARS
        YearData y = years.get(i)
        if y.complete and y.yr < curYr
            sizes.push(float(y.rets.size()))
        i -= 1
    sizes.size() > 0 ? sizes.median() : na
 
//@function Indices into `years` of the most recent complete years before `curYr` that pass the cycle filter.
// A year must also have at least MIN_BAR_SHARE of the symbol's typical bar count, which catches thin data.
selectYears(array<YearData> years, int curYr, int maxYears, string cycle) =>
    float typical = typicalBars(years, curYr)
    array<int> sel = array.new<int>()
    int i = years.size() - 1
    while i >= 0 and sel.size() < maxYears
        YearData y = years.get(i)
        if y.yr < curYr and y.complete and y.rets.size() >= MIN_BAR_SHARE * typical and cycleMatch(y.yr, cycle)
            sel.unshift(i)
        i -= 1
    sel
 
//@function Composite path on the 365-day grid. Each selected year contributes, per calendar day, its last bar on or
// before that day (0% before the first bar), or with `nearest` (weekly charts) the bar closest to that day, so week-end
// dates that shift between years don't lag. Then combined per day and smoothed.
buildComposite(array<YearData> years, array<int> sel, string avgMethod, int smooth, bool nearest) =>
    array<float> grid = array.new<float>()
    if sel.size() > 0
        matrix<float> m = matrix.new<float>(sel.size(), DAYS, 0.0)
        for [row, idx] in sel
            YearData y = years.get(idx)
            int   n = y.doys.size()
            int   p = 0    // first bar after day k
            for k = 0 to DAYS - 1
                while p < n and y.doys.get(p) <= k
                    p += 1
                float v = p > 0 ? y.rets.get(p - 1) : 0.0
                if nearest and p < n
                    int prevDoy = p > 0 ? y.doys.get(p - 1) : -1
                    if y.doys.get(p) - k < k - prevDoy
                        v := y.rets.get(p)
                m.set(row, k, v)
        for k = 0 to DAYS - 1
            grid.push(aggregate(m.col(k), avgMethod))
    smoothPath(grid, smooth)
// SHARED END
 
//#endregion
 
//#region ———————————————————— Data collection
 
// Same bookkeeping as Seasonality.pine (without smoothing or the price-chart data).
bool supported = timeframe.isdwm and chart.is_standard
bool nearest   = timeframe.isweekly
int  barEnd  = time_close - 1
int  yr      = year(barEnd)
int  doy     = barDoy(barEnd)
int  barDays = timeframe.isdaily ? timeframe.multiplier : timeframe.isweekly ? 7 * timeframe.multiplier : 31 * timeframe.multiplier
int  edgeDays = EDGE_DAYS + barDays
int  endDoy   = DAYS - 1 - (timeframe.ismonthly ? 0 : edgeDays)
int  lastYr = year(timeframe.ismonthly ? last_bar_time + 15 * MS_PER_DAY : last_bar_time + (timeframe.isdaily ? math.min(time_close - time, MS_PER_DAY) : time_close - time) - 1)
bool isNewYear = bar_index == 0 or yr != yr[1]
 
var array<YearData> years         = array.new<YearData>()
var array<float>    composite     = array.new<float>()
var array<int>      selected      = array.new<int>()
var float           yearBase      = na
var bool            yearBaseFresh = false
var int             yearStartBar  = 0
 
if supported
    if isNewYear
        bool endedOnTime = bar_index > 0 and barDoy(barEnd[1]) >= endDoy
        if years.size() > 0 and years.last().yr == yr[1]
            YearData prev = years.last()
            int maxGap = 0
            if prev.doys.size() > 1
                for j = 1 to prev.doys.size() - 1
                    maxGap := math.max(maxGap, prev.doys.get(j) - prev.doys.get(j - 1))
            bool spansYear = prev.doys.first() <= edgeDays and endedOnTime
            bool noGaps    = maxGap <= MAX_GAP_DAYS + barDays
            bool positive  = prev.rets.min() > -1.0
            prev.complete := spansYear and noGaps and positive and yearBaseFresh
        yearBaseFresh := endedOnTime
        yearStartBar  := bar_index
        yearBase      := bar_index > 0 and yr[1] == yr - 1 and close[1] > 0 ? close[1] : na
        if not na(yearBase) and (years.size() == 0 or years.last().yr != yr)
            years.push(YearData.new(yr, false, array.new<int>(), array.new<float>()))
        selected  := selectYears(years, yr, yearsInput, cycleInput)
        composite := buildComposite(years, selected, avgInput, 1, nearest)
 
    if not na(yearBase) and years.size() > 0 and years.last().yr == yr
        YearData cur = years.last()
        int   j = bar_index - yearStartBar
        float r = close / yearBase - 1.0
        if cur.rets.size() > j
            cur.doys.set(j, doy)
            cur.rets.set(j, r)
        else
            cur.doys.push(doy)
            cur.rets.push(r)
 
//#endregion
 
//#region ———————————————————— Columns
 
//@function Calendar days [first, last] (0-364) of the week (Mon-Sun), month or quarter containing timestamp `t`,
// clipped to the year.
periodBounds(int t, string period) =>
    int m  = month(t)
    int s0 = 0
    int e0 = DAYS - 1
    if period == PERIOD_WEEK
        // From the week's Monday and Sunday dates, so a leap day doesn't shift the week.
        int fromMon = (dayofweek(t) - dayofweek.monday + 7) % 7
        int mon     = t - fromMon * MS_PER_DAY
        int sun     = t + (6 - fromMon) * MS_PER_DAY
        s0 := year(mon) < year(t) ? 0 : dayOfYear(mon)
        e0 := year(sun) > year(t) ? DAYS - 1 : dayOfYear(sun)
    else
        int first = period == PERIOD_QUARTER ? 3 * math.floor((m - 1) / 3.0) + 1 : m
        int last  = period == PERIOD_QUARTER ? first + 2 : m
        s0 := monthStart(first)
        e0 := last == 12 ? DAYS - 1 : monthStart(last + 1) - 1
    [s0, e0]
 
//@function The composite's change from the end of calendar day `fromDoy` (-1 = last year's close) to day `toDoy`.
compChange(array<float> comp, int fromDoy, int toDoy) =>
    (1.0 + comp.get(toDoy)) / (1.0 + (fromDoy < 0 ? 0.0 : comp.get(fromDoy))) - 1.0
 
int  periodDays = periodInput == PERIOD_WEEK ? 7 : periodInput == PERIOD_MONTH ? 28 : periodInput == PERIOD_QUARTER ? 90 : 0
// Multi-unit bars (2M, 3W, ...) can straddle a period boundary, so periods need 1D, 1W or 1M bars.
bool usePeriods = periodDays > barDays and timeframe.multiplier == 1
bool hasComp    = composite.size() == DAYS
bool isLastYear = yr == lastYr
 
// Chart-bar columns: the composite's change across this bar, from the previous bar's date (or last year's close on
// the year's first bar), and this year's actual change.
float seasChg = na
if hasComp
    seasChg := compChange(composite, isNewYear ? -1 : doy[1], doy)
float actChg = close / close[1] - 1.0
bool  barCols = isLastYear and not usePeriods
plot(barCols ? seasChg * 100 : na, "Seasonal change", color.new(seasColInput, 50), style = plot.style_columns)
plot(barCols and not na(yearBase) ? actChg * 100 : na, "This year's change", actChg >= 0 ? upColInput : dnColInput, 3,
     plot.style_histogram)
hline(0, "Zero", color.new(color.gray, 50), hline.style_dotted)
 
// Period columns: this year's periods, kept per year. Each period records its calendar days, its first and latest
// bar times, the close it starts from (the previous period's last close) and its change so far.
var array<int>   pFirstDoy = array.new<int>()
var array<int>   pLastDoy  = array.new<int>()
var array<int>   pFirstT   = array.new<int>()
var array<int>   pLastT    = array.new<int>()
var array<float> pBase     = array.new<float>()
var array<float> pChg      = array.new<float>()
if usePeriods and supported
    if isNewYear
        pFirstDoy := array.new<int>()
        pLastDoy  := array.new<int>()
        pFirstT   := array.new<int>()
        pLastT    := array.new<int>()
        pBase     := array.new<float>()
        pChg      := array.new<float>()
    if not na(yearBase)
        [s0, e0] = periodBounds(barEnd, periodInput)
        // Checking the last stored period keeps this idempotent across realtime ticks.
        if pFirstDoy.size() == 0 or pFirstDoy.last() != s0
            pFirstDoy.push(s0)
            pLastDoy.push(e0)
            pFirstT.push(time)
            pLastT.push(time)
            pBase.push(close[1])
            pChg.push(0.0)
        pLastT.set(pLastT.size() - 1, time)
        pChg.set(pChg.size() - 1, close / pBase.last() - 1.0)
 
//@function Draws one column as a box from `left` to `right` (bar times), from 0 to `v` (a fraction), with its value
// as a label beyond its end when `withValue`.
column(int left, int right, float v, color fill, color border, bool withValue) =>
    box.new(left, math.max(v, 0.0) * 100, right, math.min(v, 0.0) * 100, border_color = border,
         xloc = xloc.bar_time, bgcolor = fill)
    if withValue
        // Rounded first, so tiny negatives print "0.0%" rather than "-0.0%".
        float pct = math.round(v * 1000) / 10.0
        label.new(int((left + right) / 2), v * 100, (pct > 0 ? "+" : "") + str.tostring(pct == 0 ? 0.0 : pct, "0.0") + "%",
             xloc = xloc.bar_time, style = v >= 0 ? label.style_label_down : label.style_label_up, color = color(na),
             textcolor = border, size = size.small)
 
// Its content depends only on inputs, so it is built once.
var table key = showKeyInput ? table.new(position.top_right, 2, 1, bgcolor = color.new(#1e222d, 20)) : na
if barstate.isfirst and not na(key)
    key.cell(0, 0, "■ Seasonal", text_color = seasColInput, text_size = size.small)
    key.cell(1, 0, "■ This year", text_color = upColInput, text_size = size.small)
 
if barstate.islast
    // Delete from the newest down, so it works whether or not `box.all` / `label.all` shrink as drawings are deleted.
    array<box> oldBoxes = box.all
    if oldBoxes.size() > 0
        for i = oldBoxes.size() - 1 to 0
            oldBoxes.get(i).delete()
    array<label> oldLabels = label.all
    if oldLabels.size() > 0
        for i = oldLabels.size() - 1 to 0
            oldLabels.get(i).delete()
 
    if supported
        // Expected future bar times from TradingView's own calendar, up to year end.
        array<int> fTimes = array.new<int>()
        array<int> fEnds  = array.new<int>()
        for k = 1 to 500
            int fClose = time_close(timeframe.period, bars_back = -k)
            if na(fClose) or year(fClose - 1) != yr
                break
            fTimes.push(time(timeframe.period, bars_back = -k))
            fEnds.push(fClose - 1)
        int   n         = fTimes.size()
        // Period boxes reach half a bar beyond their first and last bars, so a one-bar period still has width.
        int   half      = timeframe.in_seconds() * 500
        color solidFill = color.new(seasColInput, 40)
        color border    = color.new(seasColInput, 0)
        // Bars or periods to Dec 31: lighter than the past, but still easy to read.
        color futFill   = color.new(seasColInput, 65)
        color futBorder = color.new(seasColInput, 35)
 
        if not usePeriods
            if hasComp and n > 0
                // One lighter box per future bar, centered on it: its edges sit halfway to the neighbouring bars.
                for k = 0 to n - 1
                    int t     = fTimes.get(k)
                    int tPrev = k == 0 ? time : fTimes.get(k - 1)
                    int tNext = k + 1 < n ? fTimes.get(k + 1) : t + (t - tPrev)
                    int dPrev = k == 0 ? doy : barDoy(fEnds.get(k - 1))
                    column(int((tPrev + t) / 2), int((t + tNext) / 2), compChange(composite, dPrev, barDoy(fEnds.get(k))), futFill, futBorder, false)
        else if pFirstDoy.size() > 0
            // This year's periods, each split in two side by side: the seasonal change across the whole period on the
            // left, this year's change so far on the right. The current period also spans its remaining future bars.
            int cur      = pFirstDoy.size() - 1
            int curRight = pLastT.last()
            if n > 0
                for k = 0 to n - 1
                    [fs, fe] = periodBounds(fEnds.get(k), periodInput)
                    if fs == pFirstDoy.last()
                        curRight := fTimes.get(k)
            for [p, s0] in pFirstDoy
                int left  = pFirstT.get(p) - half
                int right = (p == cur ? curRight : pLastT.get(p)) + half
                int mid   = int((left + right) / 2)
                if hasComp
                    column(left, mid, compChange(composite, s0 - 1, pLastDoy.get(p)), solidFill, border, showValInput)
                float act    = pChg.get(p)
                color actCol = act >= 0 ? upColInput : dnColInput
                column(mid, right, act, color.new(actCol, 40), actCol, showValInput)
            // Later periods to Dec 31: the seasonal half only, over their expected bars.
            if hasComp
                int q = 0
                while q < n
                    [fs, fe] = periodBounds(fEnds.get(q), periodInput)
                    if fs == pFirstDoy.last()
                        q += 1
                        continue
                    int left  = fTimes.get(q)
                    int right = left
                    while q < n
                        [gs, ge] = periodBounds(fEnds.get(q), periodInput)
                        if gs != fs
                            break
                        right := fTimes.get(q)
                        q += 1
                    column(left - half, int((left + right) / 2), compChange(composite, fs - 1, fe), futFill, futBorder, showValInput)
 
//#endregion

← 返回列表