Sure! I'd be happy to help you create a Python program that backtests an EMA crossover strategy against a buy-and-hold strategy. We'll use yfinance for data retrieval, pandas for data manipulation, matplotlib for plotting, and Streamlit for the frontend.
Here's how we'll proceed:
- Set up the Streamlit frontend to collect user inputs.
- Retrieve historical data from Yahoo Finance using
yfinance.
- Calculate EMAs based on user inputs and the selected interval.
- Implement the EMA crossover strategy.
- Backtest the strategy and collect trade information.
- Calculate performance metrics: total return, Sharpe ratio, win rate, and max drawdown.
- Visualize the results using candlestick charts and mark buy/sell signals.
- Display trade logs under the chart.
Let's start step by step.
1. Set Up the Streamlit Frontend
First, ensure you have Streamlit installed:
pip install streamlit
Now, create a Python script, say ema_backtester.py, and begin by importing necessary libraries and setting up the Streamlit interface.
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 matplotlib.dates as mdates
from matplotlib import style
import warnings
warnings.filterwarnings('ignore')
style.use('ggplot')
# 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)
start_date = st.date_input('Start Date:', datetime(2010, 1, 1))
end_date = st.date_input('End Date:', datetime.today())
2. Retrieve Historical Data
Based on the user inputs, retrieve the historical data using yfinance.
# 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()
3. Calculate EMAs
Calculate EMAs based on the selected interval. The EMA periods should be adjusted appropriately.
# 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()
4. Implement the EMA Crossover Strategy
Implement the trading logic: buy when the short EMA crosses above the long EMA and sell when it crosses below.
# Implement the EMA crossover strategy
data['Position'] = 0 # Default position is neutral (0)
data['Position'] = np.where(data['EMA_short'] > data['EMA_long'], 1, -1)
# Generate trading signals
data['Signal'] = data['Position'].diff()
5. Backtest the Strategy and Collect Trades
Identify the points where signals occur and record the trades.
# Initialize lists to store trade entries and exits
trade_entries = []
trade_exits = []
entry_price = []
exit_price = []
drawdowns = []
in_position = False
peak_price = 0
max_drawdown = 0
for i in range(len(data)):
if data['Signal'].iloc[i] == 2: # Buy signal
if not in_position:
in_position = True
trade_entries.append(data.index[i])
entry_price.append(data['Close'].iloc[i])
peak_price = data['Close'].iloc[i]
max_drawdown = 0
elif data['Signal'].iloc[i] == -2: # Sell signal
if in_position:
in_position = False
trade_exits.append(data.index[i])
exit_price.append(data['Close'].iloc[i])
drawdowns.append(max_drawdown)
elif in_position:
# Update peak price and calculate drawdown
price = data['Close'].iloc[i]
peak_price = max(peak_price, price)
drawdown = (price - peak_price) / peak_price
max_drawdown = min(max_drawdown, 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])
drawdowns.append(max_drawdown)
6. Calculate Performance Metrics
Now calculate the total return, Sharpe ratio, win rate, and max 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 total return
total_return = trades['Return'].sum()
# Calculate win rate
win_rate = len(trades[trades['Return'] > 0]) / len(trades) if len(trades) > 0 else 0
# Calculate Sharpe ratio
daily_returns = data['Close'].pct_change().dropna()
sharpe_ratio = (daily_returns.mean() / daily_returns.std()) * np.sqrt(252)
# Calculate max drawdown
max_drawdown_overall = trades['Drawdown'].min() * 100 # As a percentage
7. Visualize the Results
Plot the candlestick chart with buy/sell signals.
import mplfinance as mpf
# Prepare data for mplfinance
data_for_plot = data.copy()
data_for_plot.index.name = 'Date'
# Mark buy and sell signals
buy_signals = data_for_plot[data['Signal'] == 2]
sell_signals = data_for_plot[data['Signal'] == -2]
# Create additional plots for EMA and signals
apds = [
mpf.make_addplot(data['EMA_short'], color='green'),
mpf.make_addplot(data['EMA_long'], color='red'),
mpf.make_addplot(buy_signals['Close'], type='scatter', markersize=100, marker='^', color='blue'),
mpf.make_addplot(sell_signals['Close'], 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)
# Display the plot in Streamlit
st.pyplot(fig)
8. Display Performance Metrics and Trade Logs
# Display performance metrics
st.subheader('Performance Metrics')
st.write(f"Total 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 trade logs
st.subheader('Trade Logs')
st.dataframe(trades)
Complete Code
Putting it all together, here's the complete script:
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)
start_date = st.date_input('Start Date:', datetime(2010, 1, 1))
end_date = st.date_input('End Date:', datetime.today())
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'] = 0 # Default position is neutral (0)
data['Position'] = np.where(data['EMA_short'] > data['EMA_long'], 1, -1)
# 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
peak_price = 0
max_drawdown = 0
for i in range(len(data)):
if data['Signal'].iloc[i] == 2: # Buy signal
if not in_position:
in_position = True
trade_entries.append(data.index[i])
entry_price.append(data['Close'].iloc[i])
peak_price = data['Close'].iloc[i]
max_drawdown = 0
elif data['Signal'].iloc[i] == -2: # Sell signal
if in_position:
in_position = False
trade_exits.append(data.index[i])
exit_price.append(data['Close'].iloc[i])
drawdowns.append(max_drawdown)
elif in_position:
# Update peak price and calculate drawdown
price = data['Close'].iloc[i]
peak_price = max(peak_price, price)
drawdown = (price - peak_price) / peak_price
max_drawdown = min(max_drawdown, 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])
drawdowns.append(max_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 total return
total_return = trades['Return'].sum()
# Calculate win rate
win_rate = len(trades[trades['Return'] > 0]) / len(trades) if len(trades) > 0 else 0
# Calculate Sharpe ratio
period_return = data['Close'].pct_change().dropna()
if interval == '1d':
sharpe_ratio = (period_return.mean() / period_return.std()) * np.sqrt(252)
elif interval == '1wk':
sharpe_ratio = (period_return.mean() / period_return.std()) * np.sqrt(52)
elif interval == '1mo':
sharpe_ratio = (period_return.mean() / period_return.std()) * np.sqrt(12)
elif interval == '1h':
sharpe_ratio = (period_return.mean() / period_return.std()) * np.sqrt(252 * 6.5) # Assuming 6.5 trading hours per day
# Calculate max drawdown
max_drawdown_overall = trades['Drawdown'].min() * 100 # As a percentage
# Prepare data for mplfinance
data_for_plot = data.copy()
data_for_plot.index.name = 'Date'
# Mark buy and sell signals
buy_signals = data_for_plot[data['Signal'] == 2]
sell_signals = data_for_plot[data['Signal'] == -2]
# Create additional plots for EMA and signals
apds = [
mpf.make_addplot(data['EMA_short'], color='green', width=1),
mpf.make_addplot(data['EMA_long'], color='red', width=1),
mpf.make_addplot(buy_signals['Close'], type='scatter', markersize=50, marker='^', color='blue'),
mpf.make_addplot(sell_signals['Close'], type='scatter', markersize=50, 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)
# Display the plot in Streamlit
st.pyplot(fig)
# Display performance metrics
st.subheader('Performance Metrics')
st.write(f"Total 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 trade logs
st.subheader('Trade Logs')
st.dataframe(trades)
Usage
To run the Streamlit app, open your terminal and execute:
streamlit run ema_backtester.py
Notes
-
Adjusting EMA Periods Based on Interval: As per your requirement, the EMA periods should adapt to the selected candle interval. The code above takes the user inputs for EMA periods and applies them directly, which works because the data's frequency changes with the interval.
For example:
- If the interval is
1d (daily), ema_short=12 computes a 12-day EMA.
- If the interval is
1wk (weekly), ema_short=12 computes a 12-week EMA.
-
Sharpe Ratio Calculation: The Sharpe ratio is annualized based on the interval frequency.
-
Max Drawdown Calculation: The max drawdown is calculated per your definition, tracking the lowest point below the entry price during each trade.
-
Buy-and-Hold Comparison: If you want to compare the EMA strategy to a buy-and-hold strategy, you can calculate the total return of buying at the start date and holding until the end date.
buy_and_hold_return = (data['Close'].iloc[-1] - data['Close'].iloc[0]) / data['Close'].iloc[0]
st.write(f"Buy and Hold Total Return: {buy_and_hold_return * 100:.2f}%")
Feel free to customize the code further to suit your needs!
Let me know if you need any more assistance or modifications.