In this thread, we are going to cover the differences between Quantopian and QuantConnect APIs.
Basic Algorithm
In QuantConnect, all algorithms must have an Initialize method to setup your strategy. Once setup most algorithms have OnData event handlers to process market data and make trading decisions:
# Quantopian
def initialize(context):
# Reference to AAPL
context.aapl = sid(24)
def handle_data(context, data):
# Position 100% of our portfolio to be long in AAPL
order_target_percent(context.aapl, 1.00)# QuantConnect
class MyAlgo(QCAlgorithm):
def Initialize(self):
# Reference to AAPL
self.aapl = self.AddEquity("AAPL")
def OnData(self, data):
# Position 100% of our portfolio to be long in AAPL
self.SetHoldings("AAPL", 1.00)
Please note that we must define a class with the QuantConnect API and it must inherit from QCAlgorithm.
self refers to the instance attributes of the algorithm class. It is used to access methods and members of QCAlgorithm like AddEquity in the example above.
Alexandre Catarino
Core Functions
An algorithm on QuantConnect has 2 core functions: Initialize and OnData. On Initialize is mandatory.
Initialize
The Initialize method is called to setup your strategy. Here you can request data, set starting cash or warm up periods. It requires self as an input, since we need to use methods from the instance to setup our strategy:
class MyAlgo(QCAlgorithm): def Initialize(self): self.SetCash(1000000) self.SetStartDate(2015,2,26) self.SetEndDate(2017,6,08) self.AddForex("EURUSD")
OnData
Requested data is passed into event handlers for you to use to make trading decisions.
It is called one every time new data is available. If you have subscribed to minute data only, it will be called avery minute, if you have subscribed to daily data only, it will be called every day, etc...
It requires self and data. data is an object that groups all data types together at a single moment in time in the OnData(self, data) handler. Slice is short for "time slice" - representing a slice of time and values of the data at that time:
class MyAlgo(QCAlgorithm): def OnData(self, data): #Access data in a Slice object: # 1. Grouped Properties: Ticks, Bars, Delistings, SymbolChangedEvents, Splits and Dividends bars = data.Bars; # e.g. bars["IBM"].Open delistings = data.Delistings # 2. Dynamic String / Symbol Indexer: bar = data["IBM"] # e.g. bar.Open - TradeBar properties OHLCV spyTickList = data["SPY"] # Tick assets return a list of Tick objects
Alexandre Catarino
Referencing Securities
In QuantConnect we can subscribe to different asset types with different resolution and different "markets". For instance, we can select forex data from FXCM or Oanda. Please checkout the docs, under Asset Classes, for more detailed information about data subscription.
While Quantopian relies on the sid method to robustly refer to a security, since tickers can change, in QuantConnect we create an ID for each symbol for the same effect. The unique security symbol is mapped to the ticker you used to subscribe them and you can use both:
class MyAlgo(QCAlgorithm): def Initialize(self): equity = self.AddEquity("BAC") self.bac = equity.Symbol print str(self.bac.ID) # prints NB R735QTJ8XC9X def OnData(self, data): print data[self.bac].Close == data["BAC"].Close # prints True
Alexandre Catarino
Ordering Securities
Algorithms can place an order through calling the appropriate method in the API. Going long is denoted with a ordering positive number, and short a negative one. LEAN does not support hedging (long and short at the same time).
Please checkout the docs, under Trading and Orders, for detailed information and a complete information.
In this post, we will focus on SetHoldings method which is equivalent to Quantopian's order_target_percent:
# Quantopian order_target_percent(sid(24), 0.50) order_target_percent(sid(24), -0.50) # QuantConnect self.SetHoldings("AAPL", 0.50) self.SetHoldings("AAPL", -0.50)
The quantity of shares used in SetHoldings is calculated by CalculateOrderQuantity method.
AMDQuant
Thanks for the tips. Can you advise why am having trouble scheduling an event in Python? I get a error. (I'm on my phone, hard to add details now).
AMDQuant
Please disregard my last question. I think I found what I need on this sample Algo.
... Link broken
Alexandre Catarino
The history() Function
In QuantConnect, Historical Data Requests are handled slightly different from Quantopian. While in Quantopian the history() function is a method from the data object that arrives in handle_data, QuantConnect's History method belongs to QCAlgorithm:
# Quantopain
# Get the 10-day trailing price history of AAPL in the form of a Series.
hist = data.history(sid(24), 'price', 10, '1d')
# Mean price over the last 10 days.
mean_price = hist.mean()
# QuantConnect
# Get the 10-day trailing bar history of AAPL in the form of list of bars
# Using the "symbol" method returns a list of tradebars.
hist = self.History("AAPL", 10, Resolution.Daily)
for bar in hist:
open = bar.Open
# Get the 10-day trailing bar history of AAPL in the form of pandas DataFrame
# Use a list of tickers to get back a pandas dataframe
hist = self.History(["AAPL"], 10, Resolution.Daily)
The following code snippets are working examples in each platform:
def initialize(context):
# AAPL, MSFT, SPY
context.security_list = [sid(24), sid(8554), sid(5061)]
def handle_data(context, data):
hist = data.history(context.security_list, 'volume', 10, '1m').mean()
print hist.mean()
class MyAlgo(QCAlgorithm):
def Initialize(self):
self.AddEquity("SPY")
self.AddEquity("BAC")
self.AddEquity("IBM")
self.security_list = ["SPY", "BAC", "IBM"]
def OnData(self, data):
hist = self.History(self.security_list, 10, Resolution.Minute)
self.Log(str(hist['volume'].mean()))
Alexandre Catarino
Scheduling Functions
Scheduled events allow you to trigger code to run at specific times of day. This happens regardless of your data events. The schedule API requires a date and time rule to specify when the event is fired:
# Quantopian
schedule_function(func=rebalance,
date_rules=date_rules.every_day(),
time_rules=time_rules.market_open(hours=1))
# QuantConnect
self.Schedule.On(self.DateRules.EveryDay("SPY"),
self.TimeRules.AfterMarketOpen(self.spy, 60),
Action(self.rebalance))
Unlike Quantopian, the func does not require a data object:
def rebalance(self):
self.Log("EveryDay.SPY 60 min after open: Fired at: {0}".format(self.Time))
At this point, we need to introduce another member of QCAlgorithm: Securities. This object have the information about all the subcribed securities and can be accessed anywhere in the algorithm, unlike the Slice object that arrives at OnData:
def rebalance(self):
spy = self.Securities["SPY"]
price = spy.Price
self.Log("EveryDay.SPY 60 min after open: Fired at: {0}".format(self.Time))
The following working example takes a long position in SPY at the start of the week, and closes out the position at 3:30pm on the last day of the week:
def initialize(context):
context.spy = sid(8554)
schedule_function(open_positions, date_rules.week_start(), time_rules.market_open())
schedule_function(close_positions, date_rules.week_end(), time_rules.market_close(minutes=30))
def open_positions(context, data):
order_target_percent(context.spy, 0.10)
def close_positions(context, data):
order_target_percent(context.spy, 0)
class MyAlgo(QCAlgorithm):
def Initialize(self):
AddEquity("SPY")
self.Schedule.On(self.DateRules.Every(DayOfWeek.Monday, DayOfWeek.Monday), \
self.TimeRules.AfterMarketOpen(self.spy), \
Action(self.open_positions))
self.Schedule.On(self.DateRules.Every(DayOfWeek.Friday, DayOfWeek.Friday), \
self.TimeRules.BeforeMarketClose(self.spy, 30), \
Action(self.close_positions))
def open_positions(self):
self.SetHoldings("SPY", 0.10)
def close_positions(self):
self.Liquidate("SPY")
From complete Date and Time rules, please checkout these reference tables. Since the equivalent date rule for week start and week end are missing, we can look into implementing it.
Alexandre Catarino
Managing Your Portfolio
Another key member in the QCAlgorithm is Portfolio. While Securities keep information about the securities that have been subscribed, Portfolio provides easy access to the holding properties. In order to know whether a security has an open position, we can look for the Invested/HoldStock member of SecurityHolding (Portfolio is an enhanced dictionary wihere the keys are the symbols and the value are SecurityHolding object).
Here is a simple example on how to close all open positions:
self.Liquidate()
Yes, that is it. The Liquidate method, without any paramenter, will close all open positions.
Let now see how this is done in Quantopian and similarly in QuantConnect:
# Quantopian for security in context.portfolio.positions: order_target_percent(security, 0) # QuantConnect for security in self.Portfolio.Values: if security.Invested: self.Liquidate(security.Symbol)
Alexandre Catarino
Plotting Variables
We provide a powerful charting API which can be build many chart types. At its simplest it can be used with a single line of code:
self.Plot("Series Name", value)
While Quantopian only allows one chart with some series, we allow many charts with some series two, since we can create more than one chart, add series into it and, finally, add the charts in the algorithm usinf AddChart method:
# In your initialize method: # Note - use single quotation marks: ' instead of double " # Chart - Master Container for the Chart: stockPlot = Chart('Trade Plot') # On the Trade Plotter Chart we want 3 series: trades and price: stockPlot.AddSeries(Series('Buy', SeriesType.Scatter, 0)) stockPlot.AddSeries(Series('Sell', SeriesType.Scatter, 0)) stockPlot.AddSeries(Series('Price', SeriesType.Line, 0)) self.AddChart(stockPlot) // Later in your OnData(self, data): self.Plot('Trade Plot', 'Price', self.lastPrice)
Please checkout fully working backtest below.
Alexandre Catarino
Slippage and Commission
At the moment, it is not possible to customize slippage and commission in Python algorithm, despite the fact we can do it in C# algorithms. However, commission are modeled, by default, with the specifications from the brokerages.
AMDQuant
Thank you for all you've written here so far, Alexandre. Regarding scheduling functions/events to run, is it possible to schedule a function/event before market open? I've tried with
self.Schedule.On(self.DateRules.EveryDay(), self.TimeRules.At(9, 0), Action(self.BeforeTradingStart))
followed with
def BeforeTradingStart(self): # This is where we will run daily code checks to ensure lists are synced with positions. # additionally, will determine how many days a position has been held in Portfolio self.Log("BTS")
my log keeps showing:
2017-02-22 09:31:00 :BTS
Alexandre Catarino
Managing Orders
In QCAlgorithm, all orders are recorded in the Transactions object. This object have several methods to select orders under any criteria:
# Cancel all open orders from SPY
cancelledOrders = self.Transactions.CancelOpenOrders("SPY")
# Cancel order #10
cancelledOrder = self.Transactions.CancelOrder(10)
# Get open orders
openOrders = self.Transactions.GetOpenOrders()
# Get open orders from SPY
openOrders = self.Transactions.GetOpenOrders("SPY")
# Get open order #10
openOrder = self.Transactions.GetOrderById(10)
# Get all orders
orders = self.Transactions.GetOrders()
# Get order ticket #10
orderTicket = self.Transactions.GetOrderTicket(10)
# Get all orders tickets
openOrderTickets = self.Transactions.GetOrderTickets()
Quantopian's API has three methods for managing existing orders: cancel_order(order), get_open_orders(sid) and get_order(order). For this thread, let's compare the methods for getting open orders in a working example:
# Quantopian
def initialize(context):
# Relatively illiquid stock.
context.xtl = sid(40768)
def handle_data(context, data):
# Get all open orders.
open_orders = get_open_orders()
if context.xtl not in open_orders and data.can_trade(context.xtl):
order_target_percent(context.xtl, 1.0)
# QuantConnect
class MyAlgo(QCAlgorithm):
def Initialize(self):
# Relatively illiquid stock.
self.AddEquity("XTL")
def OnData(self, data):
# Get all open orders.
open_orders = self.Transactions.GetOpenOrders()
if len(open_orders) == 0 and not Portfolio.Invested:
self.SetHoldings("XTL", 1)
Yan Xiaowei
Demo Algorithm 1; Simple SMA Weekly Mean-reversion Strategy
This algorithm calculates 30-day SMA and 10-day SMA for each stock and it's rebalanced weekly. Every Monday if the 10-day SMA is higher than the 30-day SMA, I short the stock, and vice versa.
Tom Lin
Thanks Alexandre! Really appreciate the quality of your guide with parallel examples between the two IDE's
If it's possible in QC, could you cover the equivalent implementation of Quantopian's Pipeline API for filtering down a large universe of securities based on custom factors and fundamental data?
Jonathan Gomez
import numpy as np class TestAlgo(QCAlgorithm): def Initialize(self): # Backetst Info self.SetCash(25000) self.SetStartDate(2009,1,1) self.SetEndDate(2017,1,1) # Initialize Assets self.stocks = ["SPY","TLT"] #Schedule self.Schedule.On(self.DateRules.MonthStart(), self.TimeRules.AfterMarketOpen(0),Action(self.trade)) def trade(self): print "Test"
So if someone could help me out. If I am understanding this right, I should get a print on logs at the start of everymonth right?
Jared Broad
Jonathan Gomez - Almost. Because we are multi-asset each asset has a different start of month. So for that method you need to remember to 1) add the assets to the algorithm, and 2) specify start of month for which security. See this example algorithm attached.
self.Schedule.On(self.DateRules.MonthStart("SPY"), self.TimeRules.AfterMarketOpen("SPY"), Action(self.RebalancingCode))
The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
Vladimir Prelovac
Thanks for starting this thread, very informative.
Can you give an example of an equivalent of Quantopian pipeline with fundamentals data. Like for example selecting universe of top decile stocks by daily volume that had positive earnings in last quarter?
Does Quantconnect have any limits on account sizes connected to IB?
Alexandre Catarino
Data Normalization Mode
By default, equity prices are adjusted in QuantConnect for all resolutions.
If we want Raw prices, we need to set the data normalization mode for each equity:
equity = self.AddEquity("SPY", Resolution.Minute) equity.SetDataNormalizationMode(DataNormalizationMode.Raw)
Up next: Universe Selection (QuantConnect's equivalent to Quantopian's Pipeline)
Alexandre Catarino
Dynamic Security Selection
Pipeline is the name Quantopian has choosen for the dynamic security selection feature. In QuantConnect, we call it Universe Selection. Before we show how the differences, here is how this feature is used in each platform:
# Quantopian
from quantopian.pipeline import Pipeline
from quantopian.algorithm import attach_pipeline, pipeline_output
def initialize(context):
my_pipe = make_pipeline()
attach_pipeline(my_pipe, 'my_pipeline')
def make_pipeline():
return Pipeline()
def before_trading_start(context, data):
# Store our pipeline output DataFrame in context.
context.output = pipeline_output('my_pipeline')
# QuantConnect
from System.Collections.Generic import List
from QuantConnect.Data.UniverseSelection import *
class MyAlgorithm(QCAlgorithm):
def Initialize(self):
self.AddUniverse(self.CoarseSelectionFunction)
def CoarseSelectionFunction(self, coarse):
sortedByDollarVolume = sorted(coarse, key=lambda x: x.DollarVolume, reverse=True)
list = List[Symbol]()
for c in sortedByDollarVolume[:5]: list.Add(c.Symbol)
return list
# this event fires whenever we have changes to our universe
def OnSecuritiesChanged(self, changes):
self.changes = changes
In QuantConnect, the AddUniverse method is used to pass a function that selects the securities from a pre-defined universe passed as 'coarse'. The coarse object is a CoarseFundamental type, please checkout the docs for more information. Once the universe members change, the OnSecuritiesChanged event handler is triggered. We can make trading decisions and place orders in this method:
def OnSecuritiesChanged(self, changes):   # liquidate removed securities   for security in changes.RemovedSecurities:     if security.Invested:       self.Liquidate(security.Symbol)   # we want 20% allocation in each security in our universe   for security in changes.AddedSecurities:     self.SetHoldings(security.Symbol, 0.2)   # Store our changes output in self   self.changes = changes
Pipeline relies heavily on pandas Dataframe and has a lot of build-in factors (based on indicators) that can be used to define filters and classifiers. In QuantConnect, we need to combine our indicators to select the securities.
Alexandre Catarino
Dynamic Security Selection - Fundamental Data
At the moment, we can only get fundamental data for universe selection. To access it, we need to add a function as a second parameter in AddUniverse that will receive fine fundamental data from the universe that was pre-filtered by Coarse Fundamental:
# In Initialize self.AddUniverse(self.CoarseSelectionFunction, self.FineSelectionFunction) # sort the data by P/E ratio and take the top 'NumberOfSymbolsFine' def FineSelectionFunction(self, fine): # sort descending by P/E ratio sortedByPeRatio = sorted(fine, key=lambda x: x.ValuationRatios.PERatio, reverse=True) # take the top entries from our sorted collection topFine = sortedByPeRatio[:self.__numberOfSymbolsFine] list = List[Symbol]() for x in topFine: list.Add(x.Symbol) return list
Please checkout a fully working example below.
Alexandre Catarino
The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
To unlock posting to the community forums please complete at least 30% of Boot Camp.
You can continue your Boot Camp training progress from the terminal. We hope to see you in the community soon!