{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": "# EUR/USD Backtesting with Spread and Slippage\n\nCompare the same trades under three cost assumptions. The synthetic hourly prices are reproducible and require no data feed or API key. This exercise does not measure profitability in live trading.\n\nOpen the notebook in Jupyter and run all cells in order. The calculations use only the Python standard library. A notebook environment with IPython also displays the chart.",
      "id": "eurusd-1"
    },
    {
      "cell_type": "code",
      "metadata": {},
      "execution_count": null,
      "outputs": [],
      "source": "from dataclasses import dataclass\nfrom math import sin\nfrom random import Random\n\nPIP = 0.0001\nLOOKBACK = 12\nHOLD_BARS = 6\nSPLIT = 900\nSEED = 42\n\n\n@dataclass(frozen=True)\nclass Bar:\n    open: float\n    close: float\n\n\ndef synthetic_bars(count, seed):\n    rng = Random(seed)\n    close = 1.08\n    bars = []\n    for i in range(count):\n        opening = close + rng.gauss(0, 0.00004)\n        change = 0.00005 * sin(i / 33) + rng.gauss(0, 0.00018)\n        close = opening + change\n        bars.append(Bar(opening, close))\n    return bars\n\n\nbars = synthetic_bars(1800, SEED)",
      "id": "eurusd-2"
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": "## 1. Separate signal, execution and test period\n\nA long signal occurs when the close exceeds the previous twelve closes. Entry is at the next open and exit is at the open six simulated hours later. Only one position is open at a time. Each trade is contained within its period. Parameters are fixed and are not adjusted during the test period.",
      "id": "eurusd-3"
    },
    {
      "cell_type": "code",
      "metadata": {},
      "execution_count": null,
      "outputs": [],
      "source": "def trades_in_period(bars, start, stop):\n    trades = []\n    signal = start + LOOKBACK\n    while signal + 1 + HOLD_BARS < stop:\n        ceiling = max(bar.close for bar in bars[signal - LOOKBACK:signal])\n        if bars[signal].close > ceiling:\n            entry = signal + 1\n            exit_at = entry + HOLD_BARS\n            gross_pips = (bars[exit_at].open - bars[entry].open) / PIP\n            trades.append((signal, entry, exit_at, gross_pips))\n            signal = exit_at\n        else:\n            signal += 1\n    return trades\n\n\nperiods = {\n    \"Development\": trades_in_period(bars, 0, SPLIT),\n    \"Test\": trades_in_period(bars, SPLIT, len(bars)),\n}\nassert all(s < e < x < SPLIT for s, e, x, _ in periods[\"Development\"])\nassert all(SPLIT <= s < e < x < len(bars) for s, e, x, _ in periods[\"Test\"])",
      "id": "eurusd-4"
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": "## 2. Compare trading costs\n\nSimulated opening prices are treated as mid-prices. A buy and sell each incur half the spread. Slippage also applies on both sides. A spread of 0.8 pips plus 0.2 pips of slippage per side therefore costs 1.2 pips per completed trade. This exercise excludes commissions, financing and variable spreads.",
      "id": "eurusd-5"
    },
    {
      "cell_type": "code",
      "metadata": {},
      "execution_count": null,
      "outputs": [],
      "source": "SCENARIOS = {\n    \"No costs\": (0.0, 0.0),\n    \"Spread\": (0.8, 0.0),\n    \"Spread + slippage\": (0.8, 0.2),\n}\n\n\ndef cumulative_pips(trades, spread, slippage_per_side):\n    curve = [0.0]\n    for _, _, _, gross in trades:\n        curve.append(curve[-1] + gross - spread - 2 * slippage_per_side)\n    return curve\n\n\ndef max_drawdown(curve):\n    peak = curve[0]\n    deepest = 0.0\n    for value in curve:\n        peak = max(peak, value)\n        deepest = max(deepest, peak - value)\n    return deepest\n\n\nprint(f\"{'Period':<13} {'Scenario':<20} {'Trades':>6} {'Net pips':>11} {'Drawdown':>10}\")\nfor period, trades in periods.items():\n    for label, costs in SCENARIOS.items():\n        curve = cumulative_pips(trades, *costs)\n        print(f\"{period:<13} {label:<20} {len(trades):>6} {curve[-1]:>11.1f} {max_drawdown(curve):>10.1f}\")",
      "id": "eurusd-6"
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": "## 3. Read the test curves\n\nThe chart shows cumulative net pips after each completed trade. Drawdown is calculated at those points and excludes price moves within an open trade.",
      "id": "eurusd-7"
    },
    {
      "cell_type": "code",
      "metadata": {},
      "execution_count": null,
      "outputs": [],
      "source": "from html import escape\n\n\ndef chart_svg(curves):\n    left, right, top, bottom = 62, 614, 22, 258\n    maximum_trades = max(1, *(len(curve) - 1 for curve in curves.values()))\n    low = min(min(curve) for curve in curves.values())\n    high = max(max(curve) for curve in curves.values())\n    if high == low:\n        high += 1\n    def y(value):\n        return bottom - (value - low) * (bottom - top) / (high - low)\n\n    parts = [\n        '<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"640\" height=\"335\" '\n        'role=\"img\" aria-label=\"Cumulative net pips in the test period\">',\n        '<rect width=\"100%\" height=\"100%\" fill=\"white\"/>',\n    ]\n    for tick in range(5):\n        value = low + tick * (high - low) / 4\n        ordinate = y(value)\n        parts.append(f'<path d=\"M{left} {ordinate}H{right}\" stroke=\"#dae3e7\"/>')\n        parts.append(f'<text x=\"54\" y=\"{ordinate + 4}\" text-anchor=\"end\" font-size=\"12\">{value:.0f}</text>')\n    for i, ((name, curve), color) in enumerate(zip(curves.items(), (\"#2466aa\", \"#00806b\", \"#ac4920\"))):\n        points = \" \".join(\n            f\"{left + j * (right - left) / maximum_trades:.1f},{y(value):.1f}\"\n            for j, value in enumerate(curve)\n        )\n        parts.append(f'<polyline points=\"{points}\" fill=\"none\" stroke=\"{color}\" stroke-width=\"2\"/>')\n        parts.append(f'<text x=\"{left + i * 174}\" y=\"320\" font-size=\"13\" fill=\"{color}\">{escape(name)}</text>')\n    parts.append('<text x=\"61\" y=\"14\" font-size=\"12\">Pips</text>')\n    parts.append(f'<text x=\"{left}\" y=\"279\" font-size=\"12\">0</text>')\n    parts.append(f'<text x=\"{right}\" y=\"279\" text-anchor=\"end\" font-size=\"12\">{maximum_trades}</text>')\n    parts.append('<text x=\"338\" y=\"292\" text-anchor=\"middle\" font-size=\"12\">Completed trades</text></svg>')\n    return \"\".join(parts)\n\n\ntest_curves = {\n    label: cumulative_pips(periods[\"Test\"], *costs)\n    for label, costs in SCENARIOS.items()\n}\ntry:\n    from IPython.display import SVG, display\nexcept ImportError:\n    pass\nelse:\n    display(SVG(chart_svg(test_curves)))",
      "id": "eurusd-8"
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": "## Your next exercise\n\n1. Double the spread. How do net pips and drawdown change?\n2. Set slippage to zero. How much of the difference comes from spread alone?\n3. If you change a rule after seeing the test curve, set aside a fresh test period for the new rule.\n\n[Backtesting Lab](https://tradingschule.com/backtesting-lab/) · [Walk-forward testing](https://tradingschule.com/backtesting-lab/walk-forward/)",
      "id": "eurusd-9"
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}
