Certainly! The code you've provided is a great starting point for an EMA crossover backtesting application using Streamlit. However, there are a few issues that need to be addressed to ensure accurate performance metrics:
-
Total Return Calculation: The total return is calculated by summing the per-trade returns, which is incorrect. Total return should be calculated as the compounded return over all trades.
-
Sharpe Ratio Calculation: The Sharpe ratio is calculated using the stock's returns instead of the strategy's returns, which does not accurately reflect the strategy's risk-adjusted performance.
-
Max Drawdown Calculation: The max drawdown is calculated as the worst drawdown per trade, but it should reflect the maximum drawdown over the entire backtesting period.
-
Position Tracking: The strategy's position (in or out of the market) isn't accurately tracked over time, making it difficult to calculate per-period returns.
Below is the corrected code with detailed explanations for each fix:
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
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)
# 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'}
data = yf.download(ticker, start=start_date, end=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)
data['Signal'] = data['Position'].diff()
# Generate trading signals
data['Signal'] = data['Signal'].fillna(0)
# Corrected Position Tracking
data['Strategy_Position'] = data['Position'].shift(1).fillna(0)
# Calculate returns
data['Market_Return'] = data['Close'].pct_change()
data['Strategy_Return'] = data['Market_Return'] * data['Strategy_Position']
# Calculate cumulative returns
data['Strategy_Cumulative_Return'] = (1 + data['Strategy_Return']).cumprod()
data['Market_Cumulative_Return'] = (1 + data['Market_Return']).cumprod()
# Calculate performance metrics
total_return = data['Strategy_Cumulative_Return'].iloc[-1] - 1
buy_and_hold_return = data['Market_Cumulative_Return'].iloc[-1] - 1
# 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
# Calculate Sharpe Ratio using strategy returns
average_return = data['Strategy_Return'].mean()
std_return = data['Strategy_Return'].std()
sharpe_ratio = (average_return / std_return) * annualization_factor
# Calculate Buy and Hold Sharpe Ratio
bh_average_return = data['Market_Return'].mean()
bh_std_return = data['Market_Return'].std()
buy_and_hold_sharpe = (bh_average_return / bh_std_return) * annualization_factor
# Calculate max drawdown for the strategy
data['Strategy_Cum_Max'] = data['Strategy_Cumulative_Return'].cummax()
data['Strategy_Drawdown'] = (data['Strategy_Cumulative_Return'] - data['Strategy_Cum_Max']) / data['Strategy_Cum_Max']
max_drawdown_overall = data['Strategy_Drawdown'].min() * 100 # As a percentage
# Max drawdown for Buy and Hold
data['Market_Cum_Max'] = data['Market_Cumulative_Return'].cummax()
data['Market_Drawdown'] = (data['Market_Cumulative_Return'] - data['Market_Cum_Max']) / data['Market_Cum_Max']
buy_and_hold_max_drawdown = data['Market_Drawdown'].min() * 100
# Win Rate Calculation
trade_entries = data[data['Signal'] == 1].index
trade_exits = data[data['Signal'] == -1].index
# Ensure entries and exits are aligned
if len(trade_exits) < len(trade_entries):
trade_exits = trade_exits.append(pd.Index([data.index[-1]]))
trades = pd.DataFrame({
'Entry Time': trade_entries,
'Exit Time': trade_exits,
})
trades['Entry Price'] = data.loc[trades['Entry Time'], 'Close'].values
trades['Exit Price'] = data.loc[trades['Exit Time'], 'Close'].values
trades['Return'] = (trades['Exit Price'] - trades['Entry Price']) / trades['Entry Price']
trades['Return (%)'] = trades['Return'] * 100
win_rate = len(trades[trades['Return'] > 0]) / len(trades) if len(trades) > 0 else 0
# 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),
mpf.make_addplot(data_for_plot['EMA_long'], color='red', width=1),
mpf.make_addplot(data_for_plot['Buy_Signal_Price'], type='scatter', markersize=100, marker='^', color='blue'),
mpf.make_addplot(data_for_plot['Sell_Signal_Price'], type='scatter', markersize=100, marker='v', color='purple')
]
# 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
st.subheader('Trade Logs')
st.dataframe(trades)
Explanation of Corrections:
-
Corrected Total Return Calculation:
-
Corrected Sharpe Ratio Calculation:
-
Corrected Max Drawdown Calculation:
-
Corrected Position Tracking:
-
Win Rate Calculation:
Conclusion:
By making these corrections, the application's performance metrics will accurately reflect the EMA crossover strategy's performance compared to a buy-and-hold approach. The strategy's returns, Sharpe ratio, and max drawdown are now based on the correct calculations, providing more reliable insights into the strategy's effectiveness.