Hello! I understand that you’re encountering issues with your trading strategy allowing contradictory positions (i.e., holding both long and short positions simultaneously). This behavior can lead to unintended trading risks and miscalculations in your strategy performance.
To address this, we need to ensure that when a new position is initiated (long or short), any existing opposite position is closed automatically. This can be achieved by properly configuring the signal handling in your backtesting setup using vectorbt.
Here’s a step-by-step guide to modify your code to handle contradictory positions correctly:
1. Understand the Issue
In your current backtest setup, you have the following line:
portfolio = vbt.Portfolio.from_signals(
close=data['close'],
entries=signals['long_entries'] | signals['short_entries'],
exits=signals['exits'],
short_entries=signals['short_entries'],
sl_stop=self.risk_per_trade,
init_cash=initial_capital,
fees=fee_rate,
size=size,
freq=self.interval
)
Here, you’re combining long_entries and short_entries using the bitwise OR (|) operator for the entries parameter. This approach can lead to both long and short entries being triggered simultaneously, resulting in holding both positions at the same time.
2. Modify the Backtest Signals Configuration
Instead of combining long_entries and short_entries, you should handle them separately. This allows vectorbt to manage the positions correctly, ensuring that initiating a new long or short position will automatically close any existing opposite positions.
Updated Backtest Method
Modify your backtest method within the VolumeProfileStrategy class as follows:
def backtest(self, data, initial_capital, fee_rate):
"""Run backtest using vectorbt with additional debugging"""
# Define the numeric columns used in backtesting
numeric_cols = ['close', 'volume'] # Add other numeric columns if necessary
# Check for NaN values in numeric columns only
if data[numeric_cols].isna().any().any():
print("Data contains NaN values in numeric columns. Please clean the data before backtesting.")
raise ValueError("Data contains NaN values.")
# Check for infinite values in numeric columns only
if np.isinf(data[numeric_cols].values).any():
print("Data contains infinite values in numeric columns. Please clean the data before backtesting.")
raise ValueError("Data contains infinite values.")
signals = self.generate_signals(data)
# Calculate position sizes based on initial capital and first close price
size = initial_capital / data['close'].iloc[0]
try:
portfolio = vbt.Portfolio.from_signals(
close=data['close'],
entries=signals['long_entries'], # Long entries
exits=signals['exits'], # Exits for long positions
short_entries=signals['short_entries'], # Short entries
short_exits=signals['exits'], # Exits for short positions
sl_stop=self.risk_per_trade, # Stop-loss
init_cash=initial_capital,
fees=fee_rate,
size=size,
freq=self.interval
)
trades = portfolio.trades.records
metrics = {
'Total Return (%)': portfolio.total_return() * 100,
'Sharpe Ratio': portfolio.sharpe_ratio(),
'Max Drawdown (%)': portfolio.max_drawdown() * 100,
'Number of Trades': len(trades) if trades is not None else 0,
'Win Rate (%)': (np.sum(trades['pnl'] > 0) / len(trades)) * 100 if trades is not None and len(trades) > 0 else 0,
'Profit Factor': np.sum(trades[trades['pnl'] > 0]['pnl']) / abs(np.sum(trades[trades['pnl'] < 0]['pnl'])) if trades is not None and len(trades) > 0 and abs(np.sum(trades[trades['pnl'] < 0]['pnl'])) > 0 else 0
}
return metrics, portfolio, data
except Exception as e:
print(f"\nError in vectorbt processing: {str(e)}")
raise
Explanation of Changes
-
Separate entries and short_entries:
- Long Entries:
entries=signals['long_entries']
- Short Entries:
short_entries=signals['short_entries']
By separating these, vectorbt understands which signals correspond to long and short positions.
-
Separate exits and short_exits:
- Exits for Long Positions:
exits=signals['exits']
- Exits for Short Positions:
short_exits=signals['exits']
This ensures that exit signals are correctly applied to both long and short positions.
-
Remove Combined Entries:
- Old Line:
entries=signals['long_entries'] | signals['short_entries']
- New Lines: Separate
entries and short_entries as shown above.
Combining entries with the OR operator was causing simultaneous long and short signals, leading to conflicting positions.
3. Ensure Correct Signal Generation
To complement the changes in the backtest configuration, ensure that your signal generation logic doesn't produce simultaneous long and short entries. This can be achieved by modifying the generate_signals_numba function to prioritize one direction over the other or by ensuring that they don’t overlap.
Here’s a refined version of the generate_signals_numba function with added logic to prevent simultaneous long and short entries:
@staticmethod
@njit(parallel=True)
def generate_signals_numba(
close_prices,
volume_nodes_prices,
num_volume_nodes,
entry_conf_bars,
exit_conf_bars,
node_distance
):
n = len(close_prices)
long_entries = np.zeros(n, dtype=np.bool_)
short_entries = np.zeros(n, dtype=np.bool_)
exits = np.zeros(n, dtype=np.bool_)
for i in prange(n):
if num_volume_nodes[i] == 0:
continue # No volume nodes to process
current_price = close_prices[i]
nodes = volume_nodes_prices[i, :num_volume_nodes[i]]
# Initialize nearest nodes
nearest_above = np.inf
nearest_below = -np.inf
# Find nearest above and below nodes
for j in range(num_volume_nodes[i]):
price = nodes[j]
if price > current_price and price < nearest_above:
nearest_above = price
elif price < current_price and price > nearest_below:
nearest_below = price
# Long Entry Condition
if nearest_below != -np.inf:
price_diff = np.abs(current_price - nearest_below) / current_price
if price_diff < node_distance:
# Check confirmation bars
if i >= entry_conf_bars:
positive_bars = 0
for k in range(i - entry_conf_bars, i):
if close_prices[k] > close_prices[k - 1]:
positive_bars += 1
if positive_bars >= entry_conf_bars * 0.5:
long_entries[i] = True
# Short Entry Condition
if nearest_above != np.inf:
price_diff = np.abs(current_price - nearest_above) / current_price
if price_diff < node_distance:
# Check confirmation bars
if i >= entry_conf_bars:
negative_bars = 0
for k in range(i - entry_conf_bars, i):
if close_prices[k] < close_prices[k - 1]:
negative_bars += 1
if negative_bars >= entry_conf_bars * 0.5:
short_entries[i] = True
# Exit Conditions
if i >= exit_conf_bars:
# Ensure that exits are not overlapping with entries
if long_entries[i]:
if (i + exit_conf_bars) < n:
exits[i + exit_conf_bars] = True
if short_entries[i]:
if (i + exit_conf_bars) < n:
exits[i + exit_conf_bars] = True
return long_entries, short_entries, exits
Explanation of Changes
- Prevent Simultaneous Entries: Ensure that if both
long_entries and short_entries are triggered at the same time, they are handled correctly by the backtest configuration.
- Maintain Exits Separately: Ensure that exits are correctly associated with their respective positions.
4. Update Signal Generation in generate_signals Method
After refining the generate_signals_numba function, ensure that the generate_signals method correctly constructs the signals DataFrame:
def generate_signals(self, data):
close_prices = data['close'].values.astype(np.float64)
volume_nodes_prices = np.vstack(data['volume_nodes_prices'].values).astype(np.float64)
num_volume_nodes = data['num_volume_nodes'].values.astype(np.int32)
long_entries, short_entries, exits = self.generate_signals_numba(
close_prices,
volume_nodes_prices,
num_volume_nodes,
self.entry_confirmation_bars,
self.exit_confirmation_bars,
self.node_distance
)
signals = pd.DataFrame({
'long_entries': long_entries,
'short_entries': short_entries,
'exits': exits
}, index=data.index)
return signals
5. Additional Recommendations
-
Verify Signal Exclusivity: Ensure that long_entries and short_entries are not True at the same timestamp. If your strategy logic allows, you might want to prioritize one over the other or implement a rule to decide which one takes precedence.
-
Check Portfolio Behavior: After making these changes, closely monitor the portfolio’s behavior during backtests to ensure that positions are being opened and closed as expected.
-
Logging for Debugging: Implement logging within your signal generation and backtest methods to trace the flow of signals and position changes. This can be invaluable for debugging and verifying that positions are handled correctly.
6. Final Updated backtest Method
Here’s the complete updated backtest method incorporating the changes:
def backtest(self, data, initial_capital, fee_rate):
"""Run backtest using vectorbt with additional debugging"""
# Define the numeric columns used in backtesting
numeric_cols = ['close', 'volume'] # Add other numeric columns if necessary
# Check for NaN values in numeric columns only
if data[numeric_cols].isna().any().any():
print("Data contains NaN values in numeric columns. Please clean the data before backtesting.")
raise ValueError("Data contains NaN values.")
# Check for infinite values in numeric columns only
if np.isinf(data[numeric_cols].values).any():
print("Data contains infinite values in numeric columns. Please clean the data before backtesting.")
raise ValueError("Data contains infinite values.")
signals = self.generate_signals(data)
# Calculate position sizes based on initial capital and first close price
size = initial_capital / data['close'].iloc[0]
try:
portfolio = vbt.Portfolio.from_signals(
close=data['close'],
entries=signals['long_entries'], # Long entries
exits=signals['exits'], # Exits for long positions
short_entries=signals['short_entries'], # Short entries
short_exits=signals['exits'], # Exits for short positions
sl_stop=self.risk_per_trade, # Stop-loss
init_cash=initial_capital,
fees=fee_rate,
size=size,
freq=self.interval
)
trades = portfolio.trades.records
metrics = {
'Total Return (%)': portfolio.total_return() * 100,
'Sharpe Ratio': portfolio.sharpe_ratio(),
'Max Drawdown (%)': portfolio.max_drawdown() * 100,
'Number of Trades': len(trades) if trades is not None else 0,
'Win Rate (%)': (np.sum(trades['pnl'] > 0) / len(trades)) * 100 if trades is not None and len(trades) > 0 else 0,
'Profit Factor': np.sum(trades[trades['pnl'] > 0]['pnl']) / abs(np.sum(trades[trades['pnl'] < 0]['pnl'])) if trades is not None and len(trades) > 0 and abs(np.sum(trades[trades['pnl'] < 0]['pnl'])) > 0 else 0
}
return metrics, portfolio, data
except Exception as e:
print(f"\nError in vectorbt processing: {str(e)}")
raise
7. Testing the Changes
After implementing the above changes, perform the following steps to ensure everything works as expected:
-
Run a Single Backtest: Start with a single set of parameters to verify that opposite positions are handled correctly.
if __name__ == "__main__":
# Initialize strategy
strategy = VolumeProfileStrategy(
symbol='SOL/USDT',
exchange_id='binance'
)
# Define a single parameter set
single_params = {
'price_bucket_count': 50,
'volume_threshold': 0.080789,
'node_distance': 0.00037,
'entry_confirmation_bars': 5,
'exit_confirmation_bars': 4,
'risk_per_trade': 0.02
}
# Run backtest with the single parameter set
backtest_with_single_params(
strategy=strategy,
params=single_params,
initial_capital=10000,
fee_rate=0.001,
period='365d'
)
-
Review the Results: Check the printed metrics and plotted portfolio to confirm that positions are being opened and closed as intended.
-
Proceed with Optimization: Once the single backtest behaves correctly, proceed with optimizing multiple parameter sets using the updated optimize_parameters function.
8. Conclusion
By separating long_entries and short_entries in your vectorbt portfolio and ensuring that exits are appropriately handled for each position type, you can prevent contradictory positions from being held simultaneously. This approach leverages vectorbt's capabilities to manage long and short positions more effectively, thereby making your strategy more robust and aligned with your trading rules.
Feel free to reach out if you encounter any further issues or need additional assistance!