Writing Algorithms
Initialization
Set Dates
To set the date range of backtests, call the SetStartDate
and SetEndDate
methods. The dates you provide are based in the algorithm time zone. By default, the end date is yesterday, one millisecond before midnight. 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 and your starting cash, call the SetAccountCurrency
method. By default, the account currency is USD and your starting cash is $100,000. If you call the SetAccountCurrency
method, you must call it before you call the SetCash
method or add data. If you call the SetAccountCurrency
method more than once, only the first call takes effect.
SetAccountCurrency("BTC"); // Set account currency to Bitcoin and its quantity to 100,000 BTC SetAccountCurrency("INR"); // Set account currency to Indian Rupees and its quantity to 100,000 INR SetAccountCurrency("BTC", 10); // Set account currency to Bitcoin and its quantity to 10 BTC
self.SetAccountCurrency("BTC") # Set account currency to Bitcoin and its quantity to 100,000 BTC self.SetAccountCurrency("INR") # Set account currency to Indian Rupees and its quantity to 100,000 INR self.SetAccountCurrency("BTC", 10); // Set account currency to Bitcoin and its quantity to 10 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 Supported Models.
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:
Property: |
Property: |
Property: |
Property: |
Property: |
Property: |
Property: |
Property: |
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. The GetLastKnownPrices
method seeds the security price by gathering the security data over the last 3 days. If there is no data during this period, the security price remains at 0.
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))); // Outside of the algorithm class 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))) # Outside of the algorithm class 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"))
To set a seeder function without overwriting the reality models of the brokerage, use the standard BrokerageModelSecurityInitializer
.
SetSecurityInitializer(new BrokerageModelSecurityInitializer(BrokerageModel, new FuncSecuritySeeder(GetLastKnownPrices)));
self.SetSecurityInitializer(BrokerageModelSecurityInitializer(self.BrokerageModel, FuncSecuritySeeder(self.GetLastKnownPrices)))
Add Data
You can subscribe to asset, fundamental, alternative, and custom data. The Dataset Market provides 400TB 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 your algorithms, 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 your algorithms, 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 your algorithms, 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:
Property: |
Property: |
Property: |
Property: |
Property: |
Property: |
Property: |
Property: |
Property: |
Property: |
Property: |
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(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. The warm-up feature uses the subscriptions you add in Initialize
to gather the historical data that warms up the algorithm. If you don't create security subscriptions in the Initialize
method, the warm-up won't occur.
// 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")