Skip to content

Add StrategyScenario test harness (#625) - #647

Open
zorionarrillaga wants to merge 4 commits into
coding-kitties:mainfrom
zorionarrillaga:feat/625-strategy-scenario
Open

zorionarrillaga wants to merge 4 commits into
coding-kitties:mainfrom
zorionarrillaga:feat/625-strategy-scenario

Conversation

@zorionarrillaga

Copy link
Copy Markdown
Contributor

Closes #625.

What

StrategyScenario (in investing_algorithm_framework.testing, also exported at the top level) sets up the state a
strategy test needs before its next evaluation:

  • quote-currency cash
  • long and short trade lots with entry prices and fees
  • pending orders (BUY/SELL/SHORT/COVER)
  • stop-loss and take-profit rules
  • trailing high-water marks
  • cooldown history
start = datetime(2024, 1, 1, tzinfo=timezone.utc)
with StrategyScenario(MyStrategy(), initial_cash=1_000, trading_symbol="EUR",
                      market="BITVAVO", start=start) as scenario:
    trade = scenario.open_trade("BTC", amount=2, price=100,
                                opened_at=start - timedelta(hours=4))
    assert scenario.context.get_unallocated() == 800
    assert scenario.context.get_position("BTC").cost == 200

How

  • Seeding goes through the production services. A lot is a limit BUY or SHORT via Context followed by
    OrderService.update as the fill. Rules use Context.add_stop_loss / add_take_profit, with the same lookup as
    AttachRiskRulesPhase. Marks use the TradeService.update call the backtest evaluator makes. Cooldowns use the
    per-order body of RecordCooldownPhase, extracted unchanged as record_emission. Cash, legs, cost basis, lots, FIFO
    SELL allocations and reservations therefore move as they do in a backtest.
  • Validation: each seeding call validates its inputs before changing anything and raises ScenarioSetupError (an
    OperationalException) with the call, the numbers and a fix. Examples: not enough cash once fees and pending
    reservations are counted; an opposite-direction lot in NETTING (pointing to PositionMode.HEDGE); over-selling or
    over-covering; a mark that would already trigger a rule.
  • Consistency check: check_consistency() runs after every seed and raises ScenarioStateError listing each
    invariant that does not hold:
    • unallocated equals the quote position, and equals the cash implied by the order ledger
    • each leg equals its open lots
    • each leg cost equals Σ open price × (available + pending)
    • no negative legs
    • one leg per symbol in NETTING
    • each pending SELL's allocations match its remaining amount
  • Isolation: each scenario builds its own App and container without create_app, storage setup or wiring, and keeps
    all repository rows in its own EventMemoryState (the store event backtests use with event_state_backend="memory").
    It activates that store around every call through the new activate_event_memory helper. No database, network,
    credentials, .env or environment overrides are involved. close() (or leaving the with block) releases everything.

Choices you may want to redirect (each lives in one place):

  1. One in-memory store per scenario instead of a SQLite file. The SQLAlchemy Session is module-global, so two SQL-backed
    apps in one process share it.
  2. Seeded entries get the strategy's declared SL/TP by default (apply_strategy_rules=True).
  3. A strategy instance belongs to one scenario; reusing an instance that is in use or has already run raises.
  4. Name and location: investing_algorithm_framework.testing.StrategyScenario, re-exported at the top level.

Verified

  • tests/testing/test_strategy_scenario.py: 32 tests in under 1 s, one TestCase per acceptance criterion. It writes no
    files and runs with sockets patched to raise.
  • Existing suites unchanged:
    • services 1063 OK (+1 new helper test)
    • domain 754 OK
    • infrastructure 369 OK
    • scenarios 201 OK
  • In tests/app, the only two errors also occur on main in my environment: the tqdm notebook display patch needs
    IPython.
  • flake8 is clean.
  • The new tests also pass on Linux with Python 3.10.

Not included: evaluation steps (#626), results (#627) and examples (#628). check_consistency books an order filled
in chunks at different prices at its last price. The harness never creates that, but it should be revisited when #626
adds evaluation steps.

activate_event_memory routes repository calls into an existing
EventMemoryState without owning it; event_memory_scope now builds on
it. record_emission is the per-order body of RecordCooldownPhase,
moved unchanged so other callers can record cooldown history.
StrategyScenario seeds a strategy test with cash, long and short trade
lots, pending orders, stop-loss and take-profit rules, trailing state
and cooldown history. Every seed goes through the production order and
trade services, is validated before anything changes
(ScenarioSetupError) and is followed by a consistency check of cash,
positions, cost basis, lots and reservations (ScenarioStateError).

Each scenario keeps its state in its own EventMemoryState and builds
its App without create_app, storage or wiring, so scenarios share no
state and touch no database, network, environment or files.
Release the strategy binding when a scenario is collected without
close(), keep services reached through scenario.context scoped to the
scenario, book pending reservations at the order's reservation price
(STOP orders have no limit price), reject pair symbols, marks that
predate earlier marks or rules, malformed constructor arguments and a
start off the UTC hour, and track cooldown seeding order per symbol.
@codecov-commenter

codecov-commenter commented Nov 22, 2026 •

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

❌ Patch coverage is 99.22581% with 6 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.83%. Comparing base (8d214d7) to head (821be14).
⚠️ Report is 3 commits behind head on main.

Files with missing lines Patch % Lines
investing_algorithm_framework/testing/scenario.py 98.63% 5 Missing ⚠️
tests/testing/test_strategy_scenario.py 99.72% 1 Missing ⚠️
❗ Your organization needs to install the Codecov GitHub app to enable full functionality.
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #647      +/-   ##
==========================================
+ Coverage   82.62%   82.83%   +0.20%     
==========================================
  Files         698      701       +3     
  Lines       70594    71349     +755     
==========================================
+ Hits        58331    59104     +773     
+ Misses      12263    12245      -18     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

This branch has not been deployed

No deployments
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.

Add a public StrategyScenario test harness with consistent portfolio fixtures

3 participants