๐Ÿ“ˆ

Basic Trading Algorithm Guide

Aug 20, 2025

Overview

This lecture presents a step-by-step guide to building a basic trading algorithm on the QuantConnect platform using Python, focusing on buying and selling the SPY ETF based on simple profit/loss rules.

Algorithm Idea & Rules

  • The bot buys and holds the SPY ETF.
  • It closes the position if a gain or loss exceeds 10%.
  • After selling, it waits one month before reinvesting.
  • The process repeats indefinitely.

Setting Up QuantConnect

  • Navigate to the Lab tab and create a new algorithm.
  • Start with a blank template by exiting the Strategy Builder mode.
  • The default template includes an initialize (setup) and onData (event handler) method.

Initialization Process

  • Set the algorithmโ€™s start and end date for testing.
  • Define the starting cash balance for backtesting purposes.
  • Add SPY data using addEquity("SPY", Resolution.Daily).
  • Set data normalization mode with setDataNormalizationMode (e.g., use "raw" data for demonstration).
  • Store the SPY Symbol object for reference.
  • Set the benchmark to SPY for performance comparison.
  • Assign a brokerage model (e.g., Interactive Brokers) and account type (margin or cash).
  • Create helper variables: self.entryPrice (entry price), self.period (31 days), and self.nextEntryTime (re-entry time).

Understanding Data Handling in onData

  • onData is called with each new data point (tick or bar).
  • The data parameter (Slice object) provides access to bar, tick, and quote information via dictionaries indexed by Symbol.
  • Trade bars offer open, high, low, close, and volume data.
  • Quote bars provide bid and ask information.
  • Always check if data exists before accessing it, especially for less liquid assets.

Core Trading Logic Implementation

  • If not invested and current time >= nextEntryTime, buy SPY using a market order or setHoldings.
  • Log the purchase and record the price as entryPrice.
  • If invested, check if price deviates more than ยฑ10% from entryPrice.
  • If so, liquidate the position, log the sale, and set nextEntryTime to 31 days later.

Analyzing Backtest Results

  • Use the backtest feature to simulate performance.
  • Review equity charts, logs, and order history after backtesting.
  • Compare performance to SPY benchmark for context.
  • Understand limitations: this bot is a learning tool, not a viable trading strategy.

Key Terms & Definitions

  • SPY โ€” An ETF tracking the S&P 500 index.
  • Trade Bar โ€” Aggregated data over a set period (OHLCV: open, high, low, close, volume).
  • Quote Bar โ€” Contains bid/ask price summaries.
  • Backtesting โ€” Simulating a strategy on past market data.
  • Data Normalization Mode โ€” Adjusts data for splits/dividends.
  • Benchmark โ€” Standard for performance comparison.
  • Margin Account โ€” Allows trading with borrowed funds.

Action Items / Next Steps

  • Copy the example code from the provided link to experiment.
  • Prepare for the next lecture on dynamic trading logic and using technical indicators with QuantConnect.