You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pine Script策略中获取Avg # bars in trades变量并计算CAGR?

问题解答

1. 关于获取“Avg # bars in trades”作为变量

TradingView策略概览中的“Avg # bars in trades”是平台后台计算的统计值,Pine Script没有直接提供内置变量来读取这个值。但你可以在脚本中自行计算该指标,实现方式如下:

  • 跟踪每笔交易的持仓K线数量:开仓时记录当前K线索引,平仓时计算当前索引与开仓索引的差值,得到单交易持仓K线数
  • 维护累计的总持仓K线数和交易次数,每次平仓后更新这两个值,最终通过总持仓K线数 / 交易次数得到平均持仓K线数

示例代码片段:

//@version=5
strategy("自定义平均持仓K线数", overlay=true)

var float total_bars_in_trades = 0.0
var int trade_count = 0
var int entry_bar_index = na

// 开仓逻辑示例
if strategy.position_size == 0
    strategy.entry("Long", strategy.long)
    entry_bar_index = bar_index

// 平仓逻辑示例
if strategy.position_size > 0 and close > open
    strategy.close("Long")
    // 计算当前交易持仓K线数
    bars_in_trade = bar_index - entry_bar_index
    total_bars_in_trades += bars_in_trade
    trade_count += 1

// 计算平均持仓K线数
avg_bars_in_trades = trade_count > 0 ? total_bars_in_trades / trade_count : na
plot(avg_bars_in_trades, title="Avg Bars in Trades", color=color.blue)

2. 在策略概览中显示CAGR

TradingView默认策略概览确实没有CAGR统计项,你可以通过自定义统计指标实现,步骤如下:

  1. 计算策略的初始权益、最终权益,以及回测周期对应的年数
  2. 使用strategy.custom()函数将计算出的CAGR添加到策略概览的自定义统计区域

示例代码片段:

//@version=5
strategy("带CAGR的策略", overlay=true, initial_capital=10000)

// 计算回测周期的年数
var float start_year = na
if bar_index == 0
    start_year = year + (month - 1)/12 + (dayofmonth - 1)/365.25
current_year = year + (month - 1)/12 + (dayofmonth - 1)/365.25
years_passed = current_year - start_year

// 计算CAGR
final_equity = strategy.equity
initial_equity = strategy.initial_capital
cagr = years_passed > 0 ? pow(final_equity / initial_equity, 1 / years_passed) - 1 : na

// 将CAGR添加到策略概览
strategy.custom("CAGR", cagr, display=true, format=format.percent, precision=2)

这段代码会在策略概览的「Custom Statistics」区域显示计算后的CAGR值,格式为百分比,保留两位小数。

内容的提问来源于stack exchange,提问作者coder-ant

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 16:26:26