### Advanced Order Execution in Python Source: https://context7.com/context7/kernc_github_io_backtesting_py_doc/llms.txt Illustrates how to execute various types of orders, including market, stop-loss, take-profit, and limit orders, within a backtesting.py Strategy. This example shows how to specify order size as a percentage of available cash and set risk management parameters directly in the order methods. It uses a Simple Moving Average (SMA) crossover for trade signals. ```python from backtesting import Strategy class AdvancedOrders(Strategy): def init(self): # Assuming SMA is defined elsewhere or imported # For example: from backtesting.lib import SMA # self.sma = self.I(SMA, self.data.Close, 20) pass # Placeholder for SMA indicator initialization def next(self): # Placeholder for accessing price and SMA # price = self.data.Close[-1] # sma_value = self.sma[-1] price = 100 # Dummy value sma_value = 90 # Dummy value # Buy with 50% of available cash if not self.position and price > sma_value: self.buy(size=0.5) # Sell short with stop loss and take profit elif not self.position and price < sma_value: self.sell( size=0.3, sl=price * 1.05, # Stop loss 5% above tp=price * 0.90 # Take profit 10% below ) # Close position if exists elif self.position: self.position.close() # Limit order example if price < sma_value * 0.95: self.buy(limit=price * 0.98, size=0.25) # Output: Orders executed with proper risk management ``` -------------------------------- ### Implement Trading Strategy Logic (Python) Source: https://context7.com/context7/kernc_github_io_backtesting_py_doc/llms.txt Defines a custom trading strategy by inheriting from the Strategy class. The `init()` method is used for indicator calculations, and the `next()` method contains the trading logic executed on each bar. This example uses a Simple Moving Average (SMA) crossover. ```python from backtesting import Strategy from backtesting.lib import crossover from backtesting.test import SMA class SmaCross(Strategy): n1 = 10 # Fast moving average period n2 = 20 # Slow moving average period def init(self): # Calculate indicators once during initialization close = self.data.Close self.sma1 = self.I(SMA, close, self.n1) self.sma2 = self.I(SMA, close, self.n2) def next(self): # Execute on each new bar if crossover(self.sma1, self.sma2): self.buy() elif crossover(self.sma2, self.sma1): self.position.close() # Output: Strategy ready to backtest with simple moving average crossover logic ``` -------------------------------- ### Run Backtest and Get Performance Stats (Python) Source: https://context7.com/context7/kernc_github_io_backtesting_py_doc/llms.txt Executes a configured Backtest object and returns a pandas Series containing comprehensive performance statistics. This includes equity, returns, drawdowns, and trade-related metrics. ```python from backtesting import Backtest, Strategy from backtesting.test import GOOG bt = Backtest(GOOG, SmaCross, cash=10000, commission=.002) stats = bt.run() print(stats) # Output: # Start 2004-08-19 00:00:00 # End 2013-03-01 00:00:00 # Duration 3116 days 00:00:00 # Exposure Time [%] 94.27 # Equity Final [$] 68935.12 # Equity Peak [$] 68991.22 # Return [%] 589.35 # Buy & Hold Return [%] 703.46 # Return (Ann.) [%] 25.42 # Volatility (Ann.) [%] 38.43 # Sharpe Ratio 0.66 # Sortino Ratio 1.30 # Calmar Ratio 0.77 # Max. Drawdown [%] -33.08 # Avg. Drawdown [%] -5.58 # Max. Drawdown Duration 688 days 00:00:00 # Avg. Drawdown Duration 41 days 00:00:00 # # Trades 93 # Win Rate [%] 53.76 # Best Trade [%] 57.12 # Worst Trade [%] -16.63 # Avg. Trade [%] 1.96 # Max. Trade Duration 121 days 00:00:00 # Avg. Trade Duration 29 days 00:00:00 # Profit Factor 2.13 # Expectancy [%] 6.91 # SQN 1.78 ``` -------------------------------- ### Parameter Optimization using Grid Search in Python Source: https://context7.com/context7/kernc_github_io_backtesting_py_doc/llms.txt Shows how to optimize strategy parameters using the `bt.optimize()` method in backtesting.py. This function performs a grid search over specified parameter ranges and identifies the combination that maximizes a given metric (e.g., 'Sharpe Ratio'). It also demonstrates how to apply constraints to the parameter search. The example uses a Simple Moving Average (SMA) crossover strategy. ```python from backtesting import Backtest from backtesting.test import GOOG from backtesting.lib import SMA, crossover # Assuming SMA and crossover are available class SmaCross(Strategy): n1 = 10 n2 = 20 def init(self): self.sma1 = self.I(SMA, self.data.Close, self.n1) self.sma2 = self.I(SMA, self.data.Close, self.n2) def next(self): if crossover(self.sma1, self.sma2): self.buy() elif crossover(self.sma2, self.sma1): self.position.close() bt = Backtest(GOOG, SmaCross, cash=10000, commission=.002) # Optimize parameters with grid search stats = bt.optimize( n1=range(5, 30, 5), n2=range(10, 70, 5), maximize='Sharpe Ratio', constraint=lambda param: param.n1 < param.n2 ) print(f"Best parameters: n1={stats._strategy.n1}, n2={stats._strategy.n2}") print(f"Best Sharpe Ratio: {stats['Sharpe Ratio']:.2f}") # Output: # Best parameters: n1=10, n2=40 # Best Sharpe Ratio: 0.72 ``` -------------------------------- ### Strategy Indicator Wrapper with self.I() in Python Source: https://context7.com/context7/kernc_github_io_backtesting_py_doc/llms.txt Demonstrates how to wrap custom indicator functions using the `self.I()` method within a backtesting.py Strategy class. This method automatically handles data alignment and caching, ensuring indicators are correctly integrated into the backtesting framework. The example shows a Relative Strength Index (RSI) indicator implementation. ```python from backtesting import Strategy import pandas as pd def RSI(series, period=14): delta = series.diff() gain = (delta.where(delta > 0, 0)).rolling(window=period).mean() loss = (-delta.where(delta < 0, 0)).rolling(window=period).mean() rs = gain / loss return 100 - (100 / (1 + rs)) class RsiStrategy(Strategy): rsi_period = 14 rsi_lower = 30 rsi_upper = 70 def init(self): # Wrap custom indicator with self.I() self.rsi = self.I(RSI, self.data.Close, self.rsi_period) def next(self): if self.rsi[-1] < self.rsi_lower: self.buy() elif self.rsi[-1] > self.rsi_upper: self.position.close() # Output: RSI indicator integrated and ready for backtesting ``` -------------------------------- ### Accessing and Analyzing Trade History in Python Source: https://context7.com/context7/kernc_github_io_backtesting_py_doc/llms.txt Explains how to access the detailed trade history generated by a backtest in backtesting.py. The `stats._trades` attribute provides a pandas DataFrame containing information for each executed trade, such as entry/exit points, prices, PnL, duration, and size. The example demonstrates filtering for profitable trades and identifying the trade with the highest return percentage. ```python from backtesting import Backtest, Strategy from backtesting.test import GOOG from backtesting.lib import SMA, crossover # Assuming SMA and crossover are available import pandas as pd # Import pandas for DataFrame operations # Define a dummy SmaCross strategy if not already defined class SmaCross(Strategy): n1 = 10 n2 = 20 def init(self): self.sma1 = self.I(SMA, self.data.Close, self.n1) self.sma2 = self.I(SMA, self.data.Close, self.n2) def next(self): if crossover(self.sma1, self.sma2): self.buy() elif crossover(self.sma2, self.sma1): self.position.close() bt = Backtest(GOOG, SmaCross, cash=10000, commission=.002) stats = bt.run() # Run the backtest first # Access trade list trades = stats._trades print("Full trade history:") print(trades) # Output DataFrame with columns: # EntryBar | ExitBar | EntryPrice | ExitPrice | PnL | ReturnPct | # EntryTime | ExitTime | Duration | Size | Tag # Filter profitable trades profitable = trades[trades['PnL'] > 0] print(f"\nProfitable trades: {len(profitable)}/{len(trades)}") if not profitable.empty: print(f"Avg profit: ${profitable['PnL'].mean():.2f}") else: print("No profitable trades found.") # Find best trade if not trades.empty: best_trade = trades.loc[trades['ReturnPct'].idxmax()] print(f"Best trade: {best_trade['ReturnPct']:.2%} return") else: print("No trades found to determine the best one.") ``` -------------------------------- ### Plotting Backtest Results Interactively in Python Source: https://context7.com/context7/kernc_github_io_backtesting_py_doc/llms.txt Details how to visualize backtesting results using the `bt.plot()` method in backtesting.py. This method generates an interactive plot (using Bokeh) that displays the equity curve, trades, indicators, and drawdowns. Various options are available to customize the plot's appearance and content, such as `plot_equity`, `plot_drawdown`, and `show_legend`. The example uses the `SmaCross` strategy. ```python from backtesting import Backtest, Strategy from backtesting.test import GOOG from backtesting.lib import crossover, SMA # Assuming SMA and crossover are available # Define a dummy SmaCross strategy if not already defined class SmaCross(Strategy): n1 = 10 n2 = 20 def init(self): self.sma1 = self.I(SMA, self.data.Close, self.n1) self.sma2 = self.I(SMA, self.data.Close, self.n2) def next(self): if crossover(self.sma1, self.sma2): self.buy() elif crossover(self.sma2, self.sma1): self.position.close() bt = Backtest(GOOG, SmaCross, cash=10000, commission=.002) stats = bt.run() # Run the backtest first # Generate interactive plot with all indicators and trades bt.plot( resample=False, # Don't resample data superimpose=True, # Superimpose smaller timeframes plot_width=None, # Auto width plot_equity=True, # Show equity curve plot_return=False, # Don't show return curve plot_pl=True, # Show profit/loss plot_volume=True, # Show volume bars plot_drawdown=True, # Show drawdown smooth_equity=False, # Don't smooth equity relative_equity=True, # Show relative equity omit_missing=True, # Omit missing data gaps show_legend=True, # Show legend open_browser=True # Auto-open in browser ) # Output: Interactive Bokeh plot opens in browser showing all backtest details ``` -------------------------------- ### Initialize Backtest with Data and Strategy (Python) Source: https://context7.com/context7/kernc_github_io_backtesting_py_doc/llms.txt Initializes the Backtest class with historical OHLC data and a custom strategy. Requires pandas for data handling. The output is a Backtest object configured for simulation. ```python from backtesting import Backtest, Strategy import pandas as pd # Load historical data with required columns: Open, High, Low, Close, Volume data = pd.read_csv('GOOG.csv', index_col=0, parse_dates=True) class SmaCross(Strategy): def init(self): pass def next(self): pass # Initialize backtest with data, strategy, commission, and initial cash bt = Backtest( data, SmaCross, cash=10000, commission=.002, # 0.2% per trade exclusive_orders=True, trade_on_close=False ) # Output: Backtest object ready to run ``` -------------------------------- ### Python Walk-Forward Optimization with Backtesting.py Source: https://context7.com/context7/kernc_github_io_backtesting_py_doc/llms.txt This Python script demonstrates a walk-forward optimization process. It defines a trading strategy (SmaCross), loads historical data, and then iteratively trains and tests the strategy on sequential periods of data. The script optimizes strategy parameters on a training set and evaluates their performance on a subsequent test set, collecting results to calculate average out-of-sample returns and Sharpe Ratios. ```python from backtesting import Backtest import pandas as pd from backtesting.lib import SMA, crossover class SmaCross(Strategy): n1 = 10 n2 = 20 def init(self): self.sma1 = self.I(SMA, self.data.Close, self.n1) self.sma2 = self.I(SMA, self.data.Close, self.n2) def next(self): if crossover(self.sma1, self.sma2): self.buy() elif crossover(self.sma2, self.sma1): self.position.close() # Load full dataset data = pd.read_csv('GOOG.csv', index_col=0, parse_dates=True) # Walk-forward parameters train_period = 252 # 1 year test_period = 63 # 3 months step = 63 # Move forward 3 months results = [] for i in range(0, len(data) - train_period - test_period, step): # Training period train_data = data.iloc[i:i+train_period] bt_train = Backtest(train_data, SmaCross, cash=10000) # Optimize on training data opt_stats = bt_train.optimize( n1=range(5, 30, 5), n2=range(10, 70, 5), maximize='Sharpe Ratio', constraint=lambda p: p.n1 < p.n2 ) # Test on out-of-sample data test_data = data.iloc[i+train_period:i+train_period+test_period] bt_test = Backtest(test_data, SmaCross, cash=10000) test_stats = bt_test.run( n1=opt_stats._strategy.n1, n2=opt_stats._strategy.n2 ) results.append({ 'period': test_data.index[0], 'return': test_stats['Return [%]'], 'sharpe': test_stats['Sharpe Ratio'] }) # Analyze walk-forward results wf_df = pd.DataFrame(results) print(f"Average OOS Return: {wf_df['return'].mean():.2f}%") print(f"Average OOS Sharpe: {wf_df['sharpe'].mean():.2f}") ``` -------------------------------- ### backtesting.lib Module Source: https://kernc.github.io/backtesting.py/doc/index Collection of common building blocks, helper auxiliary functions and composable strategy classes for reuse. ```APIDOC ## Module: backtesting.lib ### Description Collection of common building blocks, helper auxiliary functions and composable strategy classes for reuse. ``` -------------------------------- ### Manage Positions with Custom Exit Rules Source: https://context7.com/context7/kernc_github_io_backtesting_py_doc/llms.txt This strategy showcases how to access and manage current position states, including entry price, P&L, and size. It implements manual stop-loss and take-profit orders based on predefined percentages of the entry price. Requires the 'backtesting' library. ```python from backtesting import Strategy from backtesting.test import SMA class PositionManagement(Strategy): stop_loss_pct = 0.05 take_profit_pct = 0.15 def init(self): self.sma = self.I(SMA, self.data.Close, 20) def next(self): price = self.data.Close[-1] # Check if we have a position if self.position: # Access position properties entry_price = self.position.pl # Entry price current_pl = self.position.pl_pct # Current P&L percentage position_size = self.position.size # Number of shares is_long = self.position.is_long is_short = self.position.is_short # Manual stop loss if is_long and price < entry_price * (1 - self.stop_loss_pct): self.position.close() # Manual take profit elif is_long and price > entry_price * (1 + self.take_profit_pct): self.position.close() # Entry logic else: if price > self.sma[-1]: self.buy() # Output: Position actively managed with custom exit rules ``` -------------------------------- ### backtesting.test Module Source: https://kernc.github.io/backtesting.py/doc/index Data and utilities for testing. ```APIDOC ## Module: backtesting.test ### Description Data and utilities for testing. ``` -------------------------------- ### Utilize Library Helpers for Crossovers and Trailing Stops Source: https://context7.com/context7/kernc_github_io_backtesting_py_doc/llms.txt This snippet demonstrates the use of utility functions from `backtesting.lib`, such as `crossover` and `cross` for detecting indicator crossovers, and `TrailingStrategy` for built-in trailing stop-loss functionality. It requires the 'backtesting' library and its test data. ```python from backtesting.lib import crossover, cross, TrailingStrategy from backtesting.test import SMA, GOOG from backtesting import Backtest # Assume 'close' and 'buy', 'position' are available in the strategy context # For demonstration, defining dummy versions: def SMA(series, n): return series.rolling(n).mean() def crossover(arr1, arr2): return arr1 > arr2 and arr1.shift(1) <= arr2.shift(1) def cross(arr1, arr2): return (arr1 > arr2) != (arr1.shift(1) > arr2.shift(1)) class DummyPosition: def close(self): pass position = DummyPosition() def buy(): pass # Crossover detection # In a real Strategy class, 'close' would be self.data.Close close = GOOG['Close'] def strategy_logic(): fast = SMA(close, 10) slow = SMA(close, 20) # Check if fast crossed above slow if crossover(fast, slow): buy() # Check if either line crossed the other if cross(fast, slow): position.close() # Using composable TrailingStrategy class MyTrailing(TrailingStrategy): n1 = 10 n2 = 20 def init(self): super().init() self.sma1 = self.I(SMA, self.data.Close, self.n1) self.sma2 = self.I(SMA, self.data.Close, self.n2) def next(self): super().next() # Handles trailing stops if crossover(self.sma1, self.sma2): self.buy() bt = Backtest(GOOG, MyTrailing, cash=10000) stats = bt.run() # Output: Strategy with built-in trailing stop functionality ``` -------------------------------- ### Prepare and Validate Data for Backtesting Source: https://context7.com/context7/kernc_github_io_backtesting_py_doc/llms.txt This code prepares and validates input data for backtesting, ensuring it adheres to the required OHLCV (Open, High, Low, Close, Volume) format with a datetime index. It includes checks for data integrity, such as sorted index, no missing values, and valid price relationships. Requires 'pandas' and 'backtesting' libraries. ```python import pandas as pd from backtesting import Backtest, Strategy from backtesting.test import SMA, GOOG # Example data and indicator # For demonstration purposes, using GOOG data directly df = GOOG.copy() # Ensure the DataFrame has the expected columns and index format # Assuming df already has 'Open', 'High', 'Low', 'Close', 'Volume' and a DatetimeIndex # Validate data assert df.index.is_monotonic_increasing, "Index must be sorted ascending" assert not df.isnull().any().any(), "No missing values allowed" assert (df['High'] >= df['Low']).all(), "High must be >= Low" assert (df['High'] >= df['Open']).all(), "High must be >= Open" assert (df['High'] >= df['Close']).all(), "High must be >= Close" assert (df['Low'] <= df['Open']).all(), "Low must be <= Open" assert (df['Low'] <= df['Close']).all(), "Low must be <= Close" # Define a dummy strategy for backtesting class SmaCross(Strategy): n1, n2 = 10, 20 def init(self): close = self.data.Close self.sma1 = self.I(SMA, close, self.n1) self.sma2 = self.I(SMA, close, self.n2) def next(self): if crossover(self.sma1, self.sma2): self.buy() elif self.sma2 > self.sma1: self.position.close() # Now ready for backtesting bt = Backtest(df, SmaCross, cash=10000) stats = bt.run() # Output: Clean, validated data ready for accurate backtesting ``` -------------------------------- ### backtesting.backtesting Module Source: https://kernc.github.io/backtesting.py/doc/index Core framework data structures. Objects from this module can also be imported from the top-level module directly. ```APIDOC ## Module: backtesting.backtesting ### Description Core framework data structures. Objects from this module can also be imported from the top-level module directly. ``` -------------------------------- ### Python Multiprocessing Pool for Backtesting Source: https://kernc.github.io/backtesting.py/doc/index Demonstrates the use of Python's multiprocessing Pool for parallelizing backtesting tasks. This function allows specifying the number of processes, an initializer function, and arguments for the initializer. It is part of the core framework. ```python from backtesting.backtesting import Pool # Example usage: # pool = Pool(processes=4) # results = pool.map(some_backtest_function, data) ``` -------------------------------- ### Combine Multiple Timeframes in Strategy Source: https://context7.com/context7/kernc_github_io_backtesting_py_doc/llms.txt This strategy demonstrates how to access and combine indicators from different timeframes (e.g., daily and weekly) within a single strategy using `resample_apply`. It ensures trades are executed only when conditions align across both timeframes. Requires the 'backtesting' library. ```python from backtesting import Strategy from backtesting.lib import resample_apply from backtesting.test import SMA class MultiTimeframe(Strategy): def init(self): # Daily indicators on primary timeframe self.sma_daily = self.I(SMA, self.data.Close, 20) # Weekly indicators using resampling def weekly_sma(series): return SMA(series, 10) self.sma_weekly = resample_apply( 'W', # Weekly timeframe weekly_sma, self.data.Close ) def next(self): # Trade only when both timeframes align if (self.data.Close[-1] > self.sma_daily[-1] and self.data.Close[-1] > self.sma_weekly[-1]): if not self.position: self.buy() elif (self.data.Close[-1] < self.sma_daily[-1] or self.data.Close[-1] < self.sma_weekly[-1]): if self.position: self.position.close() # Output: Strategy trades based on multiple timeframe confirmation ``` -------------------------------- ### Pool Function Source: https://kernc.github.io/backtesting.py/doc/index Creates a pool of worker processes for parallel execution. ```APIDOC ## Function: Pool ### Description Backtesting.py's Pool function allows for parallel execution of tasks using multiple processes. It is designed to enhance performance by distributing computational load. ### Method `Pool(processes=None, initializer=None, initargs=())` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from multiprocessing import Pool # Example usage (not a direct API call, but demonstrates function signature) with Pool(processes=4) as p: # perform some operations pass ``` ### Response #### Success Response (200) This function does not return a value in the typical HTTP response sense. It returns a `multiprocessing.Pool` object that manages worker processes. #### Response Example ```json { "message": "Pool object created successfully" } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.