Code Generator | Python
Simple Moving Average Crossover Trading Model in Python
This guide details the creation of a basic quantitative trading model using Python. It employs moving averages to generate buy/sell signals based on historical price data, including steps for data retrieval, preprocessing, signal
Prompt
Answer
Quantitative Trading Model in Python
Introduction
This document outlines the creation of a simple quantitative trading model in Python. The model will use historical price data to generate buy/sell signals based on moving averages. We'll implement the following key steps:
- Data Retrieval
- Data Preprocessing
- Signal Generation
- Backtesting
- Evaluation Metrics
Necessary Imports
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import yfinance as yf
Function: Create Trading Model
def create_trading_model(ticker: str, start_date: str, end_date: str, short_window: int, long_window: int):
"""
Create a simple moving average crossover trading model.
Parameters:
- ticker (str): The stock ticker symbol for the desired asset.
- start_date (str): The start date for historical data in 'YYYY-MM-DD' format.
- end_date (str): The end date for historical data in 'YYYY-MM-DD' format.
- short_window (int): The window size for the short-term moving average.
- long_window (int): The window size for the long-term moving average.
Returns:
- signals (pd.DataFrame): DataFrame containing stock prices and trading signals.
- performance (dict): Performance metrics of the strategy including total return and Sharpe ratio.
Raises:
- ValueError: If the date range is invalid.
- KeyError: If the ticker symbol is invalid.
"""
# Input validation
if short_window <= 0 or long_window <= 0:
raise ValueError("Short and long windows must be positive integers.")
if short_window >= long_window:
raise ValueError("Short window must be smaller than long window.")
# Step 1: Data Retrieval
df = yf.download(ticker, start=start_date, end=end_date)
# Step 2: Data Preprocessing
df['Short_MA'] = df['Close'].rolling(window=short_window).mean() # Short-term moving average
df['Long_MA'] = df['Close'].rolling(window=long_window).mean() # Long-term moving average
# Step 3: Signal Generation
df['Signal'] = 0 # Initialize signals
df['Signal'][short_window:] = np.where(df['Short_MA'][short_window:] > df['Long_MA'][short_window:], 1, 0)
df['Position'] = df['Signal'].diff() # Identify changes in signal
# Step 4: Backtesting
initial_capital = 10000 # Starting capital
shares = 100 # Number of shares to trade
df['Portfolio_Value'] = initial_capital + (df['Position'] * shares * df['Close']).cumsum()
# Step 5: Evaluation Metrics
total_return = df['Portfolio_Value'].iloc[-1] - initial_capital
daily_returns = df['Portfolio_Value'].pct_change().dropna()
sharpe_ratio = np.mean(daily_returns) / np.std(daily_returns) * np.sqrt(252) # Annualize Sharpe Ratio
performance = {'Total Return': total_return, 'Sharpe Ratio': sharpe_ratio}
return df[['Close', 'Short_MA', 'Long_MA', 'Signal', 'Position', 'Portfolio_Value']], performance
Code Usage Example
To use the function and evaluate the performance of a trading model, follow this example:
# Define parameters
ticker = 'AAPL'
start_date = '2020-01-01'
end_date = '2023-01-01'
short_window = 20
long_window = 50
# Create the trading model
signals, performance = create_trading_model(ticker, start_date, end_date, short_window, long_window)
# Display signals and performance metrics
print(signals.tail()) # Show last few rows of signals
print("Performance Metrics:", performance) # Print performance metrics
Conclusion
This code implements a basic quantitative trading model using moving averages to generate buy/sell signals. It is designed to be extendable with additional strategies or indicators as needed. For further learning on advanced models and analytics, consider exploring the courses available on the Enterprise DNA platform.
Notes
- Ensure
yfinance
is installed in your Python environment:pip install yfinance
. - Modify parameters for different tickers and timeframes to test various strategies.
This model serves as a foundational framework to build more complex trading strategies, incorporating additional features like risk management, more technical indicators, and optimization techniques as necessary.
Description
This guide details the creation of a basic quantitative trading model using Python. It employs moving averages to generate buy/sell signals based on historical price data, including steps for data retrieval, preprocessing, signal generation, backtesting, and evaluation.