total_profits = []
for i in range(30):
results_df = backtest_strategy(df.copy(), risk_percentage=1)
total_profits.append(results_df["Profit"].sum())
print("Mean total profit: ", np.array(total_profits).mean())
print("Std total profit: ", np.array(total_profits).std())
I made some statistical analysis, and on the data I should have a 76% of take profits and 24% of stop losses, and with a 1:4 ratio I should be profitable. Improve the logic of this code, because with the current backtests I don't see results aligned with the statistical analysis.
It seems that the discrepancies between your backtest results and your statistical expectations stem from a few key issues in your code:
Position Sizing Calculation: The way you're calculating position_size doesn't consider your capital, which is essential for proper risk management.
Profit Calculation and Capital Update: The profit or loss per trade isn't being calculated correctly relative to the position_size, leading to inaccurate capital updates.
Trade Entry Logic: Randomly entering trades doesn't guarantee the 76% take profit and 24% stop loss ratio you've anticipated from your statistical analysis.
Price Level Checks: Using the Close price to check for stop loss and take profit breaches can miss intraday price movements where the stop loss or take profit levels were actually hit.
Iteration Over Open Trades: Modifying a list while iterating over it can lead to unexpected behavior or errors.
Let's address each of these issues step by step and improve your code accordingly.
1. Correcting Position Sizing Calculation
In trading, position sizing based on risk is calculated using the formula:
# Calculate risk per unit (risk per share/contract)
risk_per_unit = entry_price - stop_loss_price
# Calculate position size based on risk per trade
position_size = (capital * risk_percentage) / risk_per_unit
Make sure you convert your risk_percentage to a decimal (e.g., 0.02 for 2% risk per trade).
2. Correcting Profit Calculation and Capital Update
When closing a trade, the profit or loss should be calculated based on the difference between the exit price and the entry price, multiplied by the position size:
python
profit = (exit_price - trade["Entry Price"]) * trade["Position Size"]
capital += profit # Update capital with profit or loss from the trade
This accurately reflects the monetary gain or loss from each trade.
3. Improving Trade Entry Logic
Random trade entries won't align with your statistical analysis which assumes a 76% win rate. To achieve results that reflect your statistical expectations, you need to implement a strategy that historically delivers such a win rate.
However, if you want to proceed with random entries, you can accept that the win rate might not match your expectations. Alternatively, you can design specific entry conditions based on technical indicators or patterns identified in your statistical analysis.
4. Using High and Low Prices for Stop Loss and Take Profit Checks
Using the High and Low prices allows you to check if the price levels were breached at any point during the period, not just at the close. Here's how you can adjust your code:
python
# Check for stop loss hit
if df["Low"].iloc[i] <= trade["Stop Loss"]:
exit_price = trade["Stop Loss"]
# Close the trade with stop loss
# Check for take profit hit
elif df["High"].iloc[i] >= trade["Take Profit"]:
exit_price = trade["Take Profit"]
# Close the trade with take profit
5. Safely Iterating Over and Modifying Open Trades
When you're iterating over open_trades, you shouldn't modify the list within the loop. To handle this safely, you can collect trades that need to be closed and remove them after the iteration:
python
closed_trades = []
for trade in open_trades:
# ... check conditions ...
if exit_condition_met:
closed_trades.append(trade)
# Remove closed trades after the loop
for trade in closed_trades:
open_trades.remove(trade)
Revised Code
Here’s the improved version of your backtesting function incorporating all the corrections:
python
def backtest_strategy(df, risk_percentage):
"""
Backtests the described trading strategy.
Args:
df: DataFrame containing price data and calculated indicators.
risk_percentage: Percentage of capital to risk on each trade (e.g., 0.02 for 2%).
Returns:
pandas.DataFrame: DataFrame with backtesting results including trade details.
"""
# Initialize variables
initial_capital = 10000 # Starting capital
capital = initial_capital
open_trades = []
trade_history = []
# Iterate through each row (bar) of the DataFrame
for i in range(len(df)):
# Randomly decide if opening a new trade (simulating random entry)
if np.random.rand() < 0.10: # Adjust probability for trade frequency
# Calculate position size based on risk and ATR
entry_price = df["Close"].iloc[i]
stop_loss_price = np.exp(df["-1ATR"].iloc[i])
take_profit_price = np.exp(df["+4ATR"].iloc[i])
# Ensure stop_loss_price is less than entry_price
if stop_loss_price >= entry_price:
continue # Skip this trade, invalid stop loss
risk_per_unit = entry_price - stop_loss_price
# Calculate position size based on risk per trade
position_size = (capital * risk_percentage) / risk_per_unit
# Check if position_size is feasible
if position_size <= 0:
continue # Skip this trade, invalid position size
# Open the trade and store details
open_trades.append(
{
"Entry Time": df.index[i],
"Entry Price": entry_price,
"Position Size": position_size,
"Stop Loss": stop_loss_price,
"Take Profit": take_profit_price,
"Open Index": i,
}
)
# Check for open trades and process exits
closed_trades = []
for trade in open_trades:
# Initialize exit price
exit_price = None
# Check for stop loss hit
if df["Low"].iloc[i] <= trade["Stop Loss"]:
exit_price = trade["Stop Loss"]
# Check for take profit hit
elif df["High"].iloc[i] >= trade["Take Profit"]:
exit_price = trade["Take Profit"]
# If exit price is determined, close the trade
if exit_price is not None:
profit = (exit_price - trade["Entry Price"]) * trade["Position Size"]
capital += profit
trade["Exit Time"] = df.index[i]
trade["Exit Price"] = exit_price
trade["Profit"] = profit
trade_history.append(trade)
closed_trades.append(trade)
# Remove closed trades from open_trades
for trade in closed_trades:
open_trades.remove(trade)
# Create a DataFrame from the trade history
trade_df = pd.DataFrame(trade_history)
return trade_df
Testing the Revised Code
Now, run your backtesting function with a sensible risk_percentage, such as 2%:
Repeat the backtest multiple times to get average results:
python
total_profits = []
for i in range(30):
results_df = backtest_strategy(df.copy(), risk_percentage=0.02)
total_profits.append(results_df["Profit"].sum())
print("Mean total profit: ", np.array(total_profits).mean())
print("Std total profit: ", np.array(total_profits).std())
Analyzing the Results
After correcting the calculations, you should find that:
The profit and loss per trade are now accurately reflected in your capital.
The position sizes are appropriate relative to your capital and risk per trade.
The statistical distribution of winning and losing trades is more accurate.
If you still don't see a 76% win rate, it's likely due to the random trade entries not aligning with the conditions from your statistical analysis. To fix this, consider implementing specific trade entry signals that historically result in a 76% chance of hitting your take profit before your stop loss.
Implementing Specific Trade Entry Conditions
You can use technical indicators or patterns that you've identified in your statistical analysis. For example, you might look for:
Breakouts: Enter trades when the price breaks above a resistance level or below a support level.
Trend Indicators: Use moving averages to identify trend direction and enter trades in the direction of the trend.
Volatility Contractions: Enter trades when the ATR decreases, anticipating a volatility expansion.
Example of incorporating a simple moving average crossover for trade entries:
python
# Calculate moving averages
df['MA10'] = df['Close'].rolling(window=10).mean()
df['MA20'] = df['Close'].rolling(window=20).mean()
# In your backtesting function, replace the random entry with a condition
if df['MA10'].iloc[i] > df['MA20'].iloc[i] and df['MA10'].iloc[i - 1] <= df['MA20'].iloc[i - 1]:
# Enter long trade
Conclusion
By correcting the calculations and potentially implementing specific trade entry conditions, your backtest results should better align with your statistical expectations. Remember that backtesting results can still vary due to market randomness, so it's beneficial to test over multiple periods and different market conditions.