Skip to content

Monday-open hardening: stale-harvest discard, pre-close blackout, stock-split guard - #43

Merged
nickm538 merged 2 commits into
mainfrom
claude/kind-babbage-yi1j83
Jun 13, 2026
Merged

nickm538 merged 2 commits into
mainfrom
claude/kind-babbage-yi1j83

Conversation

@nickm538

@nickm538 nickm538 commented Jun 12, 2026 •

Copy link
Copy Markdown
Owner

Why — first full live session's flight recorder exposed three real defects

rh-agent why from session 2026-06-12 (the ledger shipped in #41 doing its job):

  • A live-money bug: KLAC executed a 10:1 stock split; the daemon's stored stop stayed at the pre-split scale (2071), so the post-split quote (239) looked like a −90% crash and falsely stop-sold the book's highest-conviction name. The journal then booked a ~−$80 artifact "loss" that also poisons the AI overlay's performance context.
  • A Monday-open landmine, armed right now: a hunt kicked at 19:55 UTC was still computing at the close. Worker threads keep running while the loop idles, so the finished scan sits all weekend; the existing expiry guard stamped pending age at harvest, so Monday 09:30 would have harvested it fresh-looking and traded Monday's open on Friday-evening conviction — the literal mechanism behind the operator's long-standing "it only trades at the open" observation.
  • Hunts averaging 31.8m routinely straddle the close, continuously manufacturing the above.

What

  1. Stale-harvest discard — the harvest path now measures age from scan start; anything older than pending_scan_expiry_seconds is discarded (scan_expired at=harvest ledger event) and a fresh hunt starts immediately. Stale runs no longer pollute cadence stats either.
  2. Pre-close hunt blackout — daemon.scan_blackout_minutes_before_close: 15 (0 disables): no new hunts within 15 minutes of the bell, so close-straddling scans stop being created. Stops/TPs keep running every tick. New market_calendar.minutes_to_close() helper (regular + early-close aware).
  3. Stock-split guard — before evaluating a stop, if the stored stop towers ≥1.8× over both the live price and the broker's (split-adjusted) average cost, it's a price-scale mismatch, not a crash: re-anchor stop/TP/high-water to the live price (split_guard ledger event) instead of selling. A genuine −45% gap keeps avg cost at the stop's scale and still sells — covered by a dedicated test.

Tests

241 passed (6 new: weekend-stale harvest discard, fresh harvest still executes, blackout skip + mid-session allow, minutes_to_close math incl. early close, the live KLAC split case re-anchors, a real crash still fires). Ruff clean. One existing test pinned deterministic against wall-clock blackout timing.

Deploy note

Merge + pull + restart before Monday's open — the running daemon currently holds a finished Friday scan that this PR's harvest guard will discard at the first Monday tick.

https://claude.ai/code/session_01E9KzfCPDyYdFsufQPxURXR


Generated by Claude Code

Summary by CodeRabbit

  • New Features

    • Pre-close blackout: prevents new hunts from starting shortly before market close to avoid overnight idle scans.
    • Scan expiry: stale scans automatically discarded to prevent stale data.
    • Corporate action guard: stops and take-profits re-anchor during price-scale events (e.g., splits) instead of triggering unexpected sells.
  • Tests

    • Added comprehensive coverage for pre-close blackout, scan expiry, and corporate action protection.

…, stock-split guard

Three protections derived from the first full live session's flight
recorder (2026-06-12):

1. Stale scans now die at HARVEST. A hunt that straddles the close keeps
   computing after the bell (worker threads run while the loop idles),
   then waits overnight/weekend for the next tick; the existing expiry
   only stamped pending age at harvest time, so Monday 09:30 would have
   executed Friday-19:55 conviction. The harvest path now discards any
   finished scan older than pending_scan_expiry_seconds and hunts fresh.
   Observed live: a 19:55 UTC scan was in flight at today's close and
   would have fired at Monday's open.

2. Pre-close hunt blackout (daemon.scan_blackout_minutes_before_close,
   default 15): stop CREATING close-straddling scans in the first place.
   Stops/take-profits keep running every tick; only new hunts pause.

3. Corporate-action (split) guard in _manage_risk. KLAC's 10:1 split left
   the stored stop at the pre-split scale (2071) so the post-split quote
   (239) looked like a -90% crash and falsely stop-sold the book's
   highest-conviction name; the journal then booked a ~-$80 artifact loss.
   Discriminator: after a split the broker's avg cost is split-adjusted
   too, so the stored stop towers over BOTH price and avg cost (>=1.8x
   each) — re-anchor stop/TP/high-water to the live price instead of
   selling. A genuine crash keeps avg cost at the stop's scale and still
   sells (covered by test).

241 tests pass (6 new), ruff clean.

https://claude.ai/code/session_01E9KzfCPDyYdFsufQPxURXR
@coderabbitai

coderabbitai Bot commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR adds three hardening features to the daemon: (1) a pre-close hunt blackout window to prevent scans from straddling market close, (2) stale scan expiry validation to discard old background scan results, and (3) a corporate-action guard in risk management to re-anchor stops when price scale mismatches are detected instead of triggering false sells.

Changes

Daemon Hardening: Scheduling, Scan Lifecycle, and Risk Guards

Layer / File(s) Summary
Market close timing helper
src/rh_agent/market_calendar.py
minutes_to_close() computes float minutes until US-Eastern market close (13:00 on early-close dates, 16:00 otherwise) or returns None when market is closed, clamping sub-minute precision.
Configuration and daemon wiring
config/config.yaml, src/rh_agent/daemon.py
Adds scan_blackout_minutes_before_close: 15 config parameter; updates daemon imports to wire minutes_to_close and take_profit helpers plus split-guard ratio constant.
Scan harvest with expiry validation
src/rh_agent/daemon.py
Harvest logic discards background scans exceeding daemon.pending_scan_expiry, clearing pending state and emitting scan_expired; fresh scans record scan_done with metadata.
Pre-close blackout for hunt starts
src/rh_agent/daemon.py
Hunt submissions are suppressed when within the pre-close blackout window (via minutes_to_close) and not using "snapshot" provider; outside blackout, hunts proceed normally.
Split/corporate-action guard
src/rh_agent/daemon.py
Risk management detects price-scale mismatches (stored stop ~1.8x larger than current quote and cost) and re-anchors stop/take-profit/high-water using current ATR instead of selling; records split_guard activity and skips normal stop/TP evaluation.
Test infrastructure
tests/test_monday_open_hardening.py
Defines module docstring, _utcnow() and _mk_daemon() helpers, and _Broker test double for validating agent behavior and order submission.
Scan harvest tests
tests/test_monday_open_hardening.py
Verifies stale scans are discarded (clearing pending state, emitting scan_expired), stale discard followed by fresh hunt in same tick, and fresh scans record scan_done and update cadence stats.
Pre-close timing tests
tests/test_monday_open_hardening.py
Validates minutes_to_close() minute/timestamp mappings and None for closed markets; tests hunt suppression inside blackout and submission outside blackout on subsequent ticks.
Split guard and crash tests
tests/test_monday_open_hardening.py
Verifies split guard re-anchors without selling (emitting split_guard); confirms genuine stop-threatening crashes still trigger protective sell orders.
Existing test determinism
tests/test_portfolio_broker.py
Monkeypatches daemon.minutes_to_close to return None in cadence test, ensuring deterministic behavior independent of wall time.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰 Before the close bell chimes its song,
Stale scans are swept and sent along,
Splits are caught with guard so keen,
And hunts sleep soundly in between!
The daemon works both day and night,
Keeping every trade just right. 🌙

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 22.86% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly and specifically summarizes the three main changes in the PR: stale-harvest discard, pre-close blackout hunt suppression, and stock-split guard logic for stop-loss re-anchoring.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/kind-babbage-yi1j83

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/rh_agent/daemon.py (1)

485-514: 📐 Maintainability & Code Quality | 💤 Low value

Silent exception swallow during ATR fetch.

The try-except-pass pattern at lines 496-500 silently discards ATR fetch failures. While atr_stop() handles None ATR gracefully (falling back to the hard-stop percentage), logging the exception would aid debugging if ATR lookups fail systematically.

This is consistent with identical patterns elsewhere in this file (lines 167-172, 566-570), so this is a codebase-wide style. The guard logic itself is correct and the threshold discriminator (stop ≥1.8× both price and avg cost) is well-reasoned for detecting splits vs crashes.

♻️ Optional: log exception at debug level
             try:
                 td = self.agent.md.build(tk, deep=False)
                 atr = td.technicals.get("atr") if td else None
-            except Exception:
-                pass
+            except Exception as e:
+                log.debug("ATR lookup failed for %s split guard: %s", tk, e)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/rh_agent/daemon.py` around lines 485 - 514, The ATR fetch try/except
silently swallows errors; update the block around self.agent.md.build(tk,
deep=False) (where td and atr are set) to catch Exception as e and log the
exception at debug (or warning) level before continuing so failures to obtain
ATR are visible; ensure you still leave atr as None so atr_stop(px, atr,
atr_mult, hard_pct) behavior is unchanged and retain existing flow that
re-anchors stops and records activity.

Source: Linters/SAST tools

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@src/rh_agent/daemon.py`:
- Around line 485-514: The ATR fetch try/except silently swallows errors; update
the block around self.agent.md.build(tk, deep=False) (where td and atr are set)
to catch Exception as e and log the exception at debug (or warning) level before
continuing so failures to obtain ATR are visible; ensure you still leave atr as
None so atr_stop(px, atr, atr_mult, hard_pct) behavior is unchanged and retain
existing flow that re-anchors stops and records activity.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 40b78cd8-1dda-4769-8344-4ec1f3921e22

📥 Commits

Reviewing files that changed from the base of the PR and between ef1afe4 and 5dd53d3.

📒 Files selected for processing (5)
  • config/config.yaml
  • src/rh_agent/daemon.py
  • src/rh_agent/market_calendar.py
  • tests/test_monday_open_hardening.py
  • tests/test_portfolio_broker.py

@nickm538
nickm538 marked this pull request as ready for review June 12, 2026 23:45
Copilot AI review requested due to automatic review settings June 12, 2026 23:45

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Note

Copilot was unable to run its full agentic suite in this review.

Hardens the trading daemon against three production issues observed in the first live session: harvesting stale background scans at the next open, starting scans too close to market close, and false stop triggers caused by stock splits.

Changes:

  • Discard stale completed scans at harvest time (age measured from scan start) and record scan_expired at=harvest.
  • Add pre-close “no new hunts” blackout window plus minutes_to_close() calendar helper (early-close aware).
  • Add a stock-split scale-mismatch guard that re-anchors stop/TP/high-water instead of selling.

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 6 comments.

Show a summary per file
File Description
tests/test_portfolio_broker.py Pins minutes_to_close in an existing test to avoid wall-clock dependence from the new blackout behavior.
tests/test_monday_open_hardening.py Adds new tests covering stale-harvest discard, blackout behavior, minutes_to_close, and split-guard behavior.
src/rh_agent/market_calendar.py Introduces minutes_to_close() helper with early-close support.
src/rh_agent/daemon.py Implements stale-harvest discard, pre-close scan blackout, and split-guard risk logic.
config/config.yaml Adds daemon.scan_blackout_minutes_before_close configuration.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread src/rh_agent/market_calendar.py Outdated
Comment on lines +92 to +98
def minutes_to_close(now_utc: datetime | None = None) -> float | None:
"""Minutes until today's closing bell; None when the market is closed."""
if not is_market_open(now_utc):
return None
et = to_eastern(now_utc)
close_m = 13 * 60 if et.strftime("%Y-%m-%d") in _EARLY_CLOSE else 16 * 60
return close_m - (et.hour * 60 + et.minute + et.second / 60.0)
Comment thread src/rh_agent/market_calendar.py Outdated
Comment on lines +94 to +96
if not is_market_open(now_utc):
return None
et = to_eastern(now_utc)
Comment thread src/rh_agent/daemon.py
Comment on lines +269 to +277
if scan_age > self._pending_scan_expiry:
# The worker finished while the loop was idle (a hunt that
# straddled the close keeps computing after the bell, then
# waits overnight/all weekend for the next tick). Trading
# the next open on that conviction is the classic "mystery
# trade at 9:30" — discard it; a fresh hunt starts now.
log.warning("scan finished but is %.0fs old (> expiry %.0fs) — "
"discarding stale conviction; hunting fresh",
scan_age, self._pending_scan_expiry)
Comment thread src/rh_agent/daemon.py Outdated
# Pre-close blackout: a hunt kicked now would still be computing at
# the bell, idle overnight, and beg to fire stale at the next open.
# The risk loop (stops/TPs) keeps running every tick regardless.
blackout = float(self.cfg.get("daemon.scan_blackout_minutes_before_close", 15))
Comment thread src/rh_agent/daemon.py Outdated
Comment on lines +493 to +494
if (stop and px and avg > 0
and stop / px >= 1.8 and stop / avg >= 1.8):
Comment thread tests/test_portfolio_broker.py Outdated
Comment on lines +443 to +444
# Pin the pre-close blackout open so this test is deterministic at any wall time.
monkeypatch.setattr(daemon, "minutes_to_close", lambda now=None: None)
…nsive blackout config, named split-guard ratio

- minutes_to_close: sample the clock once and clamp at 0.0 (is_market_open
  works at minute granularity, so the final sub-minute sliver of the
  session could surface as a negative value).
- Blackout config float() coerced defensively — a YAML typo must degrade
  to the 15m default, never error every tick.
- Split-guard threshold promoted to a named module constant
  (SPLIT_GUARD_RATIO) with the discriminator rationale documented.
- Reworded the blackout-neutralizing test comment (None = market closed,
  i.e. blackout not applicable — not 'pinned open').
- Copilot's control-flow finding ('fresh hunt cannot start the same tick
  after a stale discard') is incorrect: the kick block is an elif of the
  PENDING-execution if, not of the harvest block. Added
  test_stale_discard_rekicks_fresh_hunt_same_tick proving the same-tick
  re-kick that Monday's open relies on.

242 tests pass, ruff clean.

https://claude.ai/code/session_01E9KzfCPDyYdFsufQPxURXR

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@tests/test_monday_open_hardening.py`:
- Line 100: The _Agent class currently defines a mutable class-level attribute
providers = {}, triggering RUF012; change this to an instance-level attribute
(e.g., set self.providers = {} inside _Agent.__init__) or replace the class
attribute with an immutable mapping (e.g., types.MappingProxyType or a frozen
dict) so tests and other instances don't share mutable state—update the class
definition to remove providers = {} and initialize providers in the constructor
of _Agent (or substitute an immutable mapping) accordingly.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: d3b8ff4f-493d-49f0-8766-4df356ef422a

📥 Commits

Reviewing files that changed from the base of the PR and between 5dd53d3 and 0eba6f1.

📒 Files selected for processing (4)
  • src/rh_agent/daemon.py
  • src/rh_agent/market_calendar.py
  • tests/test_monday_open_hardening.py
  • tests/test_portfolio_broker.py
🚧 Files skipped from review as they are similar to previous changes (3)
  • tests/test_portfolio_broker.py
  • src/rh_agent/market_calendar.py
  • src/rh_agent/daemon.py

monkeypatch.setattr(daemon, "minutes_to_close", lambda now=None: None)

class _Agent:
providers = {}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail
ruff check src tests --select RUF012 -n

Repository: nickm538/robinhoodagent

Length of output: 4434


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Show context around the targeted line
nl -ba tests/test_monday_open_hardening.py | sed -n '80,120p'

# Find all references in the file
rg -n "providers" tests/test_monday_open_hardening.py

Repository: nickm538/robinhoodagent

Length of output: 110


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# context around line ~100 using cat -n (nl not available)
cat -n tests/test_monday_open_hardening.py | sed -n '90,115p'

# locate all providers usage in the file
rg -n "providers" tests/test_monday_open_hardening.py

Repository: nickm538/robinhoodagent

Length of output: 1265


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Search for usages of ".providers" that could interact with the test double.
rg -n "\.providers\b" src tests | head -n 200

# Narrow to likely agent access patterns.
rg -n "(agent|self\.agent).*\.providers\b" src | head -n 200
rg -n "\.providers\[" src | head -n 200
rg -n "\.providers\.update\b" src | head -n 200

Repository: nickm538/robinhoodagent

Length of output: 7558


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect surrounding areas of each _Agent test double in the file
cat -n tests/test_monday_open_hardening.py | sed -n '40,120p'
echo "-----"
cat -n tests/test_monday_open_hardening.py | sed -n '120,210p'
echo "-----"
cat -n tests/test_monday_open_hardening.py | sed -n '210,320p'

# Search for any mutations/assignments involving agent.providers
rg -n "agent\.providers|d\.agent\.providers|\.providers\s*=" tests/test_monday_open_hardening.py

Repository: nickm538/robinhoodagent

Length of output: 10579


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect daemon providers usage around the earlier reported line
sed -n '560,680p' src/rh_agent/daemon.py

Repository: nickm538/robinhoodagent

Length of output: 3703


🏁 Script executed:

#!/bin/bash
set -euo pipefail

head -n 60 tests/test_monday_open_hardening.py
rg -n "^from types import|^import types|SimpleNamespace" tests/test_monday_open_hardening.py

Repository: nickm538/robinhoodagent

Length of output: 2445


🌐 Web query:

RUF012 mutable default value for class attribute annotating typing.ClassVar fix behavior

💡 Result:

RUF012 is a Ruff lint rule that flags mutable default values in class attributes [1]. This pattern is discouraged because such attributes are shared across all instances of a class, which can lead to unexpected bugs if one instance modifies the shared object [2][1]. To resolve a RUF012 violation, you have several options depending on the intended behavior of your code [1]: 1. Initialize in init: This is the recommended approach if the attribute is intended to be instance-specific [1]. By defining the attribute within the init method, each instance receives its own unique, mutable object [1]. class A: def init(self) -> None: self.variable: list[int] = [] 2. Use typing.ClassVar: If the attribute is explicitly intended to be shared across all instances, you should annotate it with typing.ClassVar [1]. This explicitly signals the intent to developers and tools, causing Ruff to exempt the attribute from the mutable default check [3][4]. from typing import ClassVar class A: variable: ClassVar[list[int]] = [] 3. Use immutable types: Consider using immutable alternatives, such as a tuple instead of a list, or an empty frozenset instead of a set [1]. 4. Use None as a default: Alternatively, set the attribute to None as a placeholder and initialize it later, or provide a default of None [1]. The diagnostic message for RUF012 has been improved in recent versions of Ruff to clarify that annotating with ClassVar is one of several possible solutions, rather than the only one [5][6]. Ruff also supports ClassVar without a subscript (e.g., ClassVar = []) [4].

Citations:


Fix RUF012: avoid mutable class-level providers in _Agent

tests/test_monday_open_hardening.py sets class _Agent: providers = {} (Line 100), which triggers Ruff’s RUF012 for mutable class attributes. Use an immutable mapping or an instance-level attribute instead.

Suggested fix
-from types import SimpleNamespace
+from types import MappingProxyType, SimpleNamespace
...
-        providers = {}
+        providers = MappingProxyType({})
🧰 Tools
🪛 Ruff (0.15.15)

[warning] 100-100: Mutable default value for class attribute

(RUF012)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/test_monday_open_hardening.py` at line 100, The _Agent class currently
defines a mutable class-level attribute providers = {}, triggering RUF012;
change this to an instance-level attribute (e.g., set self.providers = {} inside
_Agent.__init__) or replace the class attribute with an immutable mapping (e.g.,
types.MappingProxyType or a frozen dict) so tests and other instances don't
share mutable state—update the class definition to remove providers = {} and
initialize providers in the constructor of _Agent (or substitute an immutable
mapping) accordingly.

Sources: Coding guidelines, Linters/SAST tools

@nickm538
nickm538 merged commit 19cffe4 into main Jun 13, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants