6.1.1Algorithmic & Quant Trading

Understand algorithmic trading fundamentals

3,165 words14 min readdifficulty · medium3 backlinks

What is Algorithmic Trading?

Why it exists: Human traders face three fundamental limitations:

  1. Speed: Milliseconds matter when opportunities appear and disappear
  2. Consistency: Emotions cause deviation from optimal strategy
  3. Scale: Monitoring thousands of securities simultaneously is impossible manually

How it works: You translate a trading hypothesis into precise rules → code these rules → the program monitors markets → when conditions match, it executes trades automatically.

The Three Pillars of Algo Trading

1. Signal Generation (The "Why Trade" Decision)

What: The logic that identifies trading opportunities.

How it's built: You define conditions that must be true:

  • Technical signals: Moving average crossover, RSI oversold/overbought, breakout from range
  • Fundamental signals: P/E ratio below industry average, earnings surprise >10%
  • Statistical signals: Price deviation from mean by 2 standard deviations (mean reversion)
  • Market microstructure: Order book imbalance, bid-ask spread anomalies

Why this matters: Without a valid signal, you're just randomly executing trades. The signal is your edge—your hypothesis about what price pattern predicts future movement.

2. Risk Management (The "How Much" Decision)

What: Rules that determine position size and when to exit (stop-loss, take-profit).

Why it's critical: A profitable signal can still destroy your account if you risk too much per trade. Risk management ensures survival during losing streaks.

How: You set parameters before the trade:

Position Size=Risk Capital per TradeRisk per Share\text{Position Size} = \frac{\text{Risk Capital per Trade}}{\text{Risk per Share}}

Where:

  • Risk Capital per Trade = Account Size × Risk % (typically 1-2% of account)
  • Risk per Share = Entry Price - Stop Loss Price

Derivation:

  • If your account is 100,000 and you risk 1% per tradeRisk Capital=100{,}000 \text{ and you risk } 1\% \text{ per trade} \rightarrow \text{Risk Capital} =1,000
  • If you buy at 50withstoplossat50 with stop-loss at 48 → Risk per Share = $2
  • Position Size = 1,000/1,000 / 2 = 500 shares
  • Why this formula? It guarantees that if stopped out, you lose exactly 1,000(500shares×1,000 (500 shares × 2 loss per share), which is your predetermined1% risk.

3. Execution (The "How to Trade" Decision)

What: The method of actually placing orders to minimize costs and market impact.

Why it matters: Poor execution erodes profits. A spread of 0.10ona0.10 on a 50 stock is 0.2% slippage—do this 50 times and you've lost 10% to execution costs alone.

Types of execution algorithms:

  1. TWAP (Time-Weighted Average Price):

    • Split large order into equal chunks spread evenly over time
    • Use case: When you don't want to signal urgency and can tolerate time risk
  2. VWAP (Volume-Weighted Average Price):

    • Split order proportional to expected volume throughout the day
    • More aggressive when volume is high (liquid), passive when low
    • Use case: Benchmark against average execution price of the day
  3. Implementation Shortfall (Arrival Price):

    • Execute agressively at start, then slow down
    • Minimize opportunity cost of not being in position
    • Use case: When you have strong signal and want immediate exposure

The Algo Trading Lifecycle

1. Research → 2. Backtest → 3. Paper Trade → 4. Live Trade (small) → 5. Scale 6. Monitor
     ↑                                                                              ↓
     └────────────────────── Feedback Loop ──────────────────────┘

1. Research (Hypothesis Formation):

  • Observe market pattern or inefficiency
  • Formulate testable hypothesis: "If X happens, Y follows with Z% probability"

2. Backtest (Historical Validation):

  • Run algorithm on historical data
  • Check: Does it actually work? What's the win rate, Sharpe ratio, max drawdown?
  • Critical: Avoid look-ahead bias (using future info) and survivorship bias (ignoring delisted stocks)

3. Paper Trade (Real-time Simulation):

  • Run algorithm with live data but fake money
  • Tests: Does it handle live market conditions? Are fills realistic?

4. Small Live Trade:

  • Deploy with minimal capital
  • Verify execution, slippage, and latency match expectations

5. Scale Up:

  • Gradually increase position sizes
  • Monitor for capacity constraints (your orders start moving the market)

6. Continuous Monitoring:

  • Track performance metrics daily
  • Watch for regime changes (algorithm stops working)

Key Performance Metrics

Types of Algorithmic Trading Strategies

  1. Trend Following:

    • Assumption: Prices exhibit momentum—what goes up continues up
    • Signal: Moving average crossover, breakout from range
    • Works best in: Trending markets (post-breakout news, commodity cycles)
  2. Mean Reversion:

    • Assumption: Prices oscillate around a mean—extreme moves reverse
    • Signal: Price deviates >2 standard deviations from moving average
    • Works best in: Range-bound, chopy markets (low volatility regimes)
  3. Statistical Arbitrage:

    • Assumption: Related assets should move together—deviations are temporary
    • Signal: Cointegrated pairs diverge (e.g., Coke vs. Pepsi)
    • Example: If Coke/Pepsi spread widens, short Coke, long Pepsi, profit when spread narrows
  4. Market Making:

    • Assumption: You profit from bid-ask spread by providing liquidity
    • Method: Place limit orders on both sides, earn spread when both fill
    • Risk: Inventory risk (you end up long/short when market moves against you)
  5. High-Frequency Trading (HFT):

    • Assumption: Speed advantage lets you capture tiny inefficiencies
    • Method: Co-locate servers next to exchange, optimize to microsecond latency
    • Not accessible to retail traders (requires millions in infrastructure)
Recall Explain to a 12-Year-Old

Imagine you're playing a video game where you have to catch falling coins. At first, you play manually—you move the basket with your hands. You're pretty good, but you get tired, you blink and miss coins, and you can only watch one part of the screen.

Now imagine you write a set of rules: "If a coin appears in the top-left, move basket there. If two coins fall at once, catch the bigger one first. If a red coin appears, ignore it—it's fake."

You program the computer to follow these exact rules. Now the computer plays for you, never gets tired, never blinks, and can watch the entire screen at once. It catches way more coins than you could manually.

That's algorithmic trading. You figure out the rules for when to buy and sell stocks (the "game"), write them as code, and let the computer execute them automatically. It's faster, more consistent, and can watch thousands of stocks while you sleep. Your job is to write good rules (rules that actually catch coins, not just random movements).

Connections

  • 6.1.02-Learn-basic-backtesting – How to validate your algorithm before risking real money
  • 6.1.03-Quantitative-analysis-indicators – The technical indicators used as signals
  • 6.2.01-Risk-management-in-algo-trading – Position sizing and drawdown management
  • 3.3.01-Types-of-market-orders – Understanding order types for execution algorithms
  • 5.2.01-Technical-vs-fundamental-analysis – The signal types that feed algorithms
  • 4.1.02-Market-volatility-measurement – How volatility affects algo performance

#flashcards/stock-market

What is algorithmic trading? :: The use of computer programs to automatically execute trades based on predefined rules, mathematical models, or statistical patterns without human intervention during execution.

What are the three core decisions every trading algorithm must make?
1) Signal Generation (why trade), 2) Risk Management (how much), 3) Execution (how to trade).
What is a moving average crossover signal?
A buy signal generated when a short-term MA crosses above a long-term MA (bullish), or a sell signal when it crosses below (bearish). E.g., 50-day crossing 200-day.
How do you calculate position size in algorithmic trading?
Position Size = (Risk Capital per Trade) / (Risk per Share), where Risk per Share = Entry Price - Stop Loss Price. This ensures you lose a predetermined % if stopped out.
What is VWAP and why use it?
Volume-Weighted Average Price: sum of (Price × Volume) divided by total volume. Used as execution benchmark to ensure you're not paying more than the average trader that day.
What is overfitting in backtesting?
When your algorithm is tuned to fit historical noise rather than real patterns. It performs well in backtest but fails in live trading because it memorized past data instead of learning generalizable rules.
What is the Sharpe ratio?
(Average Return - Risk-Free Rate) / Standard Deviation. It measures return per unit of risk. Higher is better; >2.0 is excellent.
What is maximum drawdown (MDD)?
The largest peak-to-trough decline in account value during a period. Shows worst-case loss you'd have to endure before recovery.
What is mean reversion?
Trading strategy based on the assumption that prices oscillate around a mean value. When price deviates far from mean (e.g., >2 standard deviations), it will likely revert back.
What is the purpose of out-of-sample testing?
To validate that your algorithm works on data it has never seen during development, preventing overfitting to historical patterns.
Why must transaction costs be included in backtests?
Because commissions, spreads, and slipage can erase profits from high-frequency strategies. A backtest showing profit might actually lose money after real costs.
What does ATR stand for and how is it used?
Average True Range: measures volatility. Used to set stop-losses (e.g., Entry -2×ATR) that account for normal price fluctuation without premature exit.

Concept Map

motivates

includes

defined as

controls

core insight

built on

built on

answers

uses

example

requires

answers

sets

Human Trader Limits

Algorithmic Trading

Speed, Consistency, Scale

Automated Rule-Based Execution

Timing, Price, Quantity, Routing

Discretionary to Systematic

Signal Generation

Risk Management

Why Trade

Technical, Fundamental, Statistical Signals

MA Crossover 50 vs 200

Crossover Transition Check

How Much / When Exit

Position Size, Stop-Loss, Take-Profit

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Algorithmic trading matlab hai ki ap computer ko exact rules de do kiab buy karo aur kab sell karo, fir computer automatically execute kar deta hai. Yeh manual trading se kafi better hai kyunki computer emotional nahi hota, milliseconds mein decision leta hai, aur ek sath hazaron stocks ko track kar sakta hai.

Teen main chezein hoti hain har algo mein: pehla, signal generation (yeh decide karta hai ki trade kyun karna hai—jaise moving average cross ho gayi ya price oversold hai). Dosra, risk management (yeh bata hai kitne shares kharidne hain taki agar loss ho toh sirf 1-2% account ka jaye). Tesra, execution (yeh decide karta hai ki order kaise place karna hai taki slippage aur cost kam rahe—VWAP ya TWAP algorithms use karte hain).

Sabse badi galti jo naye traders karte hain woh hai overfitting: matlab backtest mein toh algorithm bahut acha lag raha tha, lekin live mein fail ho gaya kyunki woh purane data ke noise ko memorize kar liya tha, asliyat ka pattern nahi seekha. Isliye hamesha out-of-sample testing karo aur transaction costs ko backtest mein include karo, warna profit dikhega lekin reality mein paisa dob jayega.

Algorithmic trading ka matlab yeh nahi ki ap blindly computer par depend kar do—tumhe samajhna padega ki strategy kyun kaam karti hai (economic rationale), performance metrics track karne padenge (Sharpe ratio, max drawdown), aur continuously monitor karna padega ki market regime change toh nahi ho gayi. Automation ka matlab efficiency hai, magic nahi.

Test yourself — Algorithmic & Quant Trading

Connections