Hi
I am trying to create a basic mean reversion strategy and placing orders worth 10,000 dollars at each of my signal but most of the orders are coming up as invalid due to insufficient funds and when I am trying to figure out the number of orders placed it is coming up as way large amount. Can you please help me figure out my issue ?
from AlgorithmImports import *
class FlipCountTradingAlgorithm(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2020, 1, 1) # Set Start Date
self.SetEndDate(2022, 1, 1) # Set End Date
self.SetCash(10000000) # Set Strategy Cash
self.UniverseSettings.Resolution = Resolution.Daily
# Add universe selection based on the top 1000 stocks by dollar volume
self.AddUniverse(self.CoarseSelectionFunction)
# Dictionary to store stock data including the rolling window
self.data = {}
def CoarseSelectionFunction(self, coarse):
sorted_by_dollar_volume = sorted(coarse, key=lambda x: x.DollarVolume, reverse=True)
return [x.Symbol for x in sorted_by_dollar_volume[:1000]]
def OnSecuritiesChanged(self, changes):
for security in changes.RemovedSecurities:
if security.Symbol in self.data:
del self.data[security.Symbol]
for security in changes.AddedSecurities:
symbol = security.Symbol
# Initialize a RollingWindow for each added security to store the last 5 close prices
self.data[symbol] = {
'price_window': RollingWindow[Decimal](5) ,
'buy_count': 0,
'position_opened': False
}
def OnData(self, data):
for symbol, stock_data in self.data.items():
if data.Bars.ContainsKey(symbol):
bar = data.Bars[symbol]
stock_data['price_window'].Add(Decimal(bar.Close))
if stock_data['price_window'].IsReady:
current_close = stock_data['price_window'][0]
past_close = stock_data['price_window'][4]
if current_close < past_close:
stock_data['buy_count'] += 1
else:
stock_data['buy_count'] = 0 # Reset if the condition breaks
# Attempt to buy $10,000 worth of stock
if stock_data['buy_count'] > 9 and not stock_data['position_opened']:
if self.Portfolio.Cash > 10000:
self.SetHoldings(symbol, 10000 / current_close)
stock_data['position_opened'] = True
#self.Debug(f"Bought {symbol} at {current_close}")
# else:
# # Find and liquidate the most profitable stock
# pass
# #self.LiquidateMostProfitable()
elif current_close < past_close and stock_data['position_opened']:
self.Liquidate(symbol)
stock_data['position_opened'] = False
#self.Debug(f"Sold {symbol} at {current_close}")
def LiquidateMostProfitable(self):
max_profit = 0
max_symbol = None
for symbol, holding in self.Portfolio.items():
profit = holding.UnrealizedProfit
if profit > max_profit:
max_profit = profit
max_symbol = symbol
if max_symbol is not None:
self.Liquidate(max_symbol)
self.Debug(f"Liquidated {max_symbol} to free up funds")
Ashutosh
Hey Tushar Verma You might want to check out the logic here. You are filtering 1000 tickers and placing orders which kills the portfolio and the liquidation logic is hardly hit to get liquid cash for further positions causing margin errors.
You might also want to add a factor for positions. Right now the orders have a huge value (for example: 623690014.3169)
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!