Any takers on this, I can use some help. I am trying to improve this algorithm to NOT buy a stock if the same stock has been sold on that same day (Technically trying to prevent day trading - am too broke to afford 25k minimum). I tried navigating my code by attempting to debug the date a symbol is sold then looping around telling the buy function not to buy any symbol that the algo had/has sold within that same market day. The ago I have so far gives an error when I attempt backtest (see attached algo). Will really appreciate any help I can get on this
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",
]
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)
Adam W
You can just create some dictionary that indicates whether you sold the stock, then use a Scheduled Function at end of each day to reset it to False.
Lemuel Mwangi
@Adam, when I run the back test on your edit, the algo is re-buying the symbols 1-2 minutes after selling them. I tried playing around the False/True flag, but doesn't see to figure how to prevent the someday rebuying after selling
Lemuel Mwangi
@Adam, when I run the back test on your edit, the algo is re-buying the symbols 1-2 minutes after selling them. I tried playing around the False/True flag, but doesn't see to figure how to prevent the someday rebuying after selling
See backtest below
Newoptionz
Lemuel Mwangi this code solves the ‘don’t buy the same day if you have sold that day' problem. It does though still initiate a buy-on open for the next day. Quite impressive 100% win rate, but this is negated by the fact that there is no stop-loss.
Thanks
Vladimir
Lemuel Mwangi
→ I am trying to improve this algorithm to NOT buy a stock if the same stock has been sold on that same day.
You can use self.Schedule.On() to trade once a day like in “Oversold CCI portfolio with Take Profit and Stop Loss”.
If you are satisfied with my answer, please accept it and don't forget to like it
Adam W
Lemuel Mwangi
@Adam, when I run the back test on your edit, the algo is re-buying the symbols 1-2 minutes after selling them. I tried playing around the False/True flag, but doesn't see to figure how to prevent the someday rebuying after selling
Try this instead. I'm running a backtest so can't check if this works, but it should.
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!