Okay, this is a great starting point for a flexible backtesting app. We'll use Streamlit for the UI.
Here's a conceptual overview:
- UI (Streamlit):
- Text area for user to input their strategy code (the "prompt").
- Button to run the backtest.
- Display area for results (metrics, charts).
- Data Loading:
pd.read_csv('data.csv') as requested.
- Strategy Execution: The user's Python code (from the prompt) will be executed. This code must modify the input DataFrame (
df) to add a 'signal' column.
signal = 1: Buy
signal = -1: Sell
signal = 0 (or NaN initially): Hold
- Backtesting Engine:
- Iterates through the data day by day.
- Manages a portfolio (cash, holdings).
- Executes trades based on the
'signal' column.
- Calculates portfolio value over time.
- Metrics Calculation: Standard performance metrics (P&L, Sharpe, Max Drawdown, etc.).
- Visualization: Plot portfolio value.
Let's create the files.
1. data.csv (Sample Data):
Create a file named data.csv in the same directory as your Python script with content like this (you can use your own data, just ensure it has 'Date', 'Open', 'High', 'Low', 'Close', 'Volume'):
Date,Open,High,Low,Close,Volume
2020-01-01,100,102,99,101,1000
2020-01-02,101,103,100,102.5,1200
2020-01-03,102.5,104,101,101.5,1100
2020-01-04,101.5,102,99,100,1300
2020-01-05,100,101,98,99,1500
2020-01-06,99,100,97,99.5,1400
2020-01-07,99.5,105,99,104,2000
2020-01-08,104,106,103,105,1800
2020-01-09,105,105.5,102,103,1700
2020-01-10,103,104,102.5,103.5,1600
2020-01-13,103.5,106,103,105.5,1900
2020-01-14,105.5,108,105,107.5,2200
2020-01-15,107.5,109,106,106.5,2100
2020-01-16,106.5,107,104,105,2000
2020-01-17,105,105.5,103,103.5,1800
... (add more data for a meaningful backtest) ...
2. backtester_app.py:
import streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# --- Configuration ---
INITIAL_CAPITAL = 100000.0
DATA_FILE = 'data.csv'
# For simplicity, we'll assume trades happen at the 'Close' price of the signal day.
# More advanced: Use 'Open' of the next day.
# --- Helper Functions ---
def load_data(filepath=DATA_FILE):
"""Loads and preprocesses the financial data."""
try:
df = pd.read_csv(filepath)
df['Date'] = pd.to_datetime(df['Date'])
df = df.sort_values('Date').set_index('Date')
# Ensure required columns exist
required_cols = ['Open', 'High', 'Low', 'Close', 'Volume']
if not all(col in df.columns for col in required_cols):
st.error(f"Data CSV must contain columns: {', '.join(required_cols)}")
return None
return df
except FileNotFoundError:
st.error(f"{filepath} not found. Please create it.")
return None
except Exception as e:
st.error(f"Error loading data: {e}")
return None
def calculate_metrics(portfolio_df, trades_df, initial_capital, benchmark_returns):
"""Calculates performance metrics."""
if portfolio_df.empty:
return pd.Series(dtype='float64')
metrics = {}
final_value = portfolio_df['value'].iloc[-1]
metrics['Final Portfolio Value'] = f"${final_value:,.2f}"
metrics['Total Return (%)'] = (final_value / initial_capital - 1) * 100
# Daily returns
portfolio_df['daily_return'] = portfolio_df['value'].pct_change().fillna(0)
# Number of trading days (approximate for annualized metrics)
days = (portfolio_df.index[-1] - portfolio_df.index[0]).days
if days > 0:
metrics['Annualized Return (%)'] = ((1 + metrics['Total Return (%)']/100)**(365.0/days) - 1) * 100
# Sharpe Ratio (assuming risk-free rate = 0 for simplicity)
# Using 252 trading days for annualization of std dev
if portfolio_df['daily_return'].std() != 0:
sharpe_ratio = (portfolio_df['daily_return'].mean() / portfolio_df['daily_return'].std()) * np.sqrt(252 if days > 252 else days)
metrics['Sharpe Ratio'] = sharpe_ratio
else:
metrics['Sharpe Ratio'] = np.nan
# Max Drawdown
portfolio_df['cumulative_max'] = portfolio_df['value'].cummax()
portfolio_df['drawdown'] = (portfolio_df['value'] - portfolio_df['cumulative_max']) / portfolio_df['cumulative_max']
metrics['Max Drawdown (%)'] = portfolio_df['drawdown'].min() * 100
else:
metrics['Annualized Return (%)'] = 0
metrics['Sharpe Ratio'] = np.nan
metrics['Max Drawdown (%)'] = 0
metrics['Number of Trades'] = len(trades_df)
if not trades_df.empty:
wins = trades_df[trades_df['PnL'] > 0]
losses = trades_df[trades_df['PnL'] < 0]
metrics['Winning Trades'] = len(wins)
metrics['Losing Trades'] = len(losses)
if len(trades_df) > 0:
metrics['Win Rate (%)'] = (len(wins) / len(trades_df)) * 100 if len(trades_df) > 0 else 0
else:
metrics['Win Rate (%)'] = 0
metrics['Average Win ($)'] = wins['PnL'].mean() if not wins.empty else 0
metrics['Average Loss ($)'] = losses['PnL'].mean() if not losses.empty else 0
if metrics['Average Loss ($)'] != 0:
metrics['Profit Factor'] = abs(wins['PnL'].sum() / losses['PnL'].sum()) if not losses.empty and losses['PnL'].sum() !=0 else np.inf
else:
metrics['Profit Factor'] = np.inf # No losses
else:
metrics['Winning Trades'] = 0
metrics['Losing Trades'] = 0
metrics['Win Rate (%)'] = 0
metrics['Average Win ($)'] = 0
metrics['Average Loss ($)'] = 0
metrics['Profit Factor'] = np.nan
metrics['Benchmark (Buy & Hold) Return (%)'] = benchmark_returns * 100
return pd.Series(metrics).map('{:,.2f}'.format).rename('Value')
# --- Core Backtesting Logic ---
def run_backtest(df_original, strategy_code, initial_capital):
df = df_original.copy() # Work on a copy
# 1. Execute user's strategy code to generate signals
# The strategy code MUST create a 'signal' column in 'df'
# 'signal': 1 for BUY, -1 for SELL, 0 for HOLD
try:
# Provide df, pd, np in the execution scope
exec_scope = {'df': df, 'pd': pd, 'np': np}
exec(strategy_code, globals(), exec_scope)
df = exec_scope['df'] # Retrieve potentially modified df
if 'signal' not in df.columns:
st.error("Strategy code MUST create a 'signal' column in the DataFrame 'df'.")
return None, None, None
# Ensure signal is numeric and fill NaNs with 0 (hold)
df['signal'] = pd.to_numeric(df['signal'], errors='coerce').fillna(0)
except Exception as e:
st.error(f"Error executing strategy code: {e}")
import traceback
st.text(traceback.format_exc())
return None, None, None
# 2. Initialize portfolio
cash = initial_capital
holdings = 0.0 # Number of shares
position = 0 # -1 for short, 0 for flat, 1 for long
portfolio_history = [] # To store (date, value)
trades = [] # To store trade details
# 3. Loop through data
for i in range(len(df)):
date = df.index[i]
current_price = df['Close'].iloc[i] # Trade at close of signal day
signal = df['signal'].iloc[i]
# Daily portfolio value update (before any trade for the day)
current_portfolio_value = cash + holdings * current_price
portfolio_history.append({'Date': date, 'value': current_portfolio_value})
# Trading Logic
# BUY signal
if signal == 1 and position <= 0: # If not already long or if short, cover and go long
if position == -1: # Cover short position
buy_price_short_cover = current_price
pnl_short = holdings * (entry_price_short - buy_price_short_cover) # holdings is negative for short
trades.append({
'Date': date, 'Type': 'COVER_SHORT', 'Price': buy_price_short_cover,
'Shares': abs(holdings), 'PnL': pnl_short
})
cash += holdings * entry_price_short # Add back initial margin (approx)
cash -= abs(holdings) * buy_price_short_cover # Cost to buy back
holdings = 0
position = 0
# Go Long
if cash > 0: # Ensure enough cash
shares_to_buy = cash / current_price # Simple: use all available cash
holdings += shares_to_buy
cash -= shares_to_buy * current_price
trades.append({
'Date': date, 'Type': 'BUY', 'Price': current_price,
'Shares': shares_to_buy, 'PnL': 0 # PnL is realized on sell
})
position = 1
entry_price_long = current_price
# SELL signal (interpret as "sell long" or "go short")
elif signal == -1 and position >= 0: # If not already short or if long, sell and go short
if position == 1: # Sell existing long position
sell_price_long_exit = current_price
pnl_long = holdings * (sell_price_long_exit - entry_price_long)
trades.append({
'Date': date, 'Type': 'SELL_LONG', 'Price': sell_price_long_exit,
'Shares': holdings, 'PnL': pnl_long
})
cash += holdings * sell_price_long_exit
holdings = 0
position = 0
# Go Short (simple: use initial capital equivalent for shorting power)
# This is a simplification. Real shorting involves margin.
if cash > 0: # Using cash as a proxy for shorting power for simplicity
shares_to_short = initial_capital / current_price # Short an amount equivalent to initial capital
holdings -= shares_to_short # Negative holdings for short
cash += shares_to_short * current_price # Proceeds from shorting (credited to account)
trades.append({
'Date': date, 'Type': 'SELL_SHORT', 'Price': current_price,
'Shares': shares_to_short, 'PnL': 0 # PnL realized on cover
})
position = -1
entry_price_short = current_price
# If HOLD signal, but we are in a position, PnL is not realized yet.
# No explicit action for signal == 0 beyond portfolio value update.
# Final portfolio value if still holding at the end
if holdings > 0: # If still long
# Simulate selling at the last price to realize PnL for metrics
final_price = df['Close'].iloc[-1]
pnl_final_long = holdings * (final_price - entry_price_long if 'entry_price_long' in locals() else final_price) # Handle case where no buy happened
trades.append({
'Date': df.index[-1], 'Type': 'AUTO_SELL_EOL', 'Price': final_price,
'Shares': holdings, 'PnL': pnl_final_long
})
cash += holdings * final_price
holdings = 0
elif holdings < 0: # If still short
# Simulate covering at the last price
final_price = df['Close'].iloc[-1]
pnl_final_short = holdings * (entry_price_short - final_price if 'entry_price_short' in locals() else 0) # holdings is negative
trades.append({
'Date': df.index[-1], 'Type': 'AUTO_COVER_EOL', 'Price': final_price,
'Shares': abs(holdings), 'PnL': pnl_final_short
})
cash += holdings * entry_price_short # Add back initial margin (approx)
cash -= abs(holdings) * final_price # Cost to buy back
holdings = 0
# Convert to DataFrames
portfolio_df_final = pd.DataFrame(portfolio_history).set_index('Date')
# Update the last portfolio value after EOL trades
if not portfolio_df_final.empty:
portfolio_df_final.iloc[-1, portfolio_df_final.columns.get_loc('value')] = cash
trades_df_final = pd.DataFrame(trades)
if not trades_df_final.empty:
trades_df_final['Date'] = pd.to_datetime(trades_df_final['Date'])
return portfolio_df_final, trades_df_final, df # Return df with signals for inspection
# --- Streamlit App UI ---
st.set_page_config(layout="wide")
st.title("📈 Dynamic Strategy Backtester")
st.sidebar.header("Configuration")
initial_capital_input = st.sidebar.number_input("Initial Capital", value=INITIAL_CAPITAL, min_value=1000.0, step=1000.0)
data_file_input = st.sidebar.text_input("Data CSV File Path", value=DATA_FILE)
st.sidebar.markdown("---")
st.sidebar.markdown("""
**Strategy Prompt Guide:**
Your Python code must:
1. Access data via a DataFrame named `df`.
2. Create a new column in `df` named `'signal'`.
* `1`: Buy signal
* `-1`: Sell signal (can mean sell long or go short)
* `0`: Hold signal (or `NaN` which will be treated as 0)
3. Available libraries in scope: `pd` (pandas), `np` (numpy).
""")
# Load data
df_original = load_data(data_file_input)
if df_original is not None:
st.subheader("Raw Data Preview (first 5 rows)")
st.dataframe(df_original.head())
# --- Strategy Input ---
default_strategy = """
# Example: Simple Moving Average Crossover
# This strategy generates 'signal' column in 'df'
# Calculate short and long moving averages
df['SMA_short'] = df['Close'].rolling(window=10).mean() # Use a shorter window
df['SMA_long'] = df['Close'].rolling(window=30).mean() # Use a longer window
# Initialize signal column
df['signal'] = 0
# Generate buy signals
# Buy when short MA crosses above long MA
df.loc[df['SMA_short'] > df['SMA_long'], 'signal'] = 1
# Generate sell signals
# Sell when short MA crosses below long MA
df.loc[df['SMA_short'] < df['SMA_long'], 'signal'] = -1
# Optional: To avoid constant trading, only trade on crossovers
# Create a 'position' column: 1 if short > long, -1 if short < long
# df['position'] = 0
# df.loc[df['SMA_short'] > df['SMA_long'], 'position'] = 1
# df.loc[df['SMA_short'] < df['SMA_long'], 'position'] = -1
# df['signal'] = df['position'].diff().fillna(0) # Take the difference to find changes
# Note: .diff() makes first valid signal NaN. fillna(0) or handle appropriately.
# This example uses the simpler direct comparison for signals.
"""
st.subheader("📝 Strategy Prompt")
strategy_code = st.text_area(
"Enter your Python strategy code below:",
value=default_strategy,
height=300
)
if st.button("🚀 Run Backtest", type="primary"):
if not strategy_code:
st.warning("Please enter a strategy prompt.")
else:
with st.spinner("🧠 Running backtest..."):
portfolio_df, trades_df, df_with_signals = run_backtest(
df_original, strategy_code, initial_capital_input
)
if portfolio_df is not None and not portfolio_df.empty:
st.subheader("📊 Backtest Results")
col1, col2 = st.columns(2)
with col1:
# Display Metrics
st.markdown("#### Performance Metrics")
if not df_original.empty and len(df_original) > 1:
benchmark_return = (df_original['Close'].iloc[-1] / df_original['Close'].iloc[0]) - 1
else:
benchmark_return = 0
metrics_s = calculate_metrics(portfolio_df, trades_df, initial_capital_input, benchmark_return)
st.table(metrics_s)
with col2:
# Plot Portfolio Value
st.markdown("#### Portfolio Value Over Time")
fig, ax = plt.subplots(figsize=(10, 5))
ax.plot(portfolio_df.index, portfolio_df['value'], label='Strategy Portfolio', color='blue')
# Add Buy & Hold Benchmark
benchmark_value = (df_original['Close'] / df_original['Close'].iloc[0]) * initial_capital_input
ax.plot(df_original.index, benchmark_value, label=f'Buy & Hold Market ({df_original.columns[3]})', linestyle='--', color='grey')
ax.set_xlabel("Date")
ax.set_ylabel("Portfolio Value ($)")
ax.set_title("Portfolio Value vs. Buy & Hold")
ax.legend()
ax.grid(True)
plt.xticks(rotation=45)
plt.tight_layout()
st.pyplot(fig)
# Display Trades
if trades_df is not None and not trades_df.empty:
st.subheader("📈 Executed Trades")
st.dataframe(trades_df.style.format({"Price": "{:.2f}", "Shares": "{:.2f}", "PnL": "{:,.2f}"}))
else:
st.info("No trades were executed by the strategy.")
# Display DataFrame with signals for debugging/verification
st.subheader("🔍 Data with Signals (first 100 rows)")
st.dataframe(df_with_signals.head(100))
elif portfolio_df is None:
st.error("Backtest failed to run due to errors in strategy code or data.")
else:
st.info("Backtest completed, but no portfolio data to display (e.g., no trades or very short data).")
else:
st.warning(f"Please create a '{DATA_FILE}' file in the same directory or provide a valid path.")
st.markdown("---")
st.markdown("Created with ❤️ by a Helpful AI")
How to Run:
- Save the Python code as
backtester_app.py.
- Make sure you have
data.csv in the same directory (or update the path).
- Install necessary libraries:
pip install streamlit pandas numpy matplotlib
- Run the Streamlit app from your terminal:
streamlit run backtester_app.py
Explanation and Key Points:
load_data(): Loads your CSV, converts 'Date' to datetime, and sets it as index.
strategy_code execution:
exec(strategy_code, globals(), exec_scope) is used to run the user's Python string.
exec_scope is a dictionary that provides a local namespace for the executed code. We pass df, pd, and np into it, so the user's code can access them.
- After execution, we retrieve the (potentially modified)
df from exec_scope.
- Crucially, the user's code must create a column named
signal in the df.
run_backtest():
- Initializes
cash, holdings, position (to track long/short/flat state).
- Iterates row by row (day by day).
- Trading Logic:
- If
signal == 1 (Buy):
- If short, covers the short position first.
- Then, if cash available, buys shares (all-in for simplicity).
- Updates
cash, holdings, position.
- Records the trade.
- If
signal == -1 (Sell):
- If long, sells the long position first.
- Then, goes short (simplified: assumes shorting power equivalent to initial capital).
- Updates
cash, holdings (becomes negative for shorts), position.
- Records the trade.
portfolio_history tracks the daily value of the portfolio.
- End-of-Loop Liquidation: If there's an open position at the end of the data, it's automatically closed at the last available price to realize final P&L.
calculate_metrics(): Computes common metrics like Total Return, Annualized Return, Sharpe Ratio, Max Drawdown, Win Rate, etc. Includes a Buy & Hold benchmark.
- Streamlit UI:
- Provides a text area for the strategy code.
- A button to trigger the backtest.
- Displays metrics in a table.
- Plots portfolio value over time against a Buy & Hold benchmark.
- Shows a list of executed trades.
To Improve/Extend (Future):
- Commissions & Slippage: Add transaction costs.
- Position Sizing: Allow more complex sizing (e.g., fixed percentage, Kelly criterion).
- Order Types: Limit, Stop-loss orders.
- Shorting Mechanics: More realistic shorting with margin accounts.
- Parameter Optimization: Allow running backtests with varying strategy parameters.
- More Metrics: Volatility, Sortino Ratio, Calmar Ratio.
- Interactive Charts: Use Plotly or Bokeh for more interactivity.
- Error Handling: More robust error handling for user strategy code.
- Data Source: Allow uploading CSV or connecting to APIs.
This provides a solid foundation for your dynamic backtesting app!