Created
June 15, 2023 16:24
-
-
Save 18182324/bc1e9aa66dc2f32788b1df13af77ffae to your computer and use it in GitHub Desktop.
SPY Trading Algo - Kaufmann Market Efficiency
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Here's a full example of Perry Kaufman's market efficiency strategy implemented in Python, including backtesting capabilities | |
#using historical data. Remember that this is a simplified example for educational purposes, and it does not include considerations | |
#such as transaction costs or slippage. | |
pip install pandas numpy yfinance matplotlib | |
import pandas as pd | |
import numpy as np | |
import yfinance as yf | |
import matplotlib.pyplot as plt | |
# Function to calculate the efficiency ratio | |
def calculate_efficiency_ratio(data, period=10): | |
movement_speed = data['Close'].diff(periods=period) | |
volatility = data['Close'].diff().abs().rolling(window=period).sum() | |
efficiency_ratio = movement_speed / volatility | |
return efficiency_ratio | |
# Function to generate entry signals | |
def generate_entry_signals(data, entry_threshold=0.6): | |
data['Entry Signal'] = np.where(data['Efficiency Ratio'] > entry_threshold, 1, 0) | |
return data['Entry Signal'] | |
# Function to backtest the strategy | |
def backtest_strategy(data, entry_threshold=0.6): | |
data['Entry Signal'] = generate_entry_signals(data, entry_threshold) | |
data['Position'] = data['Entry Signal'].shift() | |
data['Return'] = data['Close'].pct_change() | |
data['Strategy Return'] = data['Return'] * data['Position'] | |
data['Cumulative Return'] = (1 + data['Strategy Return']).cumprod() | |
return data['Cumulative Return'] | |
# Download historical data for SPY using Yahoo Finance | |
ticker = "SPY" | |
start_date = "2019-01-01" | |
end_date = "2022-12-31" | |
data = yf.download(ticker, start=start_date, end=end_date) | |
# Calculate the efficiency ratio | |
data['Efficiency Ratio'] = calculate_efficiency_ratio(data) | |
# Backtest the strategy | |
cumulative_returns = backtest_strategy(data) | |
# Plot the cumulative returns | |
plt.plot(cumulative_returns) | |
plt.title("Perry Kaufman's Market Efficiency Strategy - Cumulative Returns") | |
plt.xlabel("Date") | |
plt.ylabel("Cumulative Return") | |
plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment