Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: Demonstration of how to access the statistics results from within an algorithm through the `Statistics` property.

Output:
```python

from AlgorithmImports import *

from System.Collections.Generic import Dictionary

class StatisticsResultsAlgorithm(QCAlgorithm):

    most_traded_security_statistic = "Most Traded Security"
    most_traded_security_trade_count_statistic = "Most Traded Security Trade Count"

    def initialize(self):
        self.set_start_date(2013, 10, 7)
        self.set_end_date(2013, 10, 11)
        self.set_cash(100000)

        self.spy = self.add_equity("SPY", Resolution.MINUTE).symbol
        self.ibm = self.add_equity("IBM", Resolution.MINUTE).symbol

        self.fast_spy_ema = self.ema(self.spy, 30, Resolution.MINUTE)
        self.slow_spy_ema = self.ema(self.spy, 60, Resolution.MINUTE)

        self.fast_ibm_ema = self.ema(self.spy, 10, Resolution.MINUTE)
        self.slow_ibm_ema = self.ema(self.spy, 30, Resolution.MINUTE)

        self.trade_counts = {self.spy: 0, self.ibm: 0}

    def on_data(self, data: Slice):
        if not self.slow_spy_ema.is_ready: return

        if self.fast_spy_ema > self.slow_spy_ema:
            self.set_holdings(self.spy, 0.5)
        elif self.securities[self.spy].invested:
            self.liquidate(self.spy)

        if self.fast_ibm_ema > self.slow_ibm_ema:
            self.set_holdings(self.ibm, 0.2)
        elif self.securities[self.ibm].invested:
            self.liquidate(self.ibm)

    def on_order_event(self, order_event):
        if order_event.status == OrderStatus.FILLED:
            # We can access the statistics summary at runtime
            statistics = self.statistics.summary
            statistics_str = "".join([f"{kvp.key}: {kvp.value}" for kvp in statistics])
            self.debug(f"Statistics after fill:{statistics_str}")

            # Access a single statistic
            self.log(f"Total trades so far: {statistics[PerformanceMetrics.TOTAL_ORDERS]}")
            self.log(f"Sharpe Ratio: {statistics[PerformanceMetrics.SHARPE_RATIO]}")

            # --------

            # We can also set custom summary statistics:

            if all(count == 0 for count in self.trade_counts.values()):
                if StatisticsResultsAlgorithm.most_traded_security_statistic in statistics:
                    raise AssertionError(f"Statistic {StatisticsResultsAlgorithm.most_traded_security_statistic} should not be set yet")
                if StatisticsResultsAlgorithm.most_traded_security_trade_count_statistic in statistics:
                    raise AssertionError(f"Statistic {StatisticsResultsAlgorithm.most_traded_security_trade_count_statistic} should not be set yet")
            else:
                # The current most traded security should be set in the summary
                most_trade_security, most_trade_security_trade_count = self.get_most_trade_security()
                self.check_most_traded_security_statistic(statistics, most_trade_security, most_trade_security_trade_count)

            # Update the trade count
            self.trade_counts[order_event.symbol] += 1

            # Set the most traded security
            most_trade_security, most_trade_security_trade_count = self.get_most_trade_security()
            self.set_summary_statistic(StatisticsResultsAlgorithm.most_traded_security_statistic, str(most_trade_security))
            self.set_summary_statistic(StatisticsResultsAlgorithm.most_traded_security_trade_count_statistic, most_trade_security_trade_count)

            # Re-calculate statistics:
            statistics = self.statistics.summary

            # Let's keep track of our custom summary statistics after the update
            self.check_most_traded_security_statistic(statistics, most_trade_security, most_trade_security_trade_count)

    def on_end_of_algorithm(self):
        statistics = self.statistics.summary
        if StatisticsResultsAlgorithm.most_traded_security_statistic not in statistics:
            raise AssertionError(f"Statistic {StatisticsResultsAlgorithm.most_traded_security_statistic} should be in the summary statistics")
        if StatisticsResultsAlgorithm.most_traded_security_trade_count_statistic not in statistics:
            raise AssertionError(f"Statistic {StatisticsResultsAlgorithm.most_traded_security_trade_count_statistic} should be in the summary statistics")

        most_trade_security, most_trade_security_trade_count = self.get_most_trade_security()
        self.check_most_traded_security_statistic(statistics, most_trade_security, most_trade_security_trade_count)

    def check_most_traded_security_statistic(self, statistics: Dictionary[str, str], most_traded_security: Symbol, trade_count: int):
        most_traded_security_statistic = statistics[StatisticsResultsAlgorithm.most_traded_security_statistic]
        most_traded_security_trade_count_statistic = statistics[StatisticsResultsAlgorithm.most_traded_security_trade_count_statistic]
        self.log(f"Most traded security: {most_traded_security_statistic}")
        self.log(f"Most traded security trade count: {most_traded_security_trade_count_statistic}")

        if most_traded_security_statistic != most_traded_security:
            raise AssertionError(f"Most traded security should be {most_traded_security} but it is {most_traded_security_statistic}")

        if most_traded_security_trade_count_statistic != str(trade_count):
            raise AssertionError(f"Most traded security trade count should be {trade_count} but it is {most_traded_security_trade_count_statistic}")

    def get_most_trade_security(self) -> tuple[Symbol, int]:
        most_trade_security = max(self.trade_counts, key=lambda symbol: self.trade_counts[symbol])
        most_trade_security_trade_count = self.trade_counts[most_trade_security]
        return most_trade_security, most_trade_security_trade_count

```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: Example algorithm of using RiskParityPortfolioConstructionModel

Output:
```python

from AlgorithmImports import *
from Portfolio.RiskParityPortfolioConstructionModel import *

class RiskParityPortfolioAlgorithm(QCAlgorithm):
    '''Example algorithm of using RiskParityPortfolioConstructionModel'''

    def initialize(self):
        self.set_start_date(2021, 2, 21)  # Set Start Date
        self.set_end_date(2021, 3, 30)
        self.set_cash(100000)  # Set Strategy Cash
        self.set_security_initializer(lambda security: security.set_market_price(self.get_last_known_price(security)))

        self.add_equity("SPY", Resolution.DAILY)
        self.add_equity("AAPL", Resolution.DAILY)

        self.add_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(1)))
        self.set_portfolio_construction(RiskParityPortfolioConstructionModel())
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: Custom data universe selection regression algorithm asserting it's behavior. Similar to CustomDataUniverseRegressionAlgorithm but with a custom schedule

Output:
```python

from AlgorithmImports import *

class CustomDataUniverseScheduledRegressionAlgorithm(QCAlgorithm):
    def initialize(self):
        '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
        self.set_start_date(2014, 3, 24)
        self.set_end_date(2014, 3, 31)

        self.current_underlying_symbols = []
        self._selection_time = [datetime(2014, 3, 25), datetime(2014, 3, 27), datetime(2014, 3, 29)]
        self.universe_settings.resolution = Resolution.DAILY
        self.universe_settings.schedule.on(self.date_rules.on(self._selection_time))
        self.add_universe(CoarseFundamental, "custom-data-universe", self.universe_settings, self.selection)

        # This use case is also valid/same because it will use the algorithm settings by default
        # self.add_universe(CoarseFundamental, "custom-data-universe", self.selection)

    def selection(self, coarse):
        self.debug(f"Universe selection called: {self.time} Count: {len(coarse)}")

        expected_time = self._selection_time.pop(0)
        if expected_time != self.time:
            raise ValueError(f"Unexpected selection time {self.time} expected {expected_time}")

        # sort descending by daily dollar volume
        sorted_by_dollar_volume = sorted(coarse, key=lambda x: x.dollar_volume, reverse=True)

        # return the symbol objects of the top entries from our sorted collection
        underlying_symbols = [ x.symbol for x in sorted_by_dollar_volume[:10] ]
        custom_symbols = []
        for symbol in underlying_symbols:
            custom_symbols.append(Symbol.create_base(MyPyCustomData, symbol))
        return underlying_symbols + custom_symbols

    def on_data(self, data):
        '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.

        Arguments:
            data: Slice object keyed by symbol containing the stock data
        '''
        if not self.portfolio.invested:
            custom_data = data.get(MyPyCustomData)
            if len(custom_data) > 0:
                for symbol in self.current_underlying_symbols:
                    self.set_holdings(symbol, 1 / len(self.current_underlying_symbols))

                    if len([x for x in custom_data.keys() if x.underlying == symbol]) == 0:
                        raise ValueError(f"Custom data was not found for symbol {symbol}")
        # equity daily data arrives at 16 pm but custom data is set to arrive at midnight
        self.current_underlying_symbols = [symbol for symbol in data.keys() if symbol.security_type is SecurityType.EQUITY]

    def on_end_of_algorithm(self):
        if len(self._selection_time) != 0:
            raise ValueError(f"Unexpected selection times, missing {len(self._selection_time)}")

class MyPyCustomData(PythonData):

    def get_source(self, config, date, is_live_mode):
        source = f"{Globals.data_folder}/equity/usa/daily/{LeanData.generate_zip_file_name(config.symbol, date, config.resolution, config.tick_type)}"
        return SubscriptionDataSource(source)

    def reader(self, config, line, date, is_live_mode):
        csv = line.split(',')
        _scaleFactor = 1 / 10000

        custom = MyPyCustomData()
        custom.symbol = config.symbol
        custom.time =  datetime.strptime(csv[0], '%Y%m%d %H:%M')
        custom.open = float(csv[1]) * _scaleFactor
        custom.high = float(csv[2]) * _scaleFactor
        custom.low = float(csv[3]) * _scaleFactor
        custom.close = float(csv[4]) * _scaleFactor
        custom.value = float(csv[4]) * _scaleFactor
        custom.period = Time.ONE_DAY
        custom.end_time = custom.time + custom.period

        return custom
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: A demonstration of consolidating futures data into larger bars for your algorithm.

Output:
```python

from AlgorithmImports import *

class BasicTemplateFuturesConsolidationAlgorithm(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2013, 10, 7)
        self.set_end_date(2013, 10, 11)
        self.set_cash(1000000)

        # Subscribe and set our expiry filter for the futures chain
        futureSP500 = self.add_future(Futures.Indices.SP_500_E_MINI)
        # set our expiry filter for this future chain
        # SetFilter method accepts timedelta objects or integer for days.
        # The following statements yield the same filtering criteria
        futureSP500.set_filter(0, 182)
        # future.set_filter(timedelta(0), timedelta(182))

        self.consolidators = dict()

    def on_data(self,slice):
        pass

    def on_data_consolidated(self, sender, quote_bar):
        self.log("OnDataConsolidated called on " + str(self.time))
        self.log(str(quote_bar))

    def on_securities_changed(self, changes):
        for security in changes.added_securities:
            consolidator = QuoteBarConsolidator(timedelta(minutes=5))
            consolidator.data_consolidated += self.on_data_consolidated
            self.subscription_manager.add_consolidator(security.symbol, consolidator)
            self.consolidators[security.symbol] = consolidator

        for security in changes.removed_securities:
            consolidator = self.consolidators.pop(security.symbol)
            self.subscription_manager.remove_consolidator(security.symbol, consolidator)
            consolidator.data_consolidated -= self.on_data_consolidated
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: Demonstration algorithm of indicators history window usage

Output:
```python

from AlgorithmImports import *

class IndicatorHistoryAlgorithm(QCAlgorithm):
    '''Demonstration algorithm of indicators history window usage.'''

    def initialize(self):
        '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
        self.set_start_date(2013, 1, 1)
        self.set_end_date(2014, 12, 31)
        self.set_cash(25000)

        self._symbol = self.add_equity("SPY", Resolution.DAILY).symbol

        self.bollinger_bands = self.bb(self._symbol, 20, 2.0, resolution=Resolution.DAILY)
        # Let's keep BB values for a 20 day period
        self.bollinger_bands.window.size = 20
        # Also keep the same period of data for the middle band
        self.bollinger_bands.middle_band.window.size = 20

    def on_data(self, slice: Slice):
        # Let's wait for our indicator to fully initialize and have a full window of history data
        if not self.bollinger_bands.window.is_ready: return

        # We can access the current and oldest (in our period) values of the indicator
        self.log(f"Current BB value: {self.bollinger_bands[0].end_time} - {self.bollinger_bands[0].value}")
        self.log(f"Oldest BB value: {self.bollinger_bands[self.bollinger_bands.window.count - 1].end_time} - "
                 f"{self.bollinger_bands[self.bollinger_bands.window.count - 1].value}")

        # Let's log the BB values for the last 20 days, for demonstration purposes on how it can be enumerated
        for data_point in self.bollinger_bands:
            self.log(f"BB @{data_point.end_time}: {data_point.value}")

        # We can also do the same for internal indicators:
        middle_band = self.bollinger_bands.middle_band
        self.log(f"Current BB Middle Band value: {middle_band[0].end_time} - {middle_band[0].value}")
        self.log(f"Oldest BB Middle Band value: {middle_band[middle_band.window.count - 1].end_time} - "
                 f"{middle_band[middle_band.window.count - 1].value}")
        for data_point in middle_band:
            self.log(f"BB Middle Band @{data_point.end_time}: {data_point.value}")

        # We are done now!
        self.quit()
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: Basic template algorithm simply initializes the date range and cash

Output:
```python

from AlgorithmImports import *

class LimitFillRegressionAlgorithm(QCAlgorithm):

    def initialize(self):
        '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''

        self.set_start_date(2013,10,7)  #Set Start Date
        self.set_end_date(2013,10,11)    #Set End Date
        self.set_cash(100000)           #Set Strategy Cash
        # Find more symbols here: http://quantconnect.com/data
        self.add_equity("SPY", Resolution.SECOND)

    def on_data(self, data):
        '''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
        if data.contains_key("SPY"):
            if self.is_round_hour(self.time):
                negative = 1 if self.time < (self.start_date + timedelta(days=2)) else -1
                self.limit_order("SPY", negative*10, data["SPY"].price)

    def is_round_hour(self, date_time):
        '''Verify whether datetime is round hour'''
        return date_time.minute == 0 and date_time.second == 0

    def on_order_event(self, order_event):
        self.debug(str(order_event))
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: Regression algorithm asserting the behavior of auxiliary data history requests

Output:
```python

from AlgorithmImports import *

class HistoryAuxiliaryDataRegressionAlgorithm(QCAlgorithm):

    def initialize(self):
        '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''

        self.set_start_date(2021, 1, 1)
        self.set_end_date(2021, 1, 5)

        aapl = self.add_equity("AAPL", Resolution.DAILY).symbol

        # multi symbol request
        spy = Symbol.create("SPY", SecurityType.EQUITY, Market.USA)
        multi_symbol_request = self.history(Dividend, [ aapl, spy ], 360, Resolution.DAILY)
        if len(multi_symbol_request) != 12:
                raise ValueError(f"Unexpected multi symbol dividend count: {len(multi_symbol_request)}")

        # continuous future mapping requests
        sp500 = Symbol.create(Futures.Indices.SP_500_E_MINI, SecurityType.FUTURE, Market.CME)
        continuous_future_open_interest_mapping = self.history(SymbolChangedEvent, sp500, datetime(2007, 1, 1), datetime(2012, 1, 1), data_mapping_mode = DataMappingMode.OPEN_INTEREST)
        if len(continuous_future_open_interest_mapping) != 9:
                raise ValueError(f"Unexpected continuous future mapping event count: {len(continuous_future_open_interest_mapping)}")
        continuous_future_last_trading_day_mapping = self.history(SymbolChangedEvent, sp500, datetime(2007, 1, 1), datetime(2012, 1, 1), data_mapping_mode = DataMappingMode.LAST_TRADING_DAY)
        if len(continuous_future_last_trading_day_mapping) != 9:
                raise ValueError(f"Unexpected continuous future mapping event count: {len(continuous_future_last_trading_day_mapping)}")

        dividend = self.history(Dividend, aapl, 360)
        self.debug(str(dividend))
        if len(dividend) != 6:
            raise ValueError(f"Unexpected dividend count: {len(dividend)}")
        for distribution in dividend.distribution:
            if distribution == 0:
                raise ValueError(f"Unexpected distribution: {distribution}")

        split = self.history(Split, aapl, 360)
        self.debug(str(split))
        if len(split) != 2:
            raise ValueError(f"Unexpected split count: {len(split)}")
        for splitfactor in split.splitfactor:
            if splitfactor == 0:
                raise ValueError(f"Unexpected splitfactor: {splitfactor}")

        symbol = Symbol.create("BTCUSD", SecurityType.CRYPTO_FUTURE, Market.BINANCE)
        margin_interest = self.history(MarginInterestRate, symbol, 24 * 3, Resolution.HOUR)
        self.debug(str(margin_interest))
        if len(margin_interest) != 8:
            raise ValueError(f"Unexpected margin interest count: {len(margin_interest)}")
        for interestrate in margin_interest.interestrate:
            if interestrate == 0:
                raise ValueError(f"Unexpected interestrate: {interestrate}")

        # last trading date on 2007-05-18
        delisted_symbol = Symbol.create("AAA.1", SecurityType.EQUITY, Market.USA)
        delistings = self.history(Delisting, delisted_symbol, datetime(2007, 5, 15), datetime(2007, 5, 21))
        self.debug(str(delistings))
        if len(delistings) != 2:
            raise ValueError(f"Unexpected delistings count: {len(delistings)}")
        if delistings.iloc[0].type != DelistingType.WARNING:
            raise ValueError(f"Unexpected delisting: {delistings.iloc[0]}")
        if delistings.iloc[1].type != DelistingType.DELISTED:
            raise ValueError(f"Unexpected delisting: {delistings.iloc[1]}")

        # get's remapped:
        # 2008-09-30 spwr -> spwra
        # 2011-11-17 spwra -> spwr
        remapped_symbol = Symbol.create("SPWR", SecurityType.EQUITY, Market.USA)
        symbol_changed_events = self.history(SymbolChangedEvent, remapped_symbol, datetime(2007, 1, 1), datetime(2012, 1, 1))
        self.debug(str(symbol_changed_events))
        if len(symbol_changed_events) != 2:
            raise ValueError(f"Unexpected SymbolChangedEvents count: {len(symbol_changed_events)}")
        first_event = symbol_changed_events.iloc[0]
        if first_event.oldsymbol != "SPWR" or first_event.newsymbol != "SPWRA" or symbol_changed_events.index[0][1] != datetime(2008, 9, 30):
            raise ValueError(f"Unexpected SymbolChangedEvents: {first_event}")
        second_event = symbol_changed_events.iloc[1]
        if second_event.newsymbol != "SPWR" or second_event.oldsymbol != "SPWRA" or symbol_changed_events.index[1][1] != datetime(2011, 11, 17):
            raise ValueError(f"Unexpected SymbolChangedEvents: {second_event}")

    def on_data(self, data):
        '''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.

        Arguments:
            data: Slice object keyed by symbol containing the stock data
        '''
        if not self.portfolio.invested:
            self.set_holdings("AAPL", 1)
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: This algorithm demonstrates how to submit orders to a Financial Advisor account group, allocation profile or a single managed account.

Output:
```python

from AlgorithmImports import *

class FinancialAdvisorDemoAlgorithm(QCAlgorithm):

    def initialize(self):
        # Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must be initialized.

        self.set_start_date(2013,10,7)   #Set Start Date
        self.set_end_date(2013,10,11)    #Set End Date
        self.set_cash(100000)           #Set Strategy Cash

        self._symbol = self.add_equity("SPY", Resolution.SECOND).symbol

        # The default order properties can be set here to choose the FA settings
        # to be automatically used in any order submission method (such as SetHoldings, Buy, Sell and Order)

        # Use a default FA Account Group with an Allocation Method
        self.default_order_properties = InteractiveBrokersOrderProperties()
        # account group created manually in IB/TWS
        self.default_order_properties.fa_group = "TestGroupEQ"
        # supported allocation methods are: EqualQuantity, NetLiq, AvailableEquity, PctChange
        self.default_order_properties.fa_method = "EqualQuantity"

        # set a default FA Allocation Profile
        # DefaultOrderProperties = InteractiveBrokersOrderProperties()
        # allocation profile created manually in IB/TWS
        # self.default_order_properties.fa_profile = "TestProfileP"

        # send all orders to a single managed account
        # DefaultOrderProperties = InteractiveBrokersOrderProperties()
        # a sub-account linked to the Financial Advisor master account
        # self.default_order_properties.account = "DU123456"

    def on_data(self, data):
        # on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.

        if not self.portfolio.invested:
            # when logged into IB as a Financial Advisor, this call will use order properties
            # set in the DefaultOrderProperties property of QCAlgorithm
            self.set_holdings("SPY", 1)
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: Provides a regression baseline focused on updating orders

Output:
```python

from AlgorithmImports import *
from math import copysign

class UpdateOrderRegressionAlgorithm(QCAlgorithm):

    def initialize(self):
        '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''

        self.set_start_date(2013,1,1)    #Set Start Date
        self.set_end_date(2015,1,1)      #Set End Date
        self.set_cash(100000)           #Set Strategy Cash
        # Find more symbols here: http://quantconnect.com/data

        self.security = self.add_equity("SPY", Resolution.DAILY)

        self.last_month = -1
        self.quantity = 100
        self.delta_quantity = 10

        self.stop_percentage = 0.025
        self.stop_percentage_delta = 0.005
        self.limit_percentage = 0.025
        self.limit_percentage_delta = 0.005

        order_type_enum = [OrderType.MARKET, OrderType.LIMIT, OrderType.STOP_MARKET, OrderType.STOP_LIMIT, OrderType.MARKET_ON_OPEN, OrderType.MARKET_ON_CLOSE, OrderType.TRAILING_STOP]
        self.order_types_queue = CircularQueue[OrderType](order_type_enum)
        self.order_types_queue.circle_completed += self.on_circle_completed
        self.tickets = []

    def on_circle_completed(self, sender, event):
        '''Flip our signs when we've gone through all the order types'''
        self.quantity *= -1

    def on_data(self, data):
        '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
        if not data.bars.contains_key("SPY"):
            return

        if self.time.month != self.last_month:
            # we'll submit the next type of order from the queue
            order_type = self.order_types_queue.dequeue()
            self.log("\r\n--------------MONTH: {0}:: {1}".format(self.time.strftime("%B"), order_type))
            self.last_month = self.time.month
            self.log("ORDER TYPE:: {0}".format(order_type))
            is_long = self.quantity > 0
            stop_price = (1 + self.stop_percentage)*data["SPY"].high if is_long else (1 - self.stop_percentage)*data["SPY"].low
            limit_price = (1 - self.limit_percentage)*stop_price if is_long else (1 + self.limit_percentage)*stop_price

            if order_type == OrderType.LIMIT:
                limit_price = (1 + self.limit_percentage)*data["SPY"].high if not is_long else (1 - self.limit_percentage)*data["SPY"].low

            request = SubmitOrderRequest(order_type, self.security.symbol.security_type, "SPY", self.quantity, stop_price, limit_price, 0, 0.01, True,
                                         self.utc_time, str(int(order_type)))
            ticket = self.transactions.add_order(request)
            self.tickets.append(ticket)

        elif len(self.tickets) > 0:
            ticket = self.tickets[-1]

            if self.time.day > 8 and self.time.day < 14:
                if len(ticket.update_requests) == 0 and ticket.status is not OrderStatus.FILLED:
                    self.log("TICKET:: {0}".format(ticket))
                    update_order_fields = UpdateOrderFields()
                    update_order_fields.quantity = ticket.quantity + copysign(self.delta_quantity, self.quantity)
                    update_order_fields.tag = "Change quantity: {0}".format(self.time.day)
                    ticket.update(update_order_fields)

            elif self.time.day > 13 and self.time.day < 20:
                if len(ticket.update_requests) == 1 and ticket.status is not OrderStatus.FILLED:
                    self.log("TICKET:: {0}".format(ticket))
                    update_order_fields = UpdateOrderFields()
                    update_order_fields.limit_price = self.security.price*(1 - copysign(self.limit_percentage_delta, ticket.quantity))
                    update_order_fields.stop_price = self.security.price*(1 + copysign(self.stop_percentage_delta, ticket.quantity)) if ticket.order_type != OrderType.TRAILING_STOP else None
                    update_order_fields.tag = "Change prices: {0}".format(self.time.day)
                    ticket.update(update_order_fields)
            else:
                if len(ticket.update_requests) == 2 and ticket.status is not OrderStatus.FILLED:
                    self.log("TICKET:: {0}".format(ticket))
                    ticket.cancel("{0} and is still open!".format(self.time.day))
                    self.log("CANCELLED:: {0}".format(ticket.cancel_request))

    def on_order_event(self, orderEvent):
        order = self.transactions.get_order_by_id(orderEvent.order_id)
        ticket = self.transactions.get_order_ticket(orderEvent.order_id)

        #order cancelations update CanceledTime
        if order.status == OrderStatus.CANCELED and order.canceled_time != orderEvent.utc_time:
            raise ValueError("Expected canceled order CanceledTime to equal canceled order event time.")

        #fills update LastFillTime
        if (order.status == OrderStatus.FILLED or order.status == OrderStatus.PARTIALLY_FILLED) and order.last_fill_time != orderEvent.utc_time:
            raise ValueError("Expected filled order LastFillTime to equal fill order event time.")

        # check the ticket to see if the update was successfully processed
        if len([ur for ur in ticket.update_requests if ur.response is not None and ur.response.is_success]) > 0 and order.created_time != self.utc_time and order.last_update_time is None:
            raise ValueError("Expected updated order LastUpdateTime to equal submitted update order event time")

        if orderEvent.status == OrderStatus.FILLED:
            self.log("FILLED:: {0} FILL PRICE:: {1}".format(self.transactions.get_order_by_id(orderEvent.order_id), orderEvent.fill_price))
        else:
            self.log(orderEvent.to_string())
            self.log("TICKET:: {0}".format(ticket))
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: Example algorithm for trading continuous future

Output:
```python

from AlgorithmImports import *

class BasicTemplateFutureRolloverAlgorithm(QCAlgorithm):

    ### <summary>
    ### Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
    ### </summary>
    def initialize(self):
        self.set_start_date(2013, 10, 8)
        self.set_end_date(2013, 12, 10)
        self.set_cash(1000000)

        self._symbol_data_by_symbol = {}

        futures = [
            Futures.Indices.SP_500_E_MINI
        ]

        for future in futures:
            # Requesting data
            continuous_contract = self.add_future(future,
                resolution = Resolution.DAILY,
                extended_market_hours = True,
                data_normalization_mode = DataNormalizationMode.BACKWARDS_RATIO,
                data_mapping_mode = DataMappingMode.OPEN_INTEREST,
                contract_depth_offset = 0
            )

            symbol_data = SymbolData(self, continuous_contract)
            self._symbol_data_by_symbol[continuous_contract.symbol] = symbol_data

    ### <summary>
    ### on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.
    ### </summary>
    ### <param name="slice">Slice object keyed by symbol containing the stock data</param>
    def on_data(self, slice):
        for symbol, symbol_data in self._symbol_data_by_symbol.items():
            # Call SymbolData.update() method to handle new data slice received
            symbol_data.update(slice)

            # Check if information in SymbolData class and new slice data are ready for trading
            if not symbol_data.is_ready or not slice.bars.contains_key(symbol):
                return

            ema_current_value = symbol_data.EMA.current.value
            if ema_current_value < symbol_data.price and not symbol_data.is_long:
                self.market_order(symbol_data.mapped, 1)
            elif ema_current_value > symbol_data.price and not symbol_data.is_short:
                self.market_order(symbol_data.mapped, -1)

class SymbolData:

    ### <summary>
    ### Constructor to instantiate the information needed to be hold
    ### </summary>
    def __init__(self, algorithm, future):
        self._algorithm = algorithm
        self._future = future
        self.EMA = algorithm.ema(future.symbol, 20, Resolution.DAILY)
        self.price = 0
        self.is_long = False
        self.is_short = False

        self.reset()

    @property
    def symbol(self):
        return self._future.symbol

    @property
    def mapped(self):
        return self._future.mapped

    @property
    def is_ready(self):
        return self.mapped is not None and self.EMA.is_ready

    ### <summary>
    ### Handler of new slice of data received
    ### </summary>
    def update(self, slice):
        if slice.symbol_changed_events.contains_key(self.symbol):
            changed_event = slice.symbol_changed_events[self.symbol]
            old_symbol = changed_event.old_symbol
            new_symbol = changed_event.new_symbol
            tag = f"Rollover - Symbol changed at {self._algorithm.time}: {old_symbol} -> {new_symbol}"
            quantity = self._algorithm.portfolio[old_symbol].quantity

            # Rolling over: to liquidate any position of the old mapped contract and switch to the newly mapped contract
            self._algorithm.liquidate(old_symbol, tag = tag)
            self._algorithm.market_order(new_symbol, quantity, tag = tag)

            self.reset()

        self.price = slice.bars[self.symbol].price if slice.bars.contains_key(self.symbol) else self.price
        self.is_long = self._algorithm.portfolio[self.mapped].is_long
        self.is_short = self._algorithm.portfolio[self.mapped].is_short

    ### <summary>
    ### reset RollingWindow/indicator to adapt to newly mapped contract, then warm up the RollingWindow/indicator
    ### </summary>
    def reset(self):
        self.EMA.reset()
        self._algorithm.warm_up_indicator(self.symbol, self.EMA, Resolution.DAILY)

    ### <summary>
    ### disposal method to remove consolidator/update method handler, and reset RollingWindow/indicator to free up memory and speed
    ### </summary>
    def dispose(self):
        self.EMA.reset()
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: Continuous Futures Regression algorithm. Asserting and showcasing the behavior of adding a continuous future

Output:
```python

from AlgorithmImports import *

class ContinuousFutureRegressionAlgorithm(QCAlgorithm):
    '''Basic template algorithm simply initializes the date range and cash'''

    def initialize(self):
        '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''

        self.set_start_date(2013, 7, 1)
        self.set_end_date(2014, 1, 1)

        self._previous_mapped_contract_symbols = []
        self._last_date_log = -1
        self._continuous_contract = self.add_future(Futures.Indices.SP_500_E_MINI,
                                                  data_normalization_mode = DataNormalizationMode.BACKWARDS_RATIO,
                                                  data_mapping_mode = DataMappingMode.LAST_TRADING_DAY,
                                                  contract_depth_offset= 0)
        self._current_mapped_symbol = self._continuous_contract.symbol

    def on_data(self, data):
        '''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.

        Arguments:
            data: Slice object keyed by symbol containing the stock data
        '''
        currently_mapped_security = self.securities[self._continuous_contract.mapped]
        if len(data.keys()) != 1:
            raise ValueError(f"We are getting data for more than one symbols! {','.join(data.keys())}")

        for changed_event in data.symbol_changed_events.values():
            if changed_event.symbol == self._continuous_contract.symbol:
                self._previous_mapped_contract_symbols.append(self.symbol(changed_event.old_symbol))
                self.log(f"SymbolChanged event: {changed_event}")

                if self._current_mapped_symbol == self._continuous_contract.mapped:
                    raise ValueError(f"Continuous contract current symbol did not change! {self._continuous_contract.mapped}")

        if self._last_date_log != self.time.month and currently_mapped_security.has_data:
            self._last_date_log = self.time.month

            self.log(f"{self.time}- {currently_mapped_security.get_last_data()}")
            if self.portfolio.invested:
                self.liquidate()
            else:
                # This works because we set this contract as tradable, even if it's a canonical security
                self.buy(currently_mapped_security.symbol, 1)

            if self.time.month == 1 and self.time.year == 2013:
                response = self.history( [ self._continuous_contract.symbol ], 60 * 24 * 90)
                if response.empty:
                    raise ValueError("Unexpected empty history response")

        self._current_mapped_symbol = self._continuous_contract.mapped

    def on_order_event(self, order_event):
        if order_event.status == OrderStatus.FILLED:
            self.debug("Purchased Stock: {0}".format(order_event.symbol))

    def on_securities_changed(self, changes):
        self.debug(f"{self.time}-{changes}")

    def on_end_of_algorithm(self):
        expected_mapping_counts = 2
        if len(self._previous_mapped_contract_symbols) != expected_mapping_counts:
            raise ValueError(f"Unexpected symbol changed events: {len(self._previous_mapped_contract_symbols)}, was expecting {expected_mapping_counts}")

        delisted_securities = [
            [security for security in self.securities.total if security.symbol == symbol][0]
            for symbol in self._previous_mapped_contract_symbols
        ]
        marked_delisted_securities = [security for security in delisted_securities if security.is_delisted and not security.is_tradable]
        if len(marked_delisted_securities) != len(delisted_securities):
            raise ValueError(f"Not all delisted contracts are properly marked as delisted and non-tradable: "
                             f"only {len(marked_delisted_securities)} are marked, was expecting {len(delisted_securities)}")
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: Regression algorithm to test we can specify a custom benchmark model, and override some of its methods

Output:
```python

from AlgorithmImports import *
from CustomBrokerageModelRegressionAlgorithm import CustomBrokerageModel

class CustomBenchmarkRegressionAlgorithm(QCAlgorithm):
    def initialize(self):
        self.set_start_date(2013,10,7)
        self.set_end_date(2013,10,11)
        self.set_brokerage_model(CustomBrokerageModelWithCustomBenchmark())
        self.add_equity("SPY", Resolution.DAILY)
        self.update_request_submitted = False

    def on_data(self, slice):
        benchmark = self.benchmark.evaluate(self.time)
        if (self.time.day % 2 == 0) and (benchmark != 1):
            raise AssertionError(f"Benchmark should be 1, but was {benchmark}")

        if (self.time.day % 2 == 1) and (benchmark != 2):
            raise AssertionError(f"Benchmark should be 2, but was {benchmark}")

class CustomBenchmark:
    def evaluate(self, time):
        if time.day % 2 == 0:
            return 1
        else:
            return 2

class CustomBrokerageModelWithCustomBenchmark(CustomBrokerageModel):
    def get_benchmark(self, securities):
        return CustomBenchmark()
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: This algorithm demonstrates the various ways you can call the History function,
what it returns, and what you can do with the returned values.

Output:
```python

from AlgorithmImports import *

class HistoryAlgorithm(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2013,10, 8)  #Set Start Date
        self.set_end_date(2013,10,11)    #Set End Date
        self.set_cash(100000)           #Set Strategy Cash

        # Find more symbols here: http://quantconnect.com/data
        self.add_equity("SPY", Resolution.DAILY)
        IBM = self.add_data(CustomDataEquity, "IBM", Resolution.DAILY)
        # specifying the exchange will allow the history methods that accept a number of bars to return to work properly
        IBM.Exchange = EquityExchange()

        # we can get history in initialize to set up indicators and such
        self.daily_sma = SimpleMovingAverage(14)

        # get the last calendar year's worth of SPY data at the configured resolution (daily)
        trade_bar_history = self.history([self.securities["SPY"].symbol], timedelta(365))
        self.assert_history_count("History<TradeBar>([\"SPY\"], timedelta(365))", trade_bar_history, 250)

        # get the last calendar day's worth of SPY data at the specified resolution
        trade_bar_history = self.history(["SPY"], timedelta(1), Resolution.MINUTE)
        self.assert_history_count("History([\"SPY\"], timedelta(1), Resolution.MINUTE)", trade_bar_history, 390)

        # get the last 14 bars of SPY at the configured resolution (daily)
        trade_bar_history = self.history(["SPY"], 14)
        self.assert_history_count("History([\"SPY\"], 14)", trade_bar_history, 14)

        # get the last 14 minute bars of SPY
        trade_bar_history = self.history(["SPY"], 14, Resolution.MINUTE)
        self.assert_history_count("History([\"SPY\"], 14, Resolution.MINUTE)", trade_bar_history, 14)

        # get the historical data from last current day to this current day in minute resolution
        # with Fill Forward and Extended Market options
        interval_bar_history = self.history(["SPY"], self.time - timedelta(1), self.time, Resolution.MINUTE, True, True)
        self.assert_history_count("History([\"SPY\"], self.time - timedelta(1), self.time, Resolution.MINUTE, True, True)", interval_bar_history, 960)

        # get the historical data from last current day to this current day in minute resolution
        # with Extended Market option
        interval_bar_history = self.history(["SPY"], self.time - timedelta(1), self.time, Resolution.MINUTE, False, True)
        self.assert_history_count("History([\"SPY\"], self.time - timedelta(1), self.time, Resolution.MINUTE, False, True)", interval_bar_history, 919)

        # get the historical data from last current day to this current day in minute resolution
        # with Fill Forward option
        interval_bar_history = self.history(["SPY"], self.time - timedelta(1), self.time, Resolution.MINUTE, True, False)
        self.assert_history_count("History([\"SPY\"], self.time - timedelta(1), self.time, Resolution.MINUTE, True, False)", interval_bar_history, 390)

        # get the historical data from last current day to this current day in minute resolution
        interval_bar_history = self.history(["SPY"], self.time - timedelta(1), self.time, Resolution.MINUTE, False, False)
        self.assert_history_count("History([\"SPY\"], self.time - timedelta(1), self.time, Resolution.MINUTE, False, False)", interval_bar_history, 390)

        # we can loop over the return value from these functions and we get TradeBars
        # we can use these TradeBars to initialize indicators or perform other math
        for index, trade_bar in trade_bar_history.loc["SPY"].iterrows():
            self.daily_sma.update(index, trade_bar["close"])

        # get the last calendar year's worth of custom_data data at the configured resolution (daily)
        custom_data_history = self.history(CustomDataEquity, "IBM", timedelta(365))
        self.assert_history_count("History(CustomDataEquity, \"IBM\", timedelta(365))", custom_data_history, 250)

        # get the last 10 bars of IBM at the configured resolution (daily)
        custom_data_history = self.history(CustomDataEquity, "IBM", 14)
        self.assert_history_count("History(CustomDataEquity, \"IBM\", 14)", custom_data_history, 14)

        # we can loop over the return values from these functions and we'll get Custom data
        # this can be used in much the same way as the trade_bar_history above
        self.daily_sma.reset()
        for index, custom_data in custom_data_history.loc["IBM"].iterrows():
            self.daily_sma.update(index, custom_data["value"])

        # get the last 10 bars worth of Custom data for the specified symbols at the configured resolution (daily)
        all_custom_data = self.history(CustomDataEquity, self.securities.keys(), 14)
        self.assert_history_count("History(CustomDataEquity, self.securities.keys(), 14)", all_custom_data, 14 * 2)

        # NOTE: Using different resolutions require that they are properly implemented in your data type. If your
        #  custom data source has different resolutions, it would need to be implemented in the GetSource and
        #  Reader methods properly.
        #custom_data_history = self.history(CustomDataEquity, "IBM", timedelta(7), Resolution.MINUTE)
        #custom_data_history = self.history(CustomDataEquity, "IBM", 14, Resolution.MINUTE)
        #all_custom_data = self.history(CustomDataEquity, timedelta(365), Resolution.MINUTE)
        #all_custom_data = self.history(CustomDataEquity, self.securities.keys(), 14, Resolution.MINUTE)
        #all_custom_data = self.history(CustomDataEquity, self.securities.keys(), timedelta(1), Resolution.MINUTE)
        #all_custom_data = self.history(CustomDataEquity, self.securities.keys(), 14, Resolution.MINUTE)

        # get the last calendar year's worth of all custom_data data
        all_custom_data = self.history(CustomDataEquity, self.securities.keys(), timedelta(365))
        self.assert_history_count("History(CustomDataEquity, self.securities.keys(), timedelta(365))", all_custom_data, 250 * 2)

        # we can also access the return value from the multiple symbol functions to request a single
        # symbol and then loop over it
        single_symbol_custom = all_custom_data.loc["IBM"]
        self.assert_history_count("all_custom_data.loc[\"IBM\"]", single_symbol_custom, 250)
        for  custom_data in single_symbol_custom:
            # do something with 'IBM.custom_data_equity' custom_data data
            pass

        custom_data_spyvalues = all_custom_data.loc["IBM"]["value"]
        self.assert_history_count("all_custom_data.loc[\"IBM\"][\"value\"]", custom_data_spyvalues, 250)
        for value in custom_data_spyvalues:
            # do something with 'IBM.custom_data_equity' value data
            pass

    def on_data(self, data):
        '''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.

        Arguments:
            data: Slice object keyed by symbol containing the stock data
        '''
        if not self.portfolio.invested:
            self.set_holdings("SPY", 1)

    def assert_history_count(self, method_call, trade_bar_history, expected):
        count = len(trade_bar_history.index)
        if count != expected:
            raise AssertionError("{} expected {}, but received {}".format(method_call, expected, count))

class CustomDataEquity(PythonData):
    def get_source(self, config, date, is_live):
        zip_file_name = LeanData.generate_zip_file_name(config.Symbol, date, config.Resolution, config.TickType)
        source = Globals.data_folder + "/equity/usa/daily/" + zip_file_name
        return SubscriptionDataSource(source)

    def reader(self, config, line, date, is_live):
        if line == None:
            return None

        custom_data = CustomDataEquity()
        custom_data.symbol = config.symbol

        csv = line.split(",")
        custom_data.time = datetime.strptime(csv[0], '%Y%m%d %H:%M')
        custom_data.end_time = custom_data.time + timedelta(days=1)
        custom_data.value = float(csv[1])
        return custom_data
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: This algorithm demonstrates extended market hours trading.

Output:
```python

from AlgorithmImports import *

class ExtendedMarketTradingRegressionAlgorithm(QCAlgorithm):

    def initialize(self):
        '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
        self.set_start_date(2013,10,7)   #Set Start Date
        self.set_end_date(2013,10,11)    #Set End Date
        self.set_cash(100000)           #Set Strategy Cash
        # Find more symbols here: http://quantconnect.com/data
        self.spy = self.add_equity("SPY", Resolution.MINUTE, Market.USA, True, 1, True)

        self._last_action = None

    def on_data(self, data):
        '''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
        if self._last_action is not None and self._last_action.date() == self.time.date():
            return

        spy_bar = data.bars['SPY']

        if not self.in_market_hours():
            self.limit_order("SPY", 10, spy_bar.low)
            self._last_action = self.time

    def on_order_event(self, order_event):
        self.log(str(order_event))
        if self.in_market_hours():
            raise AssertionError("Order processed during market hours.")

    def in_market_hours(self):
        now = self.time.time()
        open = time(9,30,0)
        close = time(16,0,0)
        return (open < now) and (close > now)

```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: This example algorithm defines its own custom coarse/fine fundamental selection model
with sector weighted portfolio.

Output:
```python

from AlgorithmImports import *

class SectorWeightingFrameworkAlgorithm(QCAlgorithm):
    '''This example algorithm defines its own custom coarse/fine fundamental selection model
    with sector weighted portfolio.'''

    def initialize(self):

        # Set requested data resolution
        self.universe_settings.resolution = Resolution.DAILY

        self.set_start_date(2014, 4, 2)
        self.set_end_date(2014, 4, 6)
        self.set_cash(100000)

        # set algorithm framework models
        self.set_universe_selection(FineFundamentalUniverseSelectionModel(self.select_coarse, self.select_fine))
        self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(1)))
        self.set_portfolio_construction(SectorWeightingPortfolioConstructionModel())

    def on_order_event(self, order_event):
        if order_event.status == OrderStatus.FILLED:
            self.debug(f"Order event: {order_event}. Holding value: {self.securities[order_event.symbol].holdings.absolute_holdings_value}")

    def select_coarse(self, coarse):
        # IndustryTemplateCode of AAPL, IBM and GOOG is N, AIG is I, BAC is B. SPY have no fundamentals
        tickers = ["AAPL", "AIG", "IBM"] if self.time.date() < date(2014, 4, 4) else [ "GOOG", "BAC", "SPY" ]
        return [Symbol.create(x, SecurityType.EQUITY, Market.USA) for x in tickers]

    def select_fine(self, fine):
        return [f.symbol for f in fine]
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: Regression algorithm testing portfolio construction model control over rebalancing,
specifying a custom rebalance function that returns null in some cases, see GH 4075.

Output:
```python

from AlgorithmImports import *

class PortfolioRebalanceOnCustomFuncRegressionAlgorithm(QCAlgorithm):
    def initialize(self):
        ''' Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''

        self.universe_settings.resolution = Resolution.DAILY

        # Order margin value has to have a minimum of 0.5% of Portfolio value, allows filtering out small trades and reduce fees.
        # Commented so regression algorithm is more sensitive
        #self.settings.minimum_order_margin_portfolio_percentage = 0.005

        self.set_start_date(2015, 1, 1)
        self.set_end_date(2018, 1, 1)

        self.settings.rebalance_portfolio_on_insight_changes = False
        self.settings.rebalance_portfolio_on_security_changes = False

        self.set_universe_selection(CustomUniverseSelectionModel("CustomUniverseSelectionModel", lambda time: [ "AAPL", "IBM", "FB", "SPY", "AIG", "BAC", "BNO" ]))
        self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, TimeSpan.from_minutes(20), 0.025, None))
        self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel(self.rebalance_function))
        self.set_execution(ImmediateExecutionModel())
        self.last_rebalance_time = self.start_date

    def rebalance_function(self, time):
        # for performance only run rebalance logic once a week, monday
        if time.weekday() != 0:
            return None

        if self.last_rebalance_time == self.start_date:
            # initial rebalance
            self.last_rebalance_time = time
            return time

        deviation = 0
        count = sum(1 for security in self.securities.values() if security.invested)
        if count > 0:
            self.last_rebalance_time = time
            portfolio_value_per_security = self.portfolio.total_portfolio_value / count
            for security in self.securities.values():
                if not security.invested:
                    continue
                reserved_buying_power_for_current_position = (security.buying_power_model.get_reserved_buying_power_for_position(
                    ReservedBuyingPowerForPositionParameters(security)).absolute_used_buying_power
                                                         * security.buying_power_model.get_leverage(security)) # see GH issue 4107
                # we sum up deviation for each security
                deviation += (portfolio_value_per_security - reserved_buying_power_for_current_position) / portfolio_value_per_security

            # if securities are deviated 1.5% from their theoretical share of TotalPortfolioValue we rebalance
            if deviation >= 0.015:
                return time
        return None

    def on_order_event(self, order_event):
        if order_event.status == OrderStatus.SUBMITTED:
            if self.utc_time != self.last_rebalance_time or self.utc_time.weekday() != 0:
                raise ValueError(f"{self.utc_time} {order_event.symbol}")
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: Regression algorithm illustrating how to request history data for different data mapping modes.

Output:
```python

from AlgorithmImports import *

class HistoryWithDifferentDataMappingModeRegressionAlgorithm(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2013, 10, 6)
        self.set_end_date(2014, 1, 1)
        self._continuous_contract_symbol = self.add_future(Futures.Indices.SP_500_E_MINI, Resolution.DAILY).symbol

    def on_end_of_algorithm(self):
        history_results = [
            self.history([self._continuous_contract_symbol], self.start_date, self.end_date, Resolution.DAILY, data_mapping_mode=data_mapping_mode)
                .droplevel(0, axis=0)
                .loc[self._continuous_contract_symbol]
                .close
            for data_mapping_mode in DataMappingMode
        ]

        if any(x.size != history_results[0].size for x in history_results):
            raise AssertionError("History results bar count did not match")

        # Check that close prices at each time are different for different data mapping modes
        for j in range(history_results[0].size):
            close_prices = set(history_results[i][j] for i in range(len(history_results)))
            if len(close_prices) != len(DataMappingMode):
                raise AssertionError("History results close prices should have been different for each data mapping mode at each time")
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: Regression algorithm to assert the behavior of <see cref="MaximumSectorExposureRiskManagementModel"/>.

Output:
```python

from AlgorithmImports import *
from BaseFrameworkRegressionAlgorithm import BaseFrameworkRegressionAlgorithm
from Risk.MaximumSectorExposureRiskManagementModel import MaximumSectorExposureRiskManagementModel

class MaximumSectorExposureRiskManagementModelFrameworkRegressionAlgorithm(BaseFrameworkRegressionAlgorithm):

    def initialize(self):
        super().initialize()
        # Set requested data resolution
        self.universe_settings.resolution = Resolution.DAILY

        self.set_start_date(2014, 2, 1)  #Set Start Date
        self.set_end_date(2014, 5, 1)    #Set End Date

        # set algorithm framework models
        tickers = [ "AAPL", "MSFT", "GOOG", "AIG", "BAC" ]
        self.set_universe_selection(FineFundamentalUniverseSelectionModel(
            lambda coarse: [ x.symbol for x in coarse if x.symbol.value in tickers ],
            lambda fine: [ x.symbol for x in fine ]
        ))

        # define risk management model such that maximum weight of a single sector be 10%
        # Number of of trades changed from 34 to 30 when using the MaximumSectorExposureRiskManagementModel
        self.set_risk_management(MaximumSectorExposureRiskManagementModel(0.1))

    def on_end_of_algorithm(self):
        pass
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: This regression algorithm tests In The Money (ITM) future option expiry for puts.
We expect 3 orders from the algorithm, which are:

  * Initial entry, buy ES Put Option (expiring ITM) (buy, qty 1)
  * Option exercise, receiving short ES future contracts (sell, qty -1)
  * Future contract liquidation, due to impending expiry (buy qty 1)

Additionally, we test delistings for future options and assert that our
portfolio holdings reflect the orders the algorithm has submitted.

Output:
```python

from AlgorithmImports import *

class FutureOptionPutITMExpiryRegressionAlgorithm(QCAlgorithm):
    def initialize(self):
        self.set_start_date(2020, 1, 5)
        self.set_end_date(2020, 6, 30)

        self.es19m20 = self.add_future_contract(
            Symbol.create_future(
                Futures.Indices.SP_500_E_MINI,
                Market.CME,
                datetime(2020, 6, 19)
            ),
            Resolution.MINUTE).symbol

        # Select a future option expiring ITM, and adds it to the algorithm.
        self.es_option = self.add_future_option_contract(
            list(
                sorted([x for x in self.option_chain(self.es19m20) if x.id.strike_price >= 3300.0 and x.id.option_right == OptionRight.PUT],
                       key=lambda x: x.id.strike_price)
            )[0], Resolution.MINUTE).symbol

        self.expected_contract = Symbol.create_option(self.es19m20, Market.CME, OptionStyle.AMERICAN, OptionRight.PUT, 3300.0, datetime(2020, 6, 19))
        if self.es_option != self.expected_contract:
            raise AssertionError(f"Contract {self.expected_contract} was not found in the chain")

        self.schedule.on(self.date_rules.tomorrow, self.time_rules.after_market_open(self.es19m20, 1), self.schedule_callback)

    def schedule_callback(self):
        self.market_order(self.es_option, 1)

    def on_data(self, data: Slice):
        # Assert delistings, so that we can make sure that we receive the delisting warnings at
        # the expected time. These assertions detect bug #4872
        for delisting in data.delistings.values():
            if delisting.type == DelistingType.WARNING:
                if delisting.time != datetime(2020, 6, 19):
                    raise AssertionError(f"Delisting warning issued at unexpected date: {delisting.time}")
            elif delisting.type == DelistingType.DELISTED:
                if delisting.time != datetime(2020, 6, 20):
                    raise AssertionError(f"Delisting happened at unexpected date: {delisting.time}")

    def on_order_event(self, order_event: OrderEvent):
        if order_event.status != OrderStatus.FILLED:
            # There's lots of noise with OnOrderEvent, but we're only interested in fills.
            return

        if not self.securities.contains_key(order_event.symbol):
            raise AssertionError(f"Order event Symbol not found in Securities collection: {order_event.symbol}")

        security = self.securities[order_event.symbol]
        if security.symbol == self.es19m20:
            self.assert_future_option_order_exercise(order_event, security, self.securities[self.expected_contract])
        elif security.symbol == self.expected_contract:
            # Expected contract is ES19M20 Call Option expiring ITM @ 3250
            self.assert_future_option_contract_order(order_event, security)
        else:
            raise AssertionError(f"Received order event for unknown Symbol: {order_event.symbol}")

        self.log(f"{self.time} -- {order_event.symbol} :: Price: {self.securities[order_event.symbol].holdings.price} Qty: {self.securities[order_event.symbol].holdings.quantity} Direction: {order_event.direction} Msg: {order_event.message}")

    def assert_future_option_order_exercise(self, order_event: OrderEvent, future: Security, option_contract: Security):
        expected_liquidation_time_utc = datetime(2020, 6, 20, 4, 0, 0)

        if order_event.direction == OrderDirection.BUY and future.holdings.quantity != 0:
            # We expect the contract to have been liquidated immediately
            raise AssertionError(f"Did not liquidate existing holdings for Symbol {future.symbol}")
        if order_event.direction == OrderDirection.BUY and order_event.utc_time.replace(tzinfo=None) != expected_liquidation_time_utc:
            raise AssertionError(f"Liquidated future contract, but not at the expected time. Expected: {expected_liquidation_time_utc} - found {order_event.utc_time.replace(tzinfo=None)}")

        # No way to detect option exercise orders or any other kind of special orders
        # other than matching strings, for now.
        if "Option Exercise" in order_event.message:
            if order_event.fill_price != 3300.0:
                raise AssertionError("Option did not exercise at expected strike price (3300)")

            if future.holdings.quantity != -1:
                # Here, we expect to have some holdings in the underlying, but not in the future option anymore.
                raise AssertionError(f"Exercised option contract, but we have no holdings for Future {future.symbol}")

            if option_contract.holdings.quantity != 0:
                raise AssertionError(f"Exercised option contract, but we have holdings for Option contract {option_contract.symbol}")

    def assert_future_option_contract_order(self, order_event: OrderEvent, option: Security):
        if order_event.direction == OrderDirection.BUY and option.holdings.quantity != 1:
            raise AssertionError(f"No holdings were created for option contract {option.symbol}")

        if order_event.direction == OrderDirection.SELL and option.holdings.quantity != 0:
            raise AssertionError(f"Holdings were found after a filled option exercise")

        if "Exercise" in order_event.message and option.holdings.quantity != 0:
            raise AssertionError(f"Holdings were found after exercising option contract {option.symbol}")

    def on_end_of_algorithm(self):
        if self.portfolio.invested:
            raise AssertionError(f"Expected no holdings at end of algorithm, but are invested in: {', '.join([str(i.id) for i in self.portfolio.keys()])}")
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: A demonstration of consolidating options data into larger bars for your algorithm.

Output:
```python

from AlgorithmImports import *

class BasicTemplateOptionsConsolidationAlgorithm(QCAlgorithm):
    def initialize(self):
        self.set_start_date(2013, 10, 7)
        self.set_end_date(2013, 10, 11)
        self.set_cash(1000000)

        # Subscribe and set our filter for the options chain
        option = self.add_option('SPY')
        # set our strike/expiry filter for this option chain
        # SetFilter method accepts timedelta objects or integer for days.
        # The following statements yield the same filtering criteria
        option.set_filter(-2, +2, 0, 180)
        # option.set_filter(-2, +2, timedelta(0), timedelta(180))
        self.consolidators = dict()

    def on_quote_bar_consolidated(self, sender, quote_bar):
        self.log("OnQuoteBarConsolidated called on " + str(self.time))
        self.log(str(quote_bar))

    def on_trade_bar_consolidated(self, sender, trade_bar):
        self.log("OnTradeBarConsolidated called on " + str(self.time))
        self.log(str(trade_bar))

    def on_securities_changed(self, changes):
        for security in changes.added_securities:
            if security.type == SecurityType.EQUITY:
                trade_bar_consolidator = TradeBarConsolidator(timedelta(minutes=5))
                trade_bar_consolidator.data_consolidated += self.on_trade_bar_consolidated
                self.subscription_manager.add_consolidator(security.symbol, trade_bar_consolidator)
                self.consolidators[security.symbol] = trade_bar_consolidator
            else:
                quote_bar_consolidator = QuoteBarConsolidator(timedelta(minutes=5))
                quote_bar_consolidator.data_consolidated += self.on_quote_bar_consolidated
                self.subscription_manager.add_consolidator(security.symbol, quote_bar_consolidator)
                self.consolidators[security.symbol] = quote_bar_consolidator

        for security in changes.removed_securities:
            consolidator = self.consolidators.pop(security.symbol)
            self.subscription_manager.remove_consolidator(security.symbol, consolidator)

            if security.type == SecurityType.EQUITY:
                consolidator.data_consolidated -= self.on_trade_bar_consolidated
            else:
                consolidator.data_consolidated -= self.on_quote_bar_consolidated
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: Algorithm demonstrating and ensuring that Bybit crypto brokerage model works as expected with custom data types

Output:
```python

from datetime import time
import os
from AlgorithmImports import *

class BybitCustomDataCryptoRegressionAlgorithm(QCAlgorithm):

    def initialize(self) -> None:
        self.set_start_date(2022, 12, 13)
        self.set_end_date(2022, 12, 13)

        self.set_account_currency("USDT")
        self.set_cash(100000)

        self.set_brokerage_model(BrokerageName.BYBIT, AccountType.CASH)

        symbol = self.add_crypto("BTCUSDT").symbol
        self._btc_usdt = self.add_data(CustomCryptoData, symbol, Resolution.MINUTE).symbol

        # create two moving averages
        self._fast = self.ema(self._btc_usdt, 30, Resolution.MINUTE)
        self._slow = self.ema(self._btc_usdt, 60, Resolution.MINUTE)

    def on_data(self, data: Slice) -> None:
        if not self._slow.is_ready:
            return

        if self._fast.current.value > self._slow.current.value:
            if self.transactions.orders_count == 0:
                self.buy(self._btc_usdt, 1)
        else:
            if self.transactions.orders_count == 1:
                self.liquidate(self._btc_usdt)

    def on_order_event(self, order_event: OrderEvent) -> None:
        self.debug(f"{self.time} {order_event}")

class CustomCryptoData(PythonData):
    def get_source(self, config: SubscriptionDataConfig, date: datetime, is_live_mode: bool) -> SubscriptionDataSource:
        tick_type_string = Extensions.tick_type_to_lower(config.tick_type)
        formatted_date = date.strftime("%Y%m%d")
        source = os.path.join(Globals.data_folder, "crypto", "bybit", "minute",
                              config.symbol.value.lower(), f"{formatted_date}_{tick_type_string}.zip")

        return SubscriptionDataSource(source, SubscriptionTransportMedium.LOCAL_FILE, FileFormat.CSV)

    def reader(self, config: SubscriptionDataConfig, line: str, date: datetime, is_live_mode: bool) -> BaseData:
        csv = line.split(',')

        data = CustomCryptoData()
        data.symbol = config.symbol

        data_datetime = datetime.combine(date.date(), time()) + timedelta(milliseconds=int(csv[0]))
        data.time = Extensions.convert_to(data_datetime, config.data_time_zone, config.exchange_time_zone)
        data.end_time = data.time + timedelta(minutes=1)

        data["Open"] = float(csv[1])
        data["High"] = float(csv[2])
        data["Low"] = float(csv[3])
        data["Close"] = float(csv[4])
        data["Volume"] = float(csv[5])
        data.value = float(csv[4])

        return data
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: This base algorithm demonstrates how to use OptionStrategies helper class to batch send orders for common strategies.

Output:
```python

from AlgorithmImports import *
from QuantConnect.Securities.Positions import IPositionGroup

class OptionStrategyFactoryMethodsBaseAlgorithm(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2015, 12, 24)
        self.set_end_date(2015, 12, 24)
        self.set_cash(1000000)

        option = self.add_option("GOOG")
        self._option_symbol = option.symbol

        option.set_filter(-2, +2, 0, 180)

        self.set_benchmark("GOOG")

    def on_data(self, slice):
        if not self.portfolio.invested:
            chain = slice.option_chains.get(self._option_symbol)
            if chain is not None:
                self.trade_strategy(chain, self._option_symbol)
        else:
            # Verify that the strategy was traded
            position_group = list(self.portfolio.positions.groups)[0]

            buying_power_model = position_group.buying_power_model
            if not isinstance(buying_power_model, OptionStrategyPositionGroupBuyingPowerModel):
                raise AssertionError("Expected position group buying power model type: OptionStrategyPositionGroupBuyingPowerModel. "
                                f"Actual: {type(position_group.buying_power_model).__name__}")

            self.assert_strategy_position_group(position_group, self._option_symbol)

            # Now we should be able to close the position
            self.liquidate_strategy()

            # We can quit now, no more testing required
            self.quit()

    def on_end_of_algorithm(self):
        if self.portfolio.invested:
            raise AssertionError("Expected no holdings at end of algorithm")

        orders_count = len(list(self.transactions.get_orders(lambda order: order.status == OrderStatus.FILLED)))
        if orders_count != self.expected_orders_count():
            raise AssertionError(f"Expected {self.expected_orders_count()} orders to have been submitted and filled, "
                            f"half for buying the strategy and the other half for the liquidation. Actual {orders_count}")

    def expected_orders_count(self) -> int:
        raise NotImplementedError("ExpectedOrdersCount method is not implemented")

    def trade_strategy(self, chain: OptionChain, option_symbol: Symbol) -> None:
        raise NotImplementedError("TradeStrategy method is not implemented")

    def assert_strategy_position_group(self, position_group: IPositionGroup, option_symbol: Symbol) -> None:
        raise NotImplementedError("AssertStrategyPositionGroup method is not implemented")

    def liquidate_strategy(self) -> None:
        raise NotImplementedError("LiquidateStrategy method is not implemented")
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: This example algorithm shows how to import and use Tiingo daily prices data.

Output:
```python

from AlgorithmImports import *
from QuantConnect.Data.Custom.Tiingo import TiingoPrice

class TiingoPriceAlgorithm(QCAlgorithm):

    def initialize(self):
        # Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
        self.set_start_date(2017, 1, 1)
        self.set_end_date(2017, 12, 31)
        self.set_cash(100000)

        # Set your Tiingo API Token here
        Tiingo.set_auth_code("my-tiingo-api-token")

        self._equity = self.add_equity("AAPL").symbol
        self._aapl = self.add_data(TiingoPrice, self._equity, Resolution.DAILY).symbol

        self._ema_fast = self.ema(self._equity, 5)
        self._ema_slow = self.ema(self._equity, 10)

    def on_data(self, slice):
        # OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.

        if not slice.contains_key(self._equity): return

        # Extract Tiingo data from the slice
        row = slice[self._equity]

        if not row:
            return

        if self._ema_fast.is_ready and self._ema_slow.is_ready:
            self.log(f"{self.time} - {row.symbol.value} - {row.close} {row.value} {row.price} - EmaFast:{self._ema_fast} - EmaSlow:{self._ema_slow}")

        # Simple EMA cross
        if not self.portfolio.invested and self._ema_fast > self._ema_slow:
            self.set_holdings(self._equity, 1)

        elif self.portfolio.invested and self._ema_fast < self._ema_slow:
            self.liquidate(self._equity)
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: Regression algorithm reproducing GH issue #5921. Asserting a security can be warmup correctly on initialize

Output:
```python

from AlgorithmImports import *

class SecuritySeederRegressionAlgorithm(QCAlgorithm):
    def initialize(self):
        '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''

        self.set_start_date(2013,10, 8)
        self.set_end_date(2013,10,10)

        self.set_security_initializer(BrokerageModelSecurityInitializer(self.brokerage_model,
                                                                        FuncSecuritySeeder(self.get_last_known_prices)))
        self.add_equity("SPY", Resolution.MINUTE)

    def on_data(self, data):
        '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.

        Arguments:
            data: Slice object keyed by symbol containing the stock data
        '''
        if not self.portfolio.invested:
            self.set_holdings("SPY", 1)

    def on_securities_changed(self, changes):
        for added_security in changes.added_securities:
            if not added_security.has_data \
                or added_security.ask_price == 0 \
                or added_security.bid_price == 0 \
                or added_security.bid_size == 0 \
                or added_security.ask_size == 0 \
                or added_security.price == 0 \
                or added_security.volume == 0 \
                or added_security.high == 0 \
                or added_security.low == 0 \
                or added_security.open == 0 \
                or added_security.close == 0:
                raise ValueError(f"Security {added_security.symbol} was not warmed up!")
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: Demonstration of payments for cash dividends in backtesting. When data normalization mode is set
to "Raw" the dividends are paid as cash directly into your portfolio.

Output:
```python

from AlgorithmImports import *

class DividendAlgorithm(QCAlgorithm):

    def initialize(self):
        '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
        self.set_start_date(1998,1,1)  #Set Start Date
        self.set_end_date(2006,1,21)    #Set End Date
        self.set_cash(100000)           #Set Strategy Cash
        # Find more symbols here: http://quantconnect.com/data
        equity = self.add_equity("MSFT", Resolution.DAILY)
        equity.set_data_normalization_mode(DataNormalizationMode.RAW)

        # this will use the Tradier Brokerage open order split behavior
        # forward split will modify open order to maintain order value
        # reverse split open orders will be cancelled
        self.set_brokerage_model(BrokerageName.TRADIER_BROKERAGE)

    def on_data(self, data):
        '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
        bar = data["MSFT"]
        if self.transactions.orders_count == 0:
            self.set_holdings("MSFT", .5)
            # place some orders that won't fill, when the split comes in they'll get modified to reflect the split
            quantity = self.calculate_order_quantity("MSFT", .25)
            self.debug(f"Purchased Stock: {bar.price}")
            self.stop_market_order("MSFT", -quantity, bar.low/2)
            self.limit_order("MSFT", -quantity, bar.high*2)

        if data.dividends.contains_key("MSFT"):
            dividend = data.dividends["MSFT"]
            self.log(f"{self.time} >> DIVIDEND >> {dividend.symbol} - {dividend.distribution} - {self.portfolio.cash} - {self.portfolio['MSFT'].price}")

        if data.splits.contains_key("MSFT"):
            split = data.splits["MSFT"]
            self.log(f"{self.time} >> SPLIT >> {split.symbol} - {split.split_factor} - {self.portfolio.cash} - {self.portfolio['MSFT'].price}")

    def on_order_event(self, order_event):
        # orders get adjusted based on split events to maintain order value
        order = self.transactions.get_order_by_id(order_event.order_id)
        self.log(f"{self.time} >> ORDER >> {order}")
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: This regression algorithm tests Out of The Money (OTM) index option expiry for calls.
We expect 2 orders from the algorithm, which are:

  * Initial entry, buy SPX Call Option (expiring OTM)
    - contract expires worthless, not exercised, so never opened a position in the underlying

  * Liquidation of worthless SPX call option (expiring OTM)

Additionally, we test delistings for index options and assert that our
portfolio holdings reflect the orders the algorithm has submitted.

Output:
```python

from AlgorithmImports import *

class IndexOptionCallOTMExpiryRegressionAlgorithm(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2021, 1, 4)
        self.set_end_date(2021, 1, 31)

        self.spx = self.add_index("SPX", Resolution.MINUTE).symbol

        # Select a index option call expiring OTM, and adds it to the algorithm.
        self.spx_options = list(self.option_chain(self.spx))
        self.spx_options = [i for i in self.spx_options if i.id.strike_price <= 3200 and i.id.option_right == OptionRight.PUT and i.id.date.year == 2021 and i.id.date.month == 1]
        self.spx_option_contract = list(sorted(self.spx_options, key=lambda x: x.id.strike_price, reverse=True))[0]
        self.spx_option = self.add_index_option_contract(self.spx_option_contract, Resolution.MINUTE).symbol

        self.expected_contract = Symbol.create_option(
            self.spx,
            Market.USA,
            OptionStyle.EUROPEAN,
            OptionRight.PUT,
            3200,
            datetime(2021, 1, 15)
        )

        if self.spx_option != self.expected_contract:
            raise AssertionError(f"Contract {self.expected_contract} was not found in the chain")

        self.schedule.on(
            self.date_rules.tomorrow,
            self.time_rules.after_market_open(self.spx, 1),
            lambda: self.market_order(self.spx_option, 1)
        )

    def on_data(self, data: Slice):
        # Assert delistings, so that we can make sure that we receive the delisting warnings at
        # the expected time. These assertions detect bug #4872
        for delisting in data.delistings.values():
            if delisting.type == DelistingType.WARNING:
                if delisting.time != datetime(2021, 1, 15):
                    raise AssertionError(f"Delisting warning issued at unexpected date: {delisting.time}")

            if delisting.type == DelistingType.DELISTED:
                if delisting.time != datetime(2021, 1, 16):
                    raise AssertionError(f"Delisting happened at unexpected date: {delisting.time}")

    def on_order_event(self, order_event: OrderEvent):
        if order_event.status != OrderStatus.FILLED:
            # There's lots of noise with OnOrderEvent, but we're only interested in fills.
            return

        if order_event.symbol not in self.securities:
            raise AssertionError(f"Order event Symbol not found in Securities collection: {order_event.symbol}")

        security = self.securities[order_event.symbol]
        if security.symbol == self.spx:
            raise AssertionError("Invalid state: did not expect a position for the underlying to be opened, since this contract expires OTM")

        if security.symbol == self.expected_contract:
            self.assert_index_option_contract_order(order_event, security)
        else:
            raise AssertionError(f"Received order event for unknown Symbol: {order_event.symbol}")

    def assert_index_option_contract_order(self, order_event: OrderEvent, option: Security):
        if order_event.direction == OrderDirection.BUY and option.holdings.quantity != 1:
            raise AssertionError(f"No holdings were created for option contract {option.symbol}")
        if order_event.direction == OrderDirection.SELL and option.holdings.quantity != 0:
            raise AssertionError("Holdings were found after a filled option exercise")
        if order_event.direction == OrderDirection.SELL and not "OTM" in order_event.message:
            raise AssertionError("Contract did not expire OTM")
        if "Exercise" in order_event.message:
            raise AssertionError("Exercised option, even though it expires OTM")

    ### <summary>
    ### Ran at the end of the algorithm to ensure the algorithm has no holdings
    ### </summary>
    ### <exception cref="Exception">The algorithm has holdings</exception>
    def on_end_of_algorithm(self):
        if self.portfolio.invested:
            raise AssertionError(f"Expected no holdings at end of algorithm, but are invested in: {', '.join(self.portfolio.keys())}")
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: This regression algorithm checks if all the option chain data coming to the algo is consistent with current securities manager state

Output:
```python

from AlgorithmImports import *

class OptionChainConsistencyRegressionAlgorithm(QCAlgorithm):

    underlying_ticker = "GOOG"

    def initialize(self):

        self.set_cash(10000)
        self.set_start_date(2015,12,24)
        self.set_end_date(2015,12,24)

        self.equity = self.add_equity(self.underlying_ticker)
        self.option = self.add_option(self.underlying_ticker)

        # set our strike/expiry filter for this option chain
        self.option.set_filter(self.universe_func)

        self.set_benchmark(self.equity.symbol)

    def on_data(self, slice):
        if self.portfolio.invested: return
        for kvp in slice.option_chains:
            chain = kvp.value
            for o in chain:
                if not self.securities.contains_key(o.symbol):
                    self.log("Inconsistency found: option chains contains contract {0} that is not available in securities manager and not available for trading".format(o.symbol.value))

            contracts = filter(lambda x: x.expiry.date() == self.time.date() and
                                         x.strike < chain.underlying.price and
                                         x.right == OptionRight.CALL, chain)

            sorted_contracts = sorted(contracts, key = lambda x: x.strike, reverse = True)

            if len(sorted_contracts) > 2:
                self.market_order(sorted_contracts[2].symbol, 1)
                self.market_on_close_order(sorted_contracts[2].symbol, -1)

    # set our strike/expiry filter for this option chain
    def universe_func(self, universe):
        return universe.include_weeklys().strikes(-2, 2).expiration(timedelta(0), timedelta(10))

    def on_order_event(self, order_event):
        self.log(str(order_event))
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: Regression Channel algorithm simply initializes the date range and cash

Output:
```python

from AlgorithmImports import *

class RegressionChannelAlgorithm(QCAlgorithm):

    def initialize(self):

        self.set_cash(100000)
        self.set_start_date(2009,1,1)
        self.set_end_date(2015,1,1)

        equity = self.add_equity("SPY", Resolution.MINUTE)
        self._spy = equity.symbol
        self._holdings = equity.holdings
        self._rc = self.rc(self._spy, 30, 2, Resolution.DAILY)

        stock_plot = Chart("Trade Plot")
        stock_plot.add_series(Series("Buy", SeriesType.SCATTER, 0))
        stock_plot.add_series(Series("Sell", SeriesType.SCATTER, 0))
        stock_plot.add_series(Series("UpperChannel", SeriesType.LINE, 0))
        stock_plot.add_series(Series("LowerChannel", SeriesType.LINE, 0))
        stock_plot.add_series(Series("Regression", SeriesType.LINE, 0))
        self.add_chart(stock_plot)

    def on_data(self, data):
        if (not self._rc.is_ready) or (not data.contains_key(self._spy)): return
        if data[self._spy] is None: return
        value = data[self._spy].value
        if self._holdings.quantity <= 0 and value < self._rc.lower_channel.current.value:
            self.set_holdings(self._spy, 1)
            self.plot("Trade Plot", "Buy", value)
        if self._holdings.quantity >= 0 and value > self._rc.upper_channel.current.value:
            self.set_holdings(self._spy, -1)
            self.plot("Trade Plot", "Sell", value)

    def on_end_of_day(self, symbol):
        self.plot("Trade Plot", "UpperChannel", self._rc.upper_channel.current.value)
        self.plot("Trade Plot", "LowerChannel", self._rc.lower_channel.current.value)
        self.plot("Trade Plot", "Regression", self._rc.linear_regression.current.value)
```


Instruction: You are a quantive developer and need to generate code for use in QuantConnect's LEAN algorithm framework.

Input:
Generate a LEAN Algorithm that can be described like this
: his algorithm sends a list of portfolio targets to custom endpoint

Output:
```python

from AlgorithmImports import *

class CustomSignalExportDemonstrationAlgorithm(QCAlgorithm):

    def initialize(self) -> None:
        ''' Initialize the date and add all equity symbols present in list _symbols '''

        self.set_start_date(2013, 10, 7)   #Set Start Date
        self.set_end_date(2013, 10, 11)    #Set End Date
        self.set_cash(100000)             #Set Strategy Cash

        # Our custom signal export accepts all asset types
        self.add_equity("SPY", Resolution.SECOND)
        self.add_crypto("BTCUSD", Resolution.SECOND)
        self.add_forex("EURUSD", Resolution.SECOND)
        self.add_future_contract(Symbol.create_future("ES", Market.CME, datetime(2023, 12, 15)))
        self.add_option_contract(Symbol.create_option("SPY", Market.USA, OptionStyle.AMERICAN, OptionRight.CALL, 130, datetime(2023, 9, 1)))

        # Set CustomSignalExport signal export provider.
        self.signal_export.add_signal_export_provider(CustomSignalExport())

    def on_data(self, data: Slice) -> None:
        '''Buy and hold EURUSD and SPY'''
        for ticker in [ "SPY", "EURUSD", "BTCUSD" ]:
            if not self.portfolio[ticker].invested and self.securities[ticker].has_data:
                self.set_holdings(ticker, 0.5)

from requests import post
class CustomSignalExport:
    def send(self, parameters: SignalExportTargetParameters) -> bool:
        targets = [PortfolioTarget.percent(parameters.algorithm, x.symbol, x.quantity)
                   for x in parameters.targets]
        data = [ {'symbol' : x.symbol.value, 'quantity': x.quantity} for x in targets ]
        response = post("http://localhost:5000/", json = data)
        result = response.json()
        success = result.get('success', False)
        parameters.algorithm.log(f"Send #{len(parameters.targets)} targets. Success: {success}")
        return success

    def dispose(self):
        pass

'''
# To test the algorithm, you can create a simple Python Flask application (app.py) and run flask
# $ flask --app app run

# app.py:
from flask import Flask, request, jsonify
from json import loads
app = Flask(__name__)
@app.post('/')
def handle_positions():
    result = loads(request.data)
    print(result)
    return jsonify({'success': True,'message': f'{len(result)} positions received'})
if __name__ == '__main__':
    app.run(debug=True)
'''
```