在R中优化买卖信号:保留首次信号(类Backtrader逻辑)
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
-1is left unchanged since we want to keep all hold signals. - Non-Hold Signals: For runs of
1(sell) or0(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

