Hi Flame,
Thank you for your question, and your idea is really good. To implement various comparisons of current price to 52-week highs and lows, I build a SymbolData class for this as follows.
class SymbolData:
def __init__(self, algorithm, symbol, lookback):
self.symbol = symbol
self.Max = Maximum(lookback)
self.Min = Minimum(lookback)
### or
# self.Max = algorithm.MAX(symbol, lookback, Resolution.Daily)
# self.Min = algorithm.MIN(symbol, lookback, Resolution.Daily)
self.window = RollingWindow[TradeBar](lookback)
algorithm.Consolidate(symbol, CalendarType.Weekly, self.CalendarTradeBarHandle)
def CalendarTradeBarHandle(self, bar):
self.Max.Update(bar.EndTime, bar.Close)
self.Min.Update(bar.EndTime, bar.Close)
self.window.Add(bar)
First, I use MAX and MIN indicators to get the daily highs and lows. Then, I use Conlidator to get weekly highs and lows from daily data. As you can see, the indicators get updated through RollingWindow. After building this SymbolData Class, all we need to do is to fill the Update and OnSecuritiesChanged methods in the Alpha Model class. Since there is no specific trading logic in your description, for now, I can only write a basic structure for you in the following backtest. You can improve the algorithm based on your trading logic. For more information on Alpha Model, please see examples in this page.