quantstrat技术求助:如何基于多信号创建规则?sigComparision报错
sigComparison Issues Hey Rajat, I’ve dealt with this exact frustration before—trying to stack multiple rules like SMA50 > SMA10 and MACD > 0 using sigComparison often throws errors because that function is designed for single, discrete comparison signals (like crossovers/crossunders), not combining multiple conditional checks. Let’s walk through a cleaner, more reliable approach:
Step 1: Calculate Individual Conditions First
Instead of trying to cram everything into sigComparison calls, break down each rule into a clear boolean variable. This makes debugging way easier:
// Calculate moving averages and their condition sma50 = ta.sma(close, 50) sma10 = ta.sma(close, 10) is_sma_bullish = sma50 > sma10 // True when 50-period SMA is above 10-period // Calculate MACD and its condition [macd_line, signal_line, _] = ta.macd(close, 12, 26, 9) is_macd_positive = macd_line > 0 // True when MACD line is above zero
Step 2: Combine Conditions with Logical Operators
Now you can merge these rules based on your strategy’s needs. Use and if both conditions must be true, or or if either one is enough:
// Example 1: Both conditions need to be true for a bullish signal bullish_signal = is_sma_bullish and is_macd_positive // Example 2: Either condition triggers a signal (adjust based on your strategy) // bullish_signal = is_sma_bullish or is_macd_positive
Step 3: Use Signals (Optional: With sigComparison for Crossovers)
If you specifically need to trigger on crossover events (not just the ongoing condition), you can use ta.crossover (a wrapper for sigComparison) for each rule, then combine those event signals:
// Trigger when SMA50 crosses ABOVE SMA10 sma_crossover = ta.crossover(sma50, sma10) // Trigger when MACD line crosses ABOVE zero macd_crossover = ta.crossover(macd_line, 0) // Combine crossover events (both need to happen around the same time) bullish_crossover_signal = sma_crossover and macd_crossover
Step 4: Visualize or Execute the Signal
To see your signal in action, add a plot shape:
plotshape(bullish_signal, title="Bullish Signal", location=location.belowbar, color=color.new(color.green, 0), style=shape.labelup, text="BUY")
Common Mistakes to Avoid
- Trying to nest
sigComparisoncalls directly: This leads to syntax errors because the function expects specific inputs, not combined conditions. - Forgetting to deconstruct MACD variables: If you skip
[macd_line, signal_line, _], you’ll be comparing the wrong values. - Not accounting for lag: Make sure your indicators are calculated in the right order (no circular references).
This approach is way more flexible than forcing sigComparison to do something it’s not built for—you can easily add more rules (like RSI < 70) by just creating a new boolean variable and adding it to the combined condition.
内容的提问来源于stack exchange,提问作者Rajat

