insideout Get Pro

08 · A backtest in twenty lines

Pro

Python for Market Data, lesson 8

A backtest in twenty lines

Signal, position, return, curve, all vectorised.

You know returns, rolling windows, ranks and point-in-time joins.

Part 1. Move the shift

A simple rule on a simulated stock with no edge at all: hold it when it closes above its 5-day average, short it when it closes below. Run it as written, then change one number.

One number in a backtestLive

With shift(0), each day's position came from that day's close and earned the return into that same close. The rule looked at a price and then got paid for the move that made it. shift(1) decides at the close and holds from the next day, and the profit vanished, because there was nothing to find. Costs made it worse.

Signal and position

The signal is the rule's number at each close. The position is what you hold over the next day. In a daily backtest, today's position is yesterday's signal: pos = signal.shift(1).

Your turn

A daily backtest shows a Sharpe ratio of 11. What's the most likely explanation?

Results that good almost always mean the position earned a return it couldn't have known about. Check the shift first, then the joins, then any statistic computed over the whole history.

Part 2. Twenty lines, read in plain words

Keep going with Pro

You've done the first part. Pro opens the rest of this lesson, and every other one.

Still to come
  1. Twenty lines, read in plain words
  2. Worked: a long-short backtest
  3. The same thing, for real

Python for Market Data overviewSpotted a mistake? Tell us.