Tutorial¶
From a first backtest to a strategy of your own, tested honestly and trading a paper account. Allow half an hour. Every command here runs offline on synthetic data unless it says otherwise.
1. Install¶
git clone https://github.com/Space-Paragon1/Event-Driven-Trading-System.git
cd Event-Driven-Trading-System
python -m venv .venv && source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install -e ".[all]"
2. Run a backtest¶
With no options, trading runs a moving-average crossover on a year of synthetic daily
bars for one symbol (--no-db skips storing the run). The report:
Backtest AAPL | ma_crossover | synthetic data | 252 bars (2024-01-02 to 2024-12-31)
==============================================
PERFORMANCE REPORT
==============================================
Final equity $97,373.13
Total return -2.63 %
Buy & hold -26.60 %
CAGR -2.63 %
Volatility (ann.) 1.85 %
Sharpe ratio -1.426
...
Round trips 4
Win rate 0.0 %
Fills 8
Commission $8.00
Exposure 17.9 %
==============================================
It lost 2.6 % while the stock fell 26.6 %: it was in the market only 17.9 % of the time. Every number is computed from the equity marked to market at each bar's close, after commissions and slippage. Same seed, same numbers: runs are deterministic.
3. Change the setup¶
Options override the defaults:
trading --no-db --strategy rsi --bars 1000 --sizing percent --percent 25
trading --no-db --symbols AAA,BBB,CCC --strategy momentum_rotation --bars 1000
trading --no-db --stop-loss 5 --take-profit 10 --save-chart chart.png
For more than a few options, use a config file. Copy the defaults and keep what you change:
The configuration reference lists every setting.
4. Use real prices¶
With the data extra, Yahoo Finance supplies daily bars, adjusted for splits and
dividends. --cache-dir keeps the download with a checksum, so later runs work offline and
read exactly the same prices:
trading --symbols SPY,TLT,GLD --from 2015-01-01 --to 2025-01-01 \
--strategy momentum_rotation --cache-dir data/cache
5. Write a strategy¶
A strategy turns bars into signals: BUY (be long), SELL (be short, or flat when shorting
is off), EXIT (be flat) or HOLD. The engine handles sizing, orders, risk and fills. It
sees each bar after it closes, and any order it causes fills on a later bar, so a strategy
cannot trade on information it would not have had.
class Breakout(Strategy):
"""Long on a close above the highest high of the last *entry* bars; flat below the
lowest low of the last *exit* bars."""
name = "breakout"
def __init__(self, entry: int = 55, exit: int = 20) -> None:
super().__init__()
self.entry, self.exit = entry, exit
# One history per symbol, so a single instance can trade several symbols.
self._bars: defaultdict[str, deque[MarketDataEvent]] = defaultdict(
lambda: deque(maxlen=max(entry, exit))
)
def on_bar(self, bar: MarketDataEvent) -> Signal:
history = self._bars[bar.symbol] # earlier bars only: this one is added at the end
try:
if len(history) < (history.maxlen or 0):
return HOLD # warming up
if bar.close > max(b.high for b in list(history)[-self.entry :]):
return Direction.BUY, 1.0
if bar.close < min(b.low for b in list(history)[-self.exit :]):
return Direction.EXIT, 1.0
return HOLD
finally:
history.append(bar)
Run it with BacktestEngine(config, strategy=Breakout()).run(). The whole script is
examples/custom_strategy.py. A strategy that
decides for all symbols together, such as a rotation, subclasses PortfolioStrategy
instead; see the user guide.
6. Find out whether it works¶
A good backtest is easy to find by trying enough parameters. Three tools tell you how much to believe one.
Sweeps run every combination of parameters on the same bars and rank them. The deflated Sharpe ratio then asks whether the winner beats what luck would produce from that many tries:
trading sweep --no-db --bars 1000 \
--param strategy.fast_period=5:30:5 --param strategy.slow_period=40,60,100
Best: --param strategy.fast_period=25 --param strategy.slow_period=40
Deflated Sharpe ratio: 0.73, the probability that the best run's true Sharpe ratio is above zero after 18 trials.
Its Sharpe ratio is 0.564; luck alone would be expected to reach 0.253.
Walk-forward validation tunes on a training window, trades the next window with the chosen parameters, and repeats. Only the chained test windows count:
trading walk-forward --no-db --bars 1260 --train 504 --test 126 \
--param strategy.fast_period=5:30:5 --param strategy.slow_period=40,60,100 \
--bootstrap 2000
Bootstrap intervals (--bootstrap 2000) resample the returns to show how far the
Sharpe ratio could move on another draw of similar data. An interval that spans zero means
the result is indistinguishable from luck.
The research study applies all three to every built-in strategy on
fifteen years of ETF prices. None beat buying and holding the same ETFs after costs.
trading study runs a study of your own from a YAML file.
7. Paper trade¶
Paper trading runs the same pipeline on live bars, with an Alpaca paper account in place of the simulator. Create free paper keys at alpaca.markets, then:
export APCA_API_KEY_ID=... APCA_API_SECRET_KEY=...
trading paper --symbols SPY --dry-run --iterations 3 # logs orders, sends none
trading paper --config config/paper.yaml # trades the paper account
trading compare then replays the session's bars through a backtest and shows where the
paper fills and the simulated ones differ. To run the trader unattended, follow the
deployment guide.
Next¶
- The user guide covers every feature in depth.
- The architecture page explains how the engine keeps results causal.
- The API reference documents the classes used above.