YearlyPerformanceTable

Ku_Hero · library · 252 行 · 点赞 2 · TradingView 原页

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

Pine Script

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// (c) K'u Hero
//@version=6
// Yearly Performance Table - library  v1.01
// Reads the closed trades of the strategy it is called from (strategy.closedtrades.*) and shows:
//   - a yearly table: net profit, max drawdown, number of trades, profit factor and win rate per year,
//     plus one "All" row for the whole history;
//   - optionally a monthly table: rows = years, columns = Jan..Dec + year total.
//
// Definitions (all from closed trades only; an open position is not counted until it is closed):
//   - A trade belongs to the year / month of its EXIT time (time zone: exchange time zone by default).
//   - Net profit = sum of strategy.closedtrades.profit() (commission included, same as the Strategy Tester).
//   - Profit factor = gross profit / gross loss. No losing trade -> shown as "inf" (or "-" when there is no
//     winning trade either). Win rate = trades with profit > 0 / all trades (as in the Strategy Tester).
//   - Balance = initial capital + cumulative net profit of closed trades, updated trade by trade.
//   - Max drawdown of a year = the largest fall of that balance from its running peak inside the year.
//     The peak starts at the balance at the start of the year (the end of the previous year), so a drawdown
//     carried over from the previous year is not counted again. Max DD % = the largest (peak - trough) / peak.
//     The "All" row uses the same rule over the whole history, starting at the initial capital.
//     This is NOT the Strategy Tester's "Max equity drawdown", which also includes open-trade (intrabar) moves.
//   - Percent mode: net % of a year = net profit / balance at the start of the year; a month = net profit of the
//     month / balance at the start of that month. Monthly percentages therefore do not add up to the year figure.
//   - Years from the first chart bar to the last bar are listed; a year without closed trades shows 0 trades.
//     The "All" label shows the first and last year with closed trades, e.g. "All (1980-2026)", because older
//     years may be outside the rows shown (maxYears).
//   - While a position is open, the Strategy Tester's "Net profit" / "Gross loss" already subtract that open
//     position's entry commission. The "All" row does not (it is the sum of the closed trades listed above), so a
//     note row under the table shows the open position and the Tester's net profit for comparison.
// The tables are drawn on the last confirmed historical bar and refreshed on realtime bars. Closed trades never change: no repainting.
 
// @description Yearly performance table for strategies: net profit, max drawdown, trades, profit factor and win rate per year, plus an optional monthly P&L table. Add one call of run() to your strategy.
library("YearlyPerformanceTable", overlay = true)
 
// ===== Internal =====
 
type YearStat
    int          trades       = 0
    int          wins         = 0
    float        grossProfit  = 0.0
    float        grossLoss    = 0.0  // stored as a positive number
    float        net          = 0.0
    float        startBalance = na
    float        peak         = na
    float        maxDd        = 0.0
    float        maxDdPct     = 0.0
    array<float> mNet
    array<float> mStart
    array<int>   mTrades
 
_newYear(float balance) =>
    YearStat.new(startBalance = balance, peak = balance, mNet = array.new<float>(12, 0.0), mStart = array.new<float>(12, na), mTrades = array.new<int>(12, 0))
 
_money(float v) =>
    str.tostring(v, "#,##0.00")
 
_pct(float v) =>
    na(v) ? "-" : str.tostring(v, "#,##0.00") + "%"
 
_pfText(float gp, float gl, int n) =>
    n == 0 ? "-" : gl > 0 ? str.tostring(gp / gl, "0.00") : gp > 0 ? "inf" : "-"
 
_winText(int wins, int n) =>
    n == 0 ? "-" : str.tostring(100.0 * wins / n, "0.0") + "%"
 
_ratio(float num, float den) =>
    not na(den) and den > 0 ? 100.0 * num / den : na
 
// Accepts "UTC" / "GMT" with an optional offset (UTC+9, GMT-5, UTC+05:30) and IANA-style names (Area/City).
// Anything else (e.g. "New York") would stop the script with a runtime error, so it is replaced by the exchange time zone.
// An IANA-style name that does not exist (e.g. "Asia/Tokio") cannot be detected here.
_tzLooksValid(string s) =>
    str.match(s, "^(UTC|GMT)([+-][0-9]{1,2}(:?[0-9]{2})?)?$") != "" or str.match(s, "^[A-Za-z_]+(/[A-Za-z0-9_+-]+)+$") != ""
 
_signColor(float v, color profitColor, color lossColor, color textColor) =>
    na(v) or v == 0 ? textColor : v > 0 ? profitColor : lossColor
 
// ===== Public =====
 
// @function Collects the strategy's closed trades and draws the yearly (and optionally monthly) table.
//   Call it once per bar from the global scope of a strategy (not inside if / for), after the order calls.
// @param showYearly Show the yearly table.
// @param showMonthly Show the monthly table (rows = years, columns = months + year).
// @param valueMode "Currency" (account currency) or "Percent" (of the balance at the start of the year / month). Not case-sensitive.
// @param yearlyPosition Position of the yearly table (position.*).
// @param monthlyPosition Position of the monthly table (position.*). Use a different one from yearlyPosition.
// @param textSize Text size (size.*).
// @param maxYears Number of most recent years listed (1-60). The "All" row always covers the whole history.
// @param timezoneName Time zone used to assign trades to years / months: an IANA name ("America/New_York", "Asia/Tokyo") or "UTC" / "UTC+9" / "UTC-05:00". "" = exchange time zone. A value in another format falls back to the exchange time zone (noted in the table title).
// @param bgColor Table background.
// @param headerColor Background of the title and header cells.
// @param textColor Text color.
// @param profitColor Text color of positive values.
// @param lossColor Text color of negative values.
// @returns On the bar where the tables are drawn: a text summary, one line per year "year;trades;net;maxDD;maxDD%;PF;win%", an "All" line and a "Tester" line (closed trades, strategy.netprofit, open trades, time zone used, All label, value mode). "" on other bars.
export run(bool showYearly = true, bool showMonthly = false, string valueMode = "Currency", string yearlyPosition = position.top_right, string monthlyPosition = position.bottom_right, string textSize = size.small, int maxYears = 20, string timezoneName = "", color bgColor = #131722, color headerColor = #2A2E39, color textColor = #D1D4DC, color profitColor = #26A69A, color lossColor = #EF5350) =>
    var map<int, YearStat> stats = map.new<int, YearStat>()
    var int   processed = 0
    var float balance   = strategy.initial_capital
    var float peakAll   = strategy.initial_capital
    var float ddAll     = 0.0
    var float ddAllPct  = 0.0
    var int   nAll      = 0
    var int   winsAll   = 0
    var float gpAll     = 0.0
    var float glAll     = 0.0
    var int   firstYear = na
    var table tY        = na
    var table tM        = na
 
    string tzIn  = str.trim(timezoneName)
    bool   tzBad = tzIn != "" and not _tzLooksValid(tzIn)
    string tz    = tzIn == "" or tzBad ? syminfo.timezone : tzIn
    if na(firstYear)
        firstYear := year(time, tz)
 
    // ---- collect newly closed trades (indices are absolute; first_index skips trimmed history) ----
    int startIdx = math.max(processed, strategy.closedtrades.first_index)
    if strategy.closedtrades > startIdx
        for i = startIdx to strategy.closedtrades - 1
            float p  = nz(strategy.closedtrades.profit(i))
            int   et = strategy.closedtrades.exit_time(i)
            int   y  = year(et, tz)
            int   m  = month(et, tz) - 1
            YearStat s = stats.get(y)
            if na(s)
                s := _newYear(balance)
                stats.put(y, s)
            if na(s.mStart.get(m))
                s.mStart.set(m, balance)
            s.trades := s.trades + 1
            s.net    := s.net + p
            s.mNet.set(m, s.mNet.get(m) + p)
            s.mTrades.set(m, s.mTrades.get(m) + 1)
            nAll += 1
            if p > 0
                s.wins        := s.wins + 1
                s.grossProfit := s.grossProfit + p
                winsAll += 1
                gpAll   += p
            else if p < 0
                s.grossLoss := s.grossLoss - p
                glAll -= p
            balance += p
            // drawdown inside the year (peak starts at the start-of-year balance)
            s.peak := math.max(s.peak, balance)
            float dd = s.peak - balance
            s.maxDd := math.max(s.maxDd, dd)
            if s.peak > 0
                s.maxDdPct := math.max(s.maxDdPct, 100.0 * dd / s.peak)
            // drawdown over the whole history (peak starts at the initial capital)
            peakAll := math.max(peakAll, balance)
            float ddA = peakAll - balance
            ddAll := math.max(ddAll, ddA)
            if peakAll > 0
                ddAllPct := math.max(ddAllPct, 100.0 * ddA / peakAll)
        processed := strategy.closedtrades
 
    string summary = ""
    // last confirmed historical bar, then every realtime bar the strategy calculates on
    if barstate.islastconfirmedhistory or barstate.isrealtime
        bool  pctMode  = str.lower(str.trim(valueMode)) == "percent"
        int   nYearsMax = math.max(1, math.min(60, maxYears))
        int   lastYear = year(time, tz)
        int   y0       = math.max(firstYear, lastYear - nYearsMax + 1)
        int   nY       = lastYear - y0 + 1
        string ccy     = strategy.account_currency
        string netHead = pctMode ? "Net %" : "Net (" + ccy + ")"
        string ddHead  = pctMode ? "Max DD %" : "Max DD (" + ccy + ")"
        color  muted   = color.new(textColor, 50)
        string tzNote  = tzBad ? " | time zone '" + tzIn + "' not valid, exchange time zone used" : ""
 
        // ---- text summary (all years with trades + All) ----
        array<int> keys = stats.keys()
        array.sort(keys, order.ascending)
        string allLabel = keys.size() > 0 ? "All (" + str.tostring(keys.first()) + (keys.size() > 1 ? "-" + str.tostring(keys.last()) : "") + ")" : "All"
        for k in keys
            YearStat s = stats.get(k)
            summary += str.tostring(k) + ";" + str.tostring(s.trades) + ";" + str.tostring(s.net, "0.00") + ";" + str.tostring(s.maxDd, "0.00") + ";" + str.tostring(s.maxDdPct, "0.00") + ";" + _pfText(s.grossProfit, s.grossLoss, s.trades) + ";" + _winText(s.wins, s.trades) + "\n"
        summary += "All;" + str.tostring(nAll) + ";" + str.tostring(balance - strategy.initial_capital, "0.00") + ";" + str.tostring(ddAll, "0.00") + ";" + str.tostring(ddAllPct, "0.00") + ";" + _pfText(gpAll, glAll, nAll) + ";" + _winText(winsAll, nAll)
        summary += "\nTester;" + str.tostring(strategy.closedtrades) + ";" + str.tostring(strategy.netprofit, "0.00") + ";open trades " + str.tostring(strategy.opentrades) + ";tz " + tz + ";" + allLabel + ";" + (pctMode ? "Percent" : "Currency")
 
        // ---- yearly table ----
        if showYearly
            if na(tY)
                tY := table.new(yearlyPosition, 6, 64, bgcolor = bgColor, frame_color = color.gray, frame_width = 1, border_color = color.new(color.gray, 70), border_width = 1)
            table.clear(tY, 0, 0, 5, 63)
            table.cell(tY, 0, 0, "Yearly performance (closed trades)" + tzNote, text_color = textColor, text_size = textSize, bgcolor = headerColor)
            table.merge_cells(tY, 0, 0, 5, 0)
            array<string> heads = array.from("Year", netHead, ddHead, "Trades", "PF", "Win %")
            for c = 0 to 5
                table.cell(tY, c, 1, heads.get(c), text_color = textColor, text_size = textSize, bgcolor = headerColor)
            for j = 0 to nY - 1
                int yy = y0 + j
                int r  = j + 2
                YearStat s = stats.get(yy)
                if na(s)
                    table.cell(tY, 0, r, str.tostring(yy), text_color = muted, text_size = textSize)
                    table.cell(tY, 1, r, pctMode ? "0.00%" : "0.00", text_color = muted, text_size = textSize)
                    table.cell(tY, 2, r, pctMode ? "0.00%" : "0.00", text_color = muted, text_size = textSize)
                    table.cell(tY, 3, r, "0", text_color = muted, text_size = textSize)
                    table.cell(tY, 4, r, "-", text_color = muted, text_size = textSize)
                    table.cell(tY, 5, r, "-", text_color = muted, text_size = textSize)
                else
                    float netV = pctMode ? _ratio(s.net, s.startBalance) : s.net
                    table.cell(tY, 0, r, str.tostring(yy), text_color = textColor, text_size = textSize)
                    table.cell(tY, 1, r, pctMode ? _pct(netV) : _money(netV), text_color = _signColor(netV, profitColor, lossColor, textColor), text_size = textSize)
                    table.cell(tY, 2, r, pctMode ? _pct(s.maxDdPct) : _money(s.maxDd), text_color = textColor, text_size = textSize)
                    table.cell(tY, 3, r, str.tostring(s.trades), text_color = textColor, text_size = textSize)
                    table.cell(tY, 4, r, _pfText(s.grossProfit, s.grossLoss, s.trades), text_color = textColor, text_size = textSize)
                    table.cell(tY, 5, r, _winText(s.wins, s.trades), text_color = textColor, text_size = textSize)
            int   rT   = nY + 2
            float netA = balance - strategy.initial_capital
            float netAV = pctMode ? _ratio(netA, strategy.initial_capital) : netA
            table.cell(tY, 0, rT, allLabel, text_color = textColor, text_size = textSize, bgcolor = headerColor)
            table.cell(tY, 1, rT, pctMode ? _pct(netAV) : _money(netAV), text_color = _signColor(netAV, profitColor, lossColor, textColor), text_size = textSize, bgcolor = headerColor)
            table.cell(tY, 2, rT, pctMode ? _pct(ddAllPct) : _money(ddAll), text_color = textColor, text_size = textSize, bgcolor = headerColor)
            table.cell(tY, 3, rT, str.tostring(nAll), text_color = textColor, text_size = textSize, bgcolor = headerColor)
            table.cell(tY, 4, rT, _pfText(gpAll, glAll, nAll), text_color = textColor, text_size = textSize, bgcolor = headerColor)
            table.cell(tY, 5, rT, _winText(winsAll, nAll), text_color = textColor, text_size = textSize, bgcolor = headerColor)
            if strategy.opentrades > 0
                table.cell(tY, 0, rT + 1, "Open position not included. Tester net profit (incl. its entry commission): " + _money(strategy.netprofit), text_color = muted, text_size = textSize)
                table.merge_cells(tY, 0, rT + 1, 5, rT + 1)
 
        // ---- monthly table ----
        if showMonthly
            if na(tM)
                tM := table.new(monthlyPosition, 14, 62, bgcolor = bgColor, frame_color = color.gray, frame_width = 1, border_color = color.new(color.gray, 70), border_width = 1)
            table.clear(tM, 0, 0, 13, 61)
            table.cell(tM, 0, 0, "Monthly net " + (pctMode ? "% (of balance at month start)" : "(" + ccy + ")") + ", by exit time" + tzNote, text_color = textColor, text_size = textSize, bgcolor = headerColor)
            table.merge_cells(tM, 0, 0, 13, 0)
            array<string> mh = array.from("Year", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "Year")
            for c = 0 to 13
                table.cell(tM, c, 1, mh.get(c), text_color = textColor, text_size = textSize, bgcolor = headerColor)
            for j = 0 to nY - 1
                int yy = y0 + j
                int r  = j + 2
                YearStat s = stats.get(yy)
                table.cell(tM, 0, r, str.tostring(yy), text_color = na(s) ? muted : textColor, text_size = textSize)
                if na(s)
                    for c = 1 to 12
                        table.cell(tM, c, r, "", text_size = textSize)
                    table.cell(tM, 13, r, pctMode ? "0.00%" : "0.00", text_color = muted, text_size = textSize, bgcolor = headerColor)
                else
                    for c = 1 to 12
                        if s.mTrades.get(c - 1) > 0
                            float v = pctMode ? _ratio(s.mNet.get(c - 1), s.mStart.get(c - 1)) : s.mNet.get(c - 1)
                            table.cell(tM, c, r, pctMode ? _pct(v) : _money(v), text_color = _signColor(v, profitColor, lossColor, textColor), text_size = textSize)
                        else
                            table.cell(tM, c, r, "", text_size = textSize)
                    float yv = pctMode ? _ratio(s.net, s.startBalance) : s.net
                    table.cell(tM, 13, r, pctMode ? _pct(yv) : _money(yv), text_color = _signColor(yv, profitColor, lossColor, textColor), text_size = textSize, bgcolor = headerColor)
    summary

← 返回列表