Build a Market Feature Engine
Build an event-driven market feature engine with PyTorch.
Introduction
30 Second Summary
Two identical-looking updates can still represent two different moments in a fast-moving market. Ignoring one update can corrupt every history-based calculation that follows.
In this project, you will build a compact quantitative research lab inspired by Jane Street's public Flex Model design. The lab turns synthetic market events into stateful features before testing a linear baseline and a neural network against a controlled regime change.
What You'll Build
Running market_lab.py shows a complete research experiment unfold from raw events to an evidence-based model comparison.
By the end of this project, you'll have:
- A deterministic event replay that lets you inspect BOOK and TRADE updates, including consecutive trades at the same price.
- A parity workflow that names the first feature corrupted by the dropped-event bug. The corrected engine then proves all 600 vectors match across 4 features.
- A PyTorch model comparison with chronological train and test accuracy for a linear model and a small neural network. The generated research_report.md explains what the regime shift means without making a profitability claim.
- Secret Mission: Run a one-feature-at-a-time ablation that reveals which signal most changes out-of-sample accuracy.
Are there any prerequisites?
You need a Windows computer with internet access for the PyTorch download. Basic Python functions, classes, and binary classification are enough to begin.
Before We Start
This opening checkpoint commits you to building mini-market-feature-engine, a Jane Street-inspired event-driven market feature engine. A repeated TRADE must still update rolling history because dropping it can corrupt every feature that depends on that history.
Set Up the Market Lab
Your research question is set. Every TRADE event must reach the rolling state. Your lab now needs a foundation that reproduces the same experiment each time.
You will set up the lab in Visual Studio Code through Windows PowerShell. A project-local virtual environment keeps PyTorch separate from your other Python work.
In this step, get ready to:
- Prepare mini-market-feature-engine as a Visual Studio Code workspace.
- Verify Python 3.11 through 3.14 before creating .venv.
- Install the PyTorch 2.15.0 pin from requirements.txt.
Create the project environment
Visual Studio Code treats an opened folder as a workspace. Its integrated terminal starts inside that folder. This keeps every environment file inside the market lab.
- Press the Windows key to open the Windows search bar.
- Type Visual Studio Code.
- Press Enter to open Visual Studio Code.
Why Open a Folder as a Workspace?
A Visual Studio Code workspace anchors the editor to one folder. The integrated terminal then opens inside that folder by default.
- Press Ctrl+K Ctrl+O to open the folder picker.
- Browse to your Desktop.
- Select the new-folder control in the folder picker.
- Enter mini-market-feature-engine as the folder name.
- Select the new mini-market-feature-engine folder.
Visual Studio Code may show a Workspace Trust dialog after the folder opens. You created this empty folder yourself. It is safe to trust.
- Select Select Folder in the folder picker.
- Select Yes, I trust the authors if the Workspace Trust dialog appears.
You should see mini-market-feature-engine at the top of the Explorer sidebar. This confirms that the project folder is open as your workspace.
- Press Ctrl+Shift+` to create an integrated terminal.
- Check that the terminal tab identifies Windows PowerShell.
- Open the profile dropdown if another shell is selected.
- Select Windows PowerShell from the available profiles.
- Check the installed Python version by running this command:
python --version
What Does This Command Do?
This command asks the current Python runtime to print its version. The project supports Python 3.11 through 3.14.
✔️ I See a Supported Version
Your Python runtime is inside the supported range. The common instructions below can create the isolated environment.
ⓧ I See an Unsupported Version
The installed runtime falls outside the supported range. Python 3.14 provides a supported runtime for this project.
- Open the official Python downloads page.
- Download the standard Windows installer for Python 3.14.
- Run the downloaded installer.
- Keep the standard installation options.
- Close the current Visual Studio Code terminal after installation finishes.
- Press Ctrl+Shift+` to create a fresh Windows PowerShell terminal.
- Repeat the version check by running this command:
python --version
What Does This Command Do?
The fresh terminal resolves the newly installed Python runtime. Its output should now report a version from 3.11 through 3.14.
ⓧ Command Not Found
Windows PowerShell cannot currently find a Python runtime. Installing Python 3.14 supplies a supported runtime.
- Open the official Python downloads page.
- Download the standard Windows installer for Python 3.14.
- Run the downloaded installer.
- Keep the standard installation options.
- Close the current Visual Studio Code terminal after installation finishes.
- Press Ctrl+Shift+` to create a fresh Windows PowerShell terminal.
- Confirm that Windows PowerShell can find Python by running this command:
python --version
What Does This Command Do?
The command checks whether the fresh terminal can resolve the installed Python runtime. Its output should report a version from 3.11 through 3.14.
The supported runtime can now create an isolated copy of Python inside the project. The environment stores its executable in the Windows Scripts directory.
- Create .venv inside mini-market-feature-engine by running this command:
python -m venv .venv
What Does This Command Do?
Python creates an isolated environment named .venv inside the current workspace. Its Windows Python executable lives in .venv\Scripts.
The project can invoke that executable directly. Activation is optional when every command uses the full environment path.
- Confirm that .venv appears under mini-market-feature-engine in the Explorer sidebar.
You should see the .venv folder in the workspace. This proves the isolated environment was created in the correct location.
Environment Folder Missing?
- Check that the integrated terminal path ends with mini-market-feature-engine.
- Refresh the Explorer sidebar if the terminal command completed without an error.
Ask for help diagnosing the environment creation if the folder is still missing: help me troubleshoot why my project-local Python environment was not created
Pin and install PyTorch
A dependency pin records the exact package release used by the experiment. Anyone rebuilding the lab from requirements.txt requests the same PyTorch release.
- Select the New File icon at the top of the Explorer sidebar.
- Enter requirements.txt as the new file name.
You should see an empty requirements.txt file in the Explorer. The dependency file is ready for its version pin.
- Pin PyTorch by adding this complete line to requirements.txt:
torch==2.15.0
What Does This Pin Do?
The double equals operator requests exactly PyTorch 2.15.0. This removes package-version drift from later model comparisons.
- Save requirements.txt.
- Confirm that the editor no longer shows an unsaved-change indicator beside requirements.txt.
The saved file now contains the complete dependency definition for this project.
Pin Looks Different?
- Check that requirements.txt contains one line.
- Remove any spaces surrounding the double equals operator.
- Confirm that the version ends with 2.15.0.
Ask for help comparing the dependency file if the pin still differs: help me check my PyTorch dependency pin
✔️ Awesome, I've Got Everything
Your saved dependency file is ready to install into the isolated environment.
ⓧ I'd Like to Double Check the Full Code
Your complete requirements.txt file should match this reference exactly.
torch==2.15.0
The dependency file defines what to install. Using the executable inside .venv ensures the package stays inside this project.
This is the slowest part of the setup. A busy terminal while the package downloads is expected.
- Install the pinned dependency into .venv by running this command:
.\.venv\Scripts\python.exe -m pip install -r requirements.txt
What Does This Command Do?
The path at the start selects the Python executable inside .venv. The pip module reads the exact dependency pin from requirements.txt.
The downloaded package is installed into the isolated environment. Your system Python packages remain separate.
- Wait for the Windows PowerShell prompt to return after the installation output finishes.
You should see the package installation complete without a failure. The returned prompt confirms that Windows PowerShell is ready for the import check.
Installation Did Not Finish?
- Check that your internet connection is available for the package download.
- Confirm that requirements.txt is saved inside mini-market-feature-engine.
- Confirm that the command path starts with .\.venv\Scripts\python.exe.
Ask for help with the installation output if it still fails: help me diagnose my project-local PyTorch installation
Verify the installed version
A successful download does not prove that the project executable can import the package. The final check imports PyTorch through .\.venv\Scripts\python.exe before printing its version.
Before you run the check, which version do you expect the project environment to report?
- Verify the imported PyTorch version by running this command:
.\.venv\Scripts\python.exe -c "import torch; print(torch.__version__)"
What Does This Command Do?
The command starts the Python executable stored inside .venv. It imports PyTorch from that environment.
The torch.__version__ value identifies the installed package release. This checks both the import path and the pin.
You should see 2.15.0 printed in the terminal. That result proves the isolated environment can import the pinned PyTorch release.
Import Check Failed?
- Check that the verification path begins with .\.venv\Scripts\python.exe.
- Return to the installation output to confirm that the package download completed.
- Confirm that requirements.txt still contains the exact 2.15.0 pin.
Ask for help interpreting the import failure if the check still does not print the pinned version: help me troubleshoot the PyTorch import inside my virtual environment
That is the reproducible foundation locked in. Next, you will turn synthetic BOOK and TRADE events into the first model-ready feature vectors.
Replay Synthetic Market Events
Your isolated Python environment is ready. You can now turn the empty market lab into a research script that produces observable market events.
Raw market events become useful to a model after an event-driven feature engine converts them into numerical vectors. This first replay also keeps a naive repeated-value cutoff that creates the failure you will investigate next.
In this step, get ready to:
- Generate deterministic BOOK events plus TRADE events across two market regimes.
- Maintain four stateful features with a fixed-size rolling buffer.
- Run the events command to inspect the first three feature vectors.
Generate deterministic market ticks
A controlled generator lets you place repeated trades plus a regime boundary exactly where the experiment needs them. The fixed seed makes each replay produce the same stream.
- Create a new file named market_lab.py inside mini-market-feature-engine from the file list on the left side of Visual Studio Code.
- Add the event schema plus experiment constants by pasting this code into market_lab.py:
import argparse
import math
import random
from dataclasses import dataclass
SEED = 7
WINDOW = 10
N_TICKS = 600
FEATURE_NAMES = [
"imbalance",
"recent_trade_vs_mid",
"recent_trade_sign",
"mid_change",
]
REPORT_FILE = "research_report.md"
@dataclass(frozen=True)
class MarketEvent:
kind: str
bid: float | None = None
ask: float | None = None
bid_size: float | None = None
ask_size: float | None = None
trade_price: float | None = None
@dataclass(frozen=True)
class MarketTick:
events: list[MarketEvent]
target: float
regime: str
What Does This Code Do?
- The constants lock the random seed at 7 plus the rolling window at 10 events.
- The MarketEvent data class represents either a book update or a trade.
- The MarketTick data class groups chronological events with a target plus a regime name.
- Save market_lab.py.
- Confirm market_lab.py is listed beside requirements.txt in the file list.
You now have a visible home for the market replay plus data structures for every event it generates.
File Missing From the Project?
Check that you created market_lab.py directly inside mini-market-feature-engine. It should sit at the same level as requirements.txt.
Ask for help with the file location by selecting help me place market_lab.py in the correct Visual Studio Code folder.
Each synthetic tick starts from the current mid-price. Its book sizes create an imbalance that helps determine the next target.
- Add the first half of generate_ticks() directly below the MarketTick data class:
def generate_ticks(n_ticks: int = N_TICKS, seed: int = SEED) -> list[MarketTick]:
rng = random.Random(seed)
mid = 100.00
split = int(n_ticks * 0.70)
ticks: list[MarketTick] = []
for tick_index in range(n_ticks):
regime = "A" if tick_index < split else "B"
regime_direction = 1.0 if regime == "A" else -1.0
flow = rng.uniform(-1.0, 1.0)
bid_size = max(20.0, 120.0 + 80.0 * flow + rng.uniform(-10.0, 10.0))
ask_size = max(20.0, 120.0 - 80.0 * flow + rng.uniform(-10.0, 10.0))
How Is the Regime Created?
- The first 70% of ticks belong to regime A.
- The remaining ticks belong to regime B.
- The flow value shifts bid size plus ask size in opposite directions.
- Save market_lab.py.
- Confirm the generate_ticks() definition appears directly below MarketTick.
Generator Indentation Looks Uneven?
Keep each line from regime through ask_size indented inside the for loop. Keep the loop indented inside generate_ticks().
Ask for an indentation check by selecting help me check the indentation in the first half of generate_ticks.
The rest of the generator turns each book state into events plus a binary target. Every twenty-third tick receives a second trade at the same price.
- Complete generate_ticks() by adding this code directly below the ask_size line:
bid = round(mid - 0.01, 2)
ask = round(mid + 0.01, 2)
trade_price = ask if flow >= 0.0 else bid
trade_side = 1.0 if trade_price > mid else -1.0
imbalance = (bid_size - ask_size) / (bid_size + ask_size)
events = [
MarketEvent("BOOK", bid, ask, bid_size, ask_size),
MarketEvent("TRADE", trade_price=trade_price),
]
if tick_index % 23 == 0:
events.append(MarketEvent("TRADE", trade_price=trade_price))
score = regime_direction * (2.3 * imbalance + 0.8 * trade_side)
score += rng.gauss(0.0, 0.8)
probability_up = 1.0 / (1.0 + math.exp(-score))
target = 1.0 if rng.random() < probability_up else 0.0
ticks.append(MarketTick(events, target, regime))
mid = round(mid + (0.01 if target == 1.0 else -0.01), 2)
return ticks
Why Repeat a Trade?
Two trades at the same price remain two distinct market events. A history-dependent feature must count both observations.
The direction attached to regime_direction reverses in regime B. That controlled shift gives the later model comparison a chronological stress test.
- Save market_lab.py.
- Confirm generate_ticks() ends with return ticks aligned inside the function.
Repeated Trade Missing From the Generator?
Check that events.append(MarketEvent("TRADE", trade_price=trade_price)) is inside the condition for every twenty-third tick. Keep it outside the original events list.
Ask for a structural check by selecting help me verify that generate_ticks adds a repeated trade every twenty-third tick.
Build the rolling feature engines
The feature engine separates event handling from value evaluation. Its handlers update stored state whenever an event arrives.
A fixed-size rolling buffer keeps only the latest ten trade observations. Preallocated lists plus running sums avoid recalculating the full history after every event.
- Add the engine state plus book handler directly below generate_ticks():
class FeatureEngine:
def __init__(self, window: int = WINDOW) -> None:
self.window = window
self.mid: float | None = None
self.bid_size = 0.0
self.ask_size = 0.0
self.mid_change = 0.0
self.trade_diffs = [0.0] * window
self.trade_signs = [0.0] * window
self.next_index = 0
self.count = 0
self.diff_sum = 0.0
self.sign_sum = 0.0
def on_book(self, event: MarketEvent) -> None:
assert event.bid is not None and event.ask is not None
assert event.bid_size is not None and event.ask_size is not None
previous_mid = self.mid
self.mid = (event.bid + event.ask) / 2.0
self.bid_size = event.bid_size
self.ask_size = event.ask_size
self.mid_change = 0.0 if previous_mid is None else self.mid - previous_mid
What State Does the Engine Keep?
- The mid value is halfway between the current bid plus ask.
- The two preallocated lists hold recent trade distances plus trade directions.
- The next_index value identifies the oldest buffer slot when the window is full.
- Save market_lab.py.
- Confirm the on_book() method sits inside FeatureEngine.
Book Handler Outside the Class?
Keep def on_book aligned with def __init__. Keep every statement in each method indented one level further.
Ask for help by selecting help me check the FeatureEngine class indentation.
Trade events update the circular buffer. Once the window reaches ten trades, each new trade removes the oldest contribution before adding its own.
- Add the trade handler directly below on_book():
def on_trade(self, event: MarketEvent) -> None:
assert self.mid is not None and event.trade_price is not None
trade_diff = event.trade_price - self.mid
trade_sign = 1.0 if trade_diff > 0.0 else -1.0 if trade_diff < 0.0 else 0.0
if self.count == self.window:
self.diff_sum -= self.trade_diffs[self.next_index]
self.sign_sum -= self.trade_signs[self.next_index]
else:
self.count += 1
self.trade_diffs[self.next_index] = trade_diff
self.trade_signs[self.next_index] = trade_sign
self.diff_sum += trade_diff
self.sign_sum += trade_sign
self.next_index = (self.next_index + 1) % self.window
How Does the Rolling Buffer Work?
- The trade_diff value measures a trade against the current mid.
- The trade_sign value records whether the trade occurred above or below the mid.
- The modulo calculation wraps next_index back to the beginning after the final buffer slot.
- Save market_lab.py.
- Confirm on_trade() updates both running sums before advancing next_index.
Rolling Values in the Wrong Scope?
Keep the buffer replacement lines inside on_trade(). Keep the four update lines after the if block so they run for both a full buffer plus a growing buffer.
Ask for help by selecting help me verify the rolling-buffer update order.
The handler routes each event to the correct state update. Evaluation then exposes one four-number vector without changing the stored history.
- Add the routing plus evaluation methods directly below on_trade():
def handle(self, event: MarketEvent) -> None:
if event.kind == "BOOK":
self.on_book(event)
elif event.kind == "TRADE":
self.on_trade(event)
else:
raise ValueError(f"Unknown event kind: {event.kind}")
def evaluate(self) -> list[float]:
size_total = self.bid_size + self.ask_size
imbalance = 0.0 if size_total == 0.0 else (self.bid_size - self.ask_size) / size_total
denominator = max(self.count, 1)
return [
imbalance,
self.diff_sum / denominator,
self.sign_sum / denominator,
self.mid_change,
]
What Does Evaluation Return?
- The first value is current order-book imbalance.
- The next two values summarize recent trade distance plus recent trade direction.
- The final value measures the latest mid-price change.
- Save market_lab.py.
- Confirm the returned list follows the same order as FEATURE_NAMES.
Feature Order Does Not Match?
Compare the four expressions in evaluate() with the four entries in FEATURE_NAMES. Their positions must match because later comparisons identify mismatches by index.
Ask for help by selecting help me align evaluate with FEATURE_NAMES.
The deliberate bug treats an unchanged trade price as an event that can be discarded. That shortcut corrupts rolling history because equal values can still come from separate events.
- Add BuggyFeatureEngine directly below FeatureEngine:
class BuggyFeatureEngine(FeatureEngine):
def __init__(self, window: int = WINDOW) -> None:
super().__init__(window)
self.last_trade_price: float | None = None
def on_trade(self, event: MarketEvent) -> None:
if event.trade_price == self.last_trade_price:
return
self.last_trade_price = event.trade_price
super().on_trade(event)
Where Is the Deliberate Bug?
The early return skips a trade whenever its price matches last_trade_price. The engine therefore loses an observation that belongs in the rolling buffer.
- Save market_lab.py.
- Confirm BuggyFeatureEngine inherits from FeatureEngine.
Buggy Engine Skips Every Trade?
Keep the assignment to last_trade_price after the equality check. Keep the call to super().on_trade(event) after that assignment.
Ask for help by selecting help me check the deliberate repeated-trade skip.
A replay feeds every event through one engine instance in chronological order. It evaluates one vector after all events for a tick have updated the shared state.
- Add replay_vectors() directly below BuggyFeatureEngine:
def replay_vectors(
engine_type: type[FeatureEngine], ticks: list[MarketTick]
) -> list[list[float]]:
engine = engine_type()
vectors: list[list[float]] = []
for tick in ticks:
for event in tick.events:
engine.handle(event)
vectors.append(engine.evaluate())
return vectors
Why Reuse One Engine?
Rolling features depend on earlier events. Reusing one engine preserves the chronological state that each later tick needs.
The engine_type parameter lets the same replay run either the correct engine or the deliberately naive engine.
- Save market_lab.py.
- Confirm replay_vectors() evaluates once after the inner event loop finishes.
One Vector Appears Per Event?
Keep vectors.append(engine.evaluate()) aligned with the inner for statement. It should remain inside the tick loop plus outside the event loop.
Ask for help by selecting help me fix the nested replay loops.
Print the first feature vectors
The first three ticks provide a small visible slice of the complete stream. Their event-kind lists reveal the repeated trade while their vectors show the engine state after each tick.
- Add show_events() directly below replay_vectors():
def show_events() -> None:
ticks = generate_ticks()
engine = FeatureEngine()
for tick_index, tick in enumerate(ticks[:3]):
for event in tick.events:
engine.handle(event)
kinds = [event.kind for event in tick.events]
rounded = [round(value, 5) for value in engine.evaluate()]
print(
f"tick={tick_index:03d} regime={tick.regime} "
f"events={kinds} features={rounded}"
)
What Will Each Line Show?
- The tick number preserves chronological order.
- The regime identifies which data-generating relationship produced the tick.
- The event list plus rounded feature vector make the replay state visible in one line.
- Save market_lab.py.
- Confirm show_events() slices the generated stream to its first three ticks.
Print Statement Split Incorrectly?
Keep both formatted strings inside the same print() call. Keep the closing parenthesis aligned with the opening call.
Ask for help by selecting help me check the show_events print statement.
The command path turns the script into a small experiment runner. This step exposes the events path while reserving the remaining mode names for later experiments.
- Add the command parser at the bottom of market_lab.py:
def main() -> None:
parser = argparse.ArgumentParser(description="Event-driven market feature lab")
parser.add_argument("mode", choices=["events", "bug", "parity", "train"])
args = parser.parse_args()
if args.mode == "events":
show_events()
if __name__ == "__main__":
main()
What Does the Command Path Do?
The parser reads the experiment mode from the PowerShell command. The events branch calls show_events().
- Save market_lab.py.
- Return to the PowerShell terminal from the previous step.
Command Parser Does Not Run?
Check that the final if __name__ == "__main__": block begins at the left edge. Keep main() indented beneath it.
Ask for help by selecting help me check the market_lab.py command parser.
Before you run the replay, decide whether you expect the first tick to contain two events or a repeated third trade.
- Run the first market replay from the mini-market-feature-engine PowerShell terminal with this command:
.\.venv\Scripts\python.exe market_lab.py events
What Does This Command Do?
The command uses the project-local Python executable from .venv. It starts market_lab.py in events mode.
You should see three lines for ticks 000 through 002. Each line shows a regime name plus event kinds plus a four-number feature vector.
The first line includes one BOOK event plus two TRADE events. That repeated same-price trade proves the controlled edge case is present in the stream.
Do Not See Three Ticks?
Confirm the terminal is still working inside mini-market-feature-engine. Confirm market_lab.py is saved beside requirements.txt.
Ask for help by selecting help me debug the events replay output.
✔️ Awesome, I've got everything!
Your deterministic event replay is working. Make sure market_lab.py is saved before continuing.
ⓧ I'd like to double check the full code
Compare your complete market_lab.py file with this version.
import argparse
import math
import random
from dataclasses import dataclass
SEED = 7
WINDOW = 10
N_TICKS = 600
FEATURE_NAMES = [
"imbalance",
"recent_trade_vs_mid",
"recent_trade_sign",
"mid_change",
]
REPORT_FILE = "research_report.md"
@dataclass(frozen=True)
class MarketEvent:
kind: str
bid: float | None = None
ask: float | None = None
bid_size: float | None = None
ask_size: float | None = None
trade_price: float | None = None
@dataclass(frozen=True)
class MarketTick:
events: list[MarketEvent]
target: float
regime: str
def generate_ticks(n_ticks: int = N_TICKS, seed: int = SEED) -> list[MarketTick]:
rng = random.Random(seed)
mid = 100.00
split = int(n_ticks * 0.70)
ticks: list[MarketTick] = []
for tick_index in range(n_ticks):
regime = "A" if tick_index < split else "B"
regime_direction = 1.0 if regime == "A" else -1.0
flow = rng.uniform(-1.0, 1.0)
bid_size = max(20.0, 120.0 + 80.0 * flow + rng.uniform(-10.0, 10.0))
ask_size = max(20.0, 120.0 - 80.0 * flow + rng.uniform(-10.0, 10.0))
bid = round(mid - 0.01, 2)
ask = round(mid + 0.01, 2)
trade_price = ask if flow >= 0.0 else bid
trade_side = 1.0 if trade_price > mid else -1.0
imbalance = (bid_size - ask_size) / (bid_size + ask_size)
events = [
MarketEvent("BOOK", bid, ask, bid_size, ask_size),
MarketEvent("TRADE", trade_price=trade_price),
]
if tick_index % 23 == 0:
events.append(MarketEvent("TRADE", trade_price=trade_price))
score = regime_direction * (2.3 * imbalance + 0.8 * trade_side)
score += rng.gauss(0.0, 0.8)
probability_up = 1.0 / (1.0 + math.exp(-score))
target = 1.0 if rng.random() < probability_up else 0.0
ticks.append(MarketTick(events, target, regime))
mid = round(mid + (0.01 if target == 1.0 else -0.01), 2)
return ticks
class FeatureEngine:
def __init__(self, window: int = WINDOW) -> None:
self.window = window
self.mid: float | None = None
self.bid_size = 0.0
self.ask_size = 0.0
self.mid_change = 0.0
self.trade_diffs = [0.0] * window
self.trade_signs = [0.0] * window
self.next_index = 0
self.count = 0
self.diff_sum = 0.0
self.sign_sum = 0.0
def on_book(self, event: MarketEvent) -> None:
assert event.bid is not None and event.ask is not None
assert event.bid_size is not None and event.ask_size is not None
previous_mid = self.mid
self.mid = (event.bid + event.ask) / 2.0
self.bid_size = event.bid_size
self.ask_size = event.ask_size
self.mid_change = 0.0 if previous_mid is None else self.mid - previous_mid
def on_trade(self, event: MarketEvent) -> None:
assert self.mid is not None and event.trade_price is not None
trade_diff = event.trade_price - self.mid
trade_sign = 1.0 if trade_diff > 0.0 else -1.0 if trade_diff < 0.0 else 0.0
if self.count == self.window:
self.diff_sum -= self.trade_diffs[self.next_index]
self.sign_sum -= self.trade_signs[self.next_index]
else:
self.count += 1
self.trade_diffs[self.next_index] = trade_diff
self.trade_signs[self.next_index] = trade_sign
self.diff_sum += trade_diff
self.sign_sum += trade_sign
self.next_index = (self.next_index + 1) % self.window
def handle(self, event: MarketEvent) -> None:
if event.kind == "BOOK":
self.on_book(event)
elif event.kind == "TRADE":
self.on_trade(event)
else:
raise ValueError(f"Unknown event kind: {event.kind}")
def evaluate(self) -> list[float]:
size_total = self.bid_size + self.ask_size
imbalance = 0.0 if size_total == 0.0 else (self.bid_size - self.ask_size) / size_total
denominator = max(self.count, 1)
return [
imbalance,
self.diff_sum / denominator,
self.sign_sum / denominator,
self.mid_change,
]
class BuggyFeatureEngine(FeatureEngine):
def __init__(self, window: int = WINDOW) -> None:
super().__init__(window)
self.last_trade_price: float | None = None
def on_trade(self, event: MarketEvent) -> None:
if event.trade_price == self.last_trade_price:
return
self.last_trade_price = event.trade_price
super().on_trade(event)
def replay_vectors(
engine_type: type[FeatureEngine], ticks: list[MarketTick]
) -> list[list[float]]:
engine = engine_type()
vectors: list[list[float]] = []
for tick in ticks:
for event in tick.events:
engine.handle(event)
vectors.append(engine.evaluate())
return vectors
def show_events() -> None:
ticks = generate_ticks()
engine = FeatureEngine()
for tick_index, tick in enumerate(ticks[:3]):
for event in tick.events:
engine.handle(event)
kinds = [event.kind for event in tick.events]
rounded = [round(value, 5) for value in engine.evaluate()]
print(
f"tick={tick_index:03d} regime={tick.regime} "
f"events={kinds} features={rounded}"
)
def main() -> None:
parser = argparse.ArgumentParser(description="Event-driven market feature lab")
parser.add_argument("mode", choices=["events", "bug", "parity", "train"])
args = parser.parse_args()
if args.mode == "events":
show_events()
if __name__ == "__main__":
main()
That is your first working market replay. Next, you will compare the naive repeated-value cutoff with an independent reference calculation to expose the first corrupted feature.
Catch the Dropped-Event Bug
Your event replay now turns deterministic BOOK and TRADE events into four model-ready features. The remaining risk sits inside the state history.
Two consecutive trades can share a price while still representing two events. If replay drops the second trade, every rolling average after it can drift away from the source stream.
In this step, get ready to:
- Calculate trusted feature vectors directly from every market event.
- Compare the trusted vectors with the naive event engine.
- Expose the first feature corrupted by the repeated-trade bug.
Build an independent reference
An independent reference gives the event engine a separate answer key. It calculates features directly from each tick. Shared handler logic cannot hide the same mistake.
- Place the start of reference_vectors directly below replay_vectors in market_lab.py by adding this code:
def reference_vectors(ticks: list[MarketTick], window: int = WINDOW) -> list[list[float]]:
recent_diffs: list[float] = []
recent_signs: list[float] = []
previous_mid: float | None = None
vectors: list[list[float]] = []
for tick in ticks:
book = tick.events[0]
assert book.bid is not None and book.ask is not None
assert book.bid_size is not None and book.ask_size is not None
mid = (book.bid + book.ask) / 2.0
mid_change = 0.0 if previous_mid is None else mid - previous_mid
previous_mid = mid
How does the reference start?
- The recent_diffs and recent_signs lists hold the rolling trade history.
- The previous_mid value lets the reference calculate the change between consecutive order-book mids.
- The first event in each tick supplies the current bid, ask, and book sizes.
- Continue reference_vectors immediately below previous_mid = mid by adding the remaining calculation:
for event in tick.events[1:]:
assert event.trade_price is not None
trade_diff = event.trade_price - mid
trade_sign = 1.0 if trade_diff > 0.0 else -1.0 if trade_diff < 0.0 else 0.0
recent_diffs.append(trade_diff)
recent_signs.append(trade_sign)
recent_diffs = recent_diffs[-window:]
recent_signs = recent_signs[-window:]
imbalance = (book.bid_size - book.ask_size) / (book.bid_size + book.ask_size)
vectors.append(
[
imbalance,
sum(recent_diffs) / max(len(recent_diffs), 1),
sum(recent_signs) / max(len(recent_signs), 1),
mid_change,
]
)
return vectors
Why is this an independent reference?
- The inner loop processes every event after the BOOK event. Repeated TRADE prices still enter both history lists.
- The slices retain the latest 10 trades without using the feature engine's rolling buffer.
- Each vector follows the same feature order stored in FEATURE_NAMES.
- Add first_mismatch directly below reference_vectors in market_lab.py using this code:
def first_mismatch(
expected: list[list[float]], actual: list[list[float]], tolerance: float = 1e-12
) -> tuple[int, str, float, float] | None:
for tick_index, (expected_row, actual_row) in enumerate(zip(expected, actual)):
for feature_index, (expected_value, actual_value) in enumerate(
zip(expected_row, actual_row)
):
if abs(expected_value - actual_value) > tolerance:
return (
tick_index,
FEATURE_NAMES[feature_index],
expected_value,
actual_value,
)
return None
What does the comparison return?
- The nested loops compare vectors in chronological order. The search stops at the earliest difference.
- The 1e-12 tolerance prevents insignificant floating-point noise from becoming a mismatch.
- A mismatch contains the tick index, feature name, reference value, and engine value.
- Save market_lab.py.
- Check that the existing event replay still runs by entering this command in the PowerShell terminal from earlier:
.\.venv\Scripts\python.exe market_lab.py events
What does this check prove?
The events mode exercises the existing generator and feature engine after your additions. A successful replay proves the new functions did not break the working command path.
You should still see three ticks with event kinds, regime names, and four-number feature vectors.
Does the event replay fail?
Check the indentation inside reference_vectors. The trade loop belongs inside the tick loop. The final return vectors line belongs outside both loops.
Compare the names recent_diffs, recent_signs, and FEATURE_NAMES with the snippets above.
Ask for help with the exact traceback: help me fix my reference_vectors or first_mismatch code
Wire the failing comparison
The diagnostic mode gives the reference and BuggyFeatureEngine the same ticks. The comparison then reports the earliest point where their histories produce different features.
- Add run_bug_demo directly below show_events in market_lab.py using this code:
def run_bug_demo() -> None:
ticks = generate_ticks()
mismatch = first_mismatch(
reference_vectors(ticks), replay_vectors(BuggyFeatureEngine, ticks)
)
if mismatch is None:
raise RuntimeError("The deliberate bug was not reproduced.")
tick_index, feature_name, expected, actual = mismatch
print(
"BUG REPRODUCED: "
f"tick={tick_index} feature={feature_name} "
f"reference={expected:.6f} buggy={actual:.6f}"
)
How does the bug demonstration work?
- Both calculations receive the same deterministic ticks from generate_ticks.
- The reference processes every trade. BuggyFeatureEngine skips a trade when its price equals last_trade_price.
- The printed result records the first corrupted feature instead of hiding later differences behind a summary.
- Replace the existing main function in market_lab.py with this updated command routing:
def main() -> None:
parser = argparse.ArgumentParser(description="Event-driven market feature lab")
parser.add_argument("mode", choices=["events", "bug"])
args = parser.parse_args()
if args.mode == "events":
show_events()
else:
run_bug_demo()
What changed in the command path?
The positional mode argument now accepts events or bug. The selected value routes execution to the matching experiment.
- Save market_lab.py.
Before you run the comparison, do you think the two feature histories remain identical after a repeated same-price trade?
- Reveal the first difference by running this command in the PowerShell terminal:
.\.venv\Scripts\python.exe market_lab.py bug
What does this command test?
The bug mode compares the independent vectors with the naive replay. It reports the first feature whose value exceeds the numeric tolerance.
You should see a line beginning with BUG REPRODUCED. The line names the first mismatched tick and feature. It also shows the reference and buggy values.
That is the hidden state bug made visible. You now have a permanent regression demonstration showing how one dropped event corrupts a history-dependent feature.
Do the vectors appear to match?
Check that reference_vectors loops through tick.events[1:] without filtering repeated prices. Every trade must enter recent_diffs and recent_signs.
Check that run_bug_demo passes BuggyFeatureEngine to replay_vectors.
Ask for help with the comparison: help me find why the repeated-trade mismatch is missing
✔️ Awesome, I've got everything!
Great. Save market_lab.py with the independent reference and permanent bug demonstration in place.
ⓧ I'd like to double check the full code
Compare your cumulative market_lab.py with this version.
import argparse
import math
import random
from dataclasses import dataclass
import torch
import torch.nn as nn
SEED = 7
WINDOW = 10
N_TICKS = 600
FEATURE_NAMES = [
"imbalance",
"recent_trade_vs_mid",
"recent_trade_sign",
"mid_change",
]
REPORT_FILE = "research_report.md"
@dataclass(frozen=True)
class MarketEvent:
kind: str
bid: float | None = None
ask: float | None = None
bid_size: float | None = None
ask_size: float | None = None
trade_price: float | None = None
@dataclass(frozen=True)
class MarketTick:
events: list[MarketEvent]
target: float
regime: str
def generate_ticks(n_ticks: int = N_TICKS, seed: int = SEED) -> list[MarketTick]:
rng = random.Random(seed)
mid = 100.00
split = int(n_ticks * 0.70)
ticks: list[MarketTick] = []
for tick_index in range(n_ticks):
regime = "A" if tick_index < split else "B"
regime_direction = 1.0 if regime == "A" else -1.0
flow = rng.uniform(-1.0, 1.0)
bid_size = max(20.0, 120.0 + 80.0 * flow + rng.uniform(-10.0, 10.0))
ask_size = max(20.0, 120.0 - 80.0 * flow + rng.uniform(-10.0, 10.0))
bid = round(mid - 0.01, 2)
ask = round(mid + 0.01, 2)
trade_price = ask if flow >= 0.0 else bid
trade_side = 1.0 if trade_price > mid else -1.0
imbalance = (bid_size - ask_size) / (bid_size + ask_size)
events = [
MarketEvent("BOOK", bid, ask, bid_size, ask_size),
MarketEvent("TRADE", trade_price=trade_price),
]
if tick_index % 23 == 0:
events.append(MarketEvent("TRADE", trade_price=trade_price))
score = regime_direction * (2.3 * imbalance + 0.8 * trade_side)
score += rng.gauss(0.0, 0.8)
probability_up = 1.0 / (1.0 + math.exp(-score))
target = 1.0 if rng.random() < probability_up else 0.0
ticks.append(MarketTick(events, target, regime))
mid = round(mid + (0.01 if target == 1.0 else -0.01), 2)
return ticks
class FeatureEngine:
def __init__(self, window: int = WINDOW) -> None:
self.window = window
self.mid: float | None = None
self.bid_size = 0.0
self.ask_size = 0.0
self.mid_change = 0.0
self.trade_diffs = [0.0] * window
self.trade_signs = [0.0] * window
self.next_index = 0
self.count = 0
self.diff_sum = 0.0
self.sign_sum = 0.0
def on_book(self, event: MarketEvent) -> None:
assert event.bid is not None and event.ask is not None
assert event.bid_size is not None and event.ask_size is not None
previous_mid = self.mid
self.mid = (event.bid + event.ask) / 2.0
self.bid_size = event.bid_size
self.ask_size = event.ask_size
self.mid_change = 0.0 if previous_mid is None else self.mid - previous_mid
def on_trade(self, event: MarketEvent) -> None:
assert self.mid is not None and event.trade_price is not None
trade_diff = event.trade_price - self.mid
trade_sign = 1.0 if trade_diff > 0.0 else -1.0 if trade_diff < 0.0 else 0.0
if self.count == self.window:
self.diff_sum -= self.trade_diffs[self.next_index]
self.sign_sum -= self.trade_signs[self.next_index]
else:
self.count += 1
self.trade_diffs[self.next_index] = trade_diff
self.trade_signs[self.next_index] = trade_sign
self.diff_sum += trade_diff
self.sign_sum += trade_sign
self.next_index = (self.next_index + 1) % self.window
def handle(self, event: MarketEvent) -> None:
if event.kind == "BOOK":
self.on_book(event)
elif event.kind == "TRADE":
self.on_trade(event)
else:
raise ValueError(f"Unknown event kind: {event.kind}")
def evaluate(self) -> list[float]:
size_total = self.bid_size + self.ask_size
imbalance = 0.0 if size_total == 0.0 else (self.bid_size - self.ask_size) / size_total
denominator = max(self.count, 1)
return [
imbalance,
self.diff_sum / denominator,
self.sign_sum / denominator,
self.mid_change,
]
class BuggyFeatureEngine(FeatureEngine):
def __init__(self, window: int = WINDOW) -> None:
super().__init__(window)
self.last_trade_price: float | None = None
def on_trade(self, event: MarketEvent) -> None:
if event.trade_price == self.last_trade_price:
return
self.last_trade_price = event.trade_price
super().on_trade(event)
def replay_vectors(
engine_type: type[FeatureEngine], ticks: list[MarketTick]
) -> list[list[float]]:
engine = engine_type()
vectors: list[list[float]] = []
for tick in ticks:
for event in tick.events:
engine.handle(event)
vectors.append(engine.evaluate())
return vectors
def reference_vectors(ticks: list[MarketTick], window: int = WINDOW) -> list[list[float]]:
recent_diffs: list[float] = []
recent_signs: list[float] = []
previous_mid: float | None = None
vectors: list[list[float]] = []
for tick in ticks:
book = tick.events[0]
assert book.bid is not None and book.ask is not None
assert book.bid_size is not None and book.ask_size is not None
mid = (book.bid + book.ask) / 2.0
mid_change = 0.0 if previous_mid is None else mid - previous_mid
previous_mid = mid
for event in tick.events[1:]:
assert event.trade_price is not None
trade_diff = event.trade_price - mid
trade_sign = 1.0 if trade_diff > 0.0 else -1.0 if trade_diff < 0.0 else 0.0
recent_diffs.append(trade_diff)
recent_signs.append(trade_sign)
recent_diffs = recent_diffs[-window:]
recent_signs = recent_signs[-window:]
imbalance = (book.bid_size - book.ask_size) / (book.bid_size + book.ask_size)
vectors.append(
[
imbalance,
sum(recent_diffs) / max(len(recent_diffs), 1),
sum(recent_signs) / max(len(recent_signs), 1),
mid_change,
]
)
return vectors
def first_mismatch(
expected: list[list[float]], actual: list[list[float]], tolerance: float = 1e-12
) -> tuple[int, str, float, float] | None:
for tick_index, (expected_row, actual_row) in enumerate(zip(expected, actual)):
for feature_index, (expected_value, actual_value) in enumerate(
zip(expected_row, actual_row)
):
if abs(expected_value - actual_value) > tolerance:
return (
tick_index,
FEATURE_NAMES[feature_index],
expected_value,
actual_value,
)
return None
def show_events() -> None:
ticks = generate_ticks()
engine = FeatureEngine()
for tick_index, tick in enumerate(ticks[:3]):
for event in tick.events:
engine.handle(event)
kinds = [event.kind for event in tick.events]
rounded = [round(value, 5) for value in engine.evaluate()]
print(
f"tick={tick_index:03d} regime={tick.regime} "
f"events={kinds} features={rounded}"
)
def run_bug_demo() -> None:
ticks = generate_ticks()
mismatch = first_mismatch(
reference_vectors(ticks), replay_vectors(BuggyFeatureEngine, ticks)
)
if mismatch is None:
raise RuntimeError("The deliberate bug was not reproduced.")
tick_index, feature_name, expected, actual = mismatch
print(
"BUG REPRODUCED: "
f"tick={tick_index} feature={feature_name} "
f"reference={expected:.6f} buggy={actual:.6f}"
)
def main() -> None:
parser = argparse.ArgumentParser(description="Event-driven market feature lab")
parser.add_argument("mode", choices=["events", "bug"])
args = parser.parse_args()
if args.mode == "events":
show_events()
else:
run_bug_demo()
if __name__ == "__main__":
main()
You have turned a silent replay error into a reproducible comparison. Next, you will remove the dropped-event behavior and prove that historical replay matches the trusted reference across the full stream.
Restore Historical and Live Parity
Your bug demonstration now exposes the first vector corrupted by BuggyFeatureEngine. You have turned a silent replay error into a reproducible result.
The corrected path now needs to prove that historical replay matches simulated live processing. Jane Street's Flex Model design uses handlers to update state when events arrive.
Eval functions expose values after that state is current. You will compare this shared path against the independent reference across the full stream.
In this step, get ready to:
- Trace how every BOOK event reaches the corrected handler state.
- Trace how every TRADE event reaches the corrected handler state.
- Add the parity command path to compare corrected replay with the reference.
- Run the full-stream parity check across 600 vectors with four features.
Trace the corrected event path
The corrected engine already has separate update and evaluation paths. Tracing them shows why a repeated price still represents a new event.
- Switch back to market_lab.py in the Visual Studio Code project from the previous step.
- Locate FeatureEngine.handle().
- Follow the TRADE branch into FeatureEngine.on_trade().
- Locate FeatureEngine.evaluate().
You will find that handle() sends every trade to on_trade(). The handler pushes each trade into trade_diffs plus trade_signs before evaluate() reads the rolling state.
Why separate handlers from evaluation?
Handlers preserve event history as the stream arrives. Two trades at the same price remain two distinct updates to a rolling feature.
Evaluation reads the current state through one shared definition. This separation makes feature parity testable across historical replay and simulated live processing.
Add the parity command path
The parity path needs one trusted side plus one engine-driven side. Any difference should stop the command before it can report success.
- Find def main() near the bottom of market_lab.py.
- Replace everything from def main() through the final main() call with this parity command path:
def run_parity() -> None:
ticks = generate_ticks()
expected = reference_vectors(ticks)
actual = replay_vectors(FeatureEngine, ticks)
mismatch = first_mismatch(expected, actual)
if mismatch is not None:
raise AssertionError(f"Parity failed: {mismatch}")
print(
f"PARITY PASS: {len(actual)} vectors match across "
f"{len(FEATURE_NAMES)} features."
)
def main() -> None:
parser = argparse.ArgumentParser(description="Event-driven market feature lab")
parser.add_argument(
"mode", choices=["events", "bug", "parity"]
)
args = parser.parse_args()
if args.mode == "events":
show_events()
elif args.mode == "bug":
run_bug_demo()
else:
run_parity()
if __name__ == "__main__":
main()
What does this command path do?
- The expected vectors come from reference_vectors(), which calculates directly from every event.
- The actual vectors come from replaying FeatureEngine through its shared handler path.
- The first_mismatch() check raises an AssertionError when any value exceeds the numeric tolerance.
- The command choices preserve the existing events demonstration plus the permanent bug demonstration.
- Save market_lab.py.
The bottom of market_lab.py now exposes events, bug, plus parity as separate experiment modes.
Prove parity across the full stream
Before you run the check, do you think the corrected replay will match all 600 reference vectors?
- Run the corrected replay against the independent reference with this command:
.\.venv\Scripts\python.exe market_lab.py parity
What does this command do?
The project-local Python executable runs market_lab.py in parity mode. That mode compares every corrected vector with its independently calculated reference vector.
You should see PARITY PASS: 600 vectors match across 4 features. in the PowerShell terminal.
That is the trust boundary secured. Your corrected engine now produces the same features through the reference calculation and the shared event path.
Parity check not passing?
- Check that the parity choice appears inside the choices list in main().
- Check that the final branch calls run_parity().
- Check that FeatureEngine.on_trade() does not contain the repeated-price filter from BuggyFeatureEngine.on_trade().
- Use help me diagnose the first parity mismatch if the command raises a mismatch.
✔️ Awesome, I've got everything!
Your saved market_lab.py now keeps the bug demonstration while proving the corrected replay matches all 600 reference vectors.
ⓧ I'd like to double check the full code
Compare your cumulative market_lab.py with this reference. Your existing requirements.txt remains unchanged at torch==2.15.0.
import argparse
import math
import random
from dataclasses import dataclass
SEED = 7
WINDOW = 10
N_TICKS = 600
FEATURE_NAMES = [
"imbalance",
"recent_trade_vs_mid",
"recent_trade_sign",
"mid_change",
]
@dataclass(frozen=True)
class MarketEvent:
kind: str
bid: float | None = None
ask: float | None = None
bid_size: float | None = None
ask_size: float | None = None
trade_price: float | None = None
@dataclass(frozen=True)
class MarketTick:
events: list[MarketEvent]
target: float
regime: str
def generate_ticks(n_ticks: int = N_TICKS, seed: int = SEED) -> list[MarketTick]:
rng = random.Random(seed)
mid = 100.00
split = int(n_ticks * 0.70)
ticks: list[MarketTick] = []
for tick_index in range(n_ticks):
regime = "A" if tick_index < split else "B"
regime_direction = 1.0 if regime == "A" else -1.0
flow = rng.uniform(-1.0, 1.0)
bid_size = max(20.0, 120.0 + 80.0 * flow + rng.uniform(-10.0, 10.0))
ask_size = max(20.0, 120.0 - 80.0 * flow + rng.uniform(-10.0, 10.0))
bid = round(mid - 0.01, 2)
ask = round(mid + 0.01, 2)
trade_price = ask if flow >= 0.0 else bid
trade_side = 1.0 if trade_price > mid else -1.0
imbalance = (bid_size - ask_size) / (bid_size + ask_size)
events = [
MarketEvent("BOOK", bid, ask, bid_size, ask_size),
MarketEvent("TRADE", trade_price=trade_price),
]
if tick_index % 23 == 0:
events.append(MarketEvent("TRADE", trade_price=trade_price))
score = regime_direction * (2.3 * imbalance + 0.8 * trade_side)
score += rng.gauss(0.0, 0.8)
probability_up = 1.0 / (1.0 + math.exp(-score))
target = 1.0 if rng.random() < probability_up else 0.0
ticks.append(MarketTick(events, target, regime))
mid = round(mid + (0.01 if target == 1.0 else -0.01), 2)
return ticks
class FeatureEngine:
def __init__(self, window: int = WINDOW) -> None:
self.window = window
self.mid: float | None = None
self.bid_size = 0.0
self.ask_size = 0.0
self.mid_change = 0.0
self.trade_diffs = [0.0] * window
self.trade_signs = [0.0] * window
self.next_index = 0
self.count = 0
self.diff_sum = 0.0
self.sign_sum = 0.0
def on_book(self, event: MarketEvent) -> None:
assert event.bid is not None and event.ask is not None
assert event.bid_size is not None and event.ask_size is not None
previous_mid = self.mid
self.mid = (event.bid + event.ask) / 2.0
self.bid_size = event.bid_size
self.ask_size = event.ask_size
self.mid_change = 0.0 if previous_mid is None else self.mid - previous_mid
def on_trade(self, event: MarketEvent) -> None:
assert self.mid is not None and event.trade_price is not None
trade_diff = event.trade_price - self.mid
trade_sign = 1.0 if trade_diff > 0.0 else -1.0 if trade_diff < 0.0 else 0.0
if self.count == self.window:
self.diff_sum -= self.trade_diffs[self.next_index]
self.sign_sum -= self.trade_signs[self.next_index]
else:
self.count += 1
self.trade_diffs[self.next_index] = trade_diff
self.trade_signs[self.next_index] = trade_sign
self.diff_sum += trade_diff
self.sign_sum += trade_sign
self.next_index = (self.next_index + 1) % self.window
def handle(self, event: MarketEvent) -> None:
if event.kind == "BOOK":
self.on_book(event)
elif event.kind == "TRADE":
self.on_trade(event)
else:
raise ValueError(f"Unknown event kind: {event.kind}")
def evaluate(self) -> list[float]:
size_total = self.bid_size + self.ask_size
imbalance = 0.0 if size_total == 0.0 else (self.bid_size - self.ask_size) / size_total
denominator = max(self.count, 1)
return [
imbalance,
self.diff_sum / denominator,
self.sign_sum / denominator,
self.mid_change,
]
class BuggyFeatureEngine(FeatureEngine):
def __init__(self, window: int = WINDOW) -> None:
super().__init__(window)
self.last_trade_price: float | None = None
def on_trade(self, event: MarketEvent) -> None:
if event.trade_price == self.last_trade_price:
return
self.last_trade_price = event.trade_price
super().on_trade(event)
def replay_vectors(
engine_type: type[FeatureEngine], ticks: list[MarketTick]
) -> list[list[float]]:
engine = engine_type()
vectors: list[list[float]] = []
for tick in ticks:
for event in tick.events:
engine.handle(event)
vectors.append(engine.evaluate())
return vectors
def reference_vectors(ticks: list[MarketTick], window: int = WINDOW) -> list[list[float]]:
recent_diffs: list[float] = []
recent_signs: list[float] = []
previous_mid: float | None = None
vectors: list[list[float]] = []
for tick in ticks:
book = tick.events[0]
assert book.bid is not None and book.ask is not None
assert book.bid_size is not None and book.ask_size is not None
mid = (book.bid + book.ask) / 2.0
mid_change = 0.0 if previous_mid is None else mid - previous_mid
previous_mid = mid
for event in tick.events[1:]:
assert event.trade_price is not None
trade_diff = event.trade_price - mid
trade_sign = 1.0 if trade_diff > 0.0 else -1.0 if trade_diff < 0.0 else 0.0
recent_diffs.append(trade_diff)
recent_signs.append(trade_sign)
recent_diffs = recent_diffs[-window:]
recent_signs = recent_signs[-window:]
imbalance = (book.bid_size - book.ask_size) / (book.bid_size + book.ask_size)
vectors.append(
[
imbalance,
sum(recent_diffs) / max(len(recent_diffs), 1),
sum(recent_signs) / max(len(recent_signs), 1),
mid_change,
]
)
return vectors
def first_mismatch(
expected: list[list[float]], actual: list[list[float]], tolerance: float = 1e-12
) -> tuple[int, str, float, float] | None:
for tick_index, (expected_row, actual_row) in enumerate(zip(expected, actual)):
for feature_index, (expected_value, actual_value) in enumerate(
zip(expected_row, actual_row)
):
if abs(expected_value - actual_value) > tolerance:
return (
tick_index,
FEATURE_NAMES[feature_index],
expected_value,
actual_value,
)
return None
def show_events() -> None:
ticks = generate_ticks()
engine = FeatureEngine()
for tick_index, tick in enumerate(ticks[:3]):
for event in tick.events:
engine.handle(event)
kinds = [event.kind for event in tick.events]
rounded = [round(value, 5) for value in engine.evaluate()]
print(
f"tick={tick_index:03d} regime={tick.regime} "
f"events={kinds} features={rounded}"
)
def run_bug_demo() -> None:
ticks = generate_ticks()
mismatch = first_mismatch(
reference_vectors(ticks), replay_vectors(BuggyFeatureEngine, ticks)
)
if mismatch is None:
raise RuntimeError("The deliberate bug was not reproduced.")
tick_index, feature_name, expected, actual = mismatch
print(
"BUG REPRODUCED: "
f"tick={tick_index} feature={feature_name} "
f"reference={expected:.6f} buggy={actual:.6f}"
)
def run_parity() -> None:
ticks = generate_ticks()
expected = reference_vectors(ticks)
actual = replay_vectors(FeatureEngine, ticks)
mismatch = first_mismatch(expected, actual)
if mismatch is not None:
raise AssertionError(f"Parity failed: {mismatch}")
print(
f"PARITY PASS: {len(actual)} vectors match across "
f"{len(FEATURE_NAMES)} features."
)
def main() -> None:
parser = argparse.ArgumentParser(description="Event-driven market feature lab")
parser.add_argument(
"mode", choices=["events", "bug", "parity"]
)
args = parser.parse_args()
if args.mode == "events":
show_events()
elif args.mode == "bug":
run_bug_demo()
else:
run_parity()
if __name__ == "__main__":
main()
How to use this reference
Compare the function order plus indentation with your saved file. The final command choices should contain events, bug, plus parity.
Your feature engine now has a permanent failure demonstration plus a corrected path that passes across the full stream. Next, you will test whether a linear baseline or a small neural network handles the regime change better.
Compare Models Across a Regime Shift
Your feature engine now produces the same vectors through its trusted reference and event-driven replay. That parity gives you a reliable foundation for testing whether the features support useful predictions.
Market relationships can change over time. In this step, you will use PyTorch to compare a linear baseline with a small neural network under a deliberate distribution shift.
In this step, get ready to:
- Create a chronological split that standardizes features using training-period statistics.
- Train a linear baseline and a small neural network with reproducible initialization.
- Compare train and test accuracy and generate a research memo.
Prepare chronological features
A chronological split preserves the order in which market observations arrive. The first 70% becomes the training period. The final 30% becomes the shifted test period.
Why use training statistics only?
Each feature column needs a common scale before model training. The code calculates its mean and variance from the training period only.
Using test-period statistics would leak information from the future. Training-only standardization keeps the chronological test independent.
- Return to market_lab.py in the Visual Studio Code editor.
- Add the following function below run_parity() to create standardized chronological tensors:
def standardize_and_split(
features: list[list[float]], labels: list[float]
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
split = int(len(features) * 0.70)
train_rows = features[:split]
means: list[float] = []
scales: list[float] = []
for feature_index in range(len(features[0])):
column = [row[feature_index] for row in train_rows]
mean = sum(column) / len(column)
variance = sum((value - mean) ** 2 for value in column) / len(column)
means.append(mean)
scales.append(math.sqrt(variance) or 1.0)
scaled = [
[
(value - means[feature_index]) / scales[feature_index]
for feature_index, value in enumerate(row)
]
for row in features
]
label_rows = [[label] for label in labels]
x = torch.tensor(scaled, dtype=torch.float32)
y = torch.tensor(label_rows, dtype=torch.float32)
return x[:split], y[:split], x[split:], y[split:]
What does this code do?
- The split index places the first 70% of observations in the training period.
- The means and scales lists contain statistics calculated from train_rows only.
- The scaled features and binary labels become floating-point tensors for model training.
- The return value keeps the training tensors before the test tensors in chronological order.
- Save market_lab.py.
- Confirm that the editor shows the complete standardize_and_split() function without a Python syntax warning.
Your script now turns parity-checked vectors into chronological training and test tensors without using future statistics.
Seeing a warning in the split function?
Check that every line inside standardize_and_split() uses four spaces of indentation. Keep the nested list comprehension aligned exactly as shown.
Ask for help with the chronological split.
- Add the model factory below standardize_and_split() to create either comparison model:
def make_model(kind: str, feature_count: int) -> nn.Module:
if kind == "linear":
return nn.Linear(feature_count, 1)
if kind == "mlp":
return nn.Sequential(
nn.Linear(feature_count, 8),
nn.ReLU(),
nn.Linear(8, 1),
)
raise ValueError(f"Unknown model kind: {kind}")
Why compare these models?
The linear model provides a simple baseline. Its single layer tests whether a weighted combination of the four features is enough.
The mlp model adds a hidden layer with eight units and a nonlinear activation. The comparison tests whether extra complexity survives the shifted test period.
- Save market_lab.py.
- Confirm that make_model() contains separate branches for linear and mlp.
The two model definitions are now fixed behind one function. Each experiment can request a model by name while keeping the surrounding training loop identical.
Seeing a model definition warning?
Check that the closing parenthesis for nn.Sequential() aligns with its return statement. Keep the final ValueError outside both model branches.
Ask for help with the model factory.
Train both model types
Both models need the same scoring rule and optimization process. Keeping those pieces shared makes model complexity the main difference in the comparison.
- Add the accuracy helper below make_model() to convert logits into binary predictions:
def accuracy(model: nn.Module, x: torch.Tensor, y: torch.Tensor) -> float:
with torch.no_grad():
predicted = (model(x) >= 0.0).to(dtype=torch.float32)
return (predicted == y).to(dtype=torch.float32).mean().item()
What does this code do?
- The torch.no_grad() context disables gradient tracking during evaluation.
- The zero threshold converts each model logit into a binary prediction.
- The equality comparison produces the share of predictions that match the labels.
- The item() call returns that accuracy as a Python number.
- Save market_lab.py.
- Confirm that the editor shows accuracy() immediately below make_model().
The lab can now score either model with the same binary classification rule.
Seeing a warning in accuracy?
Check that the comparison uses >= 0.0 before the dtype conversion. Keep the return statement inside the torch.no_grad() block.
Ask for help with the accuracy calculation.
- Add the shared training loop below accuracy() to fit one requested model type:
def fit_and_score(
kind: str, features: list[list[float]], labels: list[float]
) -> tuple[float, float]:
x_train, y_train, x_test, y_test = standardize_and_split(features, labels)
torch.manual_seed(SEED)
model = make_model(kind, len(features[0]))
loss_function = nn.BCEWithLogitsLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.03)
for _ in range(250):
optimizer.zero_grad()
loss = loss_function(model(x_train), y_train)
loss.backward()
optimizer.step()
return accuracy(model, x_train, y_train), accuracy(model, x_test, y_test)
How does training stay comparable?
- The call to standardize_and_split() gives each model the same chronological data.
- The call to torch.manual_seed(SEED) resets model initialization before every comparison.
- The binary-logit loss measures classification error without requiring a separate sigmoid layer.
- The Adam optimizer updates model parameters over 250 iterations at a learning rate of 0.03.
- The return value reports training accuracy and chronological test accuracy separately.
- Save market_lab.py.
- Confirm that fit_and_score() resets the seed before calling make_model().
The shared loop now gives the linear model and neural network the same data preparation and optimization conditions.
Seeing a warning in the training loop?
Check that all four optimizer actions sit inside the 250-iteration loop. Keep the final return statement outside that loop.
Ask for help with the training loop.
Generate the research comparison
A model table alone does not explain whether the experiment is trustworthy. The final command checks parity before training and records the result beside the dataset design and limitations.
- Add the first part of run_training() below fit_and_score() to verify features and print both model rows:
def run_training() -> None:
ticks = generate_ticks()
features = replay_vectors(FeatureEngine, ticks)
mismatch = first_mismatch(reference_vectors(ticks), features)
if mismatch is not None:
raise AssertionError(f"Refusing to train on mismatched features: {mismatch}")
labels = [tick.target for tick in ticks]
results = {
kind: fit_and_score(kind, features, labels) for kind in ("linear", "mlp")
}
print("model train_accuracy test_accuracy")
for kind, (train_accuracy, test_accuracy) in results.items():
print(f"{kind:<7} {train_accuracy:>14.3f} {test_accuracy:>14.3f}")
Why check parity again?
Training stops immediately if the event replay differs from the independent reference. This prevents either model from learning from silently corrupted features.
The same parity-checked feature matrix feeds both model types. Their printed rows therefore compare modeling choices over identical observations.
- Save market_lab.py.
- Confirm that the parity assertion appears before the label list and model training.
Training is now guarded by the same feature-correctness standard you established in the previous step.
Seeing a warning in run_training?
Check that the results dictionary comprehension remains inside its braces. Keep the print loop inside run_training().
Ask for help with the comparison function.
The research memo is one formatted string inside run_training(). You will add its opening and closing pieces next.
- Add the following report opening inside run_training() immediately after the model result print loop:
winner = max(results, key=lambda name: results[name][1])
linear_train, linear_test = results["linear"]
mlp_train, mlp_test = results["mlp"]
report = f"""# Event-Driven Market Feature Research Report
## Hypothesis
Every trade event must update history-dependent feature state, even when two consecutive trades have the same price. After parity is restored, a nonlinear model may fit the synthetic signal better than a linear baseline, but neither model is guaranteed to survive a reversed test regime.
## Dataset design
- {len(ticks)} deterministic synthetic ticks
- `BOOK` and `TRADE` events, including repeated same-price trades
- Four event-derived features: {", ".join(FEATURE_NAMES)}
- First 70% in regime A; final 30% in regime B with the signal relationship reversed
## Feature parity
The corrected event replay matched the independent reference across every tick and feature before training began.
## Results
| Model | Train accuracy | Test accuracy |
| --- | ---: | ---: |
| Linear | {linear_train:.3f} | {linear_test:.3f} |
| MLP | {mlp_train:.3f} | {mlp_test:.3f} |
What goes into the report?
The opening records the hypothesis and the deterministic dataset design. It also documents that feature parity passed before training.
The model table inserts the measured train and test accuracies from this run. The next code block completes the same formatted string.
- Complete the open report string by pasting the following lines directly after the MLP table row:
The higher chronological test accuracy came from `{winner}`. The test period deliberately changes the data-generating relationship, so the train-to-test gaps are evidence about distribution shift, not evidence of a profitable trading strategy.
## Limitations
The events, labels, spread, and regime change are synthetic. The experiment excludes transaction costs, latency, queue position, execution, risk limits, and real market feedback.
## Next experiment
Run a one-feature-at-a-time ablation, then test rolling retraining that uses only the most recent observations.
"""
with open(REPORT_FILE, "w", encoding="utf-8") as report_file:
report_file.write(report)
print(f"Wrote {REPORT_FILE}")
How does the conclusion stay honest?
The interpretation names the model with higher chronological test accuracy. It treats the train-to-test gap as evidence about the controlled regime change.
The limitations keep synthetic classification results separate from claims about live trading. The next experiment points toward controlled feature ablation.
- Save market_lab.py.
- Confirm that the formatted report string closes before the with open block.
The training function can now print the comparison and write the same evidence into research_report.md.
Seeing an unfinished string warning?
Check that the opening f""" appears before the report title. Check that the closing """ appears on its own line before the file-writing block.
Ask for help with the report string.
- Replace the existing main() function and script entry point with the following final command routing:
def main() -> None:
parser = argparse.ArgumentParser(description="Event-driven market feature lab")
parser.add_argument("mode", choices=["events", "bug", "parity", "train"])
args = parser.parse_args()
if args.mode == "events":
show_events()
elif args.mode == "bug":
run_bug_demo()
elif args.mode == "parity":
run_parity()
else:
run_training()
if __name__ == "__main__":
main()
What does this command routing do?
The parser now accepts train alongside the three existing modes. The final branch calls run_training() when that mode is selected.
The existing event inspection and parity demonstrations remain available. Your script now supports the complete core research workflow.
- Save market_lab.py.
Before you run the comparison, which model do you think will retain more accuracy after the signal relationship reverses?
- Run the chronological model comparison in the existing PowerShell terminal with this command:
.\.venv\Scripts\python.exe market_lab.py train
What does this command do?
The project-local Python executable runs the train mode from market_lab.py. The script checks parity before fitting either model.
The command prints the two accuracy rows. It then writes the reproducible conclusion to research_report.md.
You should see a table headed by model train_accuracy test_accuracy with rows for linear and mlp. The final line should confirm that the script wrote research_report.md.
That completes the research loop. You now have parity-checked features and an out-of-sample comparison across a controlled regime shift.
Training command failed?
If Python reports a syntax problem near the report, compare the triple quotes and indentation with the full code below. If the mode is rejected, confirm that train appears in the parser choices.
Ask for help with the training run.
- Select research_report.md in the Explorer sidebar after the command finishes.
- Review the hypothesis and dataset design in the generated report.
- Compare the linear and MLP train and test accuracy rows.
- Read the regime-shift interpretation and limitations.
You should see a report that separates measured model behavior from any profitability claim. Its final section proposes one-feature-at-a-time ablation as the next experiment.
✔️ Awesome, I've got everything!
Your saved script now supports events, bug, parity, and train modes. Keep research_report.md beside it as the generated research memo.
ⓧ I'd like to double check the full code
Compare your complete market_lab.py with this reference.
import argparse
import math
import random
from dataclasses import dataclass
import torch
import torch.nn as nn
SEED = 7
WINDOW = 10
N_TICKS = 600
FEATURE_NAMES = [
"imbalance",
"recent_trade_vs_mid",
"recent_trade_sign",
"mid_change",
]
REPORT_FILE = "research_report.md"
@dataclass(frozen=True)
class MarketEvent:
kind: str
bid: float | None = None
ask: float | None = None
bid_size: float | None = None
ask_size: float | None = None
trade_price: float | None = None
@dataclass(frozen=True)
class MarketTick:
events: list[MarketEvent]
target: float
regime: str
def generate_ticks(n_ticks: int = N_TICKS, seed: int = SEED) -> list[MarketTick]:
rng = random.Random(seed)
mid = 100.00
split = int(n_ticks * 0.70)
ticks: list[MarketTick] = []
for tick_index in range(n_ticks):
regime = "A" if tick_index < split else "B"
regime_direction = 1.0 if regime == "A" else -1.0
flow = rng.uniform(-1.0, 1.0)
bid_size = max(20.0, 120.0 + 80.0 * flow + rng.uniform(-10.0, 10.0))
ask_size = max(20.0, 120.0 - 80.0 * flow + rng.uniform(-10.0, 10.0))
bid = round(mid - 0.01, 2)
ask = round(mid + 0.01, 2)
trade_price = ask if flow >= 0.0 else bid
trade_side = 1.0 if trade_price > mid else -1.0
imbalance = (bid_size - ask_size) / (bid_size + ask_size)
events = [
MarketEvent("BOOK", bid, ask, bid_size, ask_size),
MarketEvent("TRADE", trade_price=trade_price),
]
if tick_index % 23 == 0:
events.append(MarketEvent("TRADE", trade_price=trade_price))
score = regime_direction * (2.3 * imbalance + 0.8 * trade_side)
score += rng.gauss(0.0, 0.8)
probability_up = 1.0 / (1.0 + math.exp(-score))
target = 1.0 if rng.random() < probability_up else 0.0
ticks.append(MarketTick(events, target, regime))
mid = round(mid + (0.01 if target == 1.0 else -0.01), 2)
return ticks
class FeatureEngine:
def __init__(self, window: int = WINDOW) -> None:
self.window = window
self.mid: float | None = None
self.bid_size = 0.0
self.ask_size = 0.0
self.mid_change = 0.0
self.trade_diffs = [0.0] * window
self.trade_signs = [0.0] * window
self.next_index = 0
self.count = 0
self.diff_sum = 0.0
self.sign_sum = 0.0
def on_book(self, event: MarketEvent) -> None:
assert event.bid is not None and event.ask is not None
assert event.bid_size is not None and event.ask_size is not None
previous_mid = self.mid
self.mid = (event.bid + event.ask) / 2.0
self.bid_size = event.bid_size
self.ask_size = event.ask_size
self.mid_change = 0.0 if previous_mid is None else self.mid - previous_mid
def on_trade(self, event: MarketEvent) -> None:
assert self.mid is not None and event.trade_price is not None
trade_diff = event.trade_price - self.mid
trade_sign = 1.0 if trade_diff > 0.0 else -1.0 if trade_diff < 0.0 else 0.0
if self.count == self.window:
self.diff_sum -= self.trade_diffs[self.next_index]
self.sign_sum -= self.trade_signs[self.next_index]
else:
self.count += 1
self.trade_diffs[self.next_index] = trade_diff
self.trade_signs[self.next_index] = trade_sign
self.diff_sum += trade_diff
self.sign_sum += trade_sign
self.next_index = (self.next_index + 1) % self.window
def handle(self, event: MarketEvent) -> None:
if event.kind == "BOOK":
self.on_book(event)
elif event.kind == "TRADE":
self.on_trade(event)
else:
raise ValueError(f"Unknown event kind: {event.kind}")
def evaluate(self) -> list[float]:
size_total = self.bid_size + self.ask_size
imbalance = 0.0 if size_total == 0.0 else (self.bid_size - self.ask_size) / size_total
denominator = max(self.count, 1)
return [
imbalance,
self.diff_sum / denominator,
self.sign_sum / denominator,
self.mid_change,
]
class BuggyFeatureEngine(FeatureEngine):
def __init__(self, window: int = WINDOW) -> None:
super().__init__(window)
self.last_trade_price: float | None = None
def on_trade(self, event: MarketEvent) -> None:
if event.trade_price == self.last_trade_price:
return
self.last_trade_price = event.trade_price
super().on_trade(event)
def replay_vectors(
engine_type: type[FeatureEngine], ticks: list[MarketTick]
) -> list[list[float]]:
engine = engine_type()
vectors: list[list[float]] = []
for tick in ticks:
for event in tick.events:
engine.handle(event)
vectors.append(engine.evaluate())
return vectors
def reference_vectors(ticks: list[MarketTick], window: int = WINDOW) -> list[list[float]]:
recent_diffs: list[float] = []
recent_signs: list[float] = []
previous_mid: float | None = None
vectors: list[list[float]] = []
for tick in ticks:
book = tick.events[0]
assert book.bid is not None and book.ask is not None
assert book.bid_size is not None and book.ask_size is not None
mid = (book.bid + book.ask) / 2.0
mid_change = 0.0 if previous_mid is None else mid - previous_mid
previous_mid = mid
for event in tick.events[1:]:
assert event.trade_price is not None
trade_diff = event.trade_price - mid
trade_sign = 1.0 if trade_diff > 0.0 else -1.0 if trade_diff < 0.0 else 0.0
recent_diffs.append(trade_diff)
recent_signs.append(trade_sign)
recent_diffs = recent_diffs[-window:]
recent_signs = recent_signs[-window:]
imbalance = (book.bid_size - book.ask_size) / (book.bid_size + book.ask_size)
vectors.append(
[
imbalance,
sum(recent_diffs) / max(len(recent_diffs), 1),
sum(recent_signs) / max(len(recent_signs), 1),
mid_change,
]
)
return vectors
def first_mismatch(
expected: list[list[float]], actual: list[list[float]], tolerance: float = 1e-12
) -> tuple[int, str, float, float] | None:
for tick_index, (expected_row, actual_row) in enumerate(zip(expected, actual)):
for feature_index, (expected_value, actual_value) in enumerate(
zip(expected_row, actual_row)
):
if abs(expected_value - actual_value) > tolerance:
return (
tick_index,
FEATURE_NAMES[feature_index],
expected_value,
actual_value,
)
return None
def show_events() -> None:
ticks = generate_ticks()
engine = FeatureEngine()
for tick_index, tick in enumerate(ticks[:3]):
for event in tick.events:
engine.handle(event)
kinds = [event.kind for event in tick.events]
rounded = [round(value, 5) for value in engine.evaluate()]
print(
f"tick={tick_index:03d} regime={tick.regime} "
f"events={kinds} features={rounded}"
)
def run_bug_demo() -> None:
ticks = generate_ticks()
mismatch = first_mismatch(
reference_vectors(ticks), replay_vectors(BuggyFeatureEngine, ticks)
)
if mismatch is None:
raise RuntimeError("The deliberate bug was not reproduced.")
tick_index, feature_name, expected, actual = mismatch
print(
"BUG REPRODUCED: "
f"tick={tick_index} feature={feature_name} "
f"reference={expected:.6f} buggy={actual:.6f}"
)
def run_parity() -> None:
ticks = generate_ticks()
expected = reference_vectors(ticks)
actual = replay_vectors(FeatureEngine, ticks)
mismatch = first_mismatch(expected, actual)
if mismatch is not None:
raise AssertionError(f"Parity failed: {mismatch}")
print(
f"PARITY PASS: {len(actual)} vectors match across "
f"{len(FEATURE_NAMES)} features."
)
def standardize_and_split(
features: list[list[float]], labels: list[float]
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
split = int(len(features) * 0.70)
train_rows = features[:split]
means: list[float] = []
scales: list[float] = []
for feature_index in range(len(features[0])):
column = [row[feature_index] for row in train_rows]
mean = sum(column) / len(column)
variance = sum((value - mean) ** 2 for value in column) / len(column)
means.append(mean)
scales.append(math.sqrt(variance) or 1.0)
scaled = [
[
(value - means[feature_index]) / scales[feature_index]
for feature_index, value in enumerate(row)
]
for row in features
]
label_rows = [[label] for label in labels]
x = torch.tensor(scaled, dtype=torch.float32)
y = torch.tensor(label_rows, dtype=torch.float32)
return x[:split], y[:split], x[split:], y[split:]
def make_model(kind: str, feature_count: int) -> nn.Module:
if kind == "linear":
return nn.Linear(feature_count, 1)
if kind == "mlp":
return nn.Sequential(
nn.Linear(feature_count, 8),
nn.ReLU(),
nn.Linear(8, 1),
)
raise ValueError(f"Unknown model kind: {kind}")
def accuracy(model: nn.Module, x: torch.Tensor, y: torch.Tensor) -> float:
with torch.no_grad():
predicted = (model(x) >= 0.0).to(dtype=torch.float32)
return (predicted == y).to(dtype=torch.float32).mean().item()
def fit_and_score(
kind: str, features: list[list[float]], labels: list[float]
) -> tuple[float, float]:
x_train, y_train, x_test, y_test = standardize_and_split(features, labels)
torch.manual_seed(SEED)
model = make_model(kind, len(features[0]))
loss_function = nn.BCEWithLogitsLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.03)
for _ in range(250):
optimizer.zero_grad()
loss = loss_function(model(x_train), y_train)
loss.backward()
optimizer.step()
return accuracy(model, x_train, y_train), accuracy(model, x_test, y_test)
def run_training() -> None:
ticks = generate_ticks()
features = replay_vectors(FeatureEngine, ticks)
mismatch = first_mismatch(reference_vectors(ticks), features)
if mismatch is not None:
raise AssertionError(f"Refusing to train on mismatched features: {mismatch}")
labels = [tick.target for tick in ticks]
results = {
kind: fit_and_score(kind, features, labels) for kind in ("linear", "mlp")
}
print("model train_accuracy test_accuracy")
for kind, (train_accuracy, test_accuracy) in results.items():
print(f"{kind:<7} {train_accuracy:>14.3f} {test_accuracy:>14.3f}")
winner = max(results, key=lambda name: results[name][1])
linear_train, linear_test = results["linear"]
mlp_train, mlp_test = results["mlp"]
report = f"""# Event-Driven Market Feature Research Report
## Hypothesis
Every trade event must update history-dependent feature state, even when two consecutive trades have the same price. After parity is restored, a nonlinear model may fit the synthetic signal better than a linear baseline, but neither model is guaranteed to survive a reversed test regime.
## Dataset design
- {len(ticks)} deterministic synthetic ticks
- `BOOK` and `TRADE` events, including repeated same-price trades
- Four event-derived features: {", ".join(FEATURE_NAMES)}
- First 70% in regime A; final 30% in regime B with the signal relationship reversed
## Feature parity
The corrected event replay matched the independent reference across every tick and feature before training began.
## Results
| Model | Train accuracy | Test accuracy |
| --- | ---: | ---: |
| Linear | {linear_train:.3f} | {linear_test:.3f} |
| MLP | {mlp_train:.3f} | {mlp_test:.3f} |
The higher chronological test accuracy came from `{winner}`. The test period deliberately changes the data-generating relationship, so the train-to-test gaps are evidence about distribution shift, not evidence of a profitable trading strategy.
## Limitations
The events, labels, spread, and regime change are synthetic. The experiment excludes transaction costs, latency, queue position, execution, risk limits, and real market feedback.
## Next experiment
Run a one-feature-at-a-time ablation, then test rolling retraining that uses only the most recent observations.
"""
with open(REPORT_FILE, "w", encoding="utf-8") as report_file:
report_file.write(report)
print(f"Wrote {REPORT_FILE}")
def main() -> None:
parser = argparse.ArgumentParser(description="Event-driven market feature lab")
parser.add_argument("mode", choices=["events", "bug", "parity", "train"])
args = parser.parse_args()
if args.mode == "events":
show_events()
elif args.mode == "bug":
run_bug_demo()
elif args.mode == "parity":
run_parity()
else:
run_training()
if __name__ == "__main__":
main()
Secret mission
Run a Feature Ablation
Your linear model produces one out-of-sample accuracy score from four event-derived features. Remove each feature in turn to discover which signal has the largest effect after the regime shift.
Clean Up Your Resources
Clean Up Your Resources
Everything in this lab stays on your computer, so there are no ongoing costs. Choose whether to keep the files, close the lab for now, or remove it from your computer.
Resources you used:
- Local mini-market-feature-engine project folder.
- Local .venv folder containing the project-specific Python virtual environment.
- Local requirements.txt dependency file.
- Local market_lab.py event-driven research script.
- Local research_report.md generated research memo.
Keep everything running
No action is needed. Choose this option if you want to rerun the market experiments or extend the feature engine.
- Keep the mini-market-feature-engine folder in its current location.
- Reopen the folder in Visual Studio Code when you want to continue.
- Reuse the existing .venv environment when running the experiment modes.
- Retain research_report.md as the reproducible record of your model comparison.
Each experiment mode exits after printing its result. Keeping the folder leaves no process running or bill accumulating.
Pause - I'll come back to this later
Pausing preserves every project artifact while ending your current editing session.
- Close Visual Studio Code.
- Leave the mini-market-feature-engine folder in its current location.
Your code, isolated environment, ablation work, and research memo remain available. No process or bill continues in the background.
Delete - I don't want to use this again
Remove the local project folder if you do not plan to rerun the experiments.
Your other Python work stays untouched because the deletion targets only mini-market-feature-engine.
- Right-click the top-level mini-market-feature-engine folder in the Visual Studio Code file sidebar.
- Select the option that reveals the folder in the Windows file browser.
- Close Visual Studio Code.
- Move up one folder level in the Windows file browser.
- Right-click the mini-market-feature-engine folder.
- Select the option that deletes the selected folder.
The project folder should disappear from its former location. Every listed resource moves with it.
- Open the Windows recycle area from your desktop.
- Find the deleted mini-market-feature-engine folder.
- Right-click the deleted folder.
- Select the option that permanently deletes the selected folder.
- Approve the permanent deletion when Windows asks for confirmation.
You should no longer see mini-market-feature-engine in its former location. You should no longer see it in the Windows recycle area.
Nice Work!
Nice Work!
You did it! Your Jane Street-inspired quantitative research lab now turns market events into stateful features before comparing PyTorch models across a regime shift.
You've learned how to:
- Generated a deterministic market event stream with a known regime change. Turned every BOOK event plus every TRADE event into four stateful features.
- Reproduced a dropped repeated-trade bug with an independent reference calculation. Proved historical and simulated-live parity across all 600 feature vectors.
- Compared a linear baseline with a small neural network using chronological validation. Generated research_report.md to interpret distribution shift without making a profitability claim.
- Completed the optional Secret Mission by running a one-feature-at-a-time ablation. Identified the feature removal with the largest absolute change in out-of-sample accuracy.
Ready to quiz yourself?