Certainly! I'll help you create a Python program that backtests an EMA crossover strategy against a buy-and-hold strategy using Streamlit for the frontend. We'll use yfinance for market data and matplotlib for plotting.
Below is the step-by-step guide along with the code.
Overview of the Steps:
- Set up the Streamlit App: Create a user interface to input parameters.
- Fetch Market Data: Use
yfinance to get historical price data based on user input.
- Calculate EMAs and Generate Signals: Compute EMAs and identify buy/sell points.
- Backtest the Strategy: Simulate trades and calculate performance metrics.
- Calculate Performance Metrics: Total return, Sharpe ratio, win rate, max drawdown.
- Plot the Results: Plot candlestick chart with buy/sell signals.
- Display Trade Log: Show a log of all trades made during backtesting.
Step 1: Set up the Streamlit App
First, make sure you have the required libraries installed:
pip install yfinance matplotlib streamlit ta pandas
Create a new Python file, e.g., app.py.
# app.py
import streamlit as st
import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import dates as mdates
from mplfinance.original_flavor import candlestick_ohlc
from ta.trend import EMAIndicator
import numpy as np
from datetime import datetime, timedelta
Step 2: Create the Streamlit Interface
# Streamlit App
st.title('EMA Crossover Backtesting App')
# Sidebar Inputs
st.sidebar.header('User Input Parameters')
# Ticker Input
ticker = st.sidebar.text_input('Ticker Symbol', 'AAPL')
# EMA Periods
short_ema = st.sidebar.number_input('Short EMA Period', min_value=1, value=12)
long_ema = st.sidebar.number_input('Long EMA Period', min_value=1, value=26)
# Candle Interval
interval = st.sidebar.selectbox('Candle Interval', ['1h', '1d', '1wk', '1mo'])
# Backtest Period
start_date = st.sidebar.date_input('Start Date', datetime.today() - timedelta(days=365 * 5))
end_date = st.sidebar.date_input('End Date', datetime.today())
# Ensure End Date is after Start Date
if start_date > end_date:
st.sidebar.error('Error: End Date must fall after Start Date.')
Step 3: Fetch Market Data
# Fetch Data
@st.cache
def load_data(ticker, interval, start, end):
data = yf.download(tickers=ticker, start=start, end=end, interval=interval)
data.dropna(inplace=True)
return data
data_load_state = st.text('Loading data...')
data = load_data(ticker, interval, start_date, end_date)
data_load_state.text('Loading data... done!')
Step 4: Calculate EMAs and Generate Signals
# Adjust EMA periods according to interval
def get_period_multiplier(interval):
if interval == '1h':
return 1/24 # 1 hour
elif interval == '1d':
return 1 # 1 day
elif interval == '1wk':
return 7 # 7 days in a week
elif interval == '1mo':
return 30 # Approximate days in a month
period_multiplier = get_period_multiplier(interval)
adjusted_short_ema = int(short_ema * period_multiplier)
adjusted_long_ema = int(long_ema * period_multiplier)
# Ensure EMA periods are at least 1
adjusted_short_ema = max(adjusted_short_ema, 1)
adjusted_long_ema = max(adjusted_long_ema, 1)
# Calculate EMAs
data['ShortEMA'] = data['Close'].ewm(span=adjusted_short_ema, adjust=False).mean()
data['LongEMA'] = data['Close'].ewm(span=adjusted_long_ema, adjust=False).mean()
# Generate Signals
def generate_signals(data):
data['Signal'] = 0
data['Signal'][adjusted_short_ema:] = np.where(
data['ShortEMA'][adjusted_short_ema:] > data['LongEMA'][adjusted_short_ema:], 1, 0)
data['Position'] = data['Signal'].diff()
return data
data = generate_signals(data)
Step 5: Backtest the Strategy
# Backtesting Function
def backtest_strategy(data):
trades = []
position = 0
entry_price = 0
max_drawdown = 0
drawdowns = []
for i in range(len(data)):
# Buy Signal
if data['Position'][i] == 1:
entry_price = data['Close'][i]
position = 1
max_price = entry_price
min_price = entry_price
trade = {'Entry Date': data.index[i], 'Entry Price': entry_price}
# While in Position
elif position == 1:
price = data['Close'][i]
max_price = max(max_price, price)
min_price = min(min_price, price)
# Update Max Drawdown
drawdown = (min_price - entry_price) / entry_price * 100
if drawdown < max_drawdown:
max_drawdown = drawdown
# Sell Signal
elif data['Position'][i] == -1 and position == 1:
exit_price = data['Close'][i]
position = 0
trade['Exit Date'] = data.index[i]
trade['Exit Price'] = exit_price
trade['Return'] = (exit_price - entry_price) / entry_price * 100
trade['Max Drawdown'] = (min_price - entry_price) / entry_price * 100
drawdowns.append(trade['Max Drawdown'])
trades.append(trade)
# If position is still open at the end
if position == 1:
exit_price = data['Close'][-1]
trade['Exit Date'] = data.index[-1]
trade['Exit Price'] = exit_price
trade['Return'] = (exit_price - entry_price) / entry_price * 100
trade['Max Drawdown'] = (min_price - entry_price) / entry_price * 100
drawdowns.append(trade['Max Drawdown'])
trades.append(trade)
trades_df = pd.DataFrame(trades)
return trades_df, max(drawdowns, default=0)
Step 6: Calculate Performance Metrics
# Calculate Metrics
trades_df, max_drawdown = backtest_strategy(data)
if not trades_df.empty:
total_return = trades_df['Return'].sum()
win_rate = (trades_df['Return'] > 0).mean() * 100
# Calculate Sharpe Ratio
daily_returns = data['Close'].pct_change()
excess_daily_returns = daily_returns - 0.0001 # Assuming risk-free rate is near zero
sharpe_ratio = (excess_daily_returns.mean() / excess_daily_returns.std()) * np.sqrt(252)
# Buy and Hold Return
buy_hold_return = (data['Close'][-1] - data['Close'][0]) / data['Close'][0] * 100
else:
total_return = 0
win_rate = 0
sharpe_ratio = 0
buy_hold_return = 0
Step 7: Plot the Results
# Plotting
fig, ax = plt.subplots(figsize=(12,6))
# Prepare Data
data_reset = data.reset_index()
data_reset['Date'] = data_reset['Date'].map(mdates.date2num)
# Plot Candlestick Chart
ohlc = data_reset[['Date', 'Open', 'High', 'Low', 'Close']]
candlestick_ohlc(ax, ohlc.values, width=0.6, colorup='g', colordown='r')
# Plot EMAs
ax.plot(data_reset['Date'], data_reset['ShortEMA'], color='blue', label=f'{short_ema} EMA')
ax.plot(data_reset['Date'], data_reset['LongEMA'], color='red', label=f'{long_ema} EMA')
# Plot Buy Signals
ax.plot(data_reset.loc[data_reset['Position'] == 1]['Date'],
data_reset['ShortEMA'][data_reset['Position'] == 1],
'^', markersize=10, color='green', label='Buy Signal')
# Plot Sell Signals
ax.plot(data_reset.loc[data_reset['Position'] == -1]['Date'],
data_reset['ShortEMA'][data_reset['Position'] == -1],
'v', markersize=10, color='red', label='Sell Signal')
ax.xaxis_date()
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
plt.xticks(rotation=45)
plt.xlabel('Date')
plt.ylabel('Price')
plt.title(f'{ticker} Price Chart with EMA Crossover Signals')
plt.legend()
plt.grid()
st.pyplot(fig)
Step 8: Display Performance Metrics and Trade Log
# Display Metrics
st.header('Backtest Performance Metrics')
col1, col2 = st.columns(2)
col1.metric('Total Strategy Return (%)', f"{total_return:.2f}%")
col1.metric('Buy and Hold Return (%)', f"{buy_hold_return:.2f}%")
col1.metric('Win Rate (%)', f"{win_rate:.2f}%")
col2.metric('Sharpe Ratio', f"{sharpe_ratio:.2f}")
col2.metric('Max Drawdown (%)', f"{max_drawdown:.2f}%")
# Display Trade Log
st.header('Trade Log')
if not trades_df.empty:
st.dataframe(trades_df)
else:
st.write('No trades were made during this period.')
Full Code
Putting it all together, here's the full code for app.py:
# app.py
import streamlit as st
import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import dates as mdates
from mplfinance.original_flavor import candlestick_ohlc
import numpy as np
from datetime import datetime, timedelta
st.title('EMA Crossover Backtesting App')
# Sidebar Inputs
st.sidebar.header('User Input Parameters')
# Ticker Input
ticker = st.sidebar.text_input('Ticker Symbol', 'AAPL')
# EMA Periods
short_ema = st.sidebar.number_input('Short EMA Period', min_value=1, value=12)
long_ema = st.sidebar.number_input('Long EMA Period', min_value=1, value=26)
# Candle Interval
interval = st.sidebar.selectbox('Candle Interval', ['1h', '1d', '1wk', '1mo'])
# Backtest Period
start_date = st.sidebar.date_input('Start Date', datetime.today() - timedelta(days=365 * 5))
end_date = st.sidebar.date_input('End Date', datetime.today())
# Ensure End Date is after Start Date
if start_date > end_date:
st.sidebar.error('Error: End Date must fall after Start Date.')
# Fetch Data
@st.cache
def load_data(ticker, interval, start, end):
data = yf.download(tickers=ticker, start=start, end=end, interval=interval)
data.dropna(inplace=True)
return data
data_load_state = st.text('Loading data...')
data = load_data(ticker, interval, start_date, end_date)
data_load_state.text('Loading data... done!')
# Adjust EMA periods according to interval
def get_period_multiplier(interval):
if interval == '1h':
return 1/24 # 1 hour
elif interval == '1d':
return 1 # 1 day
elif interval == '1wk':
return 7 # 7 days in a week
elif interval == '1mo':
return 30 # Approximate days in a month
period_multiplier = get_period_multiplier(interval)
adjusted_short_ema = int(short_ema * period_multiplier)
adjusted_long_ema = int(long_ema * period_multiplier)
# Ensure EMA periods are at least 1
adjusted_short_ema = max(adjusted_short_ema, 1)
adjusted_long_ema = max(adjusted_long_ema, 1)
# Calculate EMAs
data['ShortEMA'] = data['Close'].ewm(span=adjusted_short_ema, adjust=False).mean()
data['LongEMA'] = data['Close'].ewm(span=adjusted_long_ema, adjust=False).mean()
# Generate Signals
def generate_signals(data):
data['Signal'] = 0
data['Signal'][adjusted_short_ema:] = np.where(
data['ShortEMA'][adjusted_short_ema:] > data['LongEMA'][adjusted_short_ema:], 1, 0)
data['Position'] = data['Signal'].diff()
return data
data = generate_signals(data)
# Backtesting Function
def backtest_strategy(data):
trades = []
position = 0
entry_price = 0
max_drawdown = 0
drawdowns = []
for i in range(len(data)):
# Buy Signal
if data['Position'][i] == 1:
entry_price = data['Close'][i]
position = 1
max_price = entry_price
min_price = entry_price
trade = {'Entry Date': data.index[i], 'Entry Price': entry_price}
# While in Position
elif position == 1:
price = data['Close'][i]
max_price = max(max_price, price)
min_price = min(min_price, price)
# Update Max Drawdown
drawdown = (min_price - entry_price) / entry_price * 100
if drawdown < max_drawdown:
max_drawdown = drawdown
# Sell Signal
elif data['Position'][i] == -1 and position == 1:
exit_price = data['Close'][i]
position = 0
trade['Exit Date'] = data.index[i]
trade['Exit Price'] = exit_price
trade['Return'] = (exit_price - entry_price) / entry_price * 100
trade['Max Drawdown'] = (min_price - entry_price) / entry_price * 100
drawdowns.append(trade['Max Drawdown'])
trades.append(trade)
# If position is still open at the end
if position == 1:
exit_price = data['Close'][-1]
trade['Exit Date'] = data.index[-1]
trade['Exit Price'] = exit_price
trade['Return'] = (exit_price - entry_price) / entry_price * 100
trade['Max Drawdown'] = (min_price - entry_price) / entry_price * 100
drawdowns.append(trade['Max Drawdown'])
trades.append(trade)
trades_df = pd.DataFrame(trades)
return trades_df, min(drawdowns, default=0)
# Calculate Metrics
trades_df, max_drawdown = backtest_strategy(data)
if not trades_df.empty:
total_return = trades_df['Return'].sum()
win_rate = (trades_df['Return'] > 0).mean() * 100
# Calculate Sharpe Ratio
daily_returns = data['Close'].pct_change()
excess_daily_returns = daily_returns - 0.0001 # Assuming risk-free rate is near zero
sharpe_ratio = (excess_daily_returns.mean() / excess_daily_returns.std()) * np.sqrt(252)
# Buy and Hold Return
buy_hold_return = (data['Close'][-1] - data['Close'][0]) / data['Close'][0] * 100
else:
total_return = 0
win_rate = 0
sharpe_ratio = 0
buy_hold_return = 0
# Plotting
fig, ax = plt.subplots(figsize=(12,6))
# Prepare Data
data_reset = data.reset_index()
# Adjust date format based on interval
if interval == '1h':
data_reset['Date'] = data_reset['Datetime']
else:
data_reset['Date'] = data_reset['Date']
data_reset['Date'] = data_reset['Date'].map(mdates.date2num)
# Plot Candlestick Chart
ohlc = data_reset[['Date', 'Open', 'High', 'Low', 'Close']]
candlestick_ohlc(ax, ohlc.values, width=0.6, colorup='g', colordown='r')
# Plot EMAs
ax.plot(data_reset['Date'], data_reset['ShortEMA'], color='blue', label=f'{short_ema} EMA')
ax.plot(data_reset['Date'], data_reset['LongEMA'], color='red', label=f'{long_ema} EMA')
# Plot Buy Signals
ax.plot(data_reset.loc[data_reset['Position'] == 1]['Date'],
data_reset['ShortEMA'][data_reset['Position'] == 1],
'^', markersize=10, color='green', label='Buy Signal')
# Plot Sell Signals
ax.plot(data_reset.loc[data_reset['Position'] == -1]['Date'],
data_reset['ShortEMA'][data_reset['Position'] == -1],
'v', markersize=10, color='red', label='Sell Signal')
ax.xaxis_date()
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
plt.xticks(rotation=45)
plt.xlabel('Date')
plt.ylabel('Price')
plt.title(f'{ticker} Price Chart with EMA Crossover Signals')
plt.legend()
plt.grid()
st.pyplot(fig)
# Display Metrics
st.header('Backtest Performance Metrics')
col1, col2 = st.columns(2)
col1.metric('Total Strategy Return (%)', f"{total_return:.2f}%")
col1.metric('Buy and Hold Return (%)', f"{buy_hold_return:.2f}%")
col1.metric('Win Rate (%)', f"{win_rate:.2f}%")
col2.metric('Sharpe Ratio', f"{sharpe_ratio:.2f}")
col2.metric('Max Drawdown (%)', f"{max_drawdown:.2f}%")
# Display Trade Log
st.header('Trade Log')
if not trades_df.empty:
st.dataframe(trades_df)
else:
st.write('No trades were made during this period.')
Running the App
Run the Streamlit app using the command:
streamlit run app.py
Explanation of Key Components
-
EMA Calculation Adjustment: The EMA periods are adjusted based on the interval selected. This ensures that the periods correspond to the time frame (e.g., 12 weeks EMA when using weekly data).
-
Signal Generation: Buy signals occur when the short EMA crosses above the long EMA, and sell signals occur when the short EMA crosses below the long EMA.
-
Max Drawdown Calculation: For each trade, we track the maximum drawdown from the entry price during the trade.
-
Performance Metrics:
- Total Return: Sum of returns from all trades.
- Win Rate: Percentage of trades that were profitable.
- Sharpe Ratio: Measure of risk-adjusted return; calculated using daily returns.
- Max Drawdown: The largest percentage drop from the entry price to the lowest price during any trade.
-
Plotting: The candlestick chart shows price movements, EMAs, and buy/sell signals.
-
Trade Log: Displays entry and exit dates, prices, returns, and max drawdown for each trade.
Notes and Considerations
-
Caching: @st.cache is used to prevent reloading data unnecessarily.
-
Date Handling: Be mindful of date formats, especially when dealing with different intervals like hourly data.
-
Error Handling: Ensure that inputs are valid (e.g., end date after start date).
-
Data Limitations: The yfinance library might have limitations on the amount of historical data available for certain intervals.
Conclusion
You now have a Streamlit app that backtests an EMA crossover strategy with adjustable parameters. This setup allows for interactive exploration of different EMAs, intervals, and periods.
Feel free to adjust and expand upon this code to add more features or improve the backtesting logic.
If you have any questions or need further assistance, don't hesitate to ask!