Skip to content
All library documents

Custom Security Initialization for Data Normalization and Seeding

Article Strategy library · Author: QuantConnect

Summary

This algorithm example explains how to customize security setup in a trading engine. A security initializer runs when a security object is created, making it a place to set properties such as data normalization and to configure security models. The example subclasses an initializer tied to a brokerage model so the platform's default model and leverage behavior can be retained.

It also provides a custom seeder that requests a recent hourly history bar and returns it as a trade bar, then configures the initializer to use raw data normalization. The sample algorithm adds SPY and enters a holding when the portfolio is not invested. These details illustrate configuration mechanics rather than a trading signal or tested strategy. The excerpt gives no comparison of normalization modes or performance evidence, so users must choose settings appropriate to their data and research goals.

Key ideas

  • A custom initializer can apply settings immediately after each security is created.
  • Subclassing the brokerage model initializer preserves its default model setup while allowing additional configuration.
  • A security seeder can use recent historical data to supply an initial trade bar.
  • The example applies raw data normalization and uses hourly SPY data.
  • The example demonstrates platform configuration and provides no strategy evaluation.

Tags

Full text
# CustomSecurityInitializerAlgorithm


# CustomSecurityInitializerAlgorithm









Our custom initializer that will set the data normalization mode.
    We sub-class the BrokerageModelSecurityInitializer so we can also
    take advantage of the default model/leverage setting behaviors

This algorithm shows how to set a custom security initializer. A security initializer is run immediately after a new security object has been created and can be used to security models and other settings, such as data normalization mode

## Source (Apache-2.0)

```python
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from AlgorithmImports import *

### <summary>
### This algorithm shows how to set a custom security initializer.
### A security initializer is run immediately after a new security object
### has been created and can be used to security models and other settings,
### such as data normalization mode
### </summary>
### <meta name="tag" content="using data" />
### <meta name="tag" content="securities and portfolio" />
### <meta name="tag" content="trading and orders" />
class CustomSecurityInitializerAlgorithm(QCAlgorithm):

    def initialize(self):
        
        # set our initializer to our custom type
        self.set_brokerage_model(BrokerageName.INTERACTIVE_BROKERS_BROKERAGE)
        
        func_security_seeder = FuncSecuritySeeder(self.custom_seed_function)
        self.set_security_initializer(CustomSecurityInitializer(self.brokerage_model, func_security_seeder, DataNormalizationMode.RAW))
        
        self.set_start_date(2013,10,1)
        self.set_end_date(2013,11,1)

        self.add_equity("SPY", Resolution.HOUR)

    def on_data(self, data):
        if not self.portfolio.invested:
            self.set_holdings("SPY", 1)

    def custom_seed_function(self, security):

        resolution = Resolution.HOUR

        df = self.history(security.symbol, 1, resolution)
        if df.empty:
            return None

        last_bar = df.unstack(level=0).iloc[-1]
        date_time = last_bar.name.to_pydatetime()
        open = last_bar.open.values[0]
        high = last_bar.high.values[0]
        low = last_bar.low.values[0]
        close = last_bar.close.values[0]
        volume = last_bar.volume.values[0]
        return TradeBar(date_time, security.symbol, open, high, low, close, volume, Extensions.to_time_span(resolution))


class CustomSecurityInitializer(BrokerageModelSecurityInitializer):
    '''Our custom initializer that will set the data normalization mode.
    We sub-class the BrokerageModelSecurityInitializer so we can also
    take advantage of the default model/leverage setting behaviors'''

    def __init__(self, brokerage_model, security_seeder, data_normalization_mode):
        '''Initializes a new instance of the CustomSecurityInitializer class with the specified normalization mode
        brokerage_model -- The brokerage model used to get fill/fee/slippage/settlement models
        security_seeder -- The security seeder to be used
        data_normalization_mode -- The desired data normalization mode'''
        self.base = BrokerageModelSecurityInitializer(brokerage_model, security_seeder)
        self.data_normalization_mode = data_normalization_mode

    def initialize(self, security):
        '''Initializes the specified security by setting up the models
        security -- The security to be initialized
        seed_security -- True to seed the security, false otherwise'''
        # first call the default implementation
        self.base.initialize(security)

        # now apply our data normalization mode
        security.set_data_normalization_mode(self.data_normalization_mode)

```

Shown in full with attribution under the source's licence. Licence: Apache-2.0

This summary was written by Stratmill's research agent from the original; it is not a copy of the source.