I want to create a backtesting python program, where I compare two EMA crossing as buy, sell signal against buy-and-hold lump sum investing. The program will use yfinance to obtain market data and use pyplot to indicate where the strategy buy and sell. It should calculate the total return, the sharp ratio, win rate, and max drawdown amout.
There should be a front end where user can enter what ticket they are backtesting for, what EMA numbers, what kind of candle(x hr, day, week, month), and what period to backtest. the EMA input should adapt to the selected candle interval. Use Streamlit as frontend.
i.e. if user input 12, 26 EMA, weekly candle, the strategy will be to buy when short 12 weeks EMA cross 26 weeks EMA, and sell when 12 weeks EMA fall below 26 weeks EMA. buy-and-hold stretegy will buy at the start of the period.
when I mean drawdown, I meant the drawdown below the long position price, so if you enter at 100 and sell at 200, but during that period the price gone to 80, the drawdown should be -20%. and the max drawdown should be the biggest drawdown among all trade, so if you trade 5 times, choice the biggest one
also create a log section under the chart section that display each buy and sell trade
Can you help me create the program
Assistant
Certainly! Below is a comprehensive Python program that fulfills your requirements for backtesting an EMA crossover strategy against a buy-and-hold strategy. The application utilizes Streamlit for the frontend, yfinance for fetching market data, and Matplotlib for plotting. It calculates key performance metrics such as Total Return, Sharpe Ratio, Win Rate, and Maximum Drawdown. Additionally, it logs each buy and sell trade.
Prerequisites
Before running the program, ensure you have the necessary Python libraries installed. You can install them using pip:
Save the following code in a file named backtest_app.py:
python
import streamlit as st
import yfinance as yf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import dates as mdates
from datetime import datetime, timedelta
# Set Streamlit page configuration
st.set_page_config(
page_title="EMA Crossover Backtester",
layout="wide",
)
# Function to calculate maximum drawdown for a trade
def calculate_max_drawdown(prices, entry_price):
drawdowns = (prices - entry_price) / entry_price
max_drawdown = drawdowns.min()
return max_drawdown * 100 # Percentage
# Function to calculate Sharpe Ratio
def calculate_sharpe_ratio(returns, risk_free_rate=0):
excess_returns = returns - risk_free_rate
if excess_returns.std() == 0:
return 0
sharpe_ratio = np.sqrt(252) * excess_returns.mean() / excess_returns.std()
return sharpe_ratio
# Streamlit Sidebar for User Inputs
st.sidebar.header("Backtesting Parameters")
# Ticker input
ticker = st.sidebar.text_input("Ticker Symbol", "AAPL")
# Select data interval
interval_options = {
"1 Hour": "1h",
"4 Hours": "4h",
"1 Day": "1d",
"1 Week": "1wk",
"1 Month": "1mo"
}
selected_interval_label = st.sidebar.selectbox("Candle Interval", list(interval_options.keys()))
selected_interval = interval_options[selected_interval_label]
# EMA inputs
col1, col2 = st.sidebar.columns(2)
short_ema = col1.number_input("Short EMA Period", min_value=1, value=12, step=1)
long_ema = col2.number_input("Long EMA Period", min_value=1, value=26, step=1)
# Backtest period
period_input = st.sidebar.text_input("Backtest Period", "5y")
# Main Area
st.title("EMA Crossover Strategy Backtester")
# Fetch Data Button
if st.sidebar.button("Run Backtest"):
with st.spinner("Fetching data..."):
try:
data = yf.download(ticker, period=period_input, interval=selected_interval, auto_adjust=True)
if data.empty:
st.error("No data fetched. Please check the ticker symbol and parameters.")
st.stop()
except Exception as e:
st.error(f"Error fetching data: {e}")
st.stop()
# Ensure data has enough points
if len(data) < max(short_ema, long_ema):
st.error("Not enough data points for the selected EMA periods.")
st.stop()
# Calculate EMAs
data['EMA_Short'] = data['Close'].ewm(span=short_ema, adjust=False).mean()
data['EMA_Long'] = data['Close'].ewm(span=long_ema, adjust=False).mean()
# Generate Buy/Sell Signals
data['Signal'] = 0
data['Signal'][short_ema:] = np.where(data['EMA_Short'][short_ema:] > data['EMA_Long'][short_ema:], 1, 0)
data['Position'] = data['Signal'].diff()
# Initialize variables for backtesting
buy_signals = data[data['Position'] == 1]
sell_signals = data[data['Position'] == -1]
# Align buy and sell signals
if sell_signals.empty or (not sell_signals.empty and buy_signals.index[-1] > sell_signals.index[-1]):
sell_signals = sell_signals.append(pd.DataFrame({'Close': [data['Close'][-1]]}, index=[data.index[-1]]))
trades = []
max_drawdowns = []
for buy in buy_signals.index:
try:
sell = sell_signals[sell_signals.index > buy].iloc[0]
except IndexError:
sell = data.index[-1]
entry_price = data.loc[buy, 'Close']
exit_price = data.loc[sell, 'Close']
trade_data = data.loc[buy:sell]
max_dd = calculate_max_drawdown(trade_data['Close'], entry_price)
trade = {
'Buy Date': buy,
'Buy Price': entry_price,
'Sell Date': sell,
'Sell Price': exit_price,
'Return (%)': ((exit_price - entry_price) / entry_price) * 100,
'Max Drawdown (%)': max_dd
}
trades.append(trade)
max_drawdowns.append(max_dd)
trades_df = pd.DataFrame(trades)
total_return = trades_df['Return (%)'].sum()
winning_trades = trades_df[trades_df['Return (%)'] > 0]
win_rate = (len(winning_trades) / len(trades_df)) * 100 if len(trades_df) > 0 else 0
max_drawdown = min(max_drawdowns) if max_drawdowns else 0
# Calculate Sharpe Ratio for strategy
# Assuming strategy return is the sequence of trade returns
strategy_returns = trades_df['Return (%)'] / 100
sharpe_ratio = calculate_sharpe_ratio(strategy_returns)
# Buy and Hold Strategy
buy_hold_return = ((data['Close'][-1] - data['Close'][0]) / data['Close'][0]) * 100
# Display Metrics
st.subheader("Performance Metrics")
metrics1, metrics2, metrics3, metrics4 = st.columns(4)
metrics1.metric("Total Return (%)", f"{total_return:.2f}")
metrics2.metric("Sharpe Ratio", f"{sharpe_ratio:.2f}")
metrics3.metric("Win Rate (%)", f"{win_rate:.2f}")
metrics4.metric("Max Drawdown (%)", f"{max_drawdown:.2f}")
placeholder = st.empty()
with placeholder.container():
st.subheader("Buy and Hold Comparison")
bh_col1, bh_col2 = st.columns(2)
bh_col1.metric("Buy and Hold Return (%)", f"{buy_hold_return:.2f}")
# Plotting the Strategy
st.subheader("Price Chart with Buy/Sell Signals")
plt.style.use('seaborn-dark')
fig, ax = plt.subplots(figsize=(14, 7))
ax.plot(data.index, data['Close'], label='Close Price', color='blue')
ax.plot(data.index, data['EMA_Short'], label=f'EMA {short_ema}', color='green')
ax.plot(data.index, data['EMA_Long'], label=f'EMA {long_ema}', color='red')
# Plot Buy Signals
ax.plot(buy_signals.index, data.loc[buy_signals.index, 'Close'], '^', markersize=10, color='g', label='Buy Signal')
# Plot Sell Signals
ax.plot(sell_signals.index, data.loc[sell_signals.index, 'Close'], 'v', markersize=10, color='r', label='Sell Signal')
ax.set_title(f'{ticker} Price Chart with EMA Crossover Signals')
ax.set_xlabel('Date')
ax.set_ylabel('Price')
ax.legend()
ax.grid(True)
st.pyplot(fig)
# Trade Log
st.subheader("Trade Log")
st.dataframe(trades_df.style.format({
'Buy Date': lambda x: x.strftime('%Y-%m-%d'),
'Sell Date': lambda x: x.strftime('%Y-%m-%d'),
'Buy Price': '{:.2f}',
'Sell Price': '{:.2f}',
'Return (%)': '{:.2f}',
'Max Drawdown (%)': '{:.2f}'
}))
# Optional: Display Buy and Hold on the same chart
st.subheader("Buy and Hold vs. EMA Strategy")
fig2, ax2 = plt.subplots(figsize=(14,7))
ax2.plot(data.index, data['Close'], label='Close Price', color='blue')
# Buy and Hold
ax2.plot(data.index, [data['Close'][0]]*len(data), '--', label='Buy and Hold', color='orange')
# EMA Strategy Cumulative Returns
cumulative_returns = (1 + strategy_returns).cumprod() - 1
ax2.plot(data.index[:len(cumulative_returns)], cumulative_returns * data['Close'][0] + data['Close'][0], label='EMA Strategy', color='purple')
ax2.set_title(f'{ticker} Buy and Hold vs. EMA Strategy')
ax2.set_xlabel('Date')
ax2.set_ylabel('Price')
ax2.legend()
ax2.grid(True)
st.pyplot(fig2)
# Optional: Display Max Drawdown Chart
st.subheader("Maximum Drawdown Over Trades")
plt.style.use('seaborn-dark')
fig3, ax3 = plt.subplots(figsize=(14, 4))
ax3.bar(trades_df.index, trades_df['Max Drawdown (%)'], color='red')
ax3.set_title('Max Drawdown Per Trade')
ax3.set_xlabel('Trade Number')
ax3.set_ylabel('Max Drawdown (%)')
st.pyplot(fig3)
else:
st.info("Please input the backtesting parameters in the sidebar and click 'Run Backtest'.")
Explanation of the Code
Imports and Configuration:
Streamlit is used for building the web application interface.
yfinance fetches historical market data.
Pandas and NumPy handle data manipulation and calculations.
Matplotlib plots the charts.
The Streamlit page is configured with a title and layout.
Helper Functions:
calculate_max_drawdown: Computes the maximum drawdown during a trade based on entry price.
calculate_sharpe_ratio: Calculates the Sharpe Ratio assuming a risk-free rate of 0%.
User Inputs via Streamlit Sidebar:
Ticker Symbol: The stock ticker to backtest (defaulted to "AAPL").
Candle Interval: Options include 1 Hour, 4 Hours, 1 Day, 1 Week, and 1 Month.
EMA Periods: Users can input the short and long EMA periods.
Backtest Period: The time span for backtesting (e.g., "5y" for five years).
Data Fetching and Preparation:
Upon clicking "Run Backtest," the app fetches historical data using yfinance.
It calculates the short and long EMAs.
Buy and sell signals are generated based on EMA crossovers.
Backtesting Logic:
Identifies buy and sell signals where the short EMA crosses above (buy) or below (sell) the long EMA.
Constructs a trades log capturing buy/sell dates, prices, returns, and maximum drawdowns.
Calculates performance metrics:
Total Return: Sum of all trade returns.
Sharpe Ratio: Risk-adjusted return.
Win Rate: Percentage of profitable trades.
Max Drawdown: The largest drop from the entry price across all trades.
Compares the strategy against a Buy and Hold approach.
Visualization:
Price Chart: Displays the stock price along with EMAs and buy/sell signals.
Trade Log: A table listing all executed trades with relevant details.
Running the Application
To run the Streamlit application, navigate to the directory containing backtest_app.py in your terminal and execute:
bash
streamlit run backtest_app.py
This command will start a local web server and open the application in your default web browser. From there, you can input your desired parameters and analyze the backtest results.
Notes and Considerations
Data Limitations: The availability of certain intervals (like hourly data) may be limited based on the ticker and backtest period. Ensure that the selected interval has sufficient data points for accurate EMA calculations.
Sharpe Ratio Calculation: The Sharpe Ratio assumes a risk-free rate of 0%. You can modify the calculate_sharpe_ratio function to include a different risk-free rate if desired.
Performance Optimization: For very long time periods or high-frequency data (like hourly intervals), the application might take longer to process. Consider optimizing data fetching or leveraging caching mechanisms if necessary.
Enhancements:
Risk Management: Incorporate stop-loss or take-profit levels.
Multiple Indicators: Add additional technical indicators for more sophisticated strategies.
Portfolio Backtesting: Extend the application to handle multiple tickers and asset allocations.
This application provides a solid foundation for backtesting EMA crossover strategies and can be extended or customized further based on specific requirements or additional features you might have in mind.