Note
Correction. I originally published a walk-forward out-of-sample return of +60.2%. That was wrong: the stitched curve joined folds at different equity levels and invented return at the seams. The correct figure is +50.0%, which makes the strategy look worse, not better. The notebook has been re-run and now shows the corrected number.
Question: Does a naive EMA(5/8) crossover survive realistic trading costs? I built this backtester to find out, and ran it on five years of daily AAPL stock prices.
Short answer: No. After costs it returns +6.7% over five years while buying and holding returns +134%, with a worse drawdown, and its mean daily return is statistically indistinguishable from zero. The repository is the evidence.
The goal here is not a profitable strategy. The goal is a backtester that I can trust to tell the truth, and a worked example of it delivering bad news cleanly.
A signal is expressed as a target position, a fraction of equity in [-1, 1], decided at the close of each bar. The engine is an explicit bar-by-bar loop, and a decision made at the close of one bar can only be filled at the open of the next. There is exactly one place in the code where a decision becomes a fill, and it is structurally incapable of seeing the future. A test scrambles every price after a chosen bar and asserts that the positions up to that bar do not move (tests/test_lookahead.py).
Every fill pays frictions, applied against the trader: half spread, slippage and commission (all in basis points, all configurable). Accounting uses an average cost basis. Cash is the single source of truth, and a reconciliation check (reconcile_pnl in backtester/metrics.py) rebuilds the equity two independent ways: once from the cash ledger plus the marked position, and once from realized trade PnL plus the mark on whatever is still open. The tests check that both residuals come out at zero.
The engine only trades when the target fraction changes. It does not rebalance back to the target every bar, so trade counts and turnover reflect real signal activity rather than accounting noise.
- One asset, one regime. Daily AAPL, 2013-02-08 to 2018-02-07 (1,259 bars). A long-biased strategy will look good here for reasons that have nothing to do with skill.
- Costs. 1.0 bps half spread, 0.5 bps slippage and 0.5 bps commission by default. These are liquid large-cap equity assumptions.
- Sharpe. rf = 0, daily returns annualized by √252, sample standard deviation (ddof=1).
- Fills. Every fill happens at the bar open, with no volume or market-impact model. Dividends are ignored (price return only), and there is no borrow cost on shorts.
- Results. Everything is in-sample on a single series, except the walk-forward test below. Treat every number as an illustration of method, not an estimate of edge.
AAPL daily, 2013-02-08 to 2018-02-07, after costs:
| EMA(5/8) long/short | Buy & hold | |
|---|---|---|
| Total return | +6.7% | +134.3% |
| Sharpe | 0.17 | 0.85 |
| Max drawdown | −43% | −32% |
| Trades | 118 | 1 |
| Win rate | 30.5% | n/a |
| Annualized turnover | 46.6× | 0 |
The mean daily return after costs has a t-stat of 0.38, so we cannot reject that it is zero. Sweeping the EMA lengths over a 6×6 grid gives after-cost Sharpes from −0.48 to +0.71 that flip sign between neighboring settings: the classic fingerprint of noise, not signal. A walk-forward test, which tunes the parameters on each training block and then trades them on the next unseen block, always lands on the same corner of the grid, (3, 89). Its out-of-sample return (+50.0%) loses to buy-and-hold over the same window (+58.3%). Even the one robust-looking result is a regime artifact, not an edge.
backtester/
data.py load_csv / load_sample / load_yfinance / generate_gbm
strategy.py Strategy base class + EMACrossover (emits target fractions)
engine.py CostModel, run_backtest: the no-lookahead simulation loop
metrics.py Sharpe, max drawdown, turnover, PnL reconciliation
analysis.py buy_and_hold, compare_costs, parameter_grid, walk_forward
tests/ 32 tests: lookahead, accounting, costs, published-result regression
notebooks/
ema_backtest.ipynb the end-to-end story, with equity curves before/after costs
data/
sample_prices.csv bundled AAPL daily OHLCV (so everything runs offline)
From a fresh clone, pip install -r requirements.txt && pytest -q runs 32 passing tests, and CI runs the same suite on Python 3.11, 3.12 and 3.13. Every headline number above is reproduced from the bundled sample data and pinned in tests/test_reference.py, so a change that moves one of them fails the build.
pip install -r requirements.txt
# the whole suite: lookahead, accounting, costs and the published numbers
pytest -q
# just the lookahead suite, the centerpiece: it fails if the engine can ever see the future
pytest -q tests/test_lookahead.py
# the full narrative with plots (needs `pip install jupyter`)
jupyter notebook notebooks/ema_backtest.ipynbA minimal end-to-end run in code:
from backtester import load_sample, EMACrossover, CostModel, run_backtest, compute_metrics
prices = load_sample("AAPL") # bundled offline data
target = EMACrossover(fast=5, slow=8).generate_signals(prices)
gross = run_backtest(prices, target, CostModel.frictionless())
net = run_backtest(prices, target, CostModel()) # realistic frictions
print(compute_metrics(gross)["total_return"], "->", compute_metrics(net)["total_return"])Using your own data. Swap load_sample("AAPL") for load_yfinance("AAPL", start="2015-01-01") (requires pip install yfinance and internet access), or for load_csv(path) with any CSV that has Date, Open, High, Low, Close columns. Everything downstream is unchanged.
The bundled sample is daily AAPL OHLCV extracted from all_stocks_5yr.csv in the public plotly/datasets mirror, chosen so the notebook and tests run fully offline and reproducibly. It is split-adjusted but not dividend-adjusted, which understates the true buy-and-hold return. That strengthens, rather than weakens, the conclusion that the active strategy underperforms.