Securities

Key Concepts

Introduction

A security is an individual financial asset that you can trade on an exchange. LEAN models these unique assets with a Security object, which the AddEquityadd_equity, AddCryptoadd_crypto, and similar methods return. The Securitiessecurities property of the QCAlgorithm class is a dictionary where the keys are Symbol objects and the values are Security objects. The Securitiessecurities dictionary contains all of the securities that have been in the algorithm during its lifetime.

// Add the SPY.
private Symbol _symbol;
_symbol = AddEquity("SPY").symbol;
# Add the SPY.
self._symbol = self.add_equity("SPY").symbol

Price

To get the current price of a security, index the Securitiessecurities dictionary and then access the pricePrice member.

// Get the price of the security.
var price = Securities[_symbol].Price;
# Get the price of the security.
price = self.securities[self._symbol].price

Holdings

The holdingsHoldings property of a Security object contains information about the investment state and history of the security.

// Use the holdings object to get information on the asset position, such as the quantity and average price.
var holdings = Securities[_symbol].Holdings;
var quantity = holdings.Quantity;
# Use the holdings object to get information on the asset position, such as the quantity and average price.
holdings = self.securities[self._symbol].holdings
quantity = holdings.quantity

Alternatively, you can get the current holdings of a security with the Portfolioportfolio dictionary.

// Get the quantity of a security you hold through the Portfolio dictionary.
var holdings = Portfolio[_symbol];
var quantity = holdings.Quantity;
# Get the quantity of a security you hold through the portfolio dictionary.
holdings = self.portfolio[self._symbol]
quantity = holdings.quantity

Reality Models

Security objects contain references to the security level reality models. To customize the behavior of each security, configure its reality models.

Tradable Status

The IsTradableis_tradable property shows whether you can trade a security. The property value is true when the security is in the universe, even if the data starts at a later day. Indices, canonical Option securities, and continuous Futures contracts are not tradable. In live mode, custom data objects are also not tradable, even if the custom data represents a tradable asset.

// Check if the security is tradable.
var tradable = Securities[_symbol].IsTradable;
# Check if the security is tradable.
tradable = self.securities[self._symbol].is_tradable

Symbol Properties

The SymbolPropertiessymbol_properties property of a Security contains properties for that specific security, such as the lot size and the minimum price variation.

// Round orders to a brokerage's lot size and minimum price variation using the symbol_properties.
var symbolProperties = Securities[_symbol].SymbolProperties;
var lotSize = symbolProperties.LotSize;
var minimumPriceVariation = symbolProperties.MinimumPriceVariation;
# Round orders to a brokerage's lot size and minimum price variation using the symbol_properties.
symbol_properties = self.securities[self._symbol].symbol_properties
lot_size = symbol_properties.lot_size
minimum_price_variation = symbol_properties.minimum_price_variation

Market Hours

The Exchangeexchange property of a Security contains information about the exchange that lists the security. For example, the Exchange.Hoursexchange.hours property contains information on the trading days and hours.

// Using the exchange object, check if the exchange's regular trading hours are open at the given time.
var exchange = Securities[_symbol].Exchange;
var hours = exchange.Hours;
var isOpenNow = hours.isOpen(Time, extendedMarketHours: false);
var minimumPriceVariation = symbolProperties.MinimumPriceVariation;
# Using the exchange object, check if the exchange's regular trading hours are open at the given time.
exchange = self.securities[self._symbol].exchange
hours = exchange.hours
is_open_now = hours.is_open(self.time, extended_market_hours=False)

Custom Security Properties

You can add propertiesattributes to the Security object. For example, you can add an exponential moving average.

// Cast the Equity to a dynamic object to add an EMA indicator to it.
dynamic equity = AddEquity("SPY");
equity.ema = EMA(equity.Symbol, 10, Resolution.Daily);
# Add an EMA indicator to the SPY Equity object.
equity = self.add_equity("SPY")
equity.ema = self.ema(equity.symbol, 10, Resolution.DAILY)

This feature is helpful because you can get the Security object from the Securitiessecurities object.

// Get the SPY Equity object from Securities to get the EMA indicator.
var ema = (decimal)(Securities["SPY"] as dynamic).ema.Current.Value;
# Get the SPY Equity object from the securities object to get the EMA indicator.
ema = self.securities["SPY"].ema.current.value

To avoid casting to and from the dynamic type, you can use the Get<T> method to access the dynamic member and return the object with its type.

// Get the SPY Equity object from Securities to get the EMA indicator and its current value
var ema = Securities["SPY"].Get<ExponentialMovingAverage>("ema");   // The type of ema is ExponentialMovingAverage
var emaValue = ema.Current.Value;    // The type of emaValue is decimal

If the type or the member name is incorrect, the Get<T> method causes a runtime error.

Properties

The Security type has the following properties:

Examples

The following examples demonstrate some common practices for securities.

Example 1: Accessing Properties

The following example shows how to access various propeties of the Security object.

public class SecuritiesUsageAlgorithm : QCAlgorithm
{
    private Equity _spy;

    public override void Initialize()
    {
        SetStartDate(2023, 1, 1);
        SetEndDate(2023, 1, 2);
        
        _spy = AddEquity("SPY");
    }

    public override void OnData(Slice slice)
    {
        // OHLCV data.
        var price = _spy.Close;
        var volume = _spy.Volume;
        // Quote data.
        var quoteSize = _spy.BidSize;
        var quotePrice = _spy.AskPrice;
        // Symbol Properties.
        var lotSize = _spy.SymbolProperties.LotSize;
        // Fundamentals cached data.
        var peRatio = _spy.Fundamentals.ValuationRatios.PERatio;
        // Properties, e.g. is tradeble, is market open, leverage, ...
        var marketOpen = _spy.IsMarketOpen;
        var leverage = _spy.Leverage;
        // Models, e.g. margin model, buying power model, ...
        var marginModel = _spy.MarginModel;
        // Portfolio Holdings reference.
        var holding = _spy.Holdings;
    }
}
class SecuritiesUsageAlgorithm(QCAlgorithm):
    def initialize(self) -> None:
        self.set_start_date(2023, 1, 1)
        self.set_end_date(2023, 1, 2)

        self.spy = self.add_equity("SPY")

    def on_data(self, slice: Slice) -> None:
        # OHLCV data.
        price = self.spy.close
        volume = self.spy.volume
        # Quote data.
        quote_size = self.spy.bid_size
        quote_price = self.spy.ask_price
        # Symbol Properties.
        lot_size = self.spy.symbol_properties.lot_size
        # Fundamentals cached data.
        pe_ratio = self.spy.fundamentals.valuation_ratios.pe_ratio
        # Properties, e.g. is tradeble, is market open, leverage, ...
        market_open = self.spy.is_market_open
        leverage = self.spy.leverage
        # Models, e.g. margin model, buying power model, ...
        margin_model = self.spy.margin_model
        # Portfolio Holdings reference.
        holding = self.spy.holdings

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: