Below are simplified examples of both a systematic trading strategy and a discretionary trading strategy implemented in Python. Note that for the discretionary strategy, since it relies on human judgment and cannot be fully automated, the Python example will provide a framework that requires manual input to simulate decision-making.
Systematic Trading Strategy Example
Strategy: Moving Average Crossover (a simple, fully automated strategy)
Logic:
Long Signal: When the 50-day moving average crosses above the 200-day moving average.
Short Signal: When the 50-day moving average crosses below the 200-day moving average.
Python Implementation:
python
import pandas as pd
import yfinance as yf
import matplotlib.pyplot as plt
def moving_average_crossover_strategy(ticker, short_window, long_window):
"""
Systematic trading strategy based on moving average crossover.
Parameters:
- ticker (str): Stock ticker symbol.
- short_window (int): Number of days for the short moving average.
- long_window (int): Number of days for the long moving average.
Returns:
- data (DataFrame): Stock data with moving averages and signals.
"""
# Download historical stock data for the specified ticker
data = yf.download(ticker, period="1y")
# Calculate moving averages
data[f'Short_MA_{short_window}'] = data['Close'].rolling(window=short_window).mean()
data[f'Long_MA_{long_window}'] = data['Close'].rolling(window=long_window).mean()
# Create signals
data['Signal'] = 0.0
# Generate a buy signal when the short MA crosses above the long MA
data.loc[(data[f'Short_MA_{short_window}'] > data[f'Long_MA_{long_window}']) & (data[f'Short_MA_{short_window}'].shift(1) < data[f'Long_MA_{long_window}'].shift(1)), 'Signal'] = 1.0
# Generate a sell signal when the short MA crosses below the long MA
data.loc[(data[f'Short_MA_{short_window}'] < data[f'Long_MA_{long_window}']) & (data[f'Short_MA_{short_window}'].shift(1) > data[f'Long_MA_{long_window}'].shift(1)), 'Signal'] = -1.0
# Plot the stock's closing price and moving averages
plt.figure(figsize=(12,6))
plt.plot(data['Close'], label='Close Price')
plt.plot(data[f'Short_MA_{short_window}'], label=f'{short_window} Day MA')
plt.plot(data[f'Long_MA_{long_window}'], label=f'{long_window} Day MA')
plt.legend(loc='upper left')
plt.show()
return data
# Execute the strategy
ticker = "AAPL"
short_window = 50
long_window = 200
strategy_data = moving_average_crossover_strategy(ticker, short_window, long_window)
print(strategy_data.head())
Discretionary Trading Strategy Example
Strategy: Manual Technical Analysis with User Input (semi-automated, requiring human judgment)
Logic:
User Evaluates: Chart patterns (e.g., Head & Shoulders, Trends), indicators (e.g., RSI, Bollinger Bands), and other technical or fundamental factors to make a trading decision.
Python's Role: Provides visualizations of the chart and technical indicators. User inputs their decision based on analysis.
Python Implementation (Enhanced for Demonstration):
python
import pandas as pd
import yfinance as yf
import matplotlib.pyplot as plt
def discretionary_trading_framework(ticker):
"""
Discretionary trading framework with manual input and technical indicators.
Parameters:
- ticker (str): Stock ticker symbol.
"""
# Download historical stock data
data = yf.download(ticker, period="3mo")
# Calculate technical indicators for user reference
data['SMA_20'] = data['Close'].rolling(window=20).mean() # 20-day Simple Moving Average
data['SMA_50'] = data['Close'].rolling(window=50).mean() # 50-day Simple Moving Average
data['RSI'] = calculate_rsi(data['Close'], 14) # Relative Strength Index
# Plot chart with indicators for user analysis
fig, axs = plt.subplots(2, figsize=(12, 10))
axs[0].plot(data['Close'], label='Close Price')
axs[0].plot(data['SMA_20'], label='20 Day SMA')
axs[0].plot(data['SMA_50'], label='50 Day SMA')
axs[0].legend(loc='upper left')
axs[0].set_title('Price Chart with SMAs')
axs[1].plot(data['RSI'], label='RSI (14 days)')
axs[1].axhline(y=30, color='r', linestyle='--', label='Oversold (30)')
axs[1].axhline(y=70, color='g', linestyle='--', label='Overbought (70)')
axs[1].legend(loc='upper left')
axs[1].set_title('Relative Strength Index (RSI)')
plt.tight_layout()
plt.show()
# **MANUAL INPUT REQUIRED**
action = input("Based on the chart, do you want to (B)uy, (S)ell, or (H)old? ").upper()
while action not in ['B', 'S', 'H']:
action = input("Invalid input. Please enter B (Buy), S (Sell), or H (Hold): ").upper()
# Log the trading decision
decision_log = f"Ticker: {ticker}, Action: {action}\n"
with open("trading_log.txt", "a") as file:
file.write(decision_log)
print(f"Decision Logged: {decision_log}")
def calculate_rsi(prices, window=14):
"""
Calculate the Relative Strength Index (RSI) for the given price series.
Parameters:
- prices (Series): Price data.
- window (int): Time window for RSI calculation.
Returns:
- rsi (Series): RSI values.
"""
delta = prices.diff(1)
up, down = delta.copy(), delta.copy()
up[up < 0] = 0
down[down > 0] = 0
roll_up = up.rolling(window).mean()
roll_down = down.rolling(window).mean().abs()
RS = roll_up / roll_down
RSI = 100.0 - (100.0 / (1.0 + RS))
return RSI
# Execute the framework
ticker = input("Enter the stock ticker you'd like to analyze: ")
discretionary_trading_framework(ticker)
Note:
The discretionary strategy example is enhanced to include more technical indicators (SMA, RSI) and a better visualization to support user decision-making.
For both examples, this is basic Python code intended for educational purposes. Real-world trading strategies, especially systematic ones, would require more robust programming, including error handling, position sizing, risk management, and potentially backtesting frameworks.