Top Related Projects
Python client for Alpaca's trade API
Download market data from Yahoo! Finance's API
Qlib is an AI-oriented quantitative investment platform that aims to realize the potential, empower research, and create value using AI technologies in quantitative investment, from exploring ideas to implementing productions. Qlib supports diverse machine learning modeling paradigms. including supervised learning, market dynamics modeling, and RL.
An Algorithmic Trading Library for Crypto-Assets in Python
An open source reinforcement learning framework for training, evaluating, and deploying robust trading agents.
Investment Research for Everyone, Everywhere.
Quick Overview
LEAN is an open-source algorithmic trading engine developed by QuantConnect. It provides a robust framework for quantitative researchers and traders to develop, backtest, and deploy trading algorithms across various asset classes, including stocks, forex, and cryptocurrencies.
Pros
- Comprehensive backtesting capabilities with support for multiple asset classes
- Extensive library of financial indicators and data sources
- Active community and regular updates
- Seamless integration with live trading platforms
Cons
- Steep learning curve for beginners
- Limited documentation for advanced features
- Resource-intensive for complex algorithms or large datasets
- Requires significant setup time for local development environment
Code Examples
- Creating a simple moving average crossover algorithm:
class SimpleMovingAverageCrossover(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2018, 1, 1)
self.SetCash(100000)
self.symbol = self.AddEquity("SPY", Resolution.Daily).Symbol
self.fast = self.SMA(self.symbol, 10, Resolution.Daily)
self.slow = self.SMA(self.symbol, 30, Resolution.Daily)
def OnData(self, data):
if not self.slow.IsReady:
return
if self.fast.Current.Value > self.slow.Current.Value:
self.SetHoldings(self.symbol, 1)
elif self.fast.Current.Value < self.slow.Current.Value:
self.Liquidate()
- Implementing a simple pairs trading strategy:
class PairsTrading(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2018, 1, 1)
self.SetCash(100000)
self.stock1 = self.AddEquity("GOOGL", Resolution.Daily).Symbol
self.stock2 = self.AddEquity("MSFT", Resolution.Daily).Symbol
self.hedge = self.HEDGE(self.stock1, self.stock2, 20)
def OnData(self, data):
if not self.hedge.IsReady:
return
if self.hedge.Current.Value > 2:
self.SetHoldings(self.stock1, -0.5)
self.SetHoldings(self.stock2, 0.5)
elif self.hedge.Current.Value < -2:
self.SetHoldings(self.stock1, 0.5)
self.SetHoldings(self.stock2, -0.5)
else:
self.Liquidate()
- Using custom data sources:
class CustomDataAlgorithm(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2018, 1, 1)
self.SetCash(100000)
self.AddData(MyCustomDataType, "CUSTOM")
def OnData(self, data):
if "CUSTOM" in data:
custom_data = data["CUSTOM"]
self.Log(f"Custom data value: {custom_data.Value}")
Getting Started
-
Install LEAN:
git clone https://github.com/QuantConnect/Lean.git cd Lean
-
Set up your development environment:
- Install .NET Core SDK
- Install Python 3.6+
- Install required packages:
pip install -r Requirements.txt
-
Run the example algorithm:
dotnet run --project Algorithm.CSharp
-
Start developing your own algorithm by creating a new Python or C# file in the respective project folder.
Competitor Comparisons
Python client for Alpaca's trade API
Pros of alpaca-trade-api-python
- Simpler API focused specifically on trading with Alpaca
- Easier to set up and use for beginners
- Lightweight and faster to implement for basic trading strategies
Cons of alpaca-trade-api-python
- Limited to Alpaca's brokerage and data services
- Less comprehensive backtesting and research capabilities
- Fewer built-in tools for advanced portfolio management and risk analysis
Code Comparison
Lean:
public class MyAlgorithm : QCAlgorithm
{
public override void Initialize()
{
SetStartDate(2020, 1, 1);
SetCash(100000);
AddEquity("AAPL");
}
}
alpaca-trade-api-python:
api = tradeapi.REST('KEY_ID', 'SECRET_KEY', base_url='https://paper-api.alpaca.markets')
api.submit_order(
symbol='AAPL',
qty=100,
side='buy',
type='market',
time_in_force='gtc'
)
The Lean framework provides a more structured approach with built-in backtesting capabilities, while alpaca-trade-api-python offers a simpler interface for direct trading through Alpaca. Lean is more suitable for comprehensive algorithmic trading strategies, while alpaca-trade-api-python is better for quick implementation of basic trading ideas using Alpaca's services.
Download market data from Yahoo! Finance's API
Pros of yfinance
- Lightweight and easy to use for quick data retrieval
- Focuses specifically on Yahoo Finance data, making it simple for users who only need this source
- Requires minimal setup and configuration
Cons of yfinance
- Limited to Yahoo Finance data, lacking the diverse data sources available in Lean
- Not designed for complex algorithmic trading or backtesting, which Lean excels at
- May have reliability issues due to dependence on Yahoo Finance's API stability
Code Comparison
yfinance:
import yfinance as yf
ticker = yf.Ticker("AAPL")
hist = ticker.history(period="1mo")
print(hist.head())
Lean:
public class AppleDataAlgorithm : QCAlgorithm
{
public override void Initialize()
{
SetStartDate(2021, 1, 1);
SetEndDate(2021, 12, 31);
AddEquity("AAPL", Resolution.Daily);
}
}
Summary
yfinance is a simple, focused library for retrieving Yahoo Finance data, ideal for quick analysis and small projects. Lean, on the other hand, is a comprehensive algorithmic trading engine with extensive features for backtesting and live trading across multiple asset classes and data sources. While yfinance is easier to get started with, Lean offers more power and flexibility for serious quantitative trading applications.
Qlib is an AI-oriented quantitative investment platform that aims to realize the potential, empower research, and create value using AI technologies in quantitative investment, from exploring ideas to implementing productions. Qlib supports diverse machine learning modeling paradigms. including supervised learning, market dynamics modeling, and RL.
Pros of qlib
- Focuses on AI-driven quantitative investment strategies
- Provides a comprehensive set of tools for machine learning in finance
- Supports advanced features like GPU acceleration and distributed training
Cons of qlib
- Less comprehensive backtesting capabilities compared to Lean
- Narrower focus on machine learning, potentially limiting traditional quant strategies
- Steeper learning curve for users not familiar with AI/ML concepts
Code Comparison
qlib example:
from qlib.contrib.model.pytorch_lstm import LSTMModel
from qlib.contrib.data.handler import Alpha158
handler = Alpha158(instruments="csi300", start_time="2010-01-01", end_time="2020-08-01")
model = LSTMModel()
Lean example:
public class MyAlgorithm : QCAlgorithm
{
public override void Initialize()
{
SetStartDate(2010, 1, 1);
SetEndDate(2020, 8, 1);
AddEquity("SPY", Resolution.Daily);
}
}
The code snippets highlight the different approaches: qlib focuses on ML models and data handling, while Lean provides a more traditional algorithmic trading framework.
An Algorithmic Trading Library for Crypto-Assets in Python
Pros of Catalyst
- Focuses on cryptocurrency trading strategies
- Supports backtesting and live trading on multiple crypto exchanges
- Provides built-in data sources for crypto markets
Cons of Catalyst
- Limited to cryptocurrency markets, less versatile for other asset classes
- Smaller community and fewer resources compared to Lean
- Less frequent updates and maintenance
Code Comparison
Catalyst:
from catalyst import run_algorithm
def initialize(context):
context.asset = symbol('btc_usdt')
def handle_data(context, data):
current_price = data.current(context.asset, 'price')
context.order(context.asset, 100)
run_algorithm(capital_base=10000, data_frequency='minute', initialize=initialize, handle_data=handle_data)
Lean:
public class BasicTemplateAlgorithm : QCAlgorithm
{
public override void Initialize()
{
SetStartDate(2013, 10, 07);
SetEndDate(2013, 10, 11);
SetCash(100000);
AddEquity("SPY", Resolution.Minute);
}
public override void OnData(Slice data)
{
if (!Portfolio.Invested)
{
SetHoldings("SPY", 1);
}
}
}
Both repositories provide algorithmic trading frameworks, but Catalyst specializes in cryptocurrency markets, while Lean offers a more comprehensive solution for various asset classes. Catalyst's Python-based approach may be more accessible for some users, while Lean's C# implementation could offer better performance for complex strategies.
An open source reinforcement learning framework for training, evaluating, and deploying robust trading agents.
Pros of tensortrade
- Focused on reinforcement learning for trading, providing a more specialized framework for AI-driven strategies
- Offers a modular and extensible architecture, allowing for easy customization of trading environments
- Integrates well with popular deep learning libraries like TensorFlow and PyTorch
Cons of tensortrade
- Less comprehensive in terms of overall trading infrastructure compared to Lean
- Smaller community and ecosystem, potentially leading to fewer resources and third-party integrations
- Still in early development stages, which may result in more frequent breaking changes
Code Comparison
tensortrade:
from tensortrade.env import TradingEnvironment
from tensortrade.features import TAIndicator
env = TradingEnvironment(
instruments=['BTC-USD'],
features=[TAIndicator('close', 'rsi', window=14)]
)
Lean:
public class MyAlgorithm : QCAlgorithm
{
public override void Initialize()
{
SetStartDate(2020, 1, 1);
AddCrypto("BTCUSD");
RSI("BTCUSD", 14, Resolution.Daily);
}
}
Both frameworks allow for easy setup of trading environments and technical indicators, but tensortrade focuses on reinforcement learning while Lean provides a more traditional algorithmic trading approach.
Investment Research for Everyone, Everywhere.
Pros of OpenBB
- More comprehensive financial data analysis toolkit, covering a wider range of financial instruments and data sources
- User-friendly terminal interface, making it accessible for non-programmers
- Actively maintained with frequent updates and community contributions
Cons of OpenBB
- Less focused on algorithmic trading and backtesting compared to Lean
- May have a steeper learning curve for users primarily interested in quantitative trading strategies
- Lacks the integrated brokerage connections and live trading capabilities of Lean
Code Comparison
OpenBB:
from openbb_terminal.sdk import openbb
# Fetch stock data
aapl_data = openbb.stocks.load("AAPL")
# Perform technical analysis
sma = openbb.ta.sma(aapl_data["Close"], 20)
Lean:
public class MyAlgorithm : QCAlgorithm
{
public override void Initialize()
{
SetStartDate(2020, 1, 1);
SetCash(100000);
AddEquity("AAPL", Resolution.Daily);
}
}
The code snippets highlight the different focus areas of the two projects. OpenBB emphasizes data analysis and visualization, while Lean is geared towards building and testing trading algorithms.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Lean Home | Documentation | Download Zip | Docker Hub | Nuget
LEAN is an event-driven, professional-caliber algorithmic trading platform built with a passion for elegant engineering and deep quant concept modeling. Out-of-the-box alternative data and live-trading support.
LEAN is modular in design, with each component pluggable and customizable. It ships with models for all major plug-in points.
QuantConnect Lean CLI is a command-line interface tool for interacting with the Lean algorithmic trading engine, which is an open-source platform for backtesting and live trading algorithms in multiple financial markets. It allows developers to manage projects, run backtests, deploy live algorithms, and perform various other tasks related to algorithmic trading directly from the terminal. The CLI simplifies the workflow by automating tasks, enabling seamless integration with cloud services, and facilitating collaboration with the QuantConnect community. It's designed for quant developers who need a powerful and flexible tool to streamline their trading strategies. Please watch the instructions videos to learn more.
Installation
pip install lean
Commands
Create a new project containing starter code
lean project-create
Run a local Jupyter Lab environment using Docker
lean research
Backtest a project locally using Docker
lean backtest
Optimize a project locally using Docker
lean optimize
Start live trading a project locally using Docker
lean live
Download the LEAN CLI Cheat Sheet for the full list of commands.
This section will cover how to install lean locally for you to use in your environment. Refer to the following readme files for a detailed guide regarding using your local IDE with Lean:
To install locally, download the zip file with the latest master and unzip it to your favorite location. Alternatively, install Git and clone the repo:
git clone https://github.com/QuantConnect/Lean.git
cd Lean
macOS
NOTE: Visual Studio for Mac has been discontinued, use Visual Studio Code instead
- Install Visual Studio Code for Mac
- Install the C# Dev Kit extension
- Install dotnet 6 SDK:
- To build the solution, either:
- choose Run Task > build from the Panel task dropdown, or
- from the command line run
dotnet build
- To run the solution, either:
- choose Run and Debug from the Activity Bar, then click Launch, or
- click F5, or
- from the command line run
cd Launcher/bin/Debug dotnet QuantConnect.Lean.Launcher.dll
Linux (Debian, Ubuntu)
- Install dotnet 6:
- Compile Lean Solution:
dotnet build QuantConnect.Lean.sln
- Run Lean:
cd Launcher/bin/Debug
dotnet QuantConnect.Lean.Launcher.dll
Windows
- Install Visual Studio
- Open
QuantConnect.Lean.sln
in Visual Studio - Build the solution by clicking Build Menu -> Build Solution (this should trigger the NuGet package restore)
- Press
F5
to run
Python Support
A full explanation of the Python installation process can be found in the Algorithm.Python project.
Local-Cloud Hybrid Development.
Seamlessly develop locally in your favorite development environment, with full autocomplete and debugging support to quickly and easily identify problems with your strategy. Please see the CLI Home for more information.
Issues and Feature Requests
Please submit bugs and feature requests as an issue to the Lean Repository. Before submitting an issue, please read the instructions to ensure it is not duplicated.
Mailing List
The mailing list for the project can be found on LEAN Forum. Please use this to ask for assistance with your installation and setup questions.
Contributors and Pull Requests
Contributions are warmly welcomed, but we ask you to read the existing code to see how it is formatted and commented on and ensure contributions match the existing style. All code submissions must include accompanying tests. Please see the contributor guidelines. All accepted pull requests will get a $50 cloud credit on QuantConnect. Once your pull request has been merged, write to us at support@quantconnect.com with a link to your PR to claim your free live trading. QC <3 Open Source.
A huge thank you to all our contributors!
Acknowledgements
The open sourcing of QuantConnect would not have been possible without the support of the Pioneers. The Pioneers formed the core 100 early adopters of QuantConnect who subscribed and allowed us to launch the project into open source.
Ryan H, Pravin B, Jimmie B, Nick C, Sam C, Mattias S, Michael H, Mark M, Madhan, Paul R, Nik M, Scott Y, BinaryExecutor.com, Tadas T, Matt B, Binumon P, Zyron, Mike O, TC, Luigi, Lester Z, Andreas H, Eugene K, Hugo P, Robert N, Christofer O, Ramesh L, Nicholas S, Jonathan E, Marc R, Raghav N, Marcus, Hakan D, Sergey M, Peter McE, Jim M, INTJCapital.com, Richard E, Dominik, John L, H. Orlandella, Stephen L, Risto K, E.Subasi, Peter W, Hui Z, Ross F, Archibald112, MooMooForex.com, Jae S, Eric S, Marco D, Jerome B, James B. Crocker, David Lypka, Edward T, Charlie Guse, Thomas D, Jordan I, Mark S, Bengt K, Marc D, Al C, Jan W, Ero C, Eranmn, Mitchell S, Helmuth V, Michael M, Jeremy P, PVS78, Ross D, Sergey K, John Grover, Fahiz Y, George L.Z., Craig E, Sean S, Brad G, Dennis H, Camila C, Egor U, David T, Cameron W, Napoleon Hernandez, Keeshen A, Daniel E, Daniel H, M.Patterson, Asen K, Virgil J, Balazs Trader, Stan L, Con L, Will D, Scott K, Barry K, Pawel D, S Ray, Richard C, Peter L, Thomas L., Wang H, Oliver Lee, Christian L..
Top Related Projects
Python client for Alpaca's trade API
Download market data from Yahoo! Finance's API
Qlib is an AI-oriented quantitative investment platform that aims to realize the potential, empower research, and create value using AI technologies in quantitative investment, from exploring ideas to implementing productions. Qlib supports diverse machine learning modeling paradigms. including supervised learning, market dynamics modeling, and RL.
An Algorithmic Trading Library for Crypto-Assets in Python
An open source reinforcement learning framework for training, evaluating, and deploying robust trading agents.
Investment Research for Everyone, Everywhere.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot