---
title: "Initialization"
description: "The Initialize method is the entry point of your algorithm where you define a series of settings, including security subscriptions, and starting cash balances."
canonical: https://www.quantconnect.com/docs/v2/writing-algorithms/initialization
markdown: https://www.quantconnect.com/docs/v2/writing-algorithms/initialization.md
language: python
source: https://github.com/QuantConnect/Documentation/tree/master/03%20Writing%20Algorithms/02%20Initialization
modified: 2026-10-29
index: https://www.quantconnect.com/llms.txt
---

# Initialization

[Documentation](https://www.quantconnect.com/docs/v2.md) > [Writing Algorithms](https://www.quantconnect.com/docs/v2/writing-algorithms.md) > Initialization

> Code examples are shown in Python. Append `?lang=csharp` to this URL for the C# version of this page.

## 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 `set_start_date` and `set_end_date` 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.

```python
# Set the start and end dates for the algorithm, defining the backtesting period.
self.set_start_date(2013, 1, 5)                  # Set the start date to January 5, 2013.
self.set_end_date(2015, 1, 5)                    # Set the end date to January 5, 2015.
self.set_end_date(datetime.now() - timedelta(7)) # Set the end date to last week.
```

Organization managers can enforce all backtests to end a certain number of months before the current date to reduce the chance of overfitting. For more information, see [Out-of-Sample Period](https://www.quantconnect.com/docs/v2/cloud-platform/backtesting/research-guide.md#06-Out-of-Sample-Period).

## 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 `set_account_currency` method. By default, the account currency is USD and your starting cash is $100,000. You must call the `set_account_currency` method before you [add data](https://www.quantconnect.com/docs/v2/writing-algorithms/initialization.md#08-Add-Data), and we recommend calling it before the `set_cash` method. If you call the `set_account_currency` method more than once with different currencies, only the first call takes effect.

```python
# Set the account currency and your starting cash.
self.set_account_currency("BTC") # Set the account currency to Bitcoin and its quantity to 100,000 BTC.
self.set_account_currency("INR") # Set the account currency to Indian Rupees and its quantity to 100,000 INR.
self.set_account_currency("BTC", 10) # Set the account currency to Bitcoin and its quantity to 10 BTC.
```

If you call `set_account_currency` after `set_cash`, one of the following applies:

- If you previously called `set_cash(amount)` and the new account currency differs, the amount carries over to the new account currency.
- If you previously called `set_cash(symbol, amount)` and the new account currency differs, the previous balance stays in its own `CashBook` entry and the new account currency starts at zero (or at `starting_cash` if you provide it).
- If the new account currency matches the previous one and you provide `starting_cash`, the new amount overrides the previous one.

```python
# set_cash(amount) then a different account currency: the amount carries over to BTC.
self.set_cash(1)
self.set_account_currency("BTC") # CashBook: BTC = 1.

# set_cash(symbol, amount) then a different account currency: USD balance is preserved, BTC starts at 0.
self.set_cash("USD", 100000)
self.set_account_currency("BTC") # CashBook: USD = 100000, BTC = 0.

# set_cash(symbol, amount) then a different account currency with starting_cash: USD is preserved, EUR starts at 50000.
self.set_cash("USD", 100000)
self.set_account_currency("EUR", 50000) # CashBook: USD = 100000, EUR = 50000.

# Same account currency with starting_cash: the new amount overrides the previous one.
self.set_cash(100000)
self.set_account_currency("USD", 200000) # CashBook: USD = 200000.
```

## Set Cash

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

```python
# Set the initial cash balance for the account for supported currencies.
self.set_cash(100000)       # Set the quantity of the account currency to 100,000.
self.set_cash("BTC", 10)    # Set the Bitcoin quantity to 10.
self.set_cash("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 `set_brokerage_model` method. For more information about each brokerage and the account types they support, see the [brokerage integration](https://www.quantconnect.com/docs/v2/cloud-platform/live-trading/brokerages.md) documentation. For more information about the reality models that the brokerage models set, see [Supported Models](https://www.quantconnect.com/docs/v2/writing-algorithms/reality-modeling/brokerages/supported-models.md).

```python
# Set the brokerage model and account type to model fees, supported order types, and available margin.
self.set_brokerage_model(BrokerageName.INTERACTIVE_BROKERS_BROKERAGE, AccountType.MARGIN)
```

The `AccountType` enumeration has the following members:

*Members of `QuantConnect.AccountType` (JSON): https://www.quantconnect.com/services/inspector?type=T:QuantConnect.AccountType&language=python*

## Set Universe Settings

The universe settings of your algorithm configure some properties of the universe constituents, including derivatives such as futures and options. The following table describes the properties of the `UniverseSettings` object:

### Property: `asynchronous`

Should the universe selection run asynchronously to boost speed?

Data Type: `bool` | Default Value: `False`

### Property: `extended_market_hours`

Should assets also feed extended market hours? You only receive extended market hours data if you create the subscription with an intraday resolution. If you create the subscription with daily resolution, the daily bars only reflect the regular trading hours.

Data Type: `bool` | Default Value: `False`

### Property: `fill_forward`

Should asset data fill forward?

Data Type: `bool` | Default Value: `True`

### Property: `minimum_time_in_universe`

What's the minimum time assets should be in the universe?

Data Type: `timedelta` | Default Value: `timedelta(1)`

### Property: `resolution`

What resolution should assets use?

Data Type: `Resolution` | Default Value: `Resolution.MINUTE`

### Method: `schedule.on`

What days should universe selection run? If it's `None`, it's the data resolution. For example, [US Equity fundamentals universes](https://www.quantconnect.com/docs/v2/writing-algorithms/universes/equity/fundamental-universes.md) are daily at midnight.

Argument Type: `IDateRule` | Default Value: `None`

### Property: `contract_depth_offset`

What offset from the current front month should be used for [continuous Future contracts](https://www.quantconnect.com/docs/v2/writing-algorithms/universes/futures.md#12-Continous-Contracts)? 0 uses the front month and 1 uses the back month contract. This setting is only available for Future assets.

Data Type: `int` | Default Value: `0`

### Property: `data_mapping_mode`

How should continuous Future contracts be mapped? This setting is only available for Future assets.

Data Type: `DataMappingMode` | Default Value: `DataMappingMode.OPEN_INTEREST`

### Property: `data_normalization_mode`

How should historical prices be adjusted? This setting is only available for Equity and Futures assets.

Data Type: `DataNormalizationMode` | Default Value: `DataNormalizationMode.ADJUSTED`

### Property: `leverage`

What leverage should assets use in the universe? This setting is not available for derivative assets.

Data Type: `float` | Default Value: `Security.NULL_LEVERAGE`

To set the `universe_settings`, 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.

```python
# Request second resolution data. This will be slow!
self.universe_settings.resolution = Resolution.SECOND
self.add_universe(self.universe.top(50))
```

For more information about universe settings, see the related documentation for [classic](https://www.quantconnect.com/docs/v2/writing-algorithms/universes/settings.md) and [framework](https://www.quantconnect.com/docs/v2/writing-algorithms/algorithm-framework/universe-selection/universe-settings.md) algorithms.

## 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](https://www.quantconnect.com/docs/v2/writing-algorithms/reality-modeling/key-concepts.md#02-Security-Level-Models) or special data requests on a per-security basis. To set the security initializer, in the `initialize` method, call the `set_security_initializer` method and then define the security initializer.

```python
# A custom security initializer can override default models such as
# setting new fee and fill models for the security.
self.set_security_initializer(self._custom_security_initializer)

def _custom_security_initializer(self, security: Security) -> None:
    security.set_fee_model(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.

```python
# Disable the trading fees for each security by using lambda function
# for the set_security_initializer argument.
self.set_security_initializer(lambda security: security.set_fee_model(ConstantFeeModel(0, "USD")))
```

If you call the `set_security_initializer` method, it overwrites the default security initializer. The default security initializer uses the [security-level reality models](https://www.quantconnect.com/docs/v2/writing-algorithms/reality-modeling/key-concepts.md#02-Security-Level-Models) of the brokerage model to set the following reality models of each security:

- [Fill](https://www.quantconnect.com/docs/v2/writing-algorithms/reality-modeling/trade-fills/key-concepts.md)
- [Slippage](https://www.quantconnect.com/docs/v2/writing-algorithms/reality-modeling/slippage/key-concepts.md)
- [Fee](https://www.quantconnect.com/docs/v2/writing-algorithms/reality-modeling/transaction-fees/key-concepts.md)
- [Buying Power](https://www.quantconnect.com/docs/v2/writing-algorithms/reality-modeling/buying-power.md)
- [Settlement](https://www.quantconnect.com/docs/v2/writing-algorithms/reality-modeling/settlement/key-concepts.md)
- [Short availability](https://www.quantconnect.com/docs/v2/writing-algorithms/reality-modeling/short-availability/key-concepts.md)
- [Margin Interest Rate](https://www.quantconnect.com/docs/v2/writing-algorithms/reality-modeling/margin-interest-rate/key-concepts.md)

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, call `add_security_initializer` before you create the subscriptions.

```python
class AddSecurityInitializerExampleAlgorithm(QCAlgorithm):
    def initialize(self) -> None:
        # In the Initialize method, set the security initializer to set models of assets.
        self.add_security_initializer(self._custom_security_initializer)

    def _custom_security_initializer(self, security: Security) -> None:
        # Overwrite some of the reality models
        security.set_fee_model(ConstantFeeModel(0, "USD"))
```

## Add Data

You can subscribe to asset, fundamental, alternative, and custom data. The [Dataset Market](https://www.quantconnect.com/datasets) 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 `add_equity` or `add_forex`. 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](https://www.quantconnect.com/docs/v2/writing-algorithms/securities/asset-classes.md).

```python
self.add_equity("AAPL")  # Add Apple 1 minute bars (minute by default)
self.add_forex("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 `add_data` method. For full examples, in the [Datasets](https://www.quantconnect.com/docs/v2/writing-algorithms/datasets/overview.md) chapter, select a dataset and see the **Requesting Data** section.

### Custom Data

To add custom data to your algorithms, call the `add_data` method. For more information about custom data, see [Importing Data](https://www.quantconnect.com/docs/v2/writing-algorithms/importing-data/key-concepts.md).

### 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](https://www.quantconnect.com/docs/v2/cloud-platform/organizations/resources.md).

## Set Indicators and Consolidators

You can create and warm-up [indicators](https://www.quantconnect.com/docs/v2/writing-algorithms/indicators/key-concepts.md) in the `initialize` method.

```python
self._symbol = self.add_equity("SPY").symbol
self._sma = self.sma(self._symbol, 20)
self.warm_up_indicator(self._symbol, self._sma)
```

## Set Algorithm Settings

The following table describes the `AlgorithmSettings` properties:

### Property: `automatic_indicator_warm_up`

A flag that defines if [automatic indicators](https://www.quantconnect.com/docs/v2/writing-algorithms/indicators/automatic-indicators.md) are [ready](https://www.quantconnect.com/docs/v2/writing-algorithms/indicators/key-concepts.md#07-Check-Readiness) on creation.

It does not account for built-in `RollingWindow` that stores their [historical values](https://www.quantconnect.com/docs/v2/writing-algorithms/indicators/key-concepts.md#06-Set-Historical-Values-Window-Size), use the `warm_up_indicator` or the `indicator_history` method instead.

Data Type: `bool` | Default Value: `False`

### Property: `seed_initial_prices`

Determines whether to seed initial prices for all selected and manually added securities.

Data Type: `bool` | Default Value: `False`

### Property: `daily_precise_end_time`

A flag that defines if daily bars should have an [end_time](https://www.quantconnect.com/docs/v2/writing-algorithms/key-concepts/time-modeling/periods.md#03-Start-and-End-Time) that matches the market close time (`True`) or the following midnight (`False`).

Data Type: `bool` | Default Value: `True`

### Property: `free_portfolio_value`

The [buying power buffer](https://www.quantconnect.com/docs/v2/writing-algorithms/trading-and-orders/position-sizing.md#06-Buying-Power-Buffer)value.

To successfully update the `free_portfolio_value`, you must update it after the `initialize` method.

Data Type: `float` | Default Value: `250`

### Property: `free_portfolio_value_percentage`

The buying power buffer percentage value.

Data Type: `float` | Default Value: `0.0025`

### Property: `ignore_unknown_asset_holdings`

Determines whether to terminate the algorithm when an asset holding is not supported by Lean or the brokerage.

Data Type: `bool` | Default Value: `True`

### Property: `liquidate_enabled`

A flag to enable and disable the `liquidate` method.

Data Type: `bool` | Default Value: `True`

### Property: `max_absolute_portfolio_target_percentage`

The absolute maximum valid total portfolio value target percentage.

Data Type: `float` | Default Value: `1000000000`

### Property: `min_absolute_portfolio_target_percentage`

The absolute minimum valid total portfolio value target percentage.

Data Type: `float` | Default Value: `0.0000000001`

### Property: `minimum_order_margin_portfolio_percentage`

The minimum order margin portfolio percentage to ignore bad orders and orders with small sizes.

Data Type: `float` | Default Value: `0.001`

### Property: `performance_sample_period`

Performance tracking sample period to use if any, useful to debug performance issues. See [Performance Chart](https://www.quantconnect.com/docs/v2/cloud-platform/backtesting/results.md#05-Performance-Chart).

Data Type: `timedelta` | Default Value: `timedelta(0)`

### Property: `rebalance_portfolio_on_insight_changes`

Rebalance the portfolio when you emit new insights or when insights expire.

Data Type: `bool/NoneType` | Default Value: `True`

### Property: `rebalance_portfolio_on_security_changes`

Rebalance the portfolio when your universe changes.

Data Type: `bool/NoneType` | Default Value: `True`

### Property: `stale_price_time_span`

The minimum time span elapsed to consider a market fill price as stale

Data Type: `timedelta` | Default Value: `timedelta(hours=1)`

### Property: `trading_days_per_year`

Number of trading days per year for this algorithm's [portfolio statistics](https://www.quantconnect.com/docs/v2/writing-algorithms/statistics.md).

Data Type: `int` | Default Value: `252`

### Property: `warm_up_resolution`

The resolution to use during the [warm-up](https://www.quantconnect.com/docs/v2/writing-algorithms/historical-data/warm-up-periods.md) period

Data Type: `Resolution/NoneType` | Default Value: `None`

To change the `settings`, update some of the preceding properties.

```python
# Set the algorithm behavior using the settings property on your algorithm.
self.settings.rebalance_portfolio_on_security_changes = False
self.settings.trading_days_per_year = 365
```

## Set Benchmark

The benchmark performance is input to calculate several statistics on your algorithm, including [alpha](https://www.quantconnect.com/docs/v2/writing-algorithms/key-concepts/glossary.md#02-alpha) and [beta](https://www.quantconnect.com/docs/v2/writing-algorithms/key-concepts/glossary.md#07-beta). To set a benchmark for your algorithm, call the `set_benchmark` method. You can set the benchmark to a security, a constant value, or a value from a [custom data source](https://www.quantconnect.com/docs/v2/writing-algorithms/importing-data/key-concepts.md). If you don't set a [brokerage model](https://www.quantconnect.com/docs/v2/writing-algorithms/reality-modeling/brokerages/key-concepts.md), the default benchmark is SPY. If you set a brokerage model, the model defines the default benchmark.

```python
# Set the benchmark to IBM
self.set_benchmark("IBM")

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

# Set the benchmark to a value from a custom data source
symbol = self.add_data(CustomData, "CustomData", Resolution.HOUR).symbol
self.set_benchmark(symbol)
```

If you pass a ticker to the `set_benchmark` 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 `set_benchmark` 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 `set_time_zone` method. This method accepts either a string following the [IANA Time Zone database](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) convention or a [NodaTime](https://nodatime.org/).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:

*Members of `QuantConnect.TimeZones` (JSON): https://www.quantconnect.com/services/inspector?type=T:QuantConnect.TimeZones&language=python*

```python
self.set_time_zone("Europe/London")
self.set_time_zone(TimeZones.CHICAGO)
```

The [algorithm time zone](https://www.quantconnect.com/docs/v2/writing-algorithms/key-concepts/time-modeling/time-zones.md#04-Algorithm-Time-Zone) may be different from the [exchange time zone](https://www.quantconnect.com/docs/v2/writing-algorithms/key-concepts/time-modeling/time-zones.md#03-Exchange-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](https://www.quantconnect.com/docs/v2/writing-algorithms/key-concepts/time-modeling/timeslices.md) 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](https://www.quantconnect.com/docs/v2/writing-algorithms/historical-data/warm-up-periods.md) pumps data into your algorithm from before the start date. To set a warm-up period, call the `set_warm_up` 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.

```python
# Wind time back 7 days from the start date
self.set_warm_up(timedelta(7))

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

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

## Set Name and Tags

You can categorize your backtest with a name and tags. To set the algorithm `name`, call the `set_name` method.

```python
# Set the name of your backtest to help categorize your results.
self.set_name("Backtest Name")
```

The `set_name` method overwrites the names of backtests of an [optimization](https://www.quantconnect.com/docs/v2/cloud-platform/optimization.md), which contains the [parameter](https://www.quantconnect.com/docs/v2/writing-algorithms/optimization/parameters.md) values. To keep these values, create a name that includes them.

```python
# Setting the backtest name to a mix of the parameters can help identify backtests in optimization results.
fast_period = self.get_parameter("fast_period", 100);
mid_period = self.get_parameter("mid_period", 200);
slow_period = self.get_parameter("slow_period", 300);
self.set_name(f"Backtest Name ({fast_period},{mid_period},{slow_period})");
```

To add tags to you algorithm, call the `add_tag` method.

```python
# Add additional information to the algorithm with tags for better organization in the backtest results.
self.add_tag("Long Only")
self.add_tag("Momentum")
```

Your algorithm can add 20 tags. The name and each tag can have up to 200 characters or else they are truncated.

## Post Initialization

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

```python
# Notify yourself when the algorithm is ready to begin trading.
def on_warmup_finished(self) -> None:
    self.log("Algorithm Ready")
```

## Examples

The following examples demonstrate some common practices for initializing algorithms.

### Example 1: Set the Data Seed

Some data feeds might not have data on its first fetch, making the algorithm prone to error. The following algorithm [seeds the initial price of each asset](https://www.quantconnect.com/docs/v2/writing-algorithms/universes/settings.md#98-Configure-Universe-Securities) to its last known price to avoid issues.

```python
# Seed with the last known price of assets to prevent $0 security price errors.
def initialize(self):
    self.settings.seed_initial_prices = True
```

### Example 2: Enable Extended Market Hours

Some traders use pre-market data for filtering assets. The following algorithm enables extended market hour data for assets in the universe.

```python
# Add a universe of assets with extended market hours data.
def initialize(self):
    self.universe_settings.extended_market_hours = True
```

### Example 3: Train Models When the Warm Up Finishes

The following algorithm uses the `on_warmup_finished` event handler to train a model with data from the warm-up period.

```python
# Train machine learning models after the algorithm warm up is done, so your models
# are ready as soon as the algorithm starts trading.
def on_warmup_finished(self) -> None:
    self.train(self.my_training_method)
```

### Other Examples

For more examples, see the following algorithms:

**Demonstration Algorithms**

- [BasicTemplateAlgorithm.py](https://github.com/QuantConnect/Lean/blob/master/Algorithm.Python/BasicTemplateAlgorithm.py) (Python)
- [BasicTemplateCryptoAlgorithm.py](https://github.com/QuantConnect/Lean/blob/master/Algorithm.Python/BasicTemplateCryptoAlgorithm.py) (Python)
- [BasicTemplateForexAlgorithm.py](https://github.com/QuantConnect/Lean/blob/master/Algorithm.Python/BasicTemplateForexAlgorithm.py) (Python)
- [BasicTemplateFuturesAlgorithm.py](https://github.com/QuantConnect/Lean/blob/master/Algorithm.Python/BasicTemplateFuturesAlgorithm.py) (Python)
- [BasicTemplateOptionsAlgorithm.py](https://github.com/QuantConnect/Lean/blob/master/Algorithm.Python/BasicTemplateOptionsAlgorithm.py) (Python)
