Skip to content

About

Execution Copilot implements classical and learning-based execution policies plus a backtester with persistent FIFO limit-order queues and latency modeling. The stack ships with FastAPI/React surfaces for inspection and a full experiment suite with committed artifacts.

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Execution Copilot

CI

A research harness for order-execution algorithms. Replay a limit order book, push a parent order through classical, contextual-bandit, or reinforcement-learning execution policies, and measure what each one costs in basis points.

Every number and figure below comes from a seeded script in this repo. docs/REPRO.md lists the exact commands.

Results

One 10,000-share AAPL buy, 1-hour horizon, 50 Monte Carlo runs per policy. Runs are paired: policies share seeds, so each sees the same price paths.

Implementation shortfall by policy, mean with 95% CI over 50 paired runs

Policy IS (bps) 95% CI Std Fill rate
PPO 5.68 [4.56, 6.80] 3.94 100%
POV 5.71 [4.02, 7.40] 5.95 100%
Almgren-Chriss 6.90 [-1.70, 15.50] 30.26 100%
LinUCB 8.34 [7.28, 9.39] 3.71 100%
Thompson Sampling 8.35 [7.34, 9.36] 3.55 100%
TWAP 14.67 [6.36, 22.97] 29.23 100%

PPO and POV lead and are statistically tied (paired t-test, p=0.95). Both beat TWAP by about 9 bps at p<0.05, and PPO beats each bandit by 2.7 bps at p<0.001 while holding the lowest fill-price variance of any policy. The bandits' own 6.3 bps edge over TWAP does not clear significance (p=0.13); TWAP's run-to-run spread is wider than the gap.

Almgren-Chriss shows why the pairing matters. Its 95% CI straddles zero because its across-run spread is 30 bps, yet the paired test against TWAP is significant at p<0.001 (Cohen's d = 3.7). Both policies ride the same price paths, so the shared path variance cancels in the difference even though it dominates each marginal interval.

Implementation shortfall decomposition

IS is measured against the arrival price and splits into four additive terms:

IS = Arrival_Cost + Timing_Cost + Opportunity_Cost + Fee_Cost

Same 50 runs, in bps:

Policy Arrival Timing Opportunity Fee Total IS
PPO 0.000 5.379 0.000 0.300 5.679
POV 0.000 5.412 0.000 0.300 5.712
Almgren-Chriss 0.000 6.605 0.000 0.300 6.905
LinUCB 0.000 8.054 0.000 0.285 8.339
Thompson Sampling 0.000 8.066 0.000 0.284 8.350
TWAP 0.000 14.368 0.000 0.300 14.669

Arrival cost is zero because the decision price is the arrival price, and opportunity cost is zero because every run fills completely, so timing cost carries the ranking. Fee cost is the one component that responds to venue choice. The single-venue policies pay a flat 0.300 bps taker fee; LinUCB and Thompson Sampling route about a third of their fills to BATS at 0.25 bps and blend down to 0.285 and 0.284. That saving is far too small to cover their 2.6 bps timing deficit, but without the fee term it would not reach IS at all.

PPO converged on sending every fill to NASDAQ, the lowest-impact venue in the config and the one Experiment 04 ranks first, without being given the venue parameters.

Full tables for all eleven experiments are in docs/EXPERIMENTAL_RESULTS.md.

Quick start

git clone https://github.com/QHarshil/Execution-Copilot.git
cd Execution-Copilot
python3 -m venv .venv && .venv/bin/pip install -r requirements.txt

Run one backtest (save as demo.py, then PYTHONPATH=. .venv/bin/python demo.py):

from src.backtesting.backtest import Backtester, BacktestConfig
from src.data.replay import create_replay_from_config
from src.metrics.metrics import MetricsEngine
from src.policies.twap import TWAPPolicy
from src.simulation.multi_venue import create_multi_venue_environment
from src.simulation.venue import OrderSide

replay = create_replay_from_config(
    symbol="AAPL", duration=3600.0, tick_interval=1.0, base_price=150.0,
    volatility=0.02, spread_bps=5.0, depth_per_level=500, num_levels=5, seed=42,
)
snapshots = replay.get_all_snapshots()

config = BacktestConfig(symbol="AAPL", side=OrderSide.BUY, total_size=10000,
                        time_horizon=3600.0, seed=42)
backtester = Backtester(config=config,
                        venues=create_multi_venue_environment(seed=42),
                        metrics_engine=MetricsEngine())

metrics, events = backtester.run(TWAPPolicy(num_slices=10), snapshots,
                                 snapshots[0].mid_price())

print(f"IS        {metrics.is_bps:.2f} bps")
print(f"  timing  {metrics.timing_cost_bps:.2f}")
print(f"  fee     {metrics.fee_cost_bps:.2f}")
print(f"fill rate {metrics.fill_rate:.0%}")

Output:

IS        8.47 bps
  timing  8.17
  fee     0.30
fill rate 100%

Every stochastic component takes an explicit seed, so that run is repeatable. Reproduce the full result set with:

PYTHONPATH=. .venv/bin/python experiments/10_all_policies_comparison.py   # ~15 s
PYTHONPATH=. .venv/bin/python run_all.py            # tests + all 11 experiments, ~2 min

What's here

Component Location Notes
Execution policies src/policies/ TWAP, POV, Almgren-Chriss, LinUCB, Thompson Sampling, Actor-Critic, PPO, DQN
Venue simulation src/simulation/ Multi-venue routing with per-venue fees, latency, impact, FIFO queues
Order book replay src/data/ Seeded synthetic GBM replay and historical L2 replay
Metrics src/metrics/ IS decomposition, markouts, fill-price risk, harm guard
Backtester src/backtesting/ Ties the above together against one BacktestConfig
Experiments experiments/ 11 scripts; all report 95% CIs, head-to-head ones add paired t-tests, Wilcoxon, Cohen's d
HTTP API src/api/ FastAPI: POST /simulate, POST /recommend
Dashboard frontend/ React client for the API
Native engine cpp/ Optional price-time-priority matcher over a lock-free SPSC ring buffer

54 tests run under pytest. CI covers Python 3.11 and 3.12, runs ruff, and smoke-tests RL training.

ruff check .
PYTHONPATH=. pytest -v

Documentation

Document Contents
docs/USAGE.md Runnable examples: backtests, historical replay, policy tuning, API, dashboard
docs/DESIGN.md Methodology: IS derivation, policy math, queue and latency models, statistics
docs/EXPERIMENTAL_RESULTS.md All eleven experiments with tables and figures
docs/REPRO.md Exact commands and seeds for every committed artifact
docs/DATA_PIPELINE.md Capturing and calibrating L2 depth data
docs/API_GUIDE.md Endpoint reference
cpp/README.md Native matching engine and its benchmark

Limitations

  • Queue and latency models are wired in and exercised, but the synthetic replay's depth is generous enough that neither changes IS. Historical L2 data is what surfaces slippage from those paths (experiments 05, 06, 11).
  • Historical coverage is two short Binance and AAPL captures. LOBSTER, ITCH, and CME feeds are not integrated.
  • Learned policies are trained on the synthetic distribution. Multi-asset scenarios and hyperparameter sweeps are not done.
  • The API ships with no auth, no rate limiting, and permissive CORS. Restrict origins and add auth before exposing it anywhere.

References

  • Almgren, R., & Chriss, N. (2001). Optimal execution of portfolio transactions. Journal of Risk, 3, 5-40.
  • Li, L., Chu, W., Langford, J., & Schapire, R. (2010). A contextual-bandit approach to personalized news article recommendation. WWW 2010.
  • Agrawal, S., & Goyal, N. (2013). Thompson sampling for contextual bandits with linear payoffs. ICML 2013.
  • Cartea, Á., Jaimungal, S., & Penalva, J. (2015). Algorithmic and High-Frequency Trading. Cambridge University Press.

License

MIT

About

Execution Copilot implements classical and learning-based execution policies plus a backtester with persistent FIFO limit-order queues and latency modeling. The stack ships with FastAPI/React surfaces for inspection and a full experiment suite with committed artifacts.

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages