In this also, does anyone know how I can modify the to get CCI for yesterday and CCI for day before yesterday? I have tried at least 50 different ways and keeps getting errors
#region imports
from AlgorithmImports import *
#endregion
from datetime import datetime
from datetime import timedelta
class BasicTemplateAlgorithm(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2021,2,20)
self.SetCash(5000000)
self.Data_Symbol = {}
tickers = ["SPY", "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)
## Dictionary for whether we can trade this symbol; we will reset this at end of each day
self.canTradeSymbol = { symbol: True for symbol in self.Data_Symbol.keys() }
self.Schedule.On(self.DateRules.EveryDay("SPY"),
self.TimeRules.BeforeMarketClose('SPY', 0),
self.ResetSymbolTraded)
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
OpenOrders = self.Transactions.GetOpenOrders(symbol)
cci = symbol_data.cci.Current.Value
close = symbol_data.close.Current.Value
openprice = symbol_data.open.Current.Value
high = symbol_data.high.Current.Value
low = symbol_data.low.Current.Value
# Check whether we can trade this symbol
can_trade = self.canTradeSymbol[symbol]
if not can_trade:
continue
if OpenOrders: return #Store only 1 order per ticker
#Buy symbol if CCI < 100
if (not invested) and (cci < -100) and nowprice > openprice:
self.MarketOrder(symbol, 1000)
self.Debug(f'Bought {symbol} at {self.Time}')
# Sell symbol
if invested and (nowprice > aveprice * 1.05):
self.MarketOrder (symbol, (-1 * quantity))
self.Debug(f'Liquidated {symbol} at {self.Time}.')
# Now after a buy/sell, we prevent future buys for the rest of the day
self.canTradeSymbol[symbol] = False
def ResetSymbolTraded(self):
## We reset this to Trade at end of each day
self.canTradeSymbol = { symbol: True for symbol in self.Data_Symbol.keys() }
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)
self.close = algo.Identity(symbol, Resolution.Daily,Field.Close)
self.open = algo.Identity(symbol, Resolution.Daily,Field.Open)
self.high = algo.Identity(symbol, Resolution.Daily,Field.High)
self.low = algo.Identity(symbol, Resolution.Daily,Field.Low)
Mia Alissi
To access the CCI values for yesterday and the day before yesterday, you can use a
RollingWindow
object. This allows you to store a history of indicator values and access them as needed. Here's how you can modify theSymbolData
class to include aRollingWindow
for the CCI indicator:In your main algorithm, you need to ensure that the
UpdateWindow
method of eachSymbolData
instance is called every time new data is received. This can be done in theEveryDayAfterMarketOpen
method, right after checking if the CCI is ready:This approach allows you to keep track of the CCI values over the last few days and use them in your trading logic. Remember to check if the
cciWindow
is ready before accessing its elements to avoid index errors.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!