For algo below, assume I only want to buy 1 share of MSFT, and prevent the algo from buying any only subsequent positions (AAPL or AMZN . . . etc) unless and until when AAPL unrealized profit is > 0%, does anyone know how I can implement that?
As in, only add new positions only if all the existing positions have an unrealized profit > 0
from datetime import datetime
from datetime import timedelta
class BasicTemplateAlgorithm(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2022,2,20)
self.SetCash(50000000)
self.Data_Symbol = {}
tickers = ["SPY", #10 stocks per row
#Longs
"AAPL", "MSFT", "AMZN", "XOM", "HD",
]
self.SetWarmUp(30, Resolution.Daily)
for stock in tickers:
symbol = self.AddEquity(stock, Resolution.Minute).Symbol
self.Data_Symbol[symbol] = SymbolData(self, symbol)
self.Schedule.On(self.DateRules.EveryDay("SPY"), self.TimeRules.Every(timedelta(minutes=1)), self.EveryDayAfterMarketOpen)
def EveryDayAfterMarketOpen(self):
if self.IsWarmingUp: return
for symbol, symbol_data in self.Data_Symbol.items():
if not symbol_data.cci.IsReady: continue
holdings = self.Portfolio[symbol]
invested = holdings.Invested
nowprice = holdings.Price
aveprice = holdings.AveragePrice
quantity = holdings.Quantity
cci = symbol_data.cci.Current.Value
#Buy symbol only if if CCI < 100 and that symbol was not sold today
if not invested and not sold_today and cci < -100:
self.MarketOrder(symbol, + mofactor)
self.Debug (symbol)
self.Debug (self.Time.date)
what_to_buy = (symbol)
when_to_buy = (self.Time.date)
tobuy = what_to_buy and when_to_buy
if invested and nowprice > aveprice * 1.01:
self.MarketOrder (symbol, (-1 * quantity))
self.Debug (symbol)
self.Debug (self.Time.date)
sold_symbol = (symbol)
when_sold = (self.Time.date)
sold_today = sold_symbol and when_sold
class SymbolData:
def __init__ (self,algo,symbol):
self.algorithm = algo
self.symbol = symbol
#CCI Functions
self.cci = algo.CCI(symbol, 14, MovingAverageType.Simple, Resolution.Daily)
Mia Alissi
To implement the functionality where the algorithm only buys a new position if all existing positions have an unrealized profit greater than 0%, you can add a check before making any new purchase. This check will iterate through all existing positions and verify if they all have an unrealized profit greater than 0%. If this condition is met, the algorithm can proceed to make a new purchase. Here's how you can modify the
EveryDayAfterMarketOpen
method to include this logic:A few things to note:
sold_today
is a flag you manage elsewhere in your code to indicate if a symbol was sold today. You need to ensure this flag is correctly updated elsewhere in your algorithm.mofactor
is mentioned in your original code snippet but not defined. Ensure it is defined appropriately elsewhere in your code.MarketOrder
function is modified to buy only 1 share of the symbol as per your requirement.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.
Lemuel Mwangi
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!