Okay, this is a fantastic project request! It involves data downloading, financial calculations, portfolio management, and GUI interaction.
Let's break down the strategy and requirements:
Strategy: "Bounce from 200 dMa"
- Condition: A stock generates a buy signal when its closing price crosses above the 200-day Moving Average (DMA), having been at or below it on the previous trading day.
- Today:
Close > 200 DMA
- Yesterday:
Close <= 200 DMA
- Action: Buy and hold. No explicit sell signal is provided, so positions will be held until the end of the backtest period.
Backtest Parameters:
- Initial Capital: $50,000
- Max Positions: 5 (meaning you can hold up to 5 different stocks at any given time).
- Backtest Period: 3 years back from the current date.
- Ticker Selection: From an unnamed column in an Excel file (using a file open dialogue).
- Compounding: Yes, profits/losses on closed trades (though none are closed in this "buy and hold" unless explicitly sold, which is not defined here) and the value of open positions will influence the overall equity curve and potential for future trades (if capital were re-deployed, which isn't the case here, as we only add new positions, not sell existing ones). The
current_capital will represent the uninvested cash, while total_portfolio_value will include both cash and the market value of open positions.
Implementation Steps:
- Libraries:
pandas for data manipulation, yfinance for historical data, datetime for date handling, tkinter for file dialogue, matplotlib for plotting.
- File Input: Use
tkinter.filedialog to let the user select the Excel file. pandas.read_excel will read it. Assume the tickers are in the first column found.
- Data Download: For each ticker, download historical daily data using
yfinance. Ensure enough past data is downloaded to calculate the initial 200 DMA (e.g., 250 days before the backtest start).
- Backtest Loop: Iterate day by day over the 3-year period.
- Portfolio State: Keep track of
current_capital (uninvested cash), open_positions (a dictionary of active trades), and equity_curve (list of total portfolio value over time).
- Signal Generation: For each ticker not currently held:
- Calculate the 200 DMA for the current day.
- Check the "bounce" condition.
- Trade Execution: If a buy signal is generated and
len(open_positions) < MAX_POSITIONS:
- Calculate the amount to invest: Distribute the
current_capital evenly among the remaining available slots for new positions. E.g., if you have 20,000cashand2slotsleft,eachnewtra10,000.
- Portfolio Valuation: At the end of each day, calculate the total portfolio value (
current_capital + sum of current_value of open_positions). Append to equity_curve.
- Results: Print a summary (final capital, total return, number of trades). Plot the
equity_curve.
Let's write the Python script.
import pandas as pd
import yfinance as yf
from datetime import datetime, timedelta
import tkinter as tk
from tkinter import filedialog, messagebox
import matplotlib.pyplot as plt
import numpy as np
# --- Configuration Parameters ---
INITIAL_CAPITAL = 50000
MAX_POSITIONS = 5
BACKTEST_PERIOD_YEARS = 3
DMA_PERIOD = 200 # Days for Moving Average
# --- Helper Functions ---
def get_tickers_from_excel():
"""Opens a file dialogue to select an Excel file and extracts tickers."""
root = tk.Tk()
root.withdraw() # Hide the main window
file_path = filedialog.askopenfilename(
title="Select Excel file with tickers",
filetypes=[("Excel files", "*.xlsx *.xls")]
)
if not file_path:
messagebox.showerror("Error", "No Excel file selected. Exiting.")
return None
try:
df = pd.read_excel(file_path, header=None) # Read without header
# Assume tickers are in the first non-empty column
# Find the first column with values that look like stock tickers (non-numeric, non-empty)
tickers = []
for col in df.columns:
# Try to convert to string and filter out potential NaNs or purely numeric values
potential_tickers = df[col].dropna().astype(str).unique()
# Basic heuristic: Check if there's at least one non-numeric looking string
if any(not s.isdigit() and s.isalnum() for s in potential_tickers):
tickers = [t for t in potential_tickers if isinstance(t, str) and t.strip()] # Filter out empty strings
break
if not tickers:
messagebox.showerror("Error", "Could not find any tickers in the selected Excel file. Please ensure tickers are in a column.")
return None
print(f"Tickers loaded: {tickers}")
return tickers
except Exception as e:
messagebox.showerror("Error", f"Failed to read Excel file: {e}")
return None
def download_data(tickers, start_date, end_date):
"""Downloads historical data for multiple tickers and calculates DMAs."""
all_data = {}
print(f"Downloading data from {start_date.strftime('%Y-%m-%d')} to {end_date.strftime('%Y-%m-%d')}...")
for ticker in tickers:
try:
# Download a bit more data to ensure 200 DMA can be calculated from the very start
df = yf.download(ticker, start=start_date - timedelta(days=DMA_PERIOD + 50), end=end_date)
if df.empty:
print(f"Warning: No data found for {ticker}. Skipping.")
continue
df['200DMA'] = df['Close'].rolling(window=DMA_PERIOD, min_periods=1).mean()
all_data[ticker] = df
print(f"Downloaded data for {ticker}")
except Exception as e:
print(f"Error downloading {ticker}: {e}. Skipping.")
return all_data
def run_backtest():
"""Executes the backtest strategy."""
tickers = get_tickers_from_excel()
if not tickers:
return
end_date = datetime.now()
start_date = end_date - timedelta(days=BACKTEST_PERIOD_YEARS * 365) # Approximate 3 years
# Download all necessary data upfront
ticker_data = download_data(tickers, start_date, end_date)
if not ticker_data:
messagebox.showerror("Error", "No valid ticker data downloaded. Exiting.")
return
# Create a unified date range for the backtest
# This ensures we iterate through all market days covered by our data
all_dates = sorted(pd.concat([data.index for data in ticker_data.values()]).unique())
backtest_dates = [d for d in all_dates if start_date <= d.to_pydatetime() <= end_date]
# --- Backtest Initialization ---
current_capital = INITIAL_CAPITAL
open_positions = {} # {ticker: {'shares': X, 'buy_price': Y, 'buy_date': Z}}
equity_curve = [] # List of (date, total_portfolio_value) tuples
trade_log = [] # For detailed record keeping
print("\n--- Starting Backtest ---")
for i, current_date in enumerate(backtest_dates):
current_date_str = current_date.strftime('%Y-%m-%d')
# Calculate current total portfolio value
total_portfolio_value = current_capital
for ticker, pos in open_positions.items():
if ticker in ticker_data:
df = ticker_data[ticker]
# Get the last available closing price up to current_date
try:
current_price_series = df.loc[df.index <= current_date, 'Close']
if not current_price_series.empty:
current_price = current_price_series.iloc[-1]
total_portfolio_value += pos['shares'] * current_price
else:
print(f"Warning: No price data for {ticker} on or before {current_date_str}. Skipping valuation for this stock today.")
except Exception as e:
print(f"Error getting price for {ticker} on {current_date_str}: {e}")
equity_curve.append((current_date, total_portfolio_value))
# Check for new buy signals
if len(open_positions) < MAX_POSITIONS:
available_slots = MAX_POSITIONS - len(open_positions)
# Allocate a portion of available capital for each new potential trade
# This ensures compounding if current_capital grows, or limits trade size if it shrinks
trade_budget_per_slot = current_capital / available_slots if available_slots > 0 else 0
for ticker in tickers:
if ticker not in open_positions and ticker in ticker_data:
df = ticker_data[ticker]
# Ensure we have enough historical data points for DMA and yesterday's close
if len(df[df.index <= current_date]) < DMA_PERIOD + 1:
# print(f"Not enough data for {ticker} on {current_date_str} to calculate DMA.")
continue
# Get today's and yesterday's data
try:
today_data_series = df.loc[df.index == current_date]
if today_data_series.empty:
# print(f"No data for {ticker} on {current_date_str}. Skipping signal check.")
continue
today_close = today_data_series['Close'].iloc[0]
today_dma = today_data_series['200DMA'].iloc[0]
# Find yesterday's data (previous trading day)
prev_trading_days = df.loc[df.index < current_date].tail(1)
if prev_trading_days.empty:
# print(f"No previous day data for {ticker} before {current_date_str}. Skipping signal check.")
continue
yesterday_close = prev_trading_days['Close'].iloc[0]
yesterday_dma = prev_trading_days['200DMA'].iloc[0]
# Check if DMA and prices are valid (not NaN)
if pd.isna(today_dma) or pd.isna(today_close) or pd.isna(yesterday_dma) or pd.isna(yesterday_close):
# print(f"NaN data for {ticker} on {current_date_str}. Skipping signal check.")
continue
# --- Bounce Strategy Logic ---
buy_signal = (today_close > today_dma) and (yesterday_close <= yesterday_dma)
if buy_signal:
if current_capital >= trade_budget_per_slot and today_close > 0:
shares_to_buy = int(trade_budget_per_slot // today_close)
if shares_to_buy > 0:
cost = shares_to_buy * today_close
current_capital -= cost
open_positions[ticker] = {
'shares': shares_to_buy,
'buy_price': today_close,
'buy_date': current_date
}
trade_log.append({
'Date': current_date,
'Ticker': ticker,
'Type': 'BUY',
'Price': today_close,
'Shares': shares_to_buy,
'Cost': cost,
'Remaining_Capital': current_capital,
'Portfolio_Value_Before_Trade': total_portfolio_value
})
print(f"[{current_date_str}] BUY {shares_to_buy} shares of {ticker} @ ${today_close:.2f}. Capital left: ${current_capital:.2f}. Positions: {len(open_positions)}/{MAX_POSITIONS}")
# Break to ensure only one trade per day (optional, but good for managing positions)
# or allow multiple if there are multiple signals and slots
# For this backtest, we'll continue to check other tickers if slots are available
else:
pass # Not enough capital for even 1 share
else:
pass # Not enough budget for this trade size or current capital insufficient
except KeyError as e:
# This can happen if 'Close' or '200DMA' columns are missing or data is malformed
print(f"Data key error for {ticker} on {current_date_str}: {e}. Skipping signal check.")
except IndexError:
# This can happen if there isn't enough historical data for .iloc[0] or .iloc[-1]
# print(f"Insufficient data index for {ticker} on {current_date_str}. Skipping signal check.")
pass # Ignore cases where there's not enough data for lookback
if i % 100 == 0: # Print progress every 100 days
print(f"Processing day {i+1}/{len(backtest_dates)} ({current_date_str}). Portfolio Value: ${total_portfolio_value:.2f}")
# --- Backtest Summary ---
print("\n--- Backtest Finished ---")
final_portfolio_value = equity_curve[-1][1] if equity_curve else INITIAL_CAPITAL
total_return = (final_portfolio_value - INITIAL_CAPITAL) / INITIAL_CAPITAL * 100
print(f"\nInitial Capital: ${INITIAL_CAPITAL:,.2f}")
print(f"Final Portfolio Value: ${final_portfolio_value:,.2f}")
print(f"Total Return: {total_return:.2f}%")
print(f"Number of Trades Executed: {len(trade_log)}")
print(f"Number of Open Positions at End: {len(open_positions)}")
# Details of open positions at the end
if open_positions:
print("\n--- Open Positions Details ---")
for ticker, pos in open_positions.items():
if ticker in ticker_data:
latest_close = ticker_data[ticker]['Close'].iloc[-1]
current_value = pos['shares'] * latest_close
profit_loss = (latest_close - pos['buy_price']) * pos['shares']
print(f"{ticker}: {pos['shares']} shares bought @ ${pos['buy_price']:.2f} on {pos['buy_date'].strftime('%Y-%m-%d')}. Current Value: ${current_value:,.2f} (P&L: ${profit_loss:,.2f})")
else:
print(f"{ticker}: Data not available for final valuation.")
# --- Plotting Equity Curve ---
if equity_curve:
dates = [item[0] for item in equity_curve]
values = [item[1] for item in equity_curve]
plt.figure(figsize=(12, 6))
plt.plot(dates, values, label='Portfolio Value', color='blue')
plt.title('Portfolio Equity Curve (200 DMA Bounce Strategy)')
plt.xlabel('Date')
plt.ylabel('Portfolio Value ($)')
plt.grid(True)
plt.legend()
plt.tight_layout()
plt.show()
else:
print("No equity curve data to plot.")
# Optional: Save trade log to CSV
if trade_log:
trade_log_df = pd.DataFrame(trade_log)
# You can save this to a file if needed:
# trade_log_df.to_csv("trade_log.csv", index=False)
# print("\nTrade log saved to trade_log.csv")
pass
if __name__ == "__main__":
run_backtest()
How to Use the Script:
- Save: Save the code above as a Python file (e.g.,
backtest_strategy.py).
- Install Libraries: If you don't have them, open your terminal or command prompt and run:
pip install pandas yfinance matplotlib openpyxl xlrd tkinter
openpyxl and xlrd are necessary for pandas to read .xlsx and .xls files, respectively.
- Prepare Your Excel File:
- Create an Excel file (e.g.,
tickers.xlsx).
- In any column, simply list the stock tickers (e.g., AAPL, MSFT, GOOG, TSLA, AMZN, NVDA, etc.). The script will try to find the first column that contains non-numeric strings.
- Example
tickers.xlsx content (column A):
AAPL
MSFT
GOOGL
SMCI
AMD
- Run the Script: Execute the script from your terminal:
python backtest_strategy.py
- Select Excel File: A file open dialogue window will appear. Navigate to and select your
tickers.xlsx file.
- Observe Output:
- The script will print messages about data downloading and trade execution.
- Once the backtest is complete, it will print a summary (initial capital, final value, total return, number of trades).
- A
matplotlib window will pop up displaying the portfolio's equity curve over the 3-year period.
Important Considerations & Limitations:
- No Sell Logic: This is a pure "buy and hold" once a position is initiated. If you want to add sell conditions (e.g., trailing stop, target profit, break below DMA), you'd need to extend the
run_backtest function to iterate through open_positions daily and check sell signals.
- Trade Sizing: The current logic tries to fill
MAX_POSITIONS by dividing the remaining available capital by the remaining available slots. This means if you have 50,000and5slots,thefirsttradeco10,000, then you have 10,000, and so on. If capital grows, subsequent trades might be larger. If capital shrinks, they might be smaller.