Hello,

I'd like help fixing the code used in the attached backtest.  I received 4 suggested changes (copied below) to fix the code used in the attached backtest, but I'm struggling to implement them.  Could you please help me implement these 4 suggested changes to the code used in the attached backtest?  This is the thread where the suggestions originally appeared:

 

 

 

Move the gap universe build schedule: Run it at 9:31am (not 9:30:10) to ensure minute bar data for 9:30 is available.

self.schedule.on(self.date_rules.every_day(), self.time_rules.at(9, 31), self._build_gap_universe)

 

Loosen the coarse filter: In _coarse_select, keep only the price-check (not volume). This keeps the candidate list feasible but doesn't drop stocks for weak prior-day volume.

selected = [c for c in coarse if c.price >= 0.5]

 

Add the true premarket volume filter in the universe build: For each symbol in your candidate set:

  1. pre_hist = self.history(symbol, 570, Resolution.MINUTE, extended_market_hours=True)
  2. pre_volume = pre_hist['volume'].sum() # sum from 00:00 → 09:30
  3. if pre_volume < 1_000_000:
  4. continue

 

Fix the gap calculation:

  1. today_open = pre_hist.iloc[-1]['open'] # This is the 9:30am bar, i.e., today's session open
  2. prev_close = self.history(symbol, 1, Resolution.DAILY).iloc[0]['close']
  3. gap_pct = (today_open - prev_close) / prev_close

 

With these changes, your actual premarket volume filter will work as you intend—and SBET (5/27) and KNW (6/6) will both pass the premarket volume test, rank by actual gap, and be eligible for trading based on true opening conditions.