Thank you for sharing your Streamlit EMA Crossover Backtesting Application code. After reviewing it, I've identified several issues that need to be addressed to ensure accurate backtesting results and robust functionality. Below are the identified issues along with their explanations and the corresponding fixes applied to the code.
Identified Issues and Fixes
-
Incorrect Calculation of Total Return:
- Issue: The total return of the EMA crossover strategy is calculated by simply summing individual trade returns. This approach doesn't account for the compounding effect of consecutive trades.
- Fix: Calculate the total return by compounding the individual trade returns. This provides a more accurate representation of the strategy's performance over time.
-
Incorrect Sharpe Ratio Calculation:
- Issue: The Sharpe ratio is computed using the underlying asset's returns instead of the strategy's returns. This misrepresents the risk-adjusted performance of the strategy.
- Fix: Calculate the Sharpe ratio based on the strategy's returns. This involves computing the strategy's periodic returns and then applying the Sharpe ratio formula.
-
Lack of Validation for EMA Periods:
- Issue: Users can input a short EMA period that is greater than or equal to the long EMA period, which can lead to erroneous signals and meaningless strategies.
- Fix: Add validation to ensure that the short EMA period is less than the long EMA period. If not, display an error message prompting the user to adjust the input.
-
Buy and Hold Win Rate Misinterpretation:
- Issue: The win rate for the buy-and-hold strategy is calculated based on a single trade, making it either 100% or 0%, which isn't particularly informative.
- Fix: Remove or clarify the win rate metric for the buy-and-hold strategy to avoid confusion. It's more meaningful to compare total returns and Sharpe ratios.
-
Strategy Returns Calculation:
- Issue: The strategy's returns are not explicitly calculated based on the positions taken during each period.
- Fix: Introduce a strategy returns calculation by multiplying the asset's periodic returns by the strategy's positions. This allows for accurate performance metrics.
-
Handling of Intraday Data End Dates:
- Issue: When fetching intraday data (e.g., 1h intervals), the
end_date might not be inclusive, potentially leading to missing the last data point.
- Fix: Adjust the
end_date by adding one day to ensure inclusivity of the end date for intraday intervals.
-
Plotting Adjustments:
- Issue: The legend might not display all necessary elements clearly.
- Fix: Ensure that all plot elements are included in the legend for clarity.
Revised Code with Fixes Applied
Below is the revised code incorporating all the fixes mentioned above. I've also added comments to highlight the changes and provide additional context.
import streamlit as st
import yfinance as yf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime, timedelta
import warnings
import mplfinance as mpf
warnings.filterwarnings('ignore')
# Streamlit frontend
st.title('EMA Crossover Backtesting Application')
# User inputs
ticker = st.text_input('Enter Stock Ticker (e.g., AAPL):', 'AAPL')
interval_options = ['1h', '1d', '1wk', '1mo']
interval = st.selectbox('Select Candle Interval:', interval_options, index=1)
ema_short = st.number_input('Short EMA Period:', min_value=1, value=12)
ema_long = st.number_input('Long EMA Period:', min_value=2, value=26)
# Validation to ensure that Short EMA < Long EMA
if ema_short >= ema_long:
st.error('Short EMA period must be less than Long EMA period.')
st.stop()
# Set default start and end dates
default_start_date = datetime(2020, 1, 1)
default_end_date = datetime.today()
start_date = st.date_input('Start Date:', value=default_start_date, min_value=datetime(2000, 1, 1), max_value=default_end_date)
end_date = st.date_input('End Date:', value=default_end_date, min_value=start_date, max_value=default_end_date)
if st.button('Run Backtest'):
# Map interval to yfinance valid intervals
interval_mapping = {'1h': '1h', '1d': '1d', '1wk': '1wk', '1mo': '1mo'}
# Adjust end_date for intraday data to include the last day
if interval == '1h':
adjusted_end_date = end_date + timedelta(days=1)
else:
adjusted_end_date = end_date
data = yf.download(ticker, start=start_date, end=adjusted_end_date, interval=interval_mapping[interval])
if data.empty:
st.error('No data found. Please adjust your inputs.')
st.stop()
# Calculate EMAs
data['EMA_short'] = data['Close'].ewm(span=ema_short, adjust=False).mean()
data['EMA_long'] = data['Close'].ewm(span=ema_long, adjust=False).mean()
# Implement the EMA crossover strategy
data['Position'] = np.where(data['EMA_short'] > data['EMA_long'], 1, 0)
# Generate trading signals
data['Signal'] = data['Position'].diff()
# Initialize lists to store trade entries and exits
trade_entries = []
trade_exits = []
entry_price = []
exit_price = []
drawdowns = []
in_position = False
entry_index = None
for i in range(len(data)):
if data['Signal'].iloc[i] == 1: # Buy signal
if not in_position:
in_position = True
trade_entries.append(data.index[i])
entry_price.append(data['Close'].iloc[i])
entry_index = i
elif data['Signal'].iloc[i] == -1: # Sell signal
if in_position:
in_position = False
trade_exits.append(data.index[i])
exit_price.append(data['Close'].iloc[i])
# Calculate drawdown during the trade
trade_data = data['Close'].iloc[entry_index:i+1]
trough_price = trade_data.min()
drawdown = (trough_price - entry_price[-1]) / entry_price[-1]
drawdowns.append(drawdown)
# Handle the case where we are still in position at the end
if in_position:
trade_exits.append(data.index[-1])
exit_price.append(data['Close'].iloc[-1])
# Calculate drawdown during the trade
trade_data = data['Close'].iloc[entry_index:]
trough_price = trade_data.min()
drawdown = (trough_price - entry_price[-1]) / entry_price[-1]
drawdowns.append(drawdown)
# Prepare a DataFrame with trade details
trades = pd.DataFrame({
'Entry Time': trade_entries,
'Exit Time': trade_exits,
'Entry Price': entry_price,
'Exit Price': exit_price,
'Drawdown': drawdowns
})
# Calculate returns per trade
trades['Return'] = (trades['Exit Price'] - trades['Entry Price']) / trades['Entry Price']
trades['Return (%)'] = trades['Return'] * 100
# Calculate compounded total return of the strategy
total_return = (1 + trades['Return']).prod() - 1
# Calculate win rate
win_rate = len(trades[trades['Return'] > 0]) / len(trades) if len(trades) > 0 else 0
# Calculate strategy returns for Sharpe ratio
data['Strategy_Return'] = data['Position'].shift(1) * data['Close'].pct_change()
strategy_return = data['Strategy_Return'].dropna()
# Calculate Sharpe ratio for the strategy
average_return = strategy_return.mean()
std_return = strategy_return.std()
# Annualization factors based on interval
if interval == '1d':
annualization_factor = np.sqrt(252) # Trading days in a year
elif interval == '1wk':
annualization_factor = np.sqrt(52) # Trading weeks in a year
elif interval == '1mo':
annualization_factor = np.sqrt(12) # Trading months in a year
elif interval == '1h':
annualization_factor = np.sqrt(252 * 6.5) # Trading hours in a year (assuming 6.5 hours per trading day)
if std_return != 0:
sharpe_ratio = (average_return / std_return) * annualization_factor
else:
sharpe_ratio = np.nan # Avoid division by zero
# Calculate max drawdown
cumulative_return = (1 + strategy_return).cumprod()
running_max = cumulative_return.cummax()
drawdown = (cumulative_return - running_max) / running_max
max_drawdown_overall = drawdown.min() * 100 # As a percentage
# Buy and Hold Strategy Metrics
buy_and_hold_return = (data['Close'].iloc[-1] / data['Close'].iloc[0]) - 1
# Calculate max drawdown for buy and hold
rolling_max = data['Close'].cummax()
daily_drawdown = (data['Close'] - rolling_max) / rolling_max
buy_and_hold_max_drawdown = daily_drawdown.min() * 100
# Calculate Sharpe ratio for buy and hold using asset returns
asset_returns = data['Close'].pct_change().dropna()
average_asset_return = asset_returns.mean()
std_asset_return = asset_returns.std()
if std_asset_return != 0:
buy_and_hold_sharpe = (average_asset_return / std_asset_return) * annualization_factor
else:
buy_and_hold_sharpe = np.nan # Avoid division by zero
# Prepare data for mplfinance
data_for_plot = data.copy()
data_for_plot.index.name = 'Date'
# Create signal columns with NaNs
data_for_plot['Buy_Signal_Price'] = np.nan
data_for_plot['Sell_Signal_Price'] = np.nan
data_for_plot.loc[data['Signal'] == 1, 'Buy_Signal_Price'] = data_for_plot['Close']
data_for_plot.loc[data['Signal'] == -1, 'Sell_Signal_Price'] = data_for_plot['Close']
# Create additional plots for EMA and signals
apds = [
mpf.make_addplot(data_for_plot['EMA_short'], color='green', width=1, label='Short EMA'),
mpf.make_addplot(data_for_plot['EMA_long'], color='red', width=1, label='Long EMA'),
mpf.make_addplot(data_for_plot['Buy_Signal_Price'], type='scatter', markersize=100, marker='^', color='blue', label='Buy Signal'),
mpf.make_addplot(data_for_plot['Sell_Signal_Price'], type='scatter', markersize=100, marker='v', color='purple', label='Sell Signal')
]
# Plot candlestick chart
fig, axlist = mpf.plot(
data_for_plot,
type='candle',
addplot=apds,
returnfig=True,
title=f'{ticker} EMA Crossover Strategy',
style='yahoo',
volume=True
)
# Add legend manually
ax = axlist[0] # Get the main axis
ax.plot([], [], color='green', label='Short EMA')
ax.plot([], [], color='red', label='Long EMA')
ax.scatter([], [], color='blue', marker='^', label='Buy Signal')
ax.scatter([], [], color='purple', marker='v', label='Sell Signal')
ax.legend()
# Display the plot in Streamlit
st.pyplot(fig)
# Display performance metrics for EMA strategy
st.subheader('EMA Crossover Strategy Performance Metrics')
st.write(f"Total Strategy Return: {total_return * 100:.2f}%")
st.write(f"Win Rate: {win_rate * 100:.2f}%")
st.write(f"Sharpe Ratio: {sharpe_ratio:.2f}")
st.write(f"Max Drawdown: {max_drawdown_overall:.2f}%")
# Display performance metrics for Buy and Hold strategy
st.subheader('Buy and Hold Strategy Performance Metrics')
st.write(f"Total Return: {buy_and_hold_return * 100:.2f}%")
st.write(f"Sharpe Ratio: {buy_and_hold_sharpe:.2f}")
st.write(f"Max Drawdown: {buy_and_hold_max_drawdown:.2f}%")
# Display trade logs
if not trades.empty:
st.subheader('Trade Logs')
st.dataframe(trades)
else:
st.write("No trades were executed based on the given strategy and parameters.")
Summary of Changes
-
Validation for EMA Periods:
- Added a check to ensure that the short EMA period is less than the long EMA period. If not, an error message is displayed, and the backtest is halted.
if ema_short >= ema_long:
st.error('Short EMA period must be less than Long EMA period.')
st.stop()
-
Adjusted end_date for Intraday Data:
- For intraday intervals (e.g., '1h'), incremented the
end_date by one day to ensure that the last day's data is included.
if interval == '1h':
adjusted_end_date = end_date + timedelta(days=1)
else:
adjusted_end_date = end_date
-
Modified Positioning Logic:
- Changed the
Position to be either 1 (long) or 0 (no position) instead of 1 or -1. This simplification avoids handling short positions and makes the strategy easier to interpret.
data['Position'] = np.where(data['EMA_short'] > data['EMA_long'], 1, 0)
-
Updated Signal Generation:
- Adjusted the signal generation to reflect the new positioning logic (
1 for buy and -1 for sell).
data['Signal'] = data['Position'].diff()
-
Accurate Total Return Calculation:
- Calculated the total return by compounding individual trade returns instead of summing them.
total_return = (1 + trades['Return']).prod() - 1
-
Correct Sharpe Ratio Calculation:
- Calculated the Sharpe ratio based on the strategy's returns instead of the asset's returns.
data['Strategy_Return'] = data['Position'].shift(1) * data['Close'].pct_change()
strategy_return = data['Strategy_Return'].dropna()
average_return = strategy_return.mean()
std_return = strategy_return.std()
sharpe_ratio = (average_return / std_return) * annualization_factor if std_return != 0 else np.nan
-
Removed Buy and Hold Win Rate:
- Removed the win rate calculation for the buy-and-hold strategy as it isn't meaningful with a single position.
- Alternatively, you can keep it for informational purposes, but it's generally not useful.
Additional Recommendations
-
Risk-Free Rate for Sharpe Ratio:
- Currently, the Sharpe ratio assumes a risk-free rate of 0. For more accurate calculations, consider allowing users to input a risk-free rate.
-
Extended Strategy Features:
- Implement features like stop-loss, take-profit, or position sizing to make the backtest more comprehensive.
-
Performance Visualization:
- Include equity curves for both the strategy and the buy-and-hold approach to provide visual insights into performance over time.
-
Error Handling for Data Fetching:
- Enhance error handling when fetching data to account for scenarios like trading halts, data unavailability for certain intervals, or API rate limits.
By addressing the identified issues and implementing the above fixes, your EMA Crossover Backtesting Application will provide more accurate and reliable performance metrics, ensuring that users can make informed decisions based on the backtest results.