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

在R中优化买卖信号:保留首次信号(类Backtrader逻辑)

Optimizing Trading Signals in R (Backtrader-style)

Got it, let's tackle this signal optimization task. The goal is to keep only the first occurrence of each consecutive non-hold signal (1 for sell, 0 for buy) and replace all subsequent duplicates in the same run with -1 (hold). Hold signals (-1) stay as-is even when consecutive.

Step-by-Step Solution

First, let's define our original signal vector:

original_signals <- c(-1, -1, -1, 1, 1, 1, 1, -1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0)

We'll use R's built-in rle() function to identify consecutive runs of the same signal. This function returns two vectors: lengths (how long each run is) and values (the signal value for that run).

Next, we'll loop through each run and build our optimized signal vector:

# Get run-length encoding of the original signals
signal_rle <- rle(original_signals)

# Initialize empty vector for optimized signals
optimized_signals <- c()

# Process each run
for (i in seq_along(signal_rle$values)) {
  current_val <- signal_rle$values[i]
  current_len <- signal_rle$lengths[i]
  
  if (current_val == -1) {
    # Keep all hold signals as-is
    optimized_signals <- c(optimized_signals, rep(current_val, current_len))
  } else {
    # Keep first occurrence of non-hold signal, replace rest with -1
    optimized_signals <- c(optimized_signals, current_val, rep(-1, current_len - 1))
  }
}

Let's Verify the Result

If we print optimized_signals, we'll get exactly the target sequence you specified:

print(optimized_signals)
# Output: -1 -1 -1 1 -1 -1 -1 -1 -1 -1 0 -1 -1 -1 -1 -1 -1 -1

How It Works

  • Run-Length Encoding: rle() breaks down the signal into chunks of consecutive identical values, making it easy to process each group.
  • Hold Signals: Any run of -1 is left unchanged since we want to keep all hold signals.
  • Non-Hold Signals: For runs of 1 (sell) or 0 (buy), we keep the first element as the original signal and replace every other element in the run with -1 (hold), eliminating redundant consecutive signals.

This logic aligns with Backtrader's approach of only acting on the first occurrence of a signal and ignoring subsequent duplicates until the signal changes.

内容的提问来源于stack exchange,提问作者Sarath_Mj

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:35:41