Skip to content

Field note No. 04 · Foundations

QuantConnect and LEAN

An open-source engine, a hosted platform, and what a practitioner should know before trusting either.

Revised September 20269 min read27 references

Educational material only. Not investment advice.

Contents
  1. 01What it is, and a short history
  2. 02Architecture
  3. 03Using it
  4. 04Data
  5. 05Strengths and cautions
  6. 06Documentation
  7. —References

Abstract

What QuantConnect and its open-source LEAN engine are; a verified history (LEAN open-sourced in January 2015, Python support in 2017, the command-line tool in 2021, PEP 8 names in 2024); the architecture that lets one algorithm run in backtest and live; the algorithm framework; a first algorithm and a trend-rule example; the data library's coverage; honest strengths and cautions; and the documentation pages worth bookmarking.

Key takeaways

  • LEAN is an open-source (Apache 2.0) C# engine, released in 2015, with Python supported through Python.NET.
  • Backtest and live parity comes from swapping the data feed and transaction handlers while the algorithm stays the same.
  • The algorithm framework separates universe, alpha, portfolio construction, risk and execution.
  • The data library covers US equities from 1998, options and futures, forex and CFDs, point-in-time.
  • Set reality models explicitly, test at the resolution you trade, record versions, and reconcile live against backtest.

Before you start

  • Basic Python
  • What a backtest is (Field note 01)
  • Field note 03 for the trend-rule example

QuantConnect is a hosted platform for researching, backtesting and trading systematic strategies, built on LEAN, an open-source trading engine. This note describes the engine’s design, what it is like to use, what data it offers, and where a practitioner should be careful. It is written from the point of view of a user, not a vendor, and every factual claim links to QuantConnect’s own documentation or source.

What it is, and a short history

QuantConnect dates LEAN to 2012.1 The engine was released as open source on 12 January 2015, in a forum announcement by Jared Broad that described it as the result of three years of development; the repository’s first public commit carries that date.2,3 It is licensed under Apache 2.0, so it can be run, modified and deployed privately without the hosted platform.3

DateMilestoneSource
12 January 2015LEAN released as open source (Apache 2.0)Forum announcement; GitHub
1 May 2017LEAN v2.4.0.0: Python library support, re-engineered on Python.NETLEAN release notes
January 2021First release of the lean command-line tool on PyPI (announced June 2021)PyPI; QuantConnect blog
April 2024Python API moves to PEP 8 names (snake_case) for new projects; the old names keep workingQuantConnect announcement

Dates as published by QuantConnect, GitHub and PyPI, checked September 2026.

The engine is written in C#. Python algorithms call the same engine through Python.NET, so a Python strategy uses the C# order, portfolio and data machinery rather than a separate reimplementation.4,5 Since 2024 the Python API uses PEP 8 names (set_holdings, on_data), and the older CamelCase names remain valid; the announcement warns that attribute names of your own can now clash with API methods, which is why the examples below prefix theirs with an underscore.6The command-line tool’s first release on PyPI and its announcement are dated in the table.7,1

Architecture

One algorithm, two worlds

LEAN is event-driven. The documentation describes it as a streaming analysis system: data is fed to the algorithm one time slice at a time, in fast-forward during a backtest and in real time when live, so the same algorithm code runs in both.8 The engine achieves this by assembling itself from handlers chosen by configuration. The data feed, the transaction handler, the setup handler and the real-time clock each have a backtesting and a live implementation; the algorithm sees the same interface either way (Figure 1).9

Figure 1LEAN: the same algorithm between two sets of handlers
LEAN architecture: a file-system data feed and a backtesting transaction handler in a backtest, a live data feed and a brokerage transaction handler live, around the same algorithmBacktestLivetime slicestime slicesordersordersFileSystemDataFeedhistorical filesBacktestingTransactionHandlerfill, fee, slippage modelsYour algorithm (QCAlgorithm)on_data · portfolio · ordersLiveTradingDataFeedstreaming dataBrokerageTransactionHandlerorders to the broker
Data-feed and transaction-handler names as in LEAN's Launcher/config.json. In a backtest, data comes from files and orders are filled by LEAN's fill, fee and slippage models; live, data streams from a feed and orders go to a brokerage. The algorithm, and the portfolio and order logic around it, do not change.

The algorithm framework

A strategy can be written as a single class, or as five pluggable models that the framework runs in sequence: universe selection chooses the securities, the alpha model emits directional insights, portfolio construction turns insights into portfolio targets (a quantity for each security), risk management adjusts the targets, and execution places the orders that move the portfolio towards them.10 The separation is the same one this series uses: a signal (Field note 03 (Indicators, and the 200-day moving average)), sizing (Field note 02 (Volatility targeting)) and execution (Field note 05 (Execution: TWAP, slicing and jitter)) are different problems and are easier to test apart.

Figure 2The algorithm framework's five models
Algorithm framework: universe selection, alpha, portfolio construction, risk management, executionUniversewhich securitiesAlphainsightsPortfoliotargetsRiskadjust targetsExecutionorders
Each model can be swapped independently; the framework passes each model's output to the next, in this order.

Around the algorithm, a brokerage model sets what a given broker allows and charges: fees, supported assets and order types, leverage and settlement, the fill, slippage and buying-power models that follow from them, and the validation of each order before it is sent.11 Data arrives at tick, second, minute, hour or daily resolution; US equity subscriptions default to minute.12

Using it

A first algorithm

The smallest useful algorithm sets a date range and starting cash, subscribes to a security and trades on data. This is LEAN’s own template, in the current Python naming:13

BasicTemplateAlgorithm.py
from AlgorithmImports import *


class BasicTemplateAlgorithm(QCAlgorithm):
    def initialize(self):
        self.set_start_date(2013, 10, 7)
        self.set_end_date(2013, 10, 11)
        self.set_cash(100000)
        self.add_equity("SPY", Resolution.MINUTE)

    def on_data(self, data):
        if not self.portfolio.invested:
            self.set_holdings("SPY", 1)
From LEAN's Algorithm.Python templates, with a debug line and comments removed.

A slightly larger example, Field note 03 (Indicators, and the 200-day moving average)’s trend rule, shows the pieces a real strategy uses: a built-in indicator registered with the engine, a warm-up period that fills it before trading starts, and an explicit guard while it warms up.14

site_research/examples/lean_trend_overlay.py
from AlgorithmImports import *


class TrendOverlay(QCAlgorithm):
    """Hold the ETF while it is above its 200-day simple moving average; otherwise hold cash.

    Field note 03's rule, written for LEAN. With daily bars the signal is only known after the
    close, so read the market-order documentation for when the resulting order fills.
    """

    def initialize(self):
        self.set_start_date(2010, 1, 1)
        self.set_end_date(2024, 12, 31)
        self.set_cash(100_000)
        # Leading underscores: in the PEP 8 API, `symbol` and `sma` are QCAlgorithm methods.
        self._symbol = self.add_equity("SPY", Resolution.DAILY).symbol
        self._trend = self.sma(self._symbol, 200, Resolution.DAILY)   # a registered indicator
        self.set_warm_up(200, Resolution.DAILY)                         # fill it before trading

    def on_data(self, data: Slice):
        if self.is_warming_up or not self._trend.is_ready:
            return
        price = self.securities[self._symbol].price
        above = price > self._trend.current.value
        if above and not self.portfolio.invested:
            self.set_holdings(self._symbol, 1.0)
        elif not above and self.portfolio.invested:
            self.liquidate(self._symbol)
Not investment advice and not a strategy we run: a teaching example. The ticker is the public ETF used throughout the documentation. In the cloud the data is included; a local run with the CLI needs the daily data downloaded first.

Where the work is done

The hosted platform provides a browser IDE, research notebooks attached to the data library, cloud backtesting and live deployment.16,17 The lean command-line tool brings the same workflow to a local editor: it runs the engine locally in Docker and can push projects to and pull them from the cloud. Its documentation states that using it requires membership of a paid organisation tier.18,19

terminal
pip install --upgrade lean      # needs Docker for local runs
lean login                      # link the CLI to your QuantConnect account
lean init                       # set up a workspace in the current directory
lean create-project "Trend Overlay"
lean backtest "Trend Overlay"   # run LEAN locally in Docker
lean cloud backtest "Trend Overlay" --push   # or push and run in the cloud
Commands from the LEAN CLI documentation. Local runs need Docker; the CLI's documentation describes the account requirements.

Data

The data library is one of the platform’s main assets: point-in-time, survivorship-bias-free US equities and a range of derivatives and alternative datasets, available in backtests and notebooks without separate licensing work. The documented coverage of the core price data:20,21,22,23,24,25

Asset classVendor (as named by QuantConnect)FromResolution / scope
US equitiesAlgoSeekJanuary 1998Tick to daily; about 27,500 securities from the full consolidated (SIP) feed, survivorship-bias free
US equity optionsAlgoSeekJanuary 2012Minute; OPRA feed
US futuresAlgoSeekMay 2009The 162 most liquid contracts on CME, CBOT, NYMEX, COMEX, CFE and ICE
ForexQuantConnect (a forex dealer's tick data)January 200771 pairs, tick to daily
CFDsQuantConnect (a forex dealer's tick data)May 200251 contracts
US fundamentalsMorningstarJanuary 1998Company fundamentals

From QuantConnect's dataset pages, September 2026. The library also lists crypto, index and index-option, future-option and alternative datasets; check each dataset page for its own start date and terms.

Equity prices are split- and dividend-adjusted by default, and raw, split-adjusted and total-return modes can be chosen per subscription (a scaled-raw mode applies to history requests).12 The choice matters: under the default adjusted mode a backtest also fills at adjusted prices, which differ from the prices a live order will see, so a strategy whose sizing, limit prices or cost model depends on the traded price may be better tested on raw data.

Strengths and cautions

In our use the engine has been mature and dependable, and most problems we have met came from defaults and assumptions rather than from the engine itself. An honest summary:

StrengthsCautions
Open source: behaviour can be read and verified in the code, not guessedDefaults are permissive: under the default brokerage model, slippage is zero until you set a model
One algorithm for backtest and live, with the same order and portfolio logicDaily bars hide intraday timing: fills on daily data can be earlier or kinder than live
Broad, survivorship-free data in the same environment as the codeCloud resources depend on the plan: backtest, research and live nodes and log sizes are capped
Python and C#, with a large public example library and an active forumThe Python-to-C# bridge adds a layer to debug, and API names changed in 2024

Four habits make results from any backtesting engine, this one included, closer to what live trading will deliver:

  1. Set the reality models explicitly. Choose the brokerage model for the broker you will use and a slippage model; do not rely on the defaults.26,27
  2. Backtest at the resolution you will trade. If live orders are sent intraday, backtest on minute data, so fills see the same prices and times.
  3. Record the engine version and parameters with every result. The engine evolves; a backtest that cannot be rerun on the same code is an anecdote.
  4. Reconcile live against backtest from the first day. Compare positions and fills, not only returns. Differences found in the first week are cheap; differences found after a year are not.

Documentation

The official documentation is extensive. These pages are the useful entry points; every link was checked in September 2026.

TopicURLWhat it covers
Documentation homewww.quantconnect.com/docs/v2Start here
Writing algorithmswww.quantconnect.com/docs/v2/writing-algorithmsThe API: securities, data, orders, scheduling
Algorithm frameworkwww.quantconnect.com/docs/v2/writing-algorithms/algorithm-framework/overviewUniverse, alpha, portfolio, risk and execution models
Algorithm enginewww.quantconnect.com/docs/v2/writing-algorithms/key-concepts/algorithm-engineThe streaming design behind backtest and live parity
Datasetswww.quantconnect.com/docs/v2/writing-algorithms/datasets/overviewWhat data exists, from whom, since when
Reality modellingwww.quantconnect.com/docs/v2/writing-algorithms/reality-modeling/key-conceptsFills, slippage, fees, brokerage models
Research environmentwww.quantconnect.com/docs/v2/research-environmentNotebooks attached to the data
LEAN CLIwww.quantconnect.com/docs/v2/lean-cliLocal and cloud workflows from a terminal
Live tradingwww.quantconnect.com/docs/v2/cloud-platform/live-tradingDeployment and supported brokerages
LEAN engine docswww.quantconnect.com/docs/v2/lean-engineRunning and extending the engine itself
LEAN on GitHubgithub.com/QuantConnect/LeanSource, issues and releases (Apache 2.0)

References

  1. QuantConnect (2021). QuantConnect releases LEAN CLI to streamline cloud and local workflows (blog; site footer: LEAN founded in 2012). https://www.quantconnect.com/blog/quantconnect-releases-lean-cli-to-streamline-cloud-and-local-workflows/ (retrieved 27 September 2026).
  2. QuantConnect (2015). Lean open source release (forum announcement, 12 January 2015). https://www.quantconnect.com/forum/discussion/400/lean-open-source-release (retrieved 27 September 2026).
  3. QuantConnect (2026). QuantConnect/Lean: Lean Algorithmic Trading Engine (source repository, Apache-2.0). https://github.com/QuantConnect/Lean (retrieved 27 September 2026).
  4. QuantConnect (2026). Python and LEAN. https://www.quantconnect.com/docs/v2/writing-algorithms/key-concepts/python-and-lean (retrieved 27 September 2026).
  5. QuantConnect (2017). LEAN release v2.4.0.0: Python library support. https://github.com/QuantConnect/Lean/releases/tag/v2.4.0.0 (retrieved 27 September 2026).
  6. QuantConnect (2024). PEP8 Python API migration (announcement). https://www.quantconnect.com/announcements/16830/pep8-python-api-migration/ (retrieved 27 September 2026).
  7. QuantConnect (2026). lean: the LEAN CLI on the Python Package Index (release history). https://pypi.org/project/lean/ (retrieved 27 September 2026).
  8. QuantConnect (2026). Algorithm engine. https://www.quantconnect.com/docs/v2/writing-algorithms/key-concepts/algorithm-engine (retrieved 27 September 2026).
  9. QuantConnect (2026). Launcher/config.json (handler configuration). https://github.com/QuantConnect/Lean/blob/master/Launcher/config.json (retrieved 27 September 2026).
  10. QuantConnect (2026). Algorithm framework overview. https://www.quantconnect.com/docs/v2/writing-algorithms/algorithm-framework/overview (retrieved 27 September 2026).
  11. QuantConnect (2026). Brokerages: key concepts. https://www.quantconnect.com/docs/v2/writing-algorithms/reality-modeling/brokerages/key-concepts (retrieved 27 September 2026).
  12. QuantConnect (2026). US equity: requesting data (resolutions, data normalization modes). https://www.quantconnect.com/docs/v2/writing-algorithms/securities/asset-classes/us-equity/requesting-data (retrieved 27 September 2026).
  13. QuantConnect (2026). BasicTemplateAlgorithm.py. https://github.com/QuantConnect/Lean/blob/master/Algorithm.Python/BasicTemplateAlgorithm.py (retrieved 27 September 2026).
  14. QuantConnect (2026). Warm up periods. https://www.quantconnect.com/docs/v2/writing-algorithms/historical-data/warm-up-periods (retrieved 27 September 2026).
  15. QuantConnect (2026). Market orders. https://www.quantconnect.com/docs/v2/writing-algorithms/trading-and-orders/order-types/market-orders (retrieved 27 September 2026).
  16. QuantConnect (2026). Cloud IDE. https://www.quantconnect.com/docs/v2/cloud-platform/projects/ide (retrieved 27 September 2026).
  17. QuantConnect (2026). Research environment. https://www.quantconnect.com/docs/v2/research-environment (retrieved 27 September 2026).
  18. QuantConnect (2026). LEAN CLI. https://www.quantconnect.com/docs/v2/lean-cli (retrieved 27 September 2026).
  19. QuantConnect (2026). Installing the LEAN CLI. https://www.quantconnect.com/docs/v2/lean-cli/installation/installing-lean-cli (retrieved 27 September 2026).
  20. QuantConnect (2026). AlgoSeek US equities (dataset). https://www.quantconnect.com/data/algoseek-us-equities (retrieved 27 September 2026).
  21. QuantConnect (2026). AlgoSeek US equity options (dataset). https://www.quantconnect.com/data/algoseek-us-equity-options (retrieved 27 September 2026).
  22. QuantConnect (2026). AlgoSeek US futures (dataset). https://www.quantconnect.com/data/algoseek-us-futures (retrieved 27 September 2026).
  23. QuantConnect (2026). QuantConnect forex (dataset). https://www.quantconnect.com/data/quantconnect-forex (retrieved 27 September 2026).
  24. QuantConnect (2026). QuantConnect CFD (dataset). https://www.quantconnect.com/data/quantconnect-cfd (retrieved 27 September 2026).
  25. QuantConnect (2026). Morningstar US fundamentals (dataset). https://www.quantconnect.com/data/morning-star-us-fundamentals (retrieved 27 September 2026).
  26. QuantConnect (2026). Slippage: key concepts. https://www.quantconnect.com/docs/v2/writing-algorithms/reality-modeling/slippage/key-concepts (retrieved 27 September 2026).
  27. QuantConnect (2026). Transaction fees: key concepts. https://www.quantconnect.com/docs/v2/writing-algorithms/reality-modeling/transaction-fees/key-concepts (retrieved 27 September 2026).