Writing Algorithms

Initialization

Introduction

The Initialize method is the entry point of your algorithm where you define a series of settings, including security subscriptions, starting cash balances, and warm-up periods. LEAN only calls the Initialize method one time, at the start of your algorithm.

Set Dates

To set the date range of backtests, call the SetStartDate and SetEndDate methods. By default, the end date is yesterday. In live trading, LEAN ignores the start and end dates.

SetStartDate(2013, 1, 5);                  // Set start date to January 5, 2013
SetEndDate(2015, 1, 5);                    // Set end date to January 5, 2015
SetEndDate(DateTime.Now.Date.AddDays(-7)); // Set end date to last week
self.SetStartDate(2013, 1, 5)                  # Set start date to January 5, 2013
self.SetEndDate(2015, 1, 5)                    # Set end date to January 5, 2015
self.SetEndDate(datetime.now() - timedelta(7)) # Set end date to last week

Set Account Currency

The algorithm equity curve, benchmark, and performance statistics are denominated in the account currency. To set the account currency, call the SetAccountCurrency method. By default, the account currency is USD. If you call the SetAccountCurrency method, you must call it before you call the SetCash method.

SetAccountCurrency("BTC");
self.SetAccountCurrency("BTC")

Set Cash

To set your starting cash in backtests, call the SetCash method. By default, your starting cash is $100,000 USD. In live trading, LEAN ignores the SetCash method and uses the cash balances in your brokerage account instead.

SetCash(100000);       // Set the quantity of the account currency to 100,000
SetCash("BTC", 10);    // Set the Bitcoin quantity to 10
SetCash("EUR", 10000); // Set the EUR quantity to 10,000
self.SetCash(100000)       # Set the quantity of the account currency to 100,000
self.SetCash("BTC", 10)    # Set the Bitcoin quantity to 10
self.SetCash("EUR", 10000) # Set the EUR quantity to 10,000

Set Brokerage and Cash Model

We model your algorithm with margin modeling by default, but you can select a cash account type. Cash accounts don't allow leveraged trading, whereas Margin accounts can support leverage on your account value. To set your brokerage and account type, call the SetBrokerageModel method. For more information about each brokerage and the account types they support, see the brokerage integration documentation. For more information about the reality models that the brokerage models set, see Brokerages.

SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Margin);
self.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Cash)

The AccountType enumeration has the following members:

Set Universe Settings

The universe settings of your algorithm configure some properties of the universe constituents. The following table describes the properties of the UniverseSettings object:

PropertyData TypeDescriptionDefault Value
ExtendedMarketHoursboolShould assets also feed extended market hours?falseFalse
FillForwardboolShould asset data fill forward?trueTrue
MinimumTimeInUniverseTimeSpantimedeltaWhat's the minimum time assets should be in the universe?TimeSpan.FromDays(1)timedelta(1)
ResolutionResolutionWhat resolution should assets use?Resolution.Minute
ContractDepthOffsetintWhat offset from the current front month should be used for continuous Future contracts? 0 uses the front month and 1 uses the back month contract. This setting is only available for Future assets.0
DataMappingModeDataMappingModeHow should continuous Future contracts be mapped? This setting is only available for Future assets.DataMappingMode.OpenInterest
DataNormalizationModeDataNormalizationModeHow should historical prices be adjusted? This setting is only available for Equity and Futures assets.DataNormalizationMode.Adjusted
LeveragedecimalfloatWhat leverage should assets use in the universe? This setting is not available for derivative assets.Security.NullLeverage

To set the UniverseSettings, update the preceding properties in the Initialize method before you add the universe. These settings are globals, so they apply to all universes you create.

// Request second resolution data. This will be slow!
UniverseSettings.Resolution = Resolution.Second;
AddUniverse(MyCoarseFilterFunction);
# Request second resolution data. This will be slow!
self.UniverseSettings.Resolution = Resolution.Second
self.AddUniverse(self.MyCoarseFilterFunction)

Set Security Initializer

Instead of configuring global universe settings, you can individually configure the settings of each security in the universe with a security initializer. Security initializers let you apply any security-level reality model or special data requests on a per-security basis. To set the security initializer, in the Initialize method, call the SetSecurityInitializer method and then define the security initializer.

//In Initialize
SetSecurityInitializer(CustomSecurityInitializer);

private void CustomSecurityInitializer(Security security)
{
    // Disable trading fees
    security.SetFeeModel(new ConstantFeeModel(0, "USD"));
}
#In Initialize
self.SetSecurityInitializer(self.CustomSecurityInitializer)

def CustomSecurityInitializer(self, security: Security) -> None:
    # Disable trading fees
    security.SetFeeModel(ConstantFeeModel(0, "USD"))

For simple requests, you can use the functional implementation of the security initializer. This style lets you configure the security object with one line of code.

SetSecurityInitializer(security => security.SetFeeModel(new ConstantFeeModel(0, "USD")));
self.SetSecurityInitializer(lambda security: security.SetFeeModel(ConstantFeeModel(0, "USD")))

In some cases, you may want to trade a security in the same time loop that you create the security subscription. To avoid errors, use a security initializer to set the market price of each security to the last known price.

var seeder = new FuncSecuritySeeder(GetLastKnownPrices);
SetSecurityInitializer(security => seeder.SeedSecurity(security));
seeder = FuncSecuritySeeder(self.GetLastKnownPrices)
self.SetSecurityInitializer(lambda security: seeder.SeedSecurity(security))

If you call the SetSecurityInitializer method, it overwrites the default security initializer. The default security initializer uses the security-level reality models of the brokerage model to set the following reality models of each security:

The default security initializer also sets the leverage of each security and intializes each security with a seeder function. To extend upon the default security initializer instead of overwriting it, create a custom BrokerageModelSecurityInitializer.

// In Initialize
SetSecurityInitializer(new MySecurityInitializer(BrokerageModel, new FuncSecuritySeeder(GetLastKnownPrices)));

class MySecurityInitializer : BrokerageModelSecurityInitializer
{
    public MySecurityInitializer(IBrokerageModel brokerageModel, ISecuritySeeder securitySeeder)
        : base(brokerageModel, securitySeeder) {}
    
    public override void Initialize(Security security)
    {
        // First, call the superclass definition
        // This method sets the reality models of each security using the default reality models of the brokerage model
        base.Initialize(security);

        // Next, overwrite some of the reality models
        security.SetFeeModel(new ConstantFeeModel(0, "USD"));
    }
}
# In Initialize
self.SetSecurityInitializer(MySecurityInitializer(self.BrokerageModel, FuncSecuritySeeder(self.GetLastKnownPrices)))


class MySecurityInitializer(BrokerageModelSecurityInitializer):

    def __init__(self, brokerage_model: IBrokerageModel, security_seeder: ISecuritySeeder) -> None:
        super().__init__(brokerage_model, security_seeder)

    def Initialize(self, security: Security) -> None:
        # First, call the superclass definition
        # This method sets the reality models of each security using the default reality models of the brokerage model
        super().Initialize(security)

        # Next, overwrite some of the reality models
        security.SetFeeModel(ConstantFeeModel(0, "USD"))

Add Data

You can subscribe to asset, fundamental, alternative, and custom data. The Dataset Market provides 40T of data that you can easily import into your algorithms.

Asset Data

To subscribe to asset data, call one of the asset subscription methods like AddEquity or AddForex. Each asset class has its own method to create subscriptions. For more information about how to create subscriptions for each asset class, see Asset Classes.

AddEquity("AAPL"); // Add Apple 1 minute bars (minute by default)
AddForex("EURUSD", Resolution.Second); // Add EURUSD 1 second bars
self.AddEquity("SPY")  # Add Apple 1 minute bars (minute by default)
self.AddForex("EURUSD", Resolution.Second) # Add EURUSD 1 second bars

In live trading, you define the securities you want, but LEAN also gets the securities in your live portfolio and sets their resolution to the lowest resolution of the subscriptions you made. For example, if you create subscriptions in your algorithm for securities with Second, Minute, and Hour resolutions, the assets in your live portfolio are given a resolution of Second.

Alternative Data

To add alternative datasets to an algorithm, call the AddData method. For full examples, in the Datasets chapter, select a dataset and see the Requesting Data section.

Custom Data

To add custom data to an algorithm, call the AddData method. For more information about custom data, see Importing Data.

Limitations

There is no official limit to how much data you can add to an algorithm, but there are practical resource limitations. Each security subscription requires about 5MB of RAM, so larger machines let you run algorithms with bigger universes. For more information about our cloud nodes, see Resources.

Set Indicators and Consolidators

You can create and warm-up indicators in the Initialize method.

private Symbol _symbol;
private SimpleMovingAverage _sma;

_symbol = AddEquity("SPY").Symbol;
_sma = SMA(_symbol, 20);
WarmUpIndicator(_symbol, _sma);
self.symbol = self.AddEquity("SPY").Symbol
self.sma = self.SMA(self.symbol, 20)
self.WarmUpIndicator(self.symbol, self.sma)

Set Algorithm Settings

The following table describes the AlgorithmSettings properties:

PropertyData TypeDescriptionDefault Value
DataSubscriptionLimitintThe maximum number of concurrent market data subscriptions available.int.MaxValue
FreePortfolioValuedecimalfloatThe buying power buffer value.250
FreePortfolioValuePercentage decimalfloatThe buying power buffer percentage value.0.0025
LiquidateEnabled boolA flag to enable and disable the Liquidate method.trueTrue
MaxAbsolutePortfolioTargetPercentagedecimalfloatThe absolute maximum valid total portfolio value target percentage.1000000000
MinAbsolutePortfolioTargetPercentage decimalfloatThe absolute minimum valid total portfolio value target percentage.0.0000000001
MinimumOrderMarginPortfolioPercentage decimalfloatThe minimum order margin portfolio percentage to ignore bad orders and orders with small sizes.
0
RebalancePortfolioOnInsightChanges bool?bool/NoneTypeRebalance the portfolio when you emit new insights or when insights expire.trueTrue
RebalancePortfolioOnSecurityChangesbool?bool/NoneTypeRebalance the portfolio when your universe changes.trueTrue
StalePriceTimeSpanTimeSpantimedeltaThe minimum time span elapsed to consider a market fill price as staleTime.OneHourtimedelta(hours=1)
WarmUpResolutionResolution?Resolution/NoneTypeThe resolution to use during the warm-up periodnullNone

To change the AlgorithmSettings, update some of the preceding properties.

Settings.RebalancePortfolioOnSecurityChanges = false;
self.Settings.RebalancePortfolioOnSecurityChanges = False

To successfully update the FreePortfolioValue, you must update it after the Initialize method.

Set Benchmark

The benchmark performance is input to calculate several statistics on your algorithm, including alpha and beta. To set a benchmark for your algorithm, call the SetBenchmark method. You can set the benchmark to a security, a constant value, or a value from a custom data source. If you don't set a brokerage model, the default benchmark is SPY. If you set a brokerage model, the model defines the default benchmark.

// Set the benchmark to IBM
SetBenchmark("IBM");

// Set the benchmark to a constant value of 0
SetBenchmark(x => 0);

// Set the benchmark to a value from a custom data source
var symbol = AddData<CustomData>("CustomData", Resolution.Hour).Symbol;
SetBenchmark(symbol);
# Set the benchmark to IBM
self.SetBenchmark("IBM")

# Set the benchmark to a constant value of 0
self.SetBenchmark(lambda x: 0)

# Set the benchmark to a value from a custom data source
self.symbol = self.AddData(CustomData, "CustomData", Resolution.Hour).Symbol
self.SetBenchmark(self.symbol)

If you pass a ticker to the SetBenchmark method, LEAN checks if you have a subscription for it. If you have a subscription for it, LEAN uses the security subscription. If you don't have a subscription for it, LEAN creates a US Equity subscription with the ticker. Since the ticker you pass may not reference a US Equity, we recommend you subscribe to the benchmark security before you call the SetBenchmark method.

Set Time Zone

LEAN supports international trading across multiple time zones and markets, so it needs a reference time zone for the algorithm to set the Time. The default time zone is Eastern Time (ET), which is UTC-4 in summer and UTC-5 in winter. To set a different time zone, call the SetTimeZone method. This method accepts either a string following the IANA Time Zone database convention or a NodaTime.DateTimeZone object. If you pass a string, the method converts it to a NodaTime.DateTimeZone object. The TimeZones class provides the following helper attributes to create NodaTime.DateTimeZone objects:

SetTimeZone("Europe/London");
SetTimeZone(NodaTime.DateTimeZone.Utc);
SetTimeZone(TimeZones.Chicago);
self.SetTimeZone("Europe/London")
self.SetTimeZone(NodaTime.DateTimeZone.Utc)
self.SetTimeZone(TimeZones.Chicago)

The algorithm time zone may be different from the data time zone. If the time zones are different, it might appear like there is a lag between the algorithm time and the first bar of a history request, but this is just the difference in time zone. All the data is internally synchronized in Coordinated Universal Time (UTC) and arrives in the same Slice object. A slice is a sliver of time with all the data available for this moment.

To keep trades easy to compare between asset classes, we mark all orders in UTC time.

Set Warm Up Period

You may need some historical data at the start of your algorithm to prime technical indicators or populate historical data arrays. The warm-up period pumps data into your algorithm from before the start date. To set a warm-up period, call the SetWarmUp method.

// Wind time back 7 days from the start date
SetWarmUp(TimeSpan.FromDays(7));

// Feed in 100 trading days worth of data before the start date
SetWarmUp(100, Resolution.Daily);

// If you don't provide a resolution argument, it uses the lowest resolution in your subscriptions
SetWarmUp(100);
# Wind time back 7 days from the start date
self.SetWarmUp(timedelta(7))

# Feed in 100 trading days worth of data before the start date
self.SetWarmUp(100, Resolution.Daily)

# If you don't provide a resolution argument, it uses the lowest resolution in your subscriptions
self.SetWarmUp(100)

Post Initialization

After the Initialize method, the PostInitialize method performs post-initialization routines, so don't override it. To be notified when the algorithm is ready to begin trading, define an OnWarmUpFinished method. This method executes even if you don't set a warm-up period.

public override void OnWarmUpFinished()
{
    Log("Algorithm Ready");
}
def OnWarmUpFinished(self) -> None:
    self.Log("Algorithm Ready")

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: