StrategyScorecard

jabez4jc · library · 240 行 · 点赞 0 · 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/
// © jabez4jc
 
//@version=6
 
// @description A strategy scorecard table: profit factor, expectancy, win rate, reward to risk, drawdown, losing streak,
//              Sharpe, Calmar, recovery factor, trade count, trade size, capital per trade, trade duration, commission
//              impact and walk-forward efficiency, each with a pass / warn / fail icon. Libraries cannot read
//              `strategy.*`, so the strategy passes its built-in figures in `Stats` and feeds its closed trades to
//              `TradeTotals.addTrade()`; `dailySharpe()` and `calmar()` keep the time-based state.
library("StrategyScorecard", overlay = true)
 
import jabez4jc/UIKit/1 as ui
 
//#region ———————————————————— Inputs from the strategy
 
// @type The strategy's built-in figures.
// @field netProfit `strategy.netprofit`.
// @field netProfitPct `strategy.netprofit_percent`.
// @field grossProfit `strategy.grossprofit`.
// @field grossLoss `strategy.grossloss`.
// @field wins `strategy.wintrades`.
// @field losses `strategy.losstrades`.
// @field avgWin `strategy.avg_winning_trade`.
// @field avgLoss `strategy.avg_losing_trade`.
// @field avgTrade `strategy.avg_trade`.
// @field maxDrawdown `strategy.max_drawdown`.
// @field maxDrawdownPct `strategy.max_drawdown_percent`.
export type Stats
    float netProfit
    float netProfitPct
    float grossProfit
    float grossLoss
    int   wins
    int   losses
    float avgWin
    float avgLoss
    float avgTrade
    float maxDrawdown
    float maxDrawdownPct
 
// @type Totals over the strategy's closed trades, built with `addTrade()`.
// @field trades Closed trades added.
// @field commission Total commission paid.
// @field minutes Total time in trades, in minutes.
// @field capital Sum of entry price x size (capital committed per trade).
// @field inSample Net profit of trades closed before the walk-forward split.
// @field outSample Net profit of trades closed on or after the split.
// @field streak Current losing streak.
// @field maxLosingStreak Longest losing streak.
export type TradeTotals
    int   trades          = 0
    float commission      = 0.0
    float minutes         = 0.0
    float capital         = 0.0
    float inSample        = 0.0
    float outSample       = 0.0
    int   streak          = 0
    int   maxLosingStreak = 0
 
// @function Adds one closed trade, e.g. `strategy.closedtrades.profit(i)` and its companions.
// @param t (TradeTotals) The totals.
// @param profit (series float) Trade profit.
// @param commission (series float) Trade commission.
// @param entryPrice (series float) Entry price.
// @param size (series float) Trade size (sign ignored).
// @param entryTime (series int) Entry time.
// @param exitTime (series int) Exit time.
// @param splitTime (series int) Walk-forward split time; `na` disables the in / out-of-sample split. Optional.
// @returns (void)
export method addTrade(TradeTotals t, float profit, float commission, float entryPrice, float size, int entryTime, int exitTime, int splitTime = na) =>
    t.trades     += 1
    t.commission += nz(commission)
    t.minutes    += math.max(0, exitTime - entryTime) / 60000.0
    t.capital    += nz(entryPrice) * math.abs(nz(size))
    if not na(splitTime)
        if exitTime < splitTime
            t.inSample += nz(profit)
        else
            t.outSample += nz(profit)
    t.streak          := profit < 0 ? t.streak + 1 : 0
    t.maxLosingStreak := math.max(t.maxLosingStreak, t.streak)
 
// @function Annualised Sharpe ratio of daily equity returns (no risk-free rate, 252 trading days). The current day's
//           return counts on the last historical bar. Call it once per bar, unconditionally.
// @param equity (series float) `strategy.equity`.
// @returns (float) The Sharpe ratio, or `na` with fewer than two days or no variation.
export dailySharpe(float equity) =>
    var float dayStart = equity
    var float priorDay = equity
    var float sum      = 0.0
    var float sumSq    = 0.0
    var int   days     = 0
    if timeframe.change("D") and not barstate.isfirst
        float r = priorDay != 0 ? (equity[1] - priorDay) / priorDay : na
        if not na(r)
            sum   += r
            sumSq += r * r
            days  += 1
        priorDay := equity[1]
        dayStart := equity
    float s  = sum
    float ss = sumSq
    int   k  = days
    if barstate.islast and not barstate.isrealtime and dayStart != 0
        float r = (equity - dayStart) / dayStart
        s  += r
        ss += r * r
        k  += 1
    float mean     = k > 0 ? s / k : na
    float variance = k > 1 ? math.max(ss / k - mean * mean, 0) : na
    variance > 0 ? mean / math.sqrt(variance) * math.sqrt(252) : na
 
// @function Calmar ratio: annualised return (or the total return during the first 30 days) over the maximum drawdown
//           percentage. Call it once per bar, unconditionally.
// @param netProfitPct (series float) `strategy.netprofit_percent`.
// @param maxDrawdownPct (series float) `strategy.max_drawdown_percent`.
// @returns (float) The Calmar ratio, or `na` while the drawdown is below 0.01%.
export calmar(float netProfitPct, float maxDrawdownPct) =>
    var int firstTime = time
    float days   = math.max((time - firstTime) / 86400000.0, 1)
    float total  = netProfitPct / 100.0
    float annual = total > -1 ? (math.pow(1 + total, 365.0 / days) - 1) * 100.0 : na
    float ret    = days >= 30 ? annual : netProfitPct
    not na(ret) and maxDrawdownPct >= 0.01 ? ret / maxDrawdownPct : na
 
//#endregion
 
//#region ———————————————————— Table
 
// "✅" when value reaches `pass`, "⚠️" from `warn` (or at / above `suspect`, which is too good to be true), "❌" below
iconAbove(float value, float warn, float pass, float suspect) =>
    na(value) ? "•" : value >= suspect ? "⚠️" : value >= pass ? "✅" : value >= warn ? "⚠️" : "❌"
 
// "✅" at or below `pass`, "⚠️" at or below `warn`, "❌" above
iconBelow(float value, float pass, float warn) =>
    na(value) ? "•" : value <= pass ? "✅" : value <= warn ? "⚠️" : "❌"
 
num(float v, string fmt) => na(v) ? "NA" : str.tostring(v, fmt)
 
row(table t, ui.Theme th, int r, string name, string value, string icon, color bg) =>
    color iconCol = icon == "✅" ? th.up : icon == "⚠️" ? th.warn : icon == "❌" ? th.down : th.neutral
    t.cell(0, r, name, text_color = th.neutral, text_size = th.textSize, bgcolor = bg)
    t.cell(1, r, value, text_color = th.neutral, text_size = th.textSize, bgcolor = bg)
    t.cell(2, r, icon, text_color = iconCol, text_size = th.textSize, bgcolor = bg)
 
// @function Draws the scorecard into a table of 3 columns and 17 rows (create it with `UIKit.newTable()`). Call it on
//           the last bar.
// @param t (table) The table.
// @param th (UIKit.Theme) Colours and text size.
// @param s (Stats) The strategy's built-in figures.
// @param tt (TradeTotals) Totals over the closed trades.
// @param sharpe (series float) From `dailySharpe()`.
// @param calmarRatio (series float) From `calmar()`.
// @param currency (series string) Currency prefix, e.g. "₹" or "$".
// @param capitalStep (series float) Rounding step of the capital-per-trade figure, e.g. 1000.
// @param sizeText (series string) Trade size description, e.g. "1 lot(s) / 65 units".
// @param showCommission (series bool) Show the commission impact row's figures.
// @param walkForward (series bool) Show the walk-forward efficiency row's figure.
// @returns (void)
export render(table t, ui.Theme th, Stats s, TradeTotals tt, float sharpe, float calmarRatio, string currency, float capitalStep, string sizeText, bool showCommission, bool walkForward) =>
    int   n          = tt.trades
    float lossAbs    = math.abs(s.grossLoss)
    float avgWin     = s.wins > 0 ? s.avgWin : na
    float avgLoss    = s.losses > 0 ? math.abs(s.avgLoss) : na
    float winRate    = n > 0 ? s.wins * 100.0 / n : na
    float pf         = lossAbs > 0 ? s.grossProfit / lossAbs : s.grossProfit > 0 ? 999.0 : na
    float rrr        = avgLoss > 0 ? avgWin / avgLoss : na
    float expectancy = n > 0 ? s.avgTrade : na
    float duration   = n > 0 ? tt.minutes / n : na
    float capital    = n > 0 ? tt.capital / n : na
    float preCost    = s.netProfit + tt.commission
    float commImpact = showCommission and preCost != 0 ? -tt.commission / math.abs(preCost) * 100.0 : na
    float wfe        = walkForward and tt.inSample != 0 ? tt.outSample / math.abs(tt.inSample) : na
    float recovery   = s.maxDrawdown > 0 ? s.netProfit / s.maxDrawdown : na
    t.cell(0, 0, "═══ STRATEGY SCORECARD ═══", text_color = th.warn, text_size = th.textSize, text_formatting = text.format_bold, bgcolor = th.footerBg)
    t.cell(1, 0, "", bgcolor = th.footerBg)
    t.cell(2, 0, "", bgcolor = th.footerBg)
    row(t, th, 1,  "Total P&L",          (na(s.netProfit) ? "NA" : currency + str.tostring(s.netProfit, "0.00")) + " / " + num(s.netProfitPct, "0.00") + "%", iconAbove(s.netProfit, 0.0, 1.0, 1e10), th.bodyBg)
    row(t, th, 2,  "Profit Factor",      num(pf, "0.00"), iconAbove(pf, 1.0, 1.5, 3.0), th.bodyBg)
    row(t, th, 3,  "Expectancy/trade",   na(expectancy) ? "NA" : currency + str.tostring(expectancy, "0.00"), iconAbove(expectancy, 0.0, 1.0, 1e10), th.bodyBg)
    row(t, th, 4,  "Win Rate",           na(winRate) ? "NA" : str.tostring(winRate, "0.00") + "%", iconAbove(winRate, 45.0, 55.0, 100.0), th.bodyBg)
    row(t, th, 5,  "Avg RRR",            na(rrr) ? "NA" : str.tostring(rrr, "0.00") + ":1", iconAbove(rrr, 1.5, 1.8, 10.0), th.bodyBg)
    row(t, th, 6,  "Max Drawdown",       na(s.maxDrawdown) ? "NA" : currency + str.tostring(s.maxDrawdown, "0.00"), iconBelow(s.maxDrawdownPct, 20.0, 30.0), th.bodyBg)
    row(t, th, 7,  "Max Losing Streak",  str.tostring(tt.maxLosingStreak) + " trades", iconBelow(tt.maxLosingStreak, 4.0, 6.0), th.bodyBg)
    row(t, th, 8,  "Sharpe Ratio",       num(sharpe, "0.00"), iconAbove(sharpe, 1.0, 2.0, 10.0), th.bodyBg)
    row(t, th, 9,  "Calmar Ratio",       num(calmarRatio, "0.00"), iconAbove(calmarRatio, 1.0, 2.0, 10.0), th.bodyBg)
    row(t, th, 10, "Recovery Factor",    num(recovery, "0.00"), iconAbove(recovery, 1.5, 3.0, 10.0), th.bodyBg)
    row(t, th, 11, "Total Trades",       str.tostring(n), iconAbove(n, 100.0, 200.0, 100000.0), th.bodyBg)
    row(t, th, 12, "Trade Size",         sizeText, sizeText != "" ? "✅" : "•", th.bodyBg)
    row(t, th, 13, "Avg Capital Req.",   na(capital) ? "NA" : currency + str.tostring(capitalStep * math.round(capital / capitalStep), "0"), capital > 0 ? "✅" : "•", th.bodyBg)
    row(t, th, 14, "Avg Trade Duration", na(duration) ? "NA" : str.tostring(duration, "0.00") + " min", duration > 0 ? "✅" : "•", th.bodyBg)
    row(t, th, 15, "Commission Impact",  showCommission ? (na(commImpact) ? "NA" : str.tostring(commImpact, "0.00") + "%") + " / " + (n > 0 ? currency + str.tostring(tt.commission / n, "0.00") : "NA") + "/trade" : "Disabled", iconBelow(math.abs(commImpact), 10.0, 20.0), th.bodyBg)
    row(t, th, 16, "Walk-Forward Eff.",  walkForward ? num(wfe, "0.00") : "Disabled", walkForward ? iconAbove(wfe, 0.3, 0.5, 10.0) : "•", th.headerBg)
 
//#endregion
 
//#region ———————————————————— Demo
 
// Libraries cannot place orders, so this demo tracks a long-only 10/30 SMA crossover by hand (1 unit, 2 commission
// per trade) and fills Stats the way a strategy would from its strategy.* figures
float demoFast = ta.sma(close, 10)
float demoSlow = ta.sma(close, 30)
var Stats       demoStats  = Stats.new(0, 0, 0, 0, 0, 0, na, na, na, 0, 0)
var TradeTotals demoTotals = TradeTotals.new()
var float demoEntry     = na
var int   demoEntryTime = na
var float demoPeak      = 100000.0
var int   demoStart     = time
int demoSplit = demoStart + int((last_bar_time - demoStart) / 2)
if na(demoEntry) and ta.crossover(demoFast, demoSlow)
    demoEntry     := close
    demoEntryTime := time
else if not na(demoEntry) and ta.crossunder(demoFast, demoSlow)
    float pnl = close - demoEntry - 2
    demoTotals.addTrade(pnl, 2, demoEntry, 1, demoEntryTime, time, demoSplit)
    demoStats.netProfit    += pnl
    demoStats.netProfitPct := demoStats.netProfit / 1000
    demoStats.grossProfit  += math.max(pnl, 0)
    demoStats.grossLoss    += math.max(-pnl, 0)
    demoStats.wins         += pnl > 0 ? 1 : 0
    demoStats.losses       += pnl < 0 ? 1 : 0
    demoStats.avgWin       := demoStats.wins > 0 ? demoStats.grossProfit / demoStats.wins : na
    demoStats.avgLoss      := demoStats.losses > 0 ? demoStats.grossLoss / demoStats.losses : na
    demoStats.avgTrade     := demoStats.netProfit / demoTotals.trades
    float equity = 100000 + demoStats.netProfit
    demoPeak                 := math.max(demoPeak, equity)
    demoStats.maxDrawdown    := math.max(demoStats.maxDrawdown, demoPeak - equity)
    demoStats.maxDrawdownPct := math.max(demoStats.maxDrawdownPct, (demoPeak - equity) / demoPeak * 100)
    demoEntry := na
 
// Time-based ratios on every bar, the table on the last
float demoOpenPnl = na(demoEntry) ? 0 : close - demoEntry
float demoSharpe  = dailySharpe(100000 + demoStats.netProfit + demoOpenPnl)
float demoCalmar  = calmar(demoStats.netProfitPct, demoStats.maxDrawdownPct)
var table demoTable = ui.newTable("Bottom Right", 3, 17)
if barstate.islast
    render(demoTable, ui.theme("Auto", "Normal"), demoStats, demoTotals, demoSharpe, demoCalmar, "$", 10, "1 unit", true, true)
 
//#endregion

← 返回列表