Zipline

Initialization

Initializing State

On QuantConnect, algorithm initialization behavior is equivalent to Quantopian's initialize method. Initialize is the method equivalent, and it is only ran once at the start of the algorithm. It is responsible for initially adding data to the algorithm, adding a universe, setting the brokerage, setting the algorithm's start and end date, etc.

The algorithm structure in QuantConnect differs from Quantopian's as well. On QuantConnect, we create a class that derives from QCAlgorithm and define our overrides/algorithm functionality there. An example of an algorithm with initialization is provided.

Quantopian

def initialize(context):
    # Adds AAPL sid to `context` for use later in `handle_data(...)`
    context.aapl = sid(24)

QuantConnect

class MyAlgorithm(QCAlgorithm):
    def initialize(self) -> None:
        # Adds minutely AAPL data to the algorithm
        self.aapl = self.add_equity("AAPL", Resolution.MINUTE)

On QuantConnect, the self parameter is the equivalent of the context parameter in Quantopian algorithms. You can use self to access algorithm resources, such as the Portfolio, Orders, Order Tickets, Securities, place orders in your algorithm, and much more.

You can read more about algorithm initialization at the Initializion documentation page.

Attaching Pipelines

The functional equivalent of Pipelines on QuantConnect are Universes. Universes can be used to dynamically select assets your algorithm wants to trade or request data from. To add a universe to your algorithm, you can call the AddUniverse() method and provide the required Coarse and Fine universe selection functions.

Coarse Universe selection is the first step of universe selection. It provides a means to filter data in a lightweight fashion before proceeding to Fine Universe selection. Coarse universe will allow you to filter assets based off top-level fundamental factors, such as Dollar Volume for the day, if a company has fundamental data, and market of the asset.

Fine Universe selection is the second step of universe selection. It provides fundamental data to your user-defined function, and can be used to filter in greater detail based on an asset's fundamental data, such as earnings, EPS, etc.

An example of coarse and fine universe selection to filter assets in our algorithm is provided. Adding universes can be used as an alternative to using AddEquityadd_equity if you prefer dynamic asset selection.

class MyUniverseAlgorithm(QCAlgorithm):
    def Initialize(self) -> None:
        self.SetStartDate(2020, 1, 1)
        self.SetEndDate(2020, 2, 1)

        self.UniverseSettings.Resolution = Resolution.Minute
        self.AddUniverse(self.CoarseSelectionFunction, self.FineSelectionFunction)

    def CoarseSelectionFunction(self, coarse: List[CoarseFundamental]) -> List[Symbol]:
        return [i.Symbol for i in coarse if i.DollarVolume > 500000 and i.HasFundamentalData]

    def FineSelectionFunction(self, fine: List[FineFundamental]) -> List[Symbol]:
        return [i.Symbol for i in fine if i.EarningReports.BasicEPS.OneMonth > 0]

You can configure universe settings by modifying the existing UniverseSettings attribute of the algorithm.

class MyUniverseAlgorithm(QCAlgorithm):
    def initialize(self) -> None:
        self.universe_settings.resolution = Resolution.MINUTE
        self.universe_settings.data_normalization_mode = DataNormalizationMode.ADJUSTED
        self.universe_settings.leverage = 1.0
        self.universe_settings.extended_market_hours = False

You can read more about universe selection at the Universe documentation page.

Scheduling Functions

Scheduled Events on QuantConnect are the equivalent of schedule_function() from Quantopian. Examples are provided comparing the Scheduled Events functionality between QuantConnect and Quantopian.

Quantopian

import quantopian.algorithm as algo

def my_scheduled_function(context, data):
    pass

def initialize(context):
    # Runs a function every day 60 minutes before U.S. Equities market close
    algo.schedule_function(
        func=my_scheduled_function,
        date_rule=algo.date_rules.every_day(),
        time_rule=algo.time_rules.market_close(minutes=60),
        calendar=algo.calendars.US_EQUITIES
    )

QuantConnect

class MyAlgorithm(QCAlgorithm):
    def my_scheduled_function(self):
        pass

    # Runs a function every day 60 minutes before SPY ETF's market close
    def initialize(self) -> None:
        self.schedule.on(
            self.date_rules.every_day(),
            self.time_rules.before_market_close("SPY", 60),
            self.my_scheduled_function
       )

You can read more about scheduled events at the Scheduled Events documentation page.

Setting Slippage and Commissions

QuantConnect supports applying slippage and commissions per individual security.

To add a slippage model to a security, we must set the SlippageModel property of the Security object to our model. A Security is returned when data is added to the algorithm. Examples of setting slippage in an algorithm is provided below for both Quantopian and QuantConnect.

Quantopian

import quantopian.algorithm as algorithm
from zipline.finance.slippage import FixedSlippage


    def initialize(context):
        # This will set slippage for all U.S. equities
        algorithm.set_slippage(us_equities=FixedSlippage(0.01))
    

QuantConnect

class MyAlgorithm(QCAlgorithm)
    def initialize(self) -> None:
        spy = self.add_equity("SPY", Resolution.MINUTE)
        # `ConstantSlippageModel` is the same as `FixedSlippage` on Quantopian.
        # This will set slippage only for the "SPY" security.
        spy.slippage_model = ConstantSlippageModel(0.01)

Commissions

To add a fee model (otherwise known as Commissions on Quantopian) to a security, we must set the FeeModel property of the Security object to our model. Examples are provided below for Quantopian and QuantConnect.

Quantopian

import quantopian.algorithm as algorithm
from zipline.finance.commission import PerShare


    def initialize(context):
        # Approximates Interactive Brokers' equities trading commissions.
        algorithm.set_commission(us_equities=Pershare(cost=0.0075))
    

QuantConnect

class MyAlgorithm(QCAlgorithm):
    def initialize(self) -> None:
       aapl = self.add_equity("AAPL", Resolution.MINUTE)
       spy = self.add_equity("SPY", Resolution.MINUTE)

       # Sets the fee model to the IB fee model, which simulates
       # the fees we would encounter in live trading.
       spy.fee_model = InteractiveBrokersFeeModel()

       # Sets the fee model to a constant fee model
       aapl.fee_model = ConstantFeeModel(0.01, "USD")

You can read more about Securities and their attributes at the Securities and Portfolio and Reality Modeling documentation pages.

Manual Asset Lookup

On QuantConnect, we provide the Symbol class to reference a security across time with a changing ticker. This is similar to Quantopian's symbol() function, which enables the same functionality.

When you add data to your algorithm, a Security object is returned. The Symbol is accessible from the Security as shown below.

class MyAlgorithm(QCAlgorithm):
    def initialize(self) -> None:
        self.set_start_date(2000, 1, 1)
        self.set_end_date(2020, 1, 1)
        # TWX will change to AOL when backtesting in the early 2000s, and will
        # change to TWX as the backtest advances past the date it was renamed.
        twx_security = self.add_equity("TWX", Resolution.MINUTE)
        twx_symbol = twx_security.symbol

To manually create a reference to an old equity, you can use the Symbol.Create() method, or the Symbol.CreateEquity() method.

You can read more about Symbols and Security Identifiers (SID) at the Security Identifiers documentation page.

You can also see our Videos. You can also get in touch with us via Discord.

Did you find this page helpful?

Contribute to the documentation: