Disclaimer
How This Book Is Structured
1. Algorithmic Trading as an Engineering Discipline
- 1.1 What we actually mean by algorithmic trading
- 1.2 Mindset: a strategy is a hypothesis, not a conviction
- 1.3 Scope of this book
- 1.4 The pipeline in one picture
pipeline.py - the skeleton we will build up across this book
Every stage logs to a single results table for auditability.
- 1.5 Why most retail strategies fail
- 1.6 A note on realism and on the numbers in this book
- Key Takeaways
- Action Steps
2. Setting Up a Reproducible Research Environment
- 2.1 Why the environment matters
- 2.2 Creating a virtual environment
From your project root
- 2.3 Freezing dependencies
- 2.4 Project layout
- 2.5 A small paths and config helper
src/utils/paths.py
- 2.6 Determinism: seeds and clocks
src/utils/determinism.py
- 2.7 Logging instead of print
src/utils/logging.py
- 2.8 Data formats: why parquet beats CSV
src/data/convert.py
- 2.9 Testing your assumptions
tests/test_indicators.py
First two windows are NaN; window 3 mean = (1+2+3)/3 = 2.0
- 2.10 A minimal runnable script
run_backtest.py
- Key Takeaways
- Action Steps
3. Market Data: Structure, Adjustment, and Quality
- 3.1 The units you are actually working with
src/data/schema.py
You must decide how to handle NaNs explicitly, not let them slide.
- 3.2 Time zones and trading calendars
src/data/calendar.py
- 3.3 Raw versus adjusted prices
src/data/adjust.py
- 3.4 Data quality profiling
src/data/profile.py
- 3.5 Handling gaps and missing days
- 3.6 Survivorship and universe construction
src/data/universe.py
- 3.7 A sample cleaning pipeline
src/data/clean.py
Drop exact duplicate timestamps, keeping the last observed bar.
Coerce prices to numeric; bad prints become NaN and are dropped here.
- Key Takeaways
- Action Steps
4. Your Indicator Toolbox: SMA, EMA, RSI, MACD, and ATR
- 4.1 Why build your own indicators
- 4.2 Simple moving average
src/indicators/trend.py
- 4.3 Exponential moving average
- 4.4 Relative strength index (RSI)
Wilder smoothing is equivalent to EMA with alpha = 1/window.
- 4.5 Average true range (ATR)
- 4.6 MACD
- 4.7 Rolling volatility and returns
- 4.8 A reusable indicator frame
src/indicators/frame.py
- 4.9 Unit-testing indicators against known values
tests/test_indicators_extra.py
- 4.10 The discipline of not over-engineering
- Key Takeaways
- Action Steps
5. From Idea to Falsifiable Strategy
- 5.1 The hypothesis statement
- 5.2 Defining the state machine
State machine for a trend-pullback strategy (illustration only)
States: FLAT, LONG
FLAT -> LONG when: trend_up AND pullback_today
LONG -> FLAT when: trend_broken OR trailing_stop OR time_stop
- 5.3 Separate signal generation from execution
src/strategies/pullback.py
Expand entry into a hold window via a time stop.
- 5.4 Parameter choices: pick values, do not optimize yet
config/params.yaml
- 5.5 What to record for every experiment
- 5.6 Falsifiability: actively try to break your idea
- 5.7 Common idea-destroying questions
- Key Takeaways
- Action Steps
6. Vectorized Backtesting: Mechanics and Costs
- 6.1 What a vectorized backtest actually computes
- 6.2 The one-period lag that kills beginners
src/backtest/returns.py
Asset return from t to t+1.
We hold target[t] over that period.
- 6.3 Modeling commissions
src/backtest/costs.py
- 6.4 Modeling slippage
Cost per trade scales with ATR (volatility) times a slippage coefficient.
- 6.5 Assembling the equity curve
src/backtest/simulate.py
- 6.6 Compounding versus fixed fractional size
- 6.7 What vectorized backtests cannot do
- 6.8 Sanity checks every backtest must pass
- Key Takeaways
- Action Steps
7. Position Sizing and Risk Budgeting
- 7.1 Size is a decision, not an afterthought
- 7.2 Fixed fractional sizing
src/risk/sizing.py
- 7.3 Volatility-targeted sizing
- 7.4 Portfolio-level risk: the heat limit
src/risk/portfolio_heat.py
- 7.5 The Kelly intuition, used conservatively
win_loss_ratio = average win / average loss
- 7.6 Drawdown control: the circuit breaker
src/risk/drawdown.py
- 7.7 Sizing constraints you must respect
- 7.8 Why this matters more than the signal
- Key Takeaways
- Action Steps
8. Stop-Loss and Exit Rules as Risk Devices
- 8.1 Exits are risk controls, not predictions
- 8.2 The hard stop
src/risk/exits.py
- 8.3 The volatility (ATR) stop
- 8.4 The trailing stop
- 8.5 The time stop
- 8.6 Combining exits with a small state machine
src/risk/position_state.py
- 8.7 The gap-down problem
- 8.8 What stops do and do not do
- Key Takeaways
- Action Steps
9. Order Types and Execution Realism
- 9.1 Why execution belongs in the backtest
- 9.2 Market orders
- 9.3 Limit orders
src/backtest/fills.py
- 9.4 Stop and stop-limit orders
- 9.5 The open-versus-close decision
- 9.6 Volume and participation limits
- 9.7 Borrow and short constraints
- 9.8 Choosing one fill convention and documenting it
- Key Takeaways
- Action Steps
10. Paper Trading and Reconciliation
- 10.1 Why paper trading still matters
- 10.2 What paper trading actually is
- 10.3 Logging the paper book
src/paper/log.py
- 10.4 Reconciliation: sim versus live
- 10.5 How long to paper trade
- 10.6 The temptation to tune mid-test
- 10.7 When paper trading says stop
- Key Takeaways
- Action Steps
11. The Bias Zoo: Look-Ahead, Survivorship, and Data Snooping
- 11.1 Why this chapter matters more than the signal
- 11.2 Look-ahead bias
src/audit/lookahead.py
- 11.3 Survivorship bias
- 11.4 Data snooping and multiple testing
src/audit/multiple_testing.py
- 11.5 Overfitting
src/audit/parameter_robustness.py
- 11.6 Selection bias in reporting
- 11.7 A pre-production checklist
- Key Takeaways
- Action Steps
12. Performance Measurement That Does Not Lie
- 12.1 Measure the right things
- 12.2 Total return and CAGR
src/metrics/performance.py
- 12.3 Volatility and Sharpe ratio
- 12.4 Sortino ratio
- 12.5 Maximum drawdown
- 12.6 Win rate, profit factor, and turnover
- 12.7 Putting a report together
- Key Takeaways
- Action Steps
13. Capstone: A Complete Rule-Based System Walkthrough
- 13.1 What this chapter is and is not
- 13.2 The hypothesis, restated
- 13.3 The full pipeline code
src/capstone/system.py
Mark to market.
Exit on trailing stop.
Enter on signal, sized by volatility risk.
- 13.4 Reading the report
- 13.5 What to vary and what to hold constant
- 13.6 Common failure modes you will see
- 13.7 When to stop developing
- Key Takeaways
- Action Steps
14. From Research to Production: A Roadmap
- 14.1 The research-to-production gap
- 14.2 Stage 1: Research validation
- 14.3 Stage 2: Paper trading
- 14.4 Stage 3: Small live deployment
- 14.5 Stage 4: Monitoring and alerting
src/prod/monitor.py
- 14.6 Stage 5: Iteration without contamination
- 14.7 Tax and record keeping
- 14.8 Knowing when to walk away
- Key Takeaways
- Action Steps
15. Worked Example: Step-by-Step on Synthetic Data
- 15.1 Why a synthetic example
- 15.2 The input series
- 15.3 Compute the SMA by hand
Expected: [nan, nan, 101.17, 101.77, 102.43, 103.27, 105.0, 106.0, 107.17, 108.17]
- 15.4 Compute ATR
- 15.5 Walk the position
- 15.6 Reconstruct a real trade from your log
- 15.7 The danger of a single example
- Key Takeaways
- Action Steps
16. A Catalog of Common Code Mistakes
- 16.1 Why this chapter exists
- 16.2 The missing shift
- 16.3 Partial-window averages
- 16.4 Adjustment factor leak
- 16.5 NaN propagation
- 16.6 Off-by-one in the time stop
- 16.7 Inconsistent cost scaling
- 16.8 Survivorship in a quick universe
- 16.9 Tuning on the test set
- 16.10 Equity curve compounding error
src/audit/mistakes.py
- 16.11 The “too clean” equity curve
- 16.12 A self-audit script
- Key Takeaways
- Action Steps
17. From One Instrument to a Small Portfolio
- 17.1 Why one instrument is not enough
- 17.2 The weights matrix
src/portfolio/weights.py
- 17.3 Volatility-targeted weights
- 17.4 Portfolio-level returns
Lag weights by one period to avoid look-ahead.
- 17.5 Correlation and the hidden risk
- 17.6 The cash buffer
- 17.7 Rebalancing rules
- 17.8 When to stop adding instruments
- Key Takeaways
- Action Steps
18. A Repeatable Research SOP and Final Checklists
- 18.1 Why an SOP
- 18.2 Stage zero: hypothesis
- 18.3 Stage one: data
- 18.4 Stage two: signal
- 18.5 Stage three: simulation
- 18.6 Stage four: validation
- 18.7 Stage five: paper trading
- 18.8 Stage six: small live deployment
- 18.9 The pre-production checklist
- 18.10 The anti-patterns list
- 18.11 Closing the loop
- Key Takeaways
- Action Steps
19. Choosing and Comparing Data Sources
- 19.1 Data is the foundation; pick it deliberately
- 19.2 The dimensions that matter
- 19.3 Free sources and their limits
- 19.4 Paid retail vendors
- 19.5 When free data is good enough
- 19.6 Auditing a new source
src/data/audit_source.py
- 19.7 Storing and versioning data
- Key Takeaways
- Action Steps
20. Rolling Analytics and Benchmarking
- 20.1 A single Sharpe hides more than it reveals
- 20.2 Rolling Sharpe
src/metrics/rolling.py
- 20.3 Calendar-year returns
- 20.4 Benchmark-relative returns
- 20.5 Rolling correlation to benchmark
- 20.6 Monthly heatmap
- 20.7 Drawdown underwater curve
- Key Takeaways
- Action Steps
21. Regime Analysis: When Does Your Strategy Actually Work?
- 21.1 Every strategy lives in a regime
- 21.2 Defining a simple regime label
src/regime/labels.py
- 21.3 Segmenting returns by regime
- 21.4 Why this changes risk management
- 21.5 Stress periods
- 21.6 Drift over time
- Key Takeaways
- Action Steps
22. A 30-Day Learning Plan
- 22.1 How to use this chapter
- 22.2 Week one: environment and data
- 22.3 Week two: signal and simulation
- 22.4 Week three: validation and bias
- 12.4 Sortino ratio
- 12.5 Maximum drawdown
- 12.6 Win rate, profit factor, and turnover
- 12.7 Putting a report together
- Key Takeaways
- Action Steps
13. Capstone: A Complete Rule-Based System Walkthrough
- 13.1 What this chapter is and is not
- 13.2 The hypothesis, restated
- 13.3 The full pipeline code
src/capstone/system.py
Mark to market.
Exit on trailing stop.
Enter on signal, sized by volatility risk.
- 13.4 Reading the report
- 13.5 What to vary and what to hold constant
- 13.6 Common failure modes you will see
- 13.7 When to stop developing
- Key Takeaways
- Action Steps
14. From Research to Production: A Roadmap
- 14.1 The research-to-production gap
- 14.2 Stage 1: Research validation
- 14.3 Stage 2: Paper trading
- 14.4 Stage 3: Small live deployment
- 14.5 Stage 4: Monitoring and alerting
src/prod/monitor.py
- 14.6 Stage 5: Iteration without contamination
- 14.7 Tax and record keeping
- 14.8 Knowing when to walk away
- Key Takeaways
- Action Steps
15. Worked Example: Step-by-Step on Synthetic Data
- 15.1 Why a synthetic example
- 15.2 The input series
- 15.3 Compute the SMA by hand
Expected: [nan, nan, 101.17, 101.77, 102.43, 103.27, 105.0, 106.0, 107.17, 108.17]
- 15.4 Compute ATR
- 15.5 Walk the position
- 15.6 Reconstruct a real trade from your log
- 15.7 The danger of a single example
- Key Takeaways
- Action Steps
16. A Catalog of Common Code Mistakes
- 16.1 Why this chapter exists
- 16.2 The missing shift
- 16.3 Partial-window averages
- 16.4 Adjustment factor leak
- 16.5 NaN propagation
- 16.6 Off-by-one in the time stop
- 16.7 Inconsistent cost scaling
- 16.8 Survivorship in a quick universe
- 16.9 Tuning on the test set
- 16.10 Equity curve compounding error
src/audit/mistakes.py
- 16.11 The “too clean” equity curve
- 16.12 A self-audit script
- Key Takeaways
- Action Steps
17. From One Instrument to a Small Portfolio
- 17.1 Why one instrument is not enough
- 17.2 The weights matrix
src/portfolio/weights.py
- 17.3 Volatility-targeted weights
- 17.4 Portfolio-level returns
Lag weights by one period to avoid look-ahead.
- 17.5 Correlation and the hidden risk
- 17.6 The cash buffer
- 17.7 Rebalancing rules
- 17.8 When to stop adding instruments
- Key Takeaways
- Action Steps
18. A Repeatable Research SOP and Final Checklists
- 18.1 Why an SOP
- 18.2 Stage zero: hypothesis
- 18.3 Stage one: data
- 18.4 Stage two: signal
- 18.5 Stage three: simulation
- 18.6 Stage four: validation
- 18.7 Stage five: paper trading
- 18.8 Stage six: small live deployment
- 18.9 The pre-production checklist
- 18.10 The anti-patterns list
- 18.11 Closing the loop
- Key Takeaways
- Action Steps
19. Choosing and Comparing Data Sources
- 19.1 Data is the foundation; pick it deliberately
- 19.2 The dimensions that matter
- 19.3 Free sources and their limits
- 19.4 Paid retail vendors
- 19.5 When free data is good enough
- 19.6 Auditing a new source
src/data/audit_source.py
- 19.7 Storing and versioning data
- Key Takeaways
- Action Steps
20. Rolling Analytics and Benchmarking
- 20.1 A single Sharpe hides more than it reveals
- 20.2 Rolling Sharpe
src/metrics/rolling.py
- 20.3 Calendar-year returns
- 20.4 Benchmark-relative returns
- 20.5 Rolling correlation to benchmark
- 20.6 Monthly heatmap
- 20.7 Drawdown underwater curve
- Key Takeaways
- Action Steps
21. Regime Analysis: When Does Your Strategy Actually Work?
- 21.1 Every strategy lives in a regime
- 21.2 Defining a simple regime label
src/regime/labels.py
- 21.3 Segmenting returns by regime
- 21.4 Why this changes risk management
- 21.5 Stress periods
- 21.6 Drift over time
- Key Takeaways
- Action Steps
22. A 30-Day Learning Plan
- 22.1 How to use this chapter
- 22.2 Week one: environment and data
- 22.3 Week two: signal and simulation
- 22.4 Week three: validation and bias
- 22.5 Week four: paper trading and deployment
- 22.6 The mindset
- Key Takeaways
- Action Steps
23. Where Strategy Ideas Actually Come From
- 23.1 Ideas are cheap; validation is the skill
- 23.2 Trend following
- 23.3 Mean reversion
- 23.4 Breakouts
- 23.5 Volatility-based
- 23.6 Cross-sectional / relative value
- 23.7 The honest assessment
- 23.8 How to generate your own ideas
- Key Takeaways
- Action Steps
24. Maintaining and Iterating a Live Systematic Book
- 24.1 A live system is not a finished product
- 24.2 The monitoring dashboard
src/prod/dashboard.py
- 24.3 What to review weekly
- 24.4 When to investigate versus when to wait
- 24.5 Iterating without contaminating the live book
src/prod/versioning.py
Promotion rule: paper version must beat live on rolling 60-day net returns
for 20 consecutive trading days before promotion.
- 24.6 The retirement decision
- 24.7 Keeping the books for tax and audit
- 24.8 The sustainable pace
- Key Takeaways
- Action Steps
25. Statistical Significance for Traders
- 25.1 Why a good backtest is not enough
- 25.2 The mean and its standard error
src/stats/significance.py
- 25.3 Confidence interval on the mean
- 25.4 The multiple-testing problem revisited
- 25.5 Effect size matters more than p-values
- 25.6 Bootstrap for non-normal returns
- 25.7 Practical rule of thumb
- Key Takeaways
- Action Steps
Closing Notes
- The method is the product
- What to expect
- Where to go next
- Final disclaimer
Frequently Asked Questions
- Do I need a powerful computer to run these strategies?
- Which programming language should I use?
- How much capital do I need to start?
- Can I use these strategies on crypto, futures, or forex?
- Why does my backtest show great results but paper trading loses?
- How many parameters should my strategy have?
- How long should I backtest for?
- Should I optimize parameters on the whole dataset?
- What is the single most important cost to model?
- Is trend following or mean reversion better?
- Can I trade these strategies without monitoring?
- Why does this book not tell me which stock to buy?
- What if I find a strategy with a Sharpe ratio of 3 in backtest?
- How do I handle dividends in adjusted data?
- When should I stop researching and start trading?
- Is algorithmic trading legal for retail traders?
- Should I use a backtesting framework instead of building my own?
- How do I handle dividends in my backtest?
- What if my strategy works in backtest but I cannot stick with it live?
- How many instruments should I trade to diversify?
- Can I combine trend and mean-reversion signals in one system?
- What data frequency do I need?
- How do I know if my costs are realistic?
- What if I cannot get survivorship-free data?
- How often should I review a live strategy?
- What is the difference between a backtest and a simulation?
- Why does my backtest look great but paper trading is worse?
- Can I use leverage in a systematic backtest?
- How do I handle corporate actions like spin-offs?
- What if two of my signals disagree on the same instrument?
- Should I optimize more parameters to improve results?
- How do I know if my edge has decayed?
- What tax records should I keep?
- Is it okay to run several uncorrelated strategies at once?
- How long should I paper trade before going live?
- What if my broker does not offer programmatic orders?
Glossary
About the Author
FREE RESOURCES