I am trying to have a basic momentum strategy but am unable to generate any trades
Can you please help me find the issue
from AlgorithmImports import *
from System.Collections.Generic import Dictionary
import numpy as np
class EqualWeightLongShort(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2020, 1, 1)
self.SetEndDate(2021, 12, 31)
self.SetCash(10000000)
self.spy = self.AddEquity("SPY", Resolution.Daily).Symbol
self.ivv = self.AddEquity("IVV", Resolution.Daily).Symbol
# Dow Jones constituents as of 2021
self.dow_jones_symbols = [
"AAPL", "AMGN", "AXP", "BA", "CAT", "CRM", "CSCO", "CVX", "DIS", "DOW",
"GS", "HD", "HON", "IBM", "INTC", "JNJ", "JPM", "KO", "MCD", "MMM",
"MRK", "MSFT", "NKE", "PG", "TRV", "UNH", "V", "VZ", "WBA", "WMT"
]
self.symbols = [self.AddEquity(symbol, Resolution.Daily).Symbol for symbol in self.dow_jones_symbols]
self.UniverseSettings.Resolution = Resolution.Daily
self.lookback = 21
self.week_lookback = 7
self.two_week_lookback = 12
self.long_list = []
self.short_list = []
self.max_allocation = 0.05
def OnData(self, data):
if not self.symbols:
return
for symbol in self.symbols:
if symbol not in data or not data[symbol] or not self.Securities[symbol].HasData:
continue
current_bar = data[symbol]
history = self.History(symbol, self.lookback + 2, Resolution.Daily)
if len(history) < self.lookback + 2:
continue
high_prices = history['high'].values
low_prices = history['low'].values
close_prices = history['close'].values
max_high = np.max(high_prices[-22:-5])
min_low = np.min(low_prices[-22:-5])
week_low = np.min(low_prices[-self.week_lookback:-5])
two_week_low = np.min(low_prices[-self.two_week_lookback:-5])
week_to_two_week_low = np.min(low_prices[-self.two_week_lookback:-7])
week_high = np.max(high_prices[-self.week_lookback:-5])
yesterday_close = close_prices[-2]
# Long entry condition
if max_high >= 20 and symbol not in self.long_list:
self.long_list.append(symbol)
if symbol in self.short_list:
self.short_list.remove(symbol)
if yesterday_close >= max_high and symbol not in self.long_list:
self.long_list.append(symbol)
if symbol in self.short_list:
self.short_list.remove(symbol)
# Short entry condition
if yesterday_close <= min_low and symbol not in self.short_list:
self.short_list.append(symbol)
if symbol in self.long_list:
self.long_list.remove(symbol)
# Long exit conditions
if symbol in self.long_list:
if yesterday_close <= week_to_two_week_low:
self.long_list.remove(symbol)
# Short exit conditions
if symbol in self.short_list:
if history['high'].iloc[-2] > week_high:
self.short_list.remove(symbol)
self.Rebalance()
def Rebalance(self):
# Remove symbols with zero quantity from lists
for symbol in list(self.Portfolio.Keys):
if self.Portfolio[symbol].Quantity == 0:
if symbol in self.long_list:
self.long_list.remove(symbol)
if symbol in self.short_list:
self.short_list.remove(symbol)
num_longs = len([s for s in self.long_list if s != self.spy])
num_shorts = len([s for s in self.short_list if s != self.ivv])
long_allocation = min(self.max_allocation, 1.0 / max(num_longs, 1))
short_allocation = min(self.max_allocation, 1.0 / max(num_shorts, 1))
total_long_allocation = long_allocation * num_longs
total_short_allocation = short_allocation * num_shorts
spy_allocation = 1 - total_long_allocation
ivv_allocation = 1 - total_short_allocation
# Place orders for long positions
for symbol in self.long_list:
if symbol != self.spy:
self.SetHoldings(symbol, long_allocation)
# Place orders for short positions
for symbol in self.short_list:
if symbol != self.ivv:
self.SetHoldings(symbol, -short_allocation)
def OnOrderEvent(self, orderEvent):
if orderEvent.Status == OrderStatus.Filled:
order = self.Transactions.GetOrderById(orderEvent.OrderId)
symbol = order.Symbol
if order.Direction == OrderDirection.Sell and symbol in self.long_list:
self.long_list.remove(symbol)
elif order.Direction == OrderDirection.Buy and symbol in self.short_list:
self.short_list.remove(symbol)
def OnEndOfDay(self):
self.Log(f"End of Day: {self.Time}, Long List: {self.long_list}, Short List: {self.short_list}")
Louis Szeto
Hi Tushar
The main problem is in line 78-84:
you are removing every stock in each list, since no stock will have non-zero quantity before opening position.
Best
Louis
The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
Tushar Verma
The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
To unlock posting to the community forums please complete at least 30% of Boot Camp.
You can continue your Boot Camp training progress from the terminal. We hope to see you in the community soon!