self.symbol = symbol
self.price_bucket_count = price_bucket_count
self.profile_period = profile_period
self.volume_threshold = volume_threshold
self.node_distance = node_distance
self.entry_confirmation_bars = entry_confirmation_bars
self.exit_confirmation_bars = exit_confirmation_bars
self.risk_per_trade = risk_per_trade
self.interval = interval
self.max_workers = max_workers
# Create exchange connection pool
self.exchange_pool = [
getattr(ccxt, exchange_id)({
'enableRateLimit': True,
'options': {'defaultType': 'future'}
}) for _ in range(max_workers)
]
self.pool_lock = Lock()
self.pool_index = 0
# Pre-compile Numba functions by running them with dummy data
self._compile_numba_functions()
def _get_exchange(self):
"""Get next available exchange instance from the pool"""
with self.pool_lock:
exchange = self.exchange_pool[self.pool_index]
self.pool_index = (self.pool_index + 1) % len(self.exchange_pool)
return exchange
def _compile_numba_functions(self):
"""Pre-compile Numba functions with dummy data"""
# Use larger dummy dataset for more robust testing
dummy_prices = np.array([100.0, 101.0, 102.0, 103.0, 104.0], dtype=np.float64)
dummy_volumes = np.array([1.0, 2.0, 3.0, 2.0, 1.0], dtype=np.float64)
# Test volume profile calculation
profile, buckets = calculate_volume_profile(dummy_prices, dummy_volumes, 5)
# Test volume nodes identification
_ = identify_volume_nodes(profile, buckets, 0.2, 0.01)
def fetch_raw_data(self, period):
"""Fetch raw OHLCV data and cache it."""
cache_filename = f"raw_ohlcv_{self.symbol}_{self.interval}_{period}.pkl"
if os.path.exists(cache_filename):
print(f"Loading raw data from cache: {cache_filename}")
df = pd.read_pickle(cache_filename)
print(f"Total fetched OHLCV records: {len(df)}")
return df
exchange = self._get_exchange()
end_time = int(time.time() * 1000)
start_time = end_time - (int(period[:-1]) * 24 * 60 * 60 * 1000)
# Fetch historical data
all_ohlcv = []
while start_time < end_time:
print(f"Fetching data from {pd.to_datetime(start_time, unit='ms')}...")
try:
ohlcv = exchange.fetch_ohlcv(
symbol=self.symbol,
timeframe=self.interval,
since=start_time,
limit=1500
)
if not ohlcv:
break
all_ohlcv.extend(ohlcv)
start_time = ohlcv[-1][0] + 1
except Exception as e:
print(f"Error fetching data: {str(e)}")
time.sleep(1)
continue
# Create DataFrame
df = pd.DataFrame(all_ohlcv, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
df.set_index('timestamp', inplace=True)
print(f"Saving raw data to cache: {cache_filename}")
df.to_pickle(cache_filename)
return df
def process_volume_nodes(self, raw_data):
"""Calculate volume nodes based on current strategy parameters."""
df = raw_data.copy()
# Convert relevant columns to NumPy arrays
close_prices = df['close'].values.astype(np.float64)
volumes = df['volume'].values.astype(np.float64)
# Calculate window size based on profile_period and interval
# Assuming profile_period is in days and interval is in minutes
# Adjust this calculation as needed based on the exact format
if self.profile_period.endswith('d') and self.interval.endswith('m'):
days = int(self.profile_period[:-1])
minutes = int(self.interval[:-1])
window_size = days * 24 * 60 // minutes
else:
raise NotImplementedError("Only daily profile_period and minute intervals are implemented.")
n = len(close_prices)
# Initialize fixed-size arrays for volume nodes
max_nodes = self.price_bucket_count # Assuming maximum nodes equal to bucket count
volume_nodes_prices = np.zeros((n, max_nodes), dtype=np.float64)
volume_nodes_volumes = np.zeros((n, max_nodes), dtype=np.float64)
num_volume_nodes = np.zeros(n, dtype=np.int32)
#print(f"Calculating volume profiles for {n} rows with current parameters...")
# Call the Numba-jitted function
process_volume_nodes_numba(
close_prices,
volumes,
window_size,
self.price_bucket_count,
self.volume_threshold,
self.node_distance,
volume_nodes_prices,
volume_nodes_volumes,
num_volume_nodes
)
# Assign results back to the DataFrame
df['volume_nodes_prices'] = list(volume_nodes_prices)
df['volume_nodes_volumes'] = list(volume_nodes_volumes)
df['num_volume_nodes'] = num_volume_nodes
#print(f"Volume nodes calculated and assigned to data.")
return df
def plot_data(self, df):
"""Plots the OHLCV and volume profile data."""
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 6))
# Plot OHLCV
ax1.plot(df.index, df['close'], label='Close Price')
ax1.set_title(f"{self.symbol} Price")
ax1.set_ylabel("Price")
ax1.legend()
# Plot Volume Profile
if 'volume_nodes_prices' in df.columns and 'volume_nodes_volumes' in df.columns:
latest_prices = df['volume_nodes_prices'].iloc[-1]
latest_volumes = df['volume_nodes_volumes'].iloc[-1]
valid = latest_volumes > 0
ax2.barh(latest_prices[valid], latest_volumes[valid], alpha=0.3)
ax2.set_title("Volume Profile")
ax2.set_xlabel("Volume")
ax2.set_ylabel("Price")
plt.tight_layout()
plt.show()
@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:
# Check if there's an open position to exit
if long_entries[i]:
if (i + exit_conf_bars) < n:
exits[i + exit_conf_bars] = True
elif short_entries[i]:
if (i + exit_conf_bars) < n:
exits[i + exit_conf_bars] = True
return long_entries, short_entries, exits
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)
# No need for volume_nodes_volumes in signal generation
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
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 and stop-losses
entry_prices = pd.Series(index=data.index, dtype=float)
entry_prices[signals['long_entries']] = data.loc[signals['long_entries'], 'close']
entry_prices[signals['short_entries']] = data.loc[signals['short_entries'], 'close']
stop_prices = pd.Series(index=data.index, dtype=float)
stop_prices[signals['long_entries']] = entry_prices[signals['long_entries']] * (1 - self.risk_per_trade)
stop_prices[signals['short_entries']] = entry_prices[signals['short_entries']] * (1 + self.risk_per_trade)
# Calculate position size 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'] | signals['short_entries'],
exits=signals['exits'],
short_entries=signals['short_entries'],
sl_stop=stop_prices,
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
def verify_volume_nodes(self, data):
"""Verify that volume nodes are being calculated correctly"""
#print("\nVerifying volume nodes calculation...")
# Check a specific time window
sample_window = data.iloc[-100:] # Last 100 rows
# Calculate volume profile for this window
prices = sample_window['close'].values.astype(np.float64)
volumes = sample_window['volume'].values.astype(np.float64)
profile, buckets = calculate_volume_profile(
prices,
volumes,
self.price_bucket_count
)
nodes = identify_volume_nodes(
profile,
buckets,
self.volume_threshold,
self.node_distance
)
'''
print(f"\nSample window statistics:")
print(f"Price range: {prices.min():.2f} - {prices.max():.2f}")
print(f"Volume range: {volumes.min():.2f} - {volumes.max():.2f}")
print(f"Number of volume nodes found: {len(nodes)}")
if len(nodes) > 0:
print("\nVolume nodes found:")
for node in nodes:
print(f"Price level: {node[0]:.2f}, Relative volume: {node[1]:.4f}")
else:
print("No volume nodes found - this may indicate an issue with the parameters")
'''
# Define parameter grid
param_grid = {
'price_bucket_count': [25],
'volume_threshold': [0.129],
'node_distance': [0.00048],
'entry_confirmation_bars': [5],
'exit_confirmation_bars': [1,2,3,4,5],
'risk_per_trade': [0.01, 0.015, 0.02, 0.025, 0.03]
}
# Optimize parameters
results = optimize_parameters(
strategy=strategy,
param_grid=param_grid,
initial_capital=10000,
fee_rate=0.001,
period='365d'
)
optimize_for = 'Sharpe Ratio'
print("\nTop 50 parameter combinations by Sharpe ratio:")
if optimize_for in results.columns:
pd.set_option('display.max_columns', None)
sorted_results = results.sort_values(optimize_for, ascending=False).head(200)
sorted_results.to_csv('sorted_results.csv', index=False) # Save to CSV without index
print(sorted_results)
else:
print("Profit Factor not found in results.")
optimizing_a = 'risk_per_trade'
optimizing_b = 'exit_confirmation_bars'
# Create the heatmap with corrected scaling
if optimize_for in results.columns:
heatmap_data = results.pivot_table(values=optimize_for, index=optimizing_a, columns=optimizing_b)
heatmap_data_clean = heatmap_data.replace([np.inf, -np.inf], np.nan)
finite_max = heatmap_data_clean.max().max()
finite_min = heatmap_data_clean.min().min()
plt.figure(figsize=(10, 8))
sns.heatmap(heatmap_data, annot=False, cmap='viridis', fmt=".2f",
vmin=finite_min, vmax=finite_max)
plt.title(optimize_for + ' Heatmap')
plt.ylabel(optimizing_a)
plt.xlabel(optimizing_b)
plt.show()
else:
print("No Sharpe Ratio data available for heatmap.")
Hello! It sounds like you're encountering an issue where adjusting the stop-loss parameters in your backtest isn't affecting the outcome as expected. This typically indicates that the stop-loss mechanism isn't being triggered or isn't correctly integrated into the backtest. Let's walk through potential causes and actionable steps to diagnose and resolve this issue.
1. Understanding the Problem
You mentioned that changing the stop-loss parameters (including removing short positions) doesn't alter the heatmap results, suggesting that:
- Stop-loss Orders Aren't Triggering: Trades aren't being closed based on stop-loss levels.
- Parameter Changes Have No Effect: Adjusting stop-loss levels doesn't impact the backtest results.
2. Potential Causes and Solutions
A. Conflict Between exits Signals and sl_stop
Issue: Your strategy defines explicit exits based on confirmation bars, which might be prematurely closing positions before the stop-loss has a chance to trigger.
Solution:
-
Remove or Modify exits Signals: To isolate the stop-loss behavior, temporarily remove the exits signals and observe if the stop-loss starts triggering.
How to Do It:
# In the backtest method, comment out the 'exits' parameter
portfolio = vbt.Portfolio.from_signals(
close=data['close'],
entries=signals['long_entries'] | signals['short_entries'],
exits=None, # Remove exits to test stop-loss
short_entries=signals['short_entries'],
sl_stop=stop_prices,
init_cash=initial_capital,
fees=fee_rate,
size=size,
freq=self.interval
)
- Analyze the Results: If the heatmap starts showing changes when you adjust
risk_per_trade, it indicates that the explicit exits were overshadowing the stop-loss mechanism.
-
Alternative Approach: Instead of using both exits signals and sl_stop, you can rely solely on sl_stop for exiting positions. This ensures that positions are closed only when the stop-loss condition is met.
B. Verification of sl_stop Alignment and Values
Issue: The stop-loss prices might not be correctly aligned with the entry points or might not be set accurately.
Solution:
-
Ensure Correct Calculation of stop_prices:
- Verify that
stop_prices are only set at entry points and are correctly calculated based on risk_per_trade.
How to Do It:
print("Stop Prices Example:")
print(stop_prices.dropna().head())
- Expected Output: This should show stop-loss prices at the entry points. Ensure that these values make sense relative to the
close prices.
-
Check for NaNs and Inappropriate Values:
- Ensure that
stop_prices contain NaN for non-entry points and valid stop-loss prices at entries.
- Use visualization to plot
close prices alongside stop_prices to confirm:
How to Do It:
import matplotlib.pyplot as plt
plt.figure(figsize=(14, 7))
plt.plot(data.index, data['close'], label='Close Price')
plt.plot(data.index, stop_prices, 'r.', label='Stop Loss')
plt.legend()
plt.show()
- Interpretation: You should see red dots (stop-loss levels) at points where positions are entered.
C. Ensuring sl_stop is Properly Integrated with vectorbt
Issue: Misalignment or incorrect usage of sl_stop with vectorbt.Portfolio.from_signals.
Solution:
-
Refer to vectorbt Documentation: Ensure that sl_stop is being used as intended. According to the vectorbt documentation, sl_stop should be an absolute price level at which to trigger the stop-loss.
-
Use sl_trigger for Clarity:
- Sometimes, explicitly defining the trigger might help. For example, setting a stop-loss based on percentage moves:
How to Do It:
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=stop_prices,
sl_trigger=signals['long_entries'] | signals['short_entries'], # Ensure stop-loss is triggered based on entries
init_cash=initial_capital,
fees=fee_rate,
size=size,
freq=self.interval
)
- Explanation: By setting
sl_trigger, you ensure that stop-loss is only considered when positions are entered.
D. Debugging and Logging
Issue: Lack of visibility into whether stop-loss conditions are being met during backtests.
Solution:
-
Enable Detailed Logging:
- Modify the
backtest method to log instances when stop-losses are hit. This can help verify if stop-losses are being evaluated.
How to Do It:
def backtest(self, data, initial_capital, fee_rate):
# ... existing code ...
try:
portfolio = vbt.Portfolio.from_signals(
# ... parameters ...
)
trades = portfolio.trades.records
# Log trades to see if stop-losses are present
print(f"Total Trades: {len(trades)}")
if len(trades) > 0:
print("Sample Trades:")
print(trades.head())
# ... existing metrics ...
return metrics, portfolio, data
except Exception as e:
print(f"\nError in vectorbt processing: {str(e)}")
raise
- Analyze the Output: Check if trades include those closed by stop-loss. The
trades.type column can be inspected to see if they were closed by stop-loss or by exits signals.
-
Visual Inspection:
- Plot the portfolio's equity curve and mark stop-loss events.
How to Do It:
portfolio.plot().show()
- Interpretation: Look for sudden drops in equity corresponding to stop-loss triggers.
E. Parameter Scaling and Sensitivity
Issue: The risk_per_trade might be set at a level that makes stop-losses too tight or too loose, effectively rendering them non-impactful.
Solution:
-
Test Extreme Values:
-
Adjust node_distance:
- Ensure that
node_distance is set appropriately, as it's used in signal generation which could influence when positions are entered and thus when stop-losses are applied.
F. Ensure Proper Precompilation with Numba
Issue: If Numba functions (especially generate_signals_numba) aren't correctly compiled or have silent failures, stop-loss signals might not be generated as intended.
Solution:
3. Step-by-Step Action Plan
-
Isolate the Stop-Loss Mechanism:
- Remove or Disable
exits Signals: Comment out the exits parameter in the Portfolio.from_signals method.
- Run the Backtest: Observe if adjusting
risk_per_trade now affects the results.
-
Verify stop_prices:
- Print or Plot Stop-Loss Levels: Ensure they are set at reasonable levels relative to
close prices.
- Check Alignment: Ensure that
stop_prices are only set at entry points and are NaN elsewhere.
-
Enable Detailed Logging:
- Print Trade Records: Check if some trades are being exited due to stop-loss.
- Plot Equity Curve: Visually inspect if there are drops corresponding to stop-loss triggers.
-
Test Parameter Sensitivity:
- Use Extreme
risk_per_trade Values: To see if there's any effect on the backtest performance.
- Adjust
node_distance as Needed: Ensure it's not preventing entries that could trigger stop-loss.
-
Ensure Proper Numba Compilation:
- Temporarily Remove
@njit: Add print statements or use Python loops to ensure that signal generation works as expected.
-
Consult Vectorbt Documentation and Examples:
- Review Usage Patterns: Ensure that
sl_stop is being used in alignment with how it's intended in vectorbt.
- Explore Sample Implementations: Compare with
vectorbt examples to spot discrepancies.
4. Additional Recommendations
-
Simplify for Debugging: Start with a minimal version of your strategy where you only focus on entries and stop-loss without additional complexities like volume nodes. Once confirmed to work, gradually reintroduce other components.
-
Visualize Trades and Stop-Losses:
- Overlay trades and their corresponding stop-loss levels on price charts using
matplotlib to visually verify if stop-losses are being hit.
-
Check for Data Issues:
- Ensure there are no missing or malformed data points that might interfere with signal generation or stop-loss evaluation.
5. Example Modification to Remove exits
Here's how you can adjust the backtest method to remove exits for testing purposes:
def backtest(self, data, initial_capital, fee_rate):
"""Run backtest using vectorbt with additional debugging"""
# ... existing code ...
try:
portfolio = vbt.Portfolio.from_signals(
close=data['close'],
entries=signals['long_entries'] | signals['short_entries'],
exits=None, # Remove exits to focus on stop-loss
short_entries=signals['short_entries'],
sl_stop=stop_prices,
init_cash=initial_capital,
fees=fee_rate,
size=size,
freq=self.interval
)
trades = portfolio.trades.records
# Log trades to see if stop-losses are present
print(f"Total Trades: {len(trades)}")
if len(trades) > 0:
print("Sample Trades:")
print(trades.head())
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
6. Conclusion
By systematically isolating and testing components of your strategy, especially the interaction between explicit exits and sl_stop, you can identify where the issue lies. Removing exits is a crucial step to ensure that stop-losses are the primary mechanism for exiting positions. Additionally, thorough verification of stop_prices and leveraging detailed logging will provide insights into whether stop-losses are functioning as intended.
If after these steps the issue persists, consider creating a minimal reproducible example and consulting the Vectorbt Community or their documentation for more targeted assistance.
Feel free to share further observations or outputs from these debugging steps, and I can help you delve deeper into the issue!