How to Build and Deploy Trading Strategies with Alpaca and QuantConnect
Discover how to build, backtest, and deploy trading strategies with Alpaca and QuantConnect's integration in this easy-to-follow guide.
Our partnership with QuantConnect offers a seamless way to build and deploy trading strategies through Alpaca. In this guide, we’ll walk you through setting up your QuantConnect account, building and deploying strategies while making the most of the integration with Alpaca.
What is QuantConnect?
Founded in 2012, QuantConnect has built an online algorithmic trading research and trading platform where you can build strategies by leveraging its Python API. QuantConnect serves more than 300,000 members and executes $5B in notional trading volumes each month.
Traditionally, quants and engineers face the painstaking process of building quantitative trading architectures. This process can take months or even years, involving the writing of data processing systems, live trading data feeds, and trade routers — expensive engineering that adds no direct value to your trading strategy.
QuantConnect allows you to move from idea to live trading within minutes. All the core infrastructure is implemented in a best-practices, highly configurable environment.
What the Alpaca and QuantConnect Integration Offers
The integration brings commission-free trading to three asset classes supported by QuantConnect: stock, equity options, and ETFs. This enables Alpaca users to harness institutional-caliber tooling for their personal trading.
Additionally, five order types are supported for US Equities: market, limit, stop market, stop limit, and trailing stop orders. For more information, see the Alpaca-QuantConnect documentation.
Create A Free Account
Getting started is simple. Head over to QuantConnect Signup to register for a free account. No credit card is required, and QuantConnect offers a generous free tier.
Building Your Strategy
To build and live trade your first strategy, follow the steps below:
- Click “Create New Algorithm” from the home page to start a new Python project.
- A list of hundreds of 50 template algorithms will appear. As you become familiar with QuantConnect, we recommend exploring these so you can improve your quant skillset. For now, just select “Use Default Template”.
- This opens a VSCode environment to build your strategy. All strategies start with requesting data and then handling the data you've requested. QuantConnect provides an interactive Juptyer notebook environment and an accurate point-in-time backtester for a fee and slippage-adjusted research. Alpaca users can eliminate fees by setting the brokerage model as shown:
from AlgorithmImports import *
class GeekyTanWolf(QCAlgorithm):
def initialize(self):
self.set_start_date(2023, 2, 7)
self.set_cash(100000)
self.add_equity("AAPL", Resolution.MINUTE)
# Disable fee modeling with Alpaca Brokerage Model
self.set_brokerage_model(BrokerageName.ALPACA)
def on_data(self, data: Slice):
if not self.portfolio.invested:
self.set_holdings("AAPL", 0.33)
- Next, we'll run a backtest and review the results. Click the orange-play ▶️ icon in the top right corner to launch your backtest. This runs a detailed intraday backtest using your project code.
- After a few seconds, your backtest will launch and stream the results to your browser. You can then zoom into the results and analyze your algorithm trades and activity as needed. Congratulations on running your first backtest!
There are thousands of API methods to make your life easier. From here, the world is your oyster. You can design and test ideas until you're comfortable deploying them in a realistic simulation environment. QuantConnect provides 150+ demonstration strategies, many of which are running live in a real-time portal to view their performance.
The 15-line example below scans 8,000 stocks each week, automatically selects the top 10 by PE ratio, allocates capital evenly among the assets, and automates a 5% trailing stop loss:
from AlgorithmImports import *
class CryingBrownScorpion(QCAlgorithm):
def initialize(self):
# Every week scan our universe
self.universe_settings.schedule.on(self.date_rules.week_start())
self.add_universe_selection(FundamentalUniverseSelectionModel(self.select))
# Invest in all assets equally, with 5% trailing stoploss
self.add_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(7)))
self.set_portfolio_construction( \
EqualWeightingPortfolioConstructionModel(timedelta(7)))
self.add_risk_management(TrailingStopRiskManagementModel(0.05))
def select(self, fundamental: List[Fundamental]):
# Screen on 900 fundamental data points per asset
filtered = [f for f in fundamental if not np.isnan(f.valuation_ratios.pe_ratio)]
sorted_by_pe_ratio = sorted(filtered, key=lambda f: f.valuation_ratios.pe_ratio, reverse=True)
return [f.symbol for f in sorted_by_pe_ratio[:10]]
Deploying Live Algorithm
Once your strategy is ready, we can deploy our strategy live or paper environment with Alpaca and QuantConnect using the following steps:
- Click the lightning bolt icon next to the Backtest button to open the Live Deployment Wizard. This opens a form to authenticate and deploy your algorithm.
- Select Alpaca from the list of broker connectivity to show the deployment options. From here, you can select your environment, either paper or live. Note that you will need a paid account on QuantConnect with a Researcher seat + 1 live node to proceed with the next steps.
- Click the checkbox to agree to Alpaca’s terms and conditions, then click the large blue “Authenticate” button to process your OAuth login with Alpaca. This will open a new tab for you to log in to Alpaca and give QuantConnect permission to use your account. Click “Allow” to proceed.
- Return to the QuantConnect Algorithm Lab and click "Deploy" to launch your strategy.
With that, you’ve just deployed your trading strategy with Alpaca. This will typically take 30-60 seconds to go live. Behind the scenes, QuantConnect is spinning up your server and installing your algorithm into their live trading environment. The interface below will appear after a few minutes.
The Alpaca and QuantConnect integration offers a streamlined workflow to bring your trading strategies to life. By leveraging QuantConnect's robust algorithmic trading tools and Alpaca’s commission-free trading, you can efficiently develop, test, and deploy your strategies across multiple asset classes.
Get started today by setting up your account, building your first algorithm, and deploying it live.
Happy trading!
Options trading is not suitable for all investors due to its inherent high risk, which can potentially result in significant losses. Please read Characteristics and Risks of Standardized Options before investing in options.
Alpaca Securities LLC and QuantConnect are not affiliated, and neither are responsible for the liabilities of the other.
Past hypothetical backtest results do not guarantee future returns, and actual results may vary from the analysis.
The Paper Trading API is offered by AlpacaDB, Inc. and does not require real money or permit a user to transact in real securities in the market. Providing use of the Paper Trading API is not an offer or solicitation to buy or sell securities, securities derivative or futures products of any kind, or any type of trading or investment advice, recommendation or strategy, given or in any manner endorsed by AlpacaDB, Inc. or any AlpacaDB, Inc. affiliate and the information made available through the Paper Trading API is not an offer or solicitation of any kind in any jurisdiction where AlpacaDB, Inc. or any AlpacaDB, Inc. affiliate (collectively, “Alpaca”) is not authorized to do business.
All investments involve risk, and the past performance of a security, or financial product does not guarantee future results or returns. There is no guarantee that any investment strategy will achieve its objectives. Please note that diversification does not assure a profit, or protect against loss. There is always the potential of losing money when you invest in securities, or other financial products. Investors should consider their investment objectives and risks carefully before investing.
Securities brokerage services are provided by Alpaca Securities LLC ("Alpaca Securities"), member FINRA/SIPC, a wholly-owned subsidiary of AlpacaDB, Inc. Technology and services are offered by AlpacaDB, Inc.
This is not an offer, solicitation of an offer, or advice to buy or sell securities or open a brokerage account in any jurisdiction where Alpaca Securities are not registered or licensed, as applicable.
The content article is for general information only and is believed to be accurate as of posting date but may be subject to change. Alpaca does not provide investment, tax, or legal advice. Please consult your own independent advisor as to any investment, tax, or legal statements made herein.