I am trying to generate weekly and monthly logs but since the max resolution is daily level I am using consolidators . The consolidators have been instead giving me daily level inputs only. I think there might be an issue with my implementation . Can someone please point out what could be the issue ?
from AlgorithmImports import *
from datetime import datetime
from QuantConnect.Data.Consolidators import TradeBarConsolidator
from QuantConnect.Data.Consolidators import CalendarType
class FlipCountTradingAlgorithm(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2018, 1, 1)
self.SetEndDate(datetime.today())
self.SetCash(10000000)
self.UniverseSettings.Resolution = Resolution.Daily
self.AddUniverse(self.CoarseSelectionFunction, self.FineSelectionFunction)
self.data = {}
consolidator = TradeBarConsolidator(CalendarType.Weekly)
consolidator.DataConsolidated += self.OnDataConsolidated
#self.SubscriptionManager.AddConsolidator(symbol, consolidator)
self.buy_threshold = 9
self.sell_threshold = 9
self.ten_billion_universe = []
self.fifteen_billion_universe = []
self.logs = {}
self.current_date = None
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[:500]]
def FineSelectionFunction(self, fine):
ten_billion_universe = [x.Symbol for x in fine if x.MarketCap > 1e10]
fifteen_billion_universe = [x.Symbol for x in fine if x.MarketCap > 1.5e10]
self.ten_billion_universe = ten_billion_universe
self.fifteen_billion_universe = fifteen_billion_universe
return list(set(ten_billion_universe + fifteen_billion_universe))
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
self.data[symbol] = ({
'price_window': RollingWindow[TradeBar](10) ,
'buy_count': 0,
'sell_count': 0
})
consolidator = TradeBarConsolidator(CalendarType.Weekly)
consolidator.DataConsolidated += self.OnDataConsolidated
self.SubscriptionManager.AddConsolidator(symbol, consolidator)
#self.RegisterIndicator(symbol, self.data[symbol]['price_window'], consolidator)
def OnDataConsolidated(self, sender, bar):
# symbol = bar.Symbol
# if symbol in self.data:
# self.data[symbol]['price_window'].Add(bar)
if bar.Symbol in self.data:
stock_data = self.data[bar.Symbol]
stock_data['price_window'].Add(bar) # Add the entire bar, not just the close price
def OnData(self, data):
if self.current_date != self.Time.date():
self.current_date = self.Time.date()
self.logs[self.current_date] = {"buy": [], "sell": []}
for symbol, stock_data in self.data.items():
if data.Bars.ContainsKey(symbol):
bar = data.Bars[symbol]
stock_data['price_window'].Add(bar)
if stock_data['price_window'].IsReady:
current_close = stock_data['price_window'][0].Close
past_close = stock_data['price_window'][4].Close
if current_close > past_close:
stock_data['buy_count'] += 1
stock_data['sell_count'] = 0
elif current_close < past_close:
stock_data['sell_count'] += 1
stock_data['buy_count'] = 0
else:
stock_data['buy_count'] = 0
stock_data['sell_count'] = 0
if symbol in self.ten_billion_universe and stock_data['buy_count'] > self.buy_threshold:
self.logs[self.current_date]["buy"].append(symbol)
if symbol in self.fifteen_billion_universe and stock_data['sell_count'] > self.sell_threshold:
self.logs[self.current_date]["sell"].append(symbol)
def OnEndOfAlgorithm(self):
self.Liquidate()
self.Debug("Liquidated all positions at the end of the algorithm.")
with open("logs.txt", 'w') as log_file:
for date, actions in self.logs.items():
buy_symbols = actions["buy"]
sell_symbols = actions["sell"]
if buy_symbols or sell_symbols:
log_line = f"{date}: Buy - {', '.join([str(symbol) for symbol in buy_symbols])}, Sell - {', '.join([str(symbol) for symbol in sell_symbols])}"
log_file.write(log_line + '\n')
self.Debug(log_line)
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!