### Complete RaptorBT Backtest Configuration Example Source: https://github.com/alphabench/raptorbt/blob/main/_autodocs/errors-and-configuration.md Demonstrates loading data, generating signals, setting global and per-instrument configurations (including stops and targets), and running a single backtest. This example covers typical parameters for equity trading. ```python import raptorbt import numpy as np # Data loading df = pd.read_csv("data.csv", index_col=0, parse_dates=True) timestamps = df.index.astype("int64").values ohlcv = {k: df[k].values for k in ["open", "high", "low", "close", "volume"]} # Signals sma_fast = df["close"].rolling(10).mean() sma_slow = df["close"].rolling(50).mean() entries = (sma_fast > sma_slow) & (sma_fast.shift(1) <= sma_slow.shift(1)) exits = (sma_fast < sma_slow) & (sma_fast.shift(1) >= sma_slow.shift(1)) # Global config config = raptorbt.PyBacktestConfig( initial_capital=100000.0, fees=0.001, # 0.1% per trade (NSE equity typical) slippage=0.0005, # 0.05% slippage upon_bar_close=True, ) config.set_fixed_stop(0.02) # 2% stop-loss config.set_fixed_target(0.05) # 5% take-profit # Per-instrument config (if using basket) inst_config = raptorbt.PyInstrumentConfig( lot_size=1.0, # No rounding (equity) alloted_capital=50000.0, # Cap at 50K ) inst_config.set_fixed_stop(0.025) # Override to 2.5% for this instrument # Run backtest result = raptorbt.run_single_backtest( timestamps=timestamps, open=ohlcv["open"], high=ohlcv["high"], low=ohlcv["low"], close=ohlcv["close"], volume=ohlcv["volume"], entries=entries.values, exits=exits.values, direction=1, weight=1.0, symbol="INFY", config=config, instrument_config=inst_config, ) # Results print(f"Return: {result.metrics.total_return_pct:.2f}%") print(f"Sharpe: {result.metrics.sharpe_ratio:.2f}") print(f"Max DD: {result.metrics.max_drawdown_pct:.2f}%") print(f"Trades: {result.metrics.total_trades}") print(f"Win Rate: {result.metrics.win_rate_pct:.1f}%") ``` -------------------------------- ### Example Usage of run_basket_backtest Source: https://github.com/alphabench/raptorbt/blob/main/_autodocs/api-reference/backtest-functions.md Demonstrates how to set up instruments, optional per-instrument configurations, and a general backtest configuration to run a basket backtest. This example uses 'majority' sync mode, entering when at least two out of three instruments signal. ```python # Three instruments in equal weight basket instruments = [ (ts, open1, high1, low1, close1, vol1, entries1, exits1, 1, 0.33, "AAPL"), (ts, open2, high2, low2, close2, vol2, entries2, exits2, 1, 0.33, "GOOGL"), (ts, open3, high3, low3, close3, vol3, entries3, exits3, 1, 0.34, "MSFT"), ] # Optional per-instrument configs inst_configs = { "AAPL": raptorbt.PyInstrumentConfig(lot_size=1.0, alloted_capital=33000), "GOOGL": raptorbt.PyInstrumentConfig(lot_size=1.0, alloted_capital=33000), "MSFT": raptorbt.PyInstrumentConfig(lot_size=1.0, alloted_capital=34000), } config = raptorbt.PyBacktestConfig(initial_capital=100000, fees=0.001) result = raptorbt.run_basket_backtest( instruments=instruments, config=config, sync_mode="majority", # Enter when 2+ of 3 signal instrument_configs=inst_configs, ) ``` -------------------------------- ### Example: Accessing Equity Curve Source: https://github.com/alphabench/raptorbt/blob/main/_autodocs/api-reference/configuration-classes.md Demonstrates how to run a backtest and access the equity curve to print starting and final capital. ```python result = raptorbt.run_single_backtest(...) equity = result.equity_curve() print(f"Starting capital: {equity[0]:.2f}") print(f"Final capital: {equity[-1]:.2f}") ``` -------------------------------- ### Install RaptorBT with Pip Source: https://github.com/alphabench/raptorbt/blob/main/_autodocs/quickstart-and-imports.md Install the raptorbt library using pip. If installing from source, navigate to the project directory and use pip install -e . ```bash pip install raptorbt # Or from source: cd raptorbt pip install -e . ``` -------------------------------- ### Example Usage of PyInstrumentConfig Source: https://github.com/alphabench/raptorbt/blob/main/_autodocs/api-reference/configuration-classes.md Demonstrates creating instrument-specific configurations for lot rounding, capital capping, and setting stop losses, then using them in a backtest. ```python # Per-instrument config with lot rounding and capital cap aapl_config = raptorbt.PyInstrumentConfig( lot_size=1.0, alloted_capital=30000.0, ) aapl_config.set_fixed_stop(0.025) # 2.5% stop override for AAPL nifty_config = raptorbt.PyInstrumentConfig( lot_size=50.0, # NIFTY lot size alloted_capital=50000.0, ) # Use in basket backtest result = raptorbt.run_basket_backtest( instruments=[...], instrument_configs={ "AAPL": aapl_config, "NIFTY": nifty_config, }, ) ``` -------------------------------- ### Example: Accessing All Backtest Data Source: https://github.com/alphabench/raptorbt/blob/main/_autodocs/api-reference/configuration-classes.md Shows how to retrieve and print key backtest results including equity, drawdown, returns, and individual trade details. ```python result = raptorbt.run_single_backtest(...) equity = result.equity_curve() drawdown = result.drawdown_curve() rets = result.returns() trades = result.trades() print(f"Final equity: {equity[-1]:.2f}") print(f"Max drawdown: {drawdown.min():.2f}") print(f"Num trades: {len(trades)}") for trade in trades: print(f" {trade.symbol} {trade.entry_idx}->{trade.exit_idx}: " f"{trade.pnl:.2f} ({trade.return_pct:.2f}%)") ``` -------------------------------- ### Minimal Backtest Example Source: https://github.com/alphabench/raptorbt/blob/main/_autodocs/quickstart-and-imports.md Run a basic backtest with randomly generated data to quickly see RaptorBT in action. Requires numpy and raptorbt. ```python import numpy as np import raptorbt # Generate sample data (random walk) np.random.seed(42) n = 500 close = np.cumprod(1 + np.random.randn(n) * 0.02) * 100 timestamps = np.arange(n, dtype=np.int64) open = high = low = close volume = np.ones(n) # Simple signals: buy every 20 bars, hold for 10 entries = np.zeros(n, dtype=bool) exits = np.zeros(n, dtype=bool) entries[::20] = True exits[10::20] = True # Backtest config = raptorbt.PyBacktestConfig(initial_capital=100000, fees=0.001) result = raptorbt.run_single_backtest( timestamps, open, high, low, close, volume, entries, exits, 1, 1.0, "TEST", config, ) # Results print(f"Return: {result.metrics.total_return_pct:.2f}%") print(f"Sharpe: {result.metrics.sharpe_ratio:.2f}") print(f"Max DD: {result.metrics.max_drawdown_pct:.2f}%") print(f"Trades: {result.metrics.total_trades}") ``` -------------------------------- ### Install RaptorBT Source: https://github.com/alphabench/raptorbt/blob/main/_autodocs/quickstart-and-imports.md Install the raptorbt package using pip. Ensure you have Python 3.10+ and NumPy installed. ```bash pip install raptorbt ``` -------------------------------- ### Errors and Configuration Source: https://github.com/alphabench/raptorbt/blob/main/_autodocs/COMPLETION_SUMMARY.txt Guide to error handling patterns and configuration best practices for RaptorBT. ```APIDOC ## Errors and Configuration This section covers error handling strategies and best practices for configuring RaptorBT. ### Error Handling - **Error Code** (string) - Description of the error and potential causes. - **Exception Type** (type) - Details on exceptions that might be raised. ### Configuration Best Practices - **Setting Name** (type) - Recommended values and usage guidelines. - **Configuration File Format** (format) - Description of the configuration file structure. ``` -------------------------------- ### Example: Long ATM Call Strategy Backtest Source: https://github.com/alphabench/raptorbt/blob/main/_autodocs/api-reference/backtest-functions.md This example demonstrates how to backtest a long ATM call strategy. It specifies sizing as 10% of capital and provides necessary parameters for underlying data, option prices, and entry/exit signals. ```python # Long ATM call strategy, sizing as 10% of capital result = raptorbt.run_options_backtest( timestamps=ts, open=underlying_open, high=underlying_high, low=underlying_low, close=underlying_close, volume=underlying_vol, option_prices=call_premium_series, entries=call_entries, exits=call_exits, direction=1, # long option_type="call", strike_selection="atm", size_type="percent", size_value=0.1, # 10% of capital lot_size=50, strike_interval=50.0, symbol="NIFTY26APR24000CE", config=config, ) ``` -------------------------------- ### Monte Carlo Portfolio Simulation Example Source: https://github.com/alphabench/raptorbt/blob/main/_autodocs/api-reference/monte-carlo.md Demonstrates how to use the `simulate_portfolio_mc` function with sample historical returns, weights, and correlation matrix. It shows how to access and interpret the simulation results, including expected return, probability of loss, VaR, CVaR, percentile paths, and final values. Includes plotting of percentile paths. ```python import numpy as np import raptorbt # Historical daily returns for two strategies (e.g., past 2 years = 504 days) strategy_a_returns = np.array([0.001, -0.002, 0.003, ...]) # 504 elements strategy_b_returns = np.array([0.002, 0.001, -0.001, ...]) # 504 elements # Portfolio: 60% Strategy A, 40% Strategy B weights = np.array([0.6, 0.4]) # Correlation matrix # Typically computed as: np.corrcoef(strategy_a_returns, strategy_b_returns) correlation_matrix = [ np.array([1.0, 0.3]), # Strategy A correlation with self and B np.array([0.3, 1.0]), # Strategy B correlation with A and self ] # Run simulation result = raptorbt.simulate_portfolio_mc( returns=[strategy_a_returns, strategy_b_returns], weights=weights, correlation_matrix=correlation_matrix, initial_value=100000.0, n_simulations=10000, horizon_days=252, # 1 year seed=42, ) # Access results print(f"Expected Return: {result['expected_return']:.2f}%") print(f"Probability of Loss: {result['probability_of_loss']:.2%}") print(f"VaR(95): {result['var_95']:.2f}%") print(f"CVaR(95): {result['cvar_95']:.2f}%") # Percentile paths show distribution of possible outcomes for pct, path in result['percentile_paths']: print(f" P{pct:.0f} final value: {path[-1]:,.2f}") # Access all terminal values for custom analysis final_vals = result['final_values'] print(f"Min final value: {final_vals.min():,.2f}") print(f"Max final value: {final_vals.max():,.2f}") print(f"Median final value: {np.median(final_vals):,.2f}") # Plot percentile paths import matplotlib.pyplot as plt days = np.arange(len(result['percentile_paths'][0][1])) for pct, path in result['percentile_paths']: plt.plot(days, path, label=f"P{pct:.0f}") plt.legend() plt.xlabel("Days") plt.ylabel("Portfolio Value") plt.show() ``` -------------------------------- ### Tick-Level Backtest Example Source: https://github.com/alphabench/raptorbt/blob/main/_autodocs/api-reference/backtest-functions.md Demonstrates how to prepare tick data, compute entry/exit signals, and run a backtest using the run_tick_backtest function. Ensure buy/sell quantity deltas are correctly calculated from cumulative data. ```python import numpy as np import raptorbt # Per-tick data (one element per tick) timestamps_ns = ... # nanoseconds ltp = ... bid = ... ask = ... buy_cum = ... # Zerodha cumulative sell_cum = ... # Zerodha cumulative # Convert to per-tick deltas buy_delta = np.diff(buy_cum, prepend=0).clip(min=0) sell_delta = np.diff(sell_cum, prepend=0).clip(min=0) # Compute entry signals spread = raptorbt.tick_spread_pct(bid, ask) bsi = raptorbt.buy_sell_imbalance_delta(buy_cum, sell_cum) ret_1m = raptorbt.return_window(timestamps_ns, ltp, window_seconds=60.0) entries = raptorbt.compute_tick_entry_signals( spread_pct=spread, bsi_delta=bsi, return_1m=ret_1m, spread_pct_max=3.0, bsi_min=0.55, return_1m_min_abs=0.3, return_direction=1, cooldown_ticks=10, ) exits = raptorbt.compute_tick_exit_signals(timestamps_ns, eod_exit_time_ns=0) # Run backtest result = raptorbt.run_tick_backtest( timestamps=timestamps_ns, ltp=ltp, bid=bid, ask=ask, buy_qty_delta=buy_delta, sell_qty_delta=sell_delta, oi=oi, entries=entries, exits=exits, symbol="NIFTY26APR24600PE", initial_capital=100000.0, fees=0.001, slippage=0.0005, stop_loss_pct=5.0, take_profit_pct=10.0, max_hold_seconds=1800, entry_cooldown_ticks=10, max_trades=50, ) print(f"Tick trades: {result.metrics.total_trades}") print(f"Profit factor: {result.metrics.profit_factor:.2f}") ``` -------------------------------- ### Run Spread Backtest - Iron Condor Example Source: https://github.com/alphabench/raptorbt/blob/main/_autodocs/api-reference/backtest-functions.md Demonstrates how to set up and run a backtest for an Iron Condor strategy. This includes defining the legs, their premiums, configuration, entry/exit signals, and risk parameters. Ensure all input arrays (timestamps, underlying_close, legs_premiums, entries, exits) are of the same length. ```python # Iron Condor: short 24500 call, short 23500 put, long 24000 call, long 24000 put items = raptorbt.PyBatchSpreadItem( strategy_id="iron_condor_24000", legs_premiums=[ call_24000_premiums, # long call call_24500_premiums, # short call put_23500_premiums, # short put put_24000_premiums, # long put ], leg_configs=[ ("CE", 24000.0, 1, 50), # long call ("CE", 24500.0, -1, 50), # short call ("PE", 23500.0, -1, 50), # short put ("PE", 24000.0, 1, 50), # long put ], entries=entries, exits=exits, spread_type="iron_condor", max_loss=5000.0, target_profit=2000.0, ) result = raptorbt.run_spread_backtest( timestamps=ts, underlying_close=underlying, legs_premiums=item.legs_premiums, leg_configs=item.leg_configs, entries=item.entries, exits=item.exits, config=config, spread_type="iron_condor", max_loss=5000.0, target_profit=2000.0, ) ``` -------------------------------- ### Python Example: Running Multiple Spread Backtests Source: https://github.com/alphabench/raptorbt/blob/main/_autodocs/api-reference/backtest-functions.md Demonstrates how to set up and execute multiple spread backtests using the batch_spread_backtest function. This includes defining spread items like Iron Condors and Strangles, configuring backtest parameters, and processing the results. ```python # Batch: multiple Iron Condor and Strangle variations items = [ raptorbt.PyBatchSpreadItem( strategy_id="iron_condor_24000", legs_premiums=[call_24000, call_24500, put_23500, put_24000], leg_configs=[ ("CE", 24000.0, 1, 50), ("CE", 24500.0, -1, 50), ("PE", 23500.0, -1, 50), ("PE", 24000.0, 1, 50), ], entries=entries, exits=exits, spread_type="iron_condor", max_loss=5000.0, target_profit=2000.0, ), raptorbt.PyBatchSpreadItem( strategy_id="strangle_23500_24500", legs_premiums=[call_24500, put_23500], leg_configs=[("CE", 24500.0, -1, 50), ("PE", 23500.0, -1, 50)], entries=entries, exits=exits, spread_type="strangle", ), ] config = raptorbt.PyBacktestConfig(initial_capital=100000, fees=0.001) results = raptorbt.batch_spread_backtest( timestamps=ts, underlying_close=underlying, items=items, config=config, ) for strategy_id, result in results: print(f"{strategy_id}: {result.metrics.total_return_pct:.2f}%") ``` -------------------------------- ### Configure Risk-Reward Target Source: https://github.com/alphabench/raptorbt/blob/main/README.md Set a target for the risk-reward ratio, ensuring that potential profits are a specified multiple of the potential loss. This example sets a 2:1 ratio. ```python config.set_risk_reward_target(ratio=2.0) # 2:1 risk-reward ratio ``` -------------------------------- ### Perform Basket Backtesting Source: https://github.com/alphabench/raptorbt/blob/main/_autodocs/quickstart-and-imports.md Conduct backtests on a basket of financial instruments, simulating a portfolio. This example demonstrates how to define instruments and run a backtest with synchronization. ```python instruments = [ (ts, o1, h1, l1, c1, v1, e1, ex1, 1, 0.33, "AAPL"), (ts, o2, h2, l2, c2, v2, e2, ex2, 1, 0.33, "GOOGL"), (ts, o3, h3, l3, c3, v3, e3, ex3, 1, 0.34, "MSFT"), ] result = raptorbt.run_basket_backtest( instruments=instruments, config=config, sync_mode="majority", ) ``` -------------------------------- ### Backtest Metrics Usage Example Source: https://github.com/alphabench/raptorbt/blob/main/_autodocs/api-reference/configuration-classes.md Demonstrates how to access individual performance metrics directly from the metrics object and how to use the to_dict() method for a formatted summary. Assumes a backtest has been run and its results stored in 'result'. ```python result = raptorbt.run_single_backtest(...) metrics = result.metrics print(f"Return: {metrics.total_return_pct:.2f}%") print(f"Sharpe: {metrics.sharpe_ratio:.2f}") print(f"Max Drawdown: {metrics.max_drawdown_pct:.2f}%") print(f"Win Rate: {metrics.win_rate_pct:.1f}%") print(f"Trades: {metrics.total_trades}") # Human-readable dict stats = metrics.to_dict() for label, value in stats.items(): print(f" {label}: {value}") ``` -------------------------------- ### Iterate and Print Trade Details Source: https://github.com/alphabench/raptorbt/blob/main/_autodocs/api-reference/configuration-classes.md Demonstrates how to retrieve trades from a backtest result and print detailed information for each trade, including entry/exit points, P&L, and fees. This example assumes a `raptorbt.run_single_backtest` function has been called. ```python result = raptorbt.run_single_backtest(...) trades = result.trades() for trade in trades: print(f"{trade.symbol} #{trade.id}:") print(f" Entry: bar {trade.entry_idx} @ {trade.entry_price:.2f}") print(f" Exit: bar {trade.exit_idx} @ {trade.exit_price:.2f} ({trade.exit_reason})") print(f" Size: {trade.size}, Direction: {trade.direction}") print(f" P&L: {trade.pnl:.2f} ({trade.return_pct:.2f}%)") print(f" Fees: {trade.fees:.2f}") ``` -------------------------------- ### Donchian Breakout Example Source: https://github.com/alphabench/raptorbt/blob/main/_autodocs/api-reference/indicators.md Illustrates how to use rolling_max and rolling_min to identify Donchian breakouts for potential trading entries. Requires high, low price series and a lookback period. ```python # Donchian breakout lookback = 20 highest = raptorbt.rolling_max(high, lookback) lowest = raptorbt.rolling_min(low, lookback) # Entry: price > highest (long) or price < lowest (short) ``` -------------------------------- ### MACD Indicator Usage Example Source: https://github.com/alphabench/raptorbt/blob/main/_autodocs/api-reference/indicators.md Demonstrates how to use the MACD function to obtain MACD line, signal line, and histogram. It also provides comments on identifying MACD crossovers and histogram divergence. ```python macd_line, signal, hist = raptorbt.macd(close) # MACD crossovers: macd_line crosses signal_line # Histogram divergence: hist changes sign ``` -------------------------------- ### SMA Crossover Strategy Implementation Source: https://github.com/alphabench/raptorbt/blob/main/_autodocs/quickstart-and-imports.md An example strategy that implements the SMA Crossover logic by overriding `compute_indicators` and `generate_signals` from the `StrategyBacktest` template. It calculates fast and slow Simple Moving Averages (SMA) and generates entry/exit signals based on their crossovers. ```python # Example: SMA Crossover Strategy class SMAStrategy(StrategyBacktest): def __init__(self, data_path, config_params, fast_period=10, slow_period=50): super().__init__(data_path, config_params) self.fast_period = fast_period self.slow_period = slow_period def compute_indicators(self): close = self.df["close"] self.sma_fast = close.rolling(self.fast_period).mean() self.sma_slow = close.rolling(self.slow_period).mean() def generate_signals(self): entries = (self.sma_fast > self.sma_slow) & \ (self.sma_fast.shift(1) <= self.sma_slow.shift(1)) exits = (self.sma_fast < self.sma_slow) & \ (self.sma_fast.shift(1) >= self.sma_slow.shift(1)) return entries, exits ``` -------------------------------- ### Initialize PyInstrumentConfig Source: https://github.com/alphabench/raptorbt/blob/main/_autodocs/GLOSSARY.md Configure instrument-specific parameters including lot size, capital allocation, and existing position details. ```python PyInstrumentConfig( lot_size=1.0, # Min tradeable quantity alloted_capital=50000.0, # Capital cap for this instrument existing_qty=None, # Existing position (future) avg_price=None, # Existing avg price (future) ) ``` -------------------------------- ### Get List of Trades Source: https://github.com/alphabench/raptorbt/blob/main/_autodocs/api-reference/configuration-classes.md Retrieves a list of all executed trades, where each trade is represented by a PyTrade object. ```python def trades() -> List[PyTrade] ``` -------------------------------- ### Get Per-Bar Returns Data Source: https://github.com/alphabench/raptorbt/blob/main/_autodocs/api-reference/configuration-classes.md Retrieves the per-bar returns as a NumPy array. This provides the fractional change in portfolio value for each bar. ```python def returns() -> np.ndarray # float64 ``` -------------------------------- ### Get Drawdown Curve Data Source: https://github.com/alphabench/raptorbt/blob/main/_autodocs/api-reference/configuration-classes.md Retrieves the drawdown at each bar as a NumPy array. This is useful for understanding the maximum historical loss from peaks. ```python def drawdown_curve() -> np.ndarray # float64 ``` -------------------------------- ### Import Configuration Classes Source: https://github.com/alphabench/raptorbt/blob/main/_autodocs/quickstart-and-imports.md Import and instantiate configuration classes for backtests and instruments. Use these to define parameters for your simulations. ```python from raptorbt import PyBacktestConfig, PyInstrumentConfig config = PyBacktestConfig(initial_capital=100000, fees=0.001) inst = PyInstrumentConfig(lot_size=1.0, alloted_capital=50000) ``` -------------------------------- ### Get Equity Curve Data Source: https://github.com/alphabench/raptorbt/blob/main/_autodocs/api-reference/configuration-classes.md Retrieves the portfolio value at each bar as a NumPy array. Useful for visualizing the equity growth over time. ```python def equity_curve() -> np.ndarray # float64 ``` -------------------------------- ### Initialize PyBacktestConfig Source: https://github.com/alphabench/raptorbt/blob/main/_autodocs/GLOSSARY.md Configure backtesting parameters such as initial capital, fees, slippage, and order fill timing. ```python PyBacktestConfig( initial_capital=100000.0, # Starting capital fees=0.001, # Per-trade fee fraction (0.001 = 0.1%) slippage=0.0005, # Per-trade slippage fraction upon_bar_close=True, # Fill at close (True) or open (False) ) ``` -------------------------------- ### CombineMode Enum for Multi-Strategy Signals Source: https://github.com/alphabench/raptorbt/blob/main/_autodocs/types.md Determines how signals from multiple strategies on the same instrument are combined. This is crucial for managing complex multi-strategy setups. ```rust pub enum CombineMode { Any, All, Majority, Weighted, Independent, } ``` ```python # Python API mapping: # "any" → CombineMode::Any # "all" → CombineMode::All # "majority" → CombineMode::Majority # "weighted" → CombineMode::Weighted # "independent" → CombineMode::Independent ``` -------------------------------- ### Configure and Modify Backtest Settings Source: https://github.com/alphabench/raptorbt/blob/main/_autodocs/api-reference/configuration-classes.md Demonstrates the creation of a PyBacktestConfig object with initial parameters and the subsequent modification of properties like initial capital and fees. It also shows how to set stop-loss and take-profit levels. ```python config = raptorbt.PyBacktestConfig( initial_capital=100000, fees=0.001, slippage=0.0005, upon_bar_close=True ) config.set_fixed_stop(0.02) config.set_fixed_target(0.05) # Modify after creation config.initial_capital = 50000 config.fees = 0.002 ``` -------------------------------- ### Running an SMA Crossover Backtest Source: https://github.com/alphabench/raptorbt/blob/main/_autodocs/quickstart-and-imports.md Demonstrates how to instantiate and run the `SMAStrategy` with specific configuration parameters and data file. It then prints the summary of the backtest results. ```python # Run it config = { "initial_capital": 100000, "fees": 0.001, "slippage": 0.0005, "symbol": "INFY", } strategy = SMAStrategy("infy_data.csv", config, fast_period=10, slow_period=50) result = strategy.run() strategy.print_summary(result) ``` -------------------------------- ### Creating and Using PyBatchSpreadItem for Backtesting Source: https://github.com/alphabench/raptorbt/blob/main/_autodocs/api-reference/configuration-classes.md Demonstrates how to instantiate PyBatchSpreadItem with specific parameters for an iron condor strategy and then use it with the batch_spread_backtest function. Shows how to process the results. ```python items = [ raptorbt.PyBatchSpreadItem( strategy_id="ic_24000", legs_premiums=[ call_24000, call_24500, put_23500, put_24000 ], leg_configs=[ ("CE", 24000.0, 1, 50), ("CE", 24500.0, -1, 50), ("PE", 23500.0, -1, 50), ("PE", 24000.0, 1, 50), ], entries=entries, exits=exits, spread_type="iron_condor", max_loss=5000.0, target_profit=2000.0, ), ] results = raptorbt.batch_spread_backtest(ts, underlying, items, config) for sid, res in results: print(f"{sid}: {res.metrics.total_return_pct:.2f}%") ``` -------------------------------- ### Build RaptorBT from Source Source: https://github.com/alphabench/raptorbt/blob/main/README.md Instructions for building the RaptorBT engine from source using maturin. Requires Rust 1.70+ and Python 3.10+. ```bash cd raptorbt maturin develop --release # editable install into the active venv cargo test # run the Rust test suite ``` -------------------------------- ### Run Single Backtest with SMA Crossover Strategy Source: https://github.com/alphabench/raptorbt/blob/main/_autodocs/api-reference/backtest-functions.md Demonstrates how to perform a single-instrument backtest using a simple moving average (SMA) crossover strategy. It includes loading OHLCV data, generating entry and exit signals, configuring backtest parameters like initial capital, fees, slippage, stop-loss, and take-profit, and finally running the backtest and accessing key performance metrics. ```python import numpy as np import pandas as pd import raptorbt # Load OHLCV data df = pd.read_csv("AAPL.csv", index_col=0, parse_dates=True) # Generate signals (SMA crossover) sma_fast = df["close"].rolling(10).mean() sma_slow = df["close"].rolling(50).mean() entries = (sma_fast > sma_slow) & (sma_fast.shift(1) <= sma_slow.shift(1)) exits = (sma_fast < sma_slow) & (sma_fast.shift(1) >= sma_slow.shift(1)) # Configure backtest config = raptorbt.PyBacktestConfig( initial_capital=100000.0, fees=0.001, # 0.1% per trade slippage=0.0005 # 0.05% per trade ) config.set_fixed_stop(0.02) # 2% stop-loss config.set_fixed_target(0.05) # 5% take-profit # Run backtest result = raptorbt.run_single_backtest( timestamps=df.index.astype("int64").values, open=df["open"].values, high=df["high"].values, low=df["low"].values, close=df["close"].values, volume=df["volume"].values, entries=entries.values.astype(bool), exits=exits.values.astype(bool), direction=1, weight=1.0, symbol="AAPL", config=config, ) # Access results print(f"Total Return: {result.metrics.total_return_pct:.2f}%") print(f"Sharpe Ratio: {result.metrics.sharpe_ratio:.2f}") print(f"Max Drawdown: {result.metrics.max_drawdown_pct:.2f}%") print(f"Total Trades: {result.metrics.total_trades}") # Get equity curve and trades equity = result.equity_curve() # numpy array of portfolio values trades = result.trades() # list of PyTrade objects ``` -------------------------------- ### Configure Instrument-Specific Settings with PyInstrumentConfig Source: https://github.com/alphabench/raptorbt/blob/main/README.md Set per-instrument configurations for lot size, allocated capital, and optional stop/target overrides. Lot size determines position sizing granularity. ```python inst_config = raptorbt.PyInstrumentConfig( lot_size=1.0, alloted_capital=50000.0, existing_qty=None, avg_price=None, ) # Optional: per-instrument stop/target overrides inst_config.set_fixed_stop(0.02) inst_config.set_trailing_stop(0.03) inst_config.set_fixed_target(0.05) ``` -------------------------------- ### Initialize PyBacktestConfig Source: https://github.com/alphabench/raptorbt/blob/main/_autodocs/api-reference/configuration-classes.md Instantiate PyBacktestConfig with core backtesting parameters like initial capital, fees, and slippage. The `upon_bar_close` parameter determines if trades are executed at bar close or bar open. ```python class PyBacktestConfig: def __init__( self, initial_capital: float = 100000.0, fees: float = 0.001, slippage: float = 0.0, upon_bar_close: bool = True, ) -> None ``` -------------------------------- ### Configure Fees and Slippage for Backtest Source: https://github.com/alphabench/raptorbt/blob/main/_autodocs/errors-and-configuration.md Set trading fees and slippage percentages in PyBacktestConfig. These parameters simulate real-world trading costs and price discrepancies, impacting profitability. ```python config = raptorbt.PyBacktestConfig( fees=0.001, # 0.1% per trade (entry and exit) slippage=0.0005, # 0.05% price slippage per trade ) ``` -------------------------------- ### Configure Backtest Settings with PyBacktestConfig Source: https://github.com/alphabench/raptorbt/blob/main/README.md Initialize and configure backtesting parameters such as initial capital, fees, slippage, and bar close behavior. Supports setting fixed, ATR, or trailing stops and targets. ```python config = raptorbt.PyBacktestConfig( initial_capital: float = 100000.0, fees: float = 0.001, slippage: float = 0.0, upon_bar_close: bool = True, ) # Stop methods config.set_fixed_stop(percent: float) config.set_atr_stop(multiplier: float, period: int) config.set_trailing_stop(percent: float) # Target methods config.set_fixed_target(percent: float) config.set_atr_target(multiplier: float, period: int) config.set_risk_reward_target(ratio: float) ``` -------------------------------- ### Configure Fill Timing: Upon Bar Open Source: https://github.com/alphabench/raptorbt/blob/main/_autodocs/errors-and-configuration.md Set the 'upon_bar_close' parameter in PyBacktestConfig to False to fill positions at the bar's opening price. This is more conservative and suitable for end-of-day signal systems. ```python config = raptorbt.PyBacktestConfig(upon_bar_close=False) # Fill at open ``` -------------------------------- ### Simulate Portfolio Monte Carlo with simulate_portfolio_mc Source: https://github.com/alphabench/raptorbt/blob/main/README.md Perform Monte Carlo simulations on a portfolio using asset returns, weights, and a correlation matrix. Specify initial value, number of simulations, and horizon. ```python result = raptorbt.simulate_portfolio_mc( returns: List[np.ndarray], weights: np.ndarray, correlation_matrix: List[np.ndarray], initial_value: float, n_simulations: int = 10000, horizon_days: int = 252, seed: int = 42, ) -> dict ``` -------------------------------- ### Configure Fixed Percentage Stop-Loss and Take-Profit Source: https://github.com/alphabench/raptorbt/blob/main/README.md Set fixed percentage-based stop-loss and take-profit levels for your backtest configuration. This is useful for simple risk management strategies. ```python config = raptorbt.PyBacktestConfig(initial_capital=100000, fees=0.001) config.set_fixed_stop(0.02) # 2% stop-loss config.set_fixed_target(0.04) # 4% take-profit ``` -------------------------------- ### Basket Configuration Sync Mode: All Source: https://github.com/alphabench/raptorbt/blob/main/_autodocs/errors-and-configuration.md Configure a basket backtest where ALL instruments must signal together for entry or exit. This results in the slowest entries but the most synchronized exits. ```python result = raptorbt.run_basket_backtest(..., sync_mode="all") ``` -------------------------------- ### Basket Configuration Sync Mode: Any Source: https://github.com/alphabench/raptorbt/blob/main/_autodocs/errors-and-configuration.md Configure a basket backtest where ANY instrument can trigger an entry or exit. This mode provides the fastest entries but leads to the most asynchronous trading behavior. ```python result = raptorbt.run_basket_backtest(..., sync_mode="any") ``` -------------------------------- ### Configure Fill Timing: Upon Bar Close Source: https://github.com/alphabench/raptorbt/blob/main/_autodocs/errors-and-configuration.md Set the 'upon_bar_close' parameter in PyBacktestConfig to True to fill positions at the bar's closing price. This is suitable for daily strategies where the closing price is known. ```python config = raptorbt.PyBacktestConfig(upon_bar_close=True) # Fill at close ``` -------------------------------- ### Configure Fixed Percentage Take-Profit Source: https://github.com/alphabench/raptorbt/blob/main/_autodocs/errors-and-configuration.md Set a fixed percentage take-profit target using config.set_fixed_target(). This defines a desired profit level based on the entry price. ```python config.set_fixed_target(0.05) # Exit at 5% gain ``` -------------------------------- ### Configure Initial Capital for Backtest Source: https://github.com/alphabench/raptorbt/blob/main/_autodocs/errors-and-configuration.md Set the initial capital for a backtest using PyBacktestConfig. This value is crucial for position sizing and calculating percentage-based performance metrics. ```python config = raptorbt.PyBacktestConfig(initial_capital=100000.0) ``` -------------------------------- ### Run Single Backtest with RaptorBT Source: https://github.com/alphabench/raptorbt/blob/main/README.md Execute a single-instrument backtest using provided OHLCV data, entry/exit signals, and configuration. Requires numpy and raptorbt. Ensure timestamps, open, high, low, close, volume, entries, and exits are defined. ```python import numpy as np import raptorbt # Configure config = raptorbt.PyBacktestConfig(initial_capital=100000, fees=0.001) # Run backtest result = raptorbt.run_single_backtest( timestamps=timestamps, open=open, high=high, low=low, close=close, volume=volume, entries=entries, exits=exits, direction=1, weight=1.0, symbol="AAPL", config=config, ) # Results print(f"Return: {result.metrics.total_return_pct:.2f}%") print(f"Sharpe: {result.metrics.sharpe_ratio:.2f}") ``` -------------------------------- ### Common RaptorBT Imports in Python Source: https://github.com/alphabench/raptorbt/blob/main/_autodocs/README.md Import necessary components for configuration, backtesting, indicators, and risk analysis. Choose backtesting functions based on your needs. ```python # Configuration from raptorbt import PyBacktestConfig, PyInstrumentConfig # Backtesting (choose one or more) from raptorbt import ( run_single_backtest, run_basket_backtest, run_options_backtest, run_pairs_backtest, run_multi_backtest, run_spread_backtest, run_tick_backtest, ) # Indicators from raptorbt import sma, ema, rsi, macd, atr, bollinger_bands # Risk analysis from raptorbt import simulate_portfolio_mc ``` -------------------------------- ### Run Multi-Strategy Backtest Source: https://github.com/alphabench/raptorbt/blob/main/README.md Combine multiple strategies on the same instrument with various combination modes. Use this to test ensemble trading approaches. ```python strategies = [ (entries_sma, exits_sma, 1, 0.4, "SMA_Crossover"), # 40% weight (entries_rsi, exits_rsi, 1, 0.35, "RSI_MeanRev"), # 35% weight (entries_bb, exits_bb, 1, 0.25, "BB_Breakout"), # 25% weight ] result = raptorbt.run_multi_backtest( timestamps=timestamps, open=open_prices, high=high_prices, low=low_prices, close=close_prices, volume=volume, strategies=strategies, config=config, combine_mode="any", # "any", "all", "majority", "weighted", "independent" ) ``` -------------------------------- ### Configuration Classes Source: https://github.com/alphabench/raptorbt/blob/main/_autodocs/COMPLETION_SUMMARY.txt Reference for configuration classes used in RaptorBT, detailing their structure, available metrics, and usage. ```APIDOC ## Configuration Classes This section provides documentation for the configuration classes available in RaptorBT. It includes details on metrics, class structures, and how to configure them for strategy development. ### Class Definition - **ClassName** - **field1** (type) - Description - **metric1** (type) - Description of metric ### Usage Example ```python # Example of using a configuration class config = ClassName(field1='value', metric1=100) ``` ### Configuration Options - **Option Name** (type) - Description and default value. ``` -------------------------------- ### Run Tick-Level Backtest with Raw Tick Data Source: https://github.com/alphabench/raptorbt/blob/main/README.md Simulates intraday strategies using raw tick data arrays. Ensure buy_qty_delta and sell_qty_delta are per-tick deltas, not cumulative sums. This function is suitable for options momentum, scalping, and scenarios where exact fill ticks matter. ```python import numpy as np import raptorbt # Raw tick arrays (one element per tick, same length N) # buy_qty_delta / sell_qty_delta must be per-tick deltas, NOT Zerodha cumulative sums result = raptorbt.run_tick_backtest( timestamps=timestamps_ns, # int64 nanoseconds-since-epoch ltp=ltp_arr, # last traded price bid=bid_arr, ask=ask_arr, buy_qty_delta=buy_delta, # pre-converted from cumulative: np.diff(buy_cum).clip(0) sell_qty_delta=sell_delta, oi=oi_arr, entries=entry_signals, # bool array — True where entry is allowed exits=exit_signals, # bool array — True where position should exit symbol="NIFTY26APR24600PE", initial_capital=100_000.0, fees=0.001, slippage=0.0005, stop_loss_pct=5.0, take_profit_pct=10.0, max_hold_seconds=1800, # 30-minute maximum hold entry_cooldown_ticks=10, # minimum ticks between entries max_trades=50, ) print(f"trades: {result.metrics.total_trades}") print(f"profit_factor: {result.metrics.profit_factor:.2f}") print(f"win_rate: {result.metrics.win_rate_pct:.1f}%") ``` -------------------------------- ### Basket Configuration Sync Mode: Master Source: https://github.com/alphabench/raptorbt/blob/main/_autodocs/errors-and-configuration.md Configure a basket backtest where only the first instrument's signal determines entry or exit. Other instruments in the basket are then allocated capital based on this master signal. ```python result = raptorbt.run_basket_backtest(..., sync_mode="master") ``` -------------------------------- ### Configure Risk-Reward Ratio Take-Profit Source: https://github.com/alphabench/raptorbt/blob/main/_autodocs/errors-and-configuration.md Set a take-profit target based on a risk-reward ratio using config.set_risk_reward_target(). This requires a stop-loss to be set first and calculates the target profit relative to the stop-loss distance. ```python config.set_risk_reward_target(ratio=2.0) ``` -------------------------------- ### PyInstrumentConfig Source: https://github.com/alphabench/raptorbt/blob/main/_autodocs/GLOSSARY.md Configuration object for instrument-specific parameters. ```APIDOC ## PyInstrumentConfig ### Description Configuration object for instrument-specific parameters. ### Parameters - **lot_size** (float) - Minimum tradeable quantity. - **alloted_capital** (float) - Capital allocation cap for this instrument. - **existing_qty** (float) - Existing position quantity (for future use). - **avg_price** (float) - Average entry price for existing position (for future use). ``` -------------------------------- ### Backtest Entry Points Source: https://github.com/alphabench/raptorbt/blob/main/_autodocs/README.md Functions to initiate different types of backtests. ```APIDOC ## Backtest Entry Points ### `run_single_backtest` Single instrument long/short backtest. ### `run_basket_backtest` Multiple instruments synchronized backtest. ### `run_options_backtest` Options strategies with strike selection. ### `run_pairs_backtest` Pairs trading (long/short two instruments) backtest. ### `run_multi_backtest` Multiple strategies on the same instrument backtest. ### `run_spread_backtest` Multi-leg options spreads backtest. ### `run_tick_backtest` Tick-level high-resolution simulation. ### `batch_spread_backtest` Parallel spread backtests. ``` -------------------------------- ### PyInstrumentConfig Class Definition Source: https://github.com/alphabench/raptorbt/blob/main/_autodocs/api-reference/configuration-classes.md Defines the configuration for a single instrument, including lot size, allocated capital, and existing position details. ```python class PyInstrumentConfig: def __init__( self, lot_size: float = None, alloted_capital: float = None, existing_qty: float = None, avg_price: float = None, ) -> None ``` -------------------------------- ### Run Options Backtest Source: https://github.com/alphabench/raptorbt/blob/main/README.md Backtest options strategies with flexible strike selection and sizing options. Suitable for strategies involving single options contracts. ```python result = raptorbt.run_options_backtest( timestamps=timestamps, open=underlying_open, high=underlying_high, low=underlying_low, close=underlying_close, volume=volume, option_prices=option_prices, # Option premium series entries=entries, exits=exits, direction=1, symbol="NIFTY_CE", config=config, option_type="call", # "call" or "put" strike_selection="atm", # "atm", "otm1", "otm2", "itm1", "itm2" size_type="percent", # "percent", "contracts", "notional", "risk" size_value=0.1, # 10% of capital lot_size=50, # Options lot size strike_interval=50.0, # Strike interval (e.g., 50 for NIFTY) ) ``` -------------------------------- ### Run Batch Spread Backtests with batch_spread_backtest Source: https://github.com/alphabench/raptorbt/blob/main/README.md Execute multiple spread backtests in parallel using provided timestamps, underlying close prices, and a list of spread items. Optionally share a PyBacktestConfig. ```python results = raptorbt.batch_spread_backtest( timestamps: np.ndarray, underlying_close: np.ndarray, items: List[PyBatchSpreadItem], config: PyBacktestConfig = None, ) -> List[Tuple[str, PyBacktestResult]] ``` -------------------------------- ### Configure Fixed Percentage Stop-Loss Source: https://github.com/alphabench/raptorbt/blob/main/_autodocs/errors-and-configuration.md Set a fixed percentage stop-loss using config.set_fixed_stop(). This defines a maximum acceptable loss per trade based on the entry price. ```python config.set_fixed_stop(0.02) # Exit at 2% loss ```