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
: In this algorithm we submit/update/cancel each order type

Output:
```python

from AlgorithmImports import *

class OrderTicketDemoAlgorithm(QCAlgorithm):
    '''In this algorithm we submit/update/cancel each order type'''
    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
        equity = self.add_equity("SPY")
        self.spy = equity.symbol

        self.__open_market_on_open_orders = []
        self.__open_market_on_close_orders = []
        self.__open_limit_orders = []
        self.__open_stop_market_orders = []
        self.__open_stop_limit_orders = []
        self.__open_trailing_stop_orders = []

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

        # LIMIT ORDERS
        self.limit_orders()

        # STOP MARKET ORDERS
        self.stop_market_orders()

        # STOP LIMIT ORDERS
        self.stop_limit_orders()

        # TRAILING STOP ORDERS
        self.trailing_stop_orders()

        # MARKET ON OPEN ORDERS
        self.market_on_open_orders()

        # MARKET ON CLOSE ORDERS
        self.market_on_close_orders()

    def market_orders(self):
        ''' MarketOrders are the only orders that are processed synchronously by default, so
        they'll fill by the next line of code. This behavior equally applies to live mode.
        You can opt out of this behavior by specifying the 'asynchronous' parameter as True.'''
        if self.time_is(7, 9, 31):
            self.log("Submitting MarketOrder")

            # submit a market order to buy 10 shares, this function returns an OrderTicket object
            # we submit the order with asynchronous = False, so it block until it is filled
            new_ticket = self.market_order(self.spy, 10, asynchronous = False)
            if new_ticket.status != OrderStatus.FILLED:
                self.log("Synchronous market order was not filled synchronously!")
                self.quit()

            # we can also submit the ticket asynchronously. In a backtest, we'll still perform the fill
            # before the next time events for your algorithm. here we'll submit the order asynchronously
            # and try to cancel it, sometimes it will, sometimes it will be filled first.
            new_ticket = self.market_order(self.spy, 10, asynchronous = True)
            response = new_ticket.cancel("Attempt to cancel async order")
            if response.is_success:
                self.log("Successfully canceled async market order: {0}".format(new_ticket.order_id))
            else:
                self.log("Unable to cancel async market order: {0}".format(response.error_code))

    def limit_orders(self):
        '''LimitOrders are always processed asynchronously. Limit orders are used to
        set 'good' entry points for an order. For example, you may wish to go
        long a stock, but want a good price, so can place a LimitOrder to buy with
        a limit price below the current market price. Likewise the opposite is True
        when selling, you can place a LimitOrder to sell with a limit price above the
        current market price to get a better sale price.
        You can submit requests to update or cancel the LimitOrder at any time.
        The 'LimitPrice' for an order can be retrieved from the ticket using the
        OrderTicket.get(OrderField) method, for example:
        Code:
            current_limit_price = order_ticket.get(OrderField.LIMIT_PRICE)'''
        if self.time_is(7, 12, 0):
            self.log("Submitting LimitOrder")

            # submit a limit order to buy 10 shares at .1% below the bar's close
            close = self.securities[self.spy.value].close
            new_ticket = self.limit_order(self.spy, 10, close * .999)
            self.__open_limit_orders.append(new_ticket)

            # submit another limit order to sell 10 shares at .1% above the bar's close
            new_ticket = self.limit_order(self.spy, -10, close * 1.001)
            self.__open_limit_orders.append(new_ticket)

        # when we submitted new limit orders we placed them into this list,
        # so while there's two entries they're still open and need processing
        if len(self.__open_limit_orders) == 2:
            open_orders = self.__open_limit_orders

            # check if either is filled and cancel the other
            long_order = open_orders[0]
            short_order = open_orders[1]
            if self.check_pair_orders_for_fills(long_order, short_order):
                self.__open_limit_orders = []
                return

            # if neither order has filled, bring in the limits by a penny
            new_long_limit = long_order.get(OrderField.LIMIT_PRICE) + 0.01
            new_short_limit = short_order.get(OrderField.LIMIT_PRICE) - 0.01
            self.log("Updating limits - Long: {0:.2f} Short: {1:.2f}".format(new_long_limit, new_short_limit))

            update_order_fields = UpdateOrderFields()
            update_order_fields.limit_price = new_long_limit
            update_order_fields.tag = "Update #{0}".format(len(long_order.update_requests) + 1)
            long_order.update(update_order_fields)

            update_order_fields = UpdateOrderFields()
            update_order_fields.limit_price = new_short_limit
            update_order_fields.tag = "Update #{0}".format(len(short_order.update_requests) + 1)
            short_order.update(update_order_fields)

    def stop_market_orders(self):
        '''StopMarketOrders work in the opposite way that limit orders do.
        When placing a long trade, the stop price must be above current
        market price. In this way it's a 'stop loss' for a short trade.
        When placing a short trade, the stop price must be below current
        market price. In this way it's a 'stop loss' for a long trade.
        You can submit requests to update or cancel the StopMarketOrder at any time.
        The 'StopPrice' for an order can be retrieved from the ticket using the
        OrderTicket.get(OrderField) method, for example:
        Code:
            current_stop_price = order_ticket.get(OrderField.STOP_PRICE)'''
        if self.time_is(7, 12 + 4, 0):
            self.log("Submitting StopMarketOrder")

            # a long stop is triggered when the price rises above the value
            # so we'll set a long stop .25% above the current bar's close
            close = self.securities[self.spy.value].close
            new_ticket = self.stop_market_order(self.spy, 10, close * 1.0025)
            self.__open_stop_market_orders.append(new_ticket)

            # a short stop is triggered when the price falls below the value
            # so we'll set a short stop .25% below the current bar's close
            new_ticket = self.stop_market_order(self.spy, -10, close * .9975)
            self.__open_stop_market_orders.append(new_ticket)

        # when we submitted new stop market orders we placed them into this list,
        # so while there's two entries they're still open and need processing
        if len(self.__open_stop_market_orders) == 2:
            # check if either is filled and cancel the other
            long_order = self.__open_stop_market_orders[0]
            short_order = self.__open_stop_market_orders[1]
            if self.check_pair_orders_for_fills(long_order, short_order):
                self.__open_stop_market_orders = []
                return

            # if neither order has filled, bring in the stops by a penny
            new_long_stop = long_order.get(OrderField.STOP_PRICE) - 0.01
            new_short_stop = short_order.get(OrderField.STOP_PRICE) + 0.01
            self.log("Updating stops - Long: {0:.2f} Short: {1:.2f}".format(new_long_stop, new_short_stop))

            update_order_fields = UpdateOrderFields()
            update_order_fields.stop_price = new_long_stop
            update_order_fields.tag = "Update #{0}".format(len(long_order.update_requests) + 1)
            long_order.update(update_order_fields)

            update_order_fields = UpdateOrderFields()
            update_order_fields.stop_price = new_short_stop
            update_order_fields.tag = "Update #{0}".format(len(short_order.update_requests) + 1)
            short_order.update(update_order_fields)
            self.log("Updated price - Long: {0} Short: {1}".format(long_order.get(OrderField.STOP_PRICE), short_order.get(OrderField.STOP_PRICE)))

    def stop_limit_orders(self):
        '''StopLimitOrders work as a combined stop and limit order. First, the
        price must pass the stop price in the same way a StopMarketOrder works,
        but then we're also guaranteed a fill price at least as good as the
        limit price. This order type can be beneficial in gap down scenarios
        where a StopMarketOrder would have triggered and given the not as beneficial
        gapped down price, whereas the StopLimitOrder could protect you from
        getting the gapped down price through prudent placement of the limit price.
        You can submit requests to update or cancel the StopLimitOrder at any time.
        The 'StopPrice' or 'LimitPrice' for an order can be retrieved from the ticket
        using the OrderTicket.get(OrderField) method, for example:
        Code:
            current_stop_price = order_ticket.get(OrderField.STOP_PRICE)
            current_limit_price = order_ticket.get(OrderField.LIMIT_PRICE)'''
        if self.time_is(8, 12, 1):
            self.log("Submitting StopLimitOrder")

            # a long stop is triggered when the price rises above the
            # value so we'll set a long stop .25% above the current bar's
            # close now we'll also be setting a limit, this means we are
            # guaranteed to get at least the limit price for our fills,
            # so make the limit price a little higher than the stop price

            close = self.securities[self.spy.value].close
            new_ticket = self.stop_limit_order(self.spy, 10, close * 1.001, close - 0.03)
            self.__open_stop_limit_orders.append(new_ticket)

            # a short stop is triggered when the price falls below the
            # value so we'll set a short stop .25% below the current bar's
            # close now we'll also be setting a limit, this means we are
            # guaranteed to get at least the limit price for our fills,
            # so make the limit price a little softer than the stop price

            new_ticket = self.stop_limit_order(self.spy, -10, close * .999, close + 0.03)
            self.__open_stop_limit_orders.append(new_ticket)

        # when we submitted new stop limit orders we placed them into this list,
        # so while there's two entries they're still open and need processing
        if len(self.__open_stop_limit_orders) == 2:
            long_order = self.__open_stop_limit_orders[0]
            short_order = self.__open_stop_limit_orders[1]
            if self.check_pair_orders_for_fills(long_order, short_order):
                self.__open_stop_limit_orders = []
                return

            # if neither order has filled, bring in the stops/limits in by a penny

            new_long_stop = long_order.get(OrderField.STOP_PRICE) - 0.01
            new_long_limit = long_order.get(OrderField.LIMIT_PRICE) + 0.01
            new_short_stop = short_order.get(OrderField.STOP_PRICE) + 0.01
            new_short_limit = short_order.get(OrderField.LIMIT_PRICE) - 0.01
            self.log("Updating stops  - Long: {0:.2f} Short: {1:.2f}".format(new_long_stop, new_short_stop))
            self.log("Updating limits - Long: {0:.2f}  Short: {1:.2f}".format(new_long_limit, new_short_limit))

            update_order_fields = UpdateOrderFields()
            update_order_fields.stop_price = new_long_stop
            update_order_fields.limit_price = new_long_limit
            update_order_fields.tag = "Update #{0}".format(len(long_order.update_requests) + 1)
            long_order.update(update_order_fields)

            update_order_fields = UpdateOrderFields()
            update_order_fields.stop_price = new_short_stop
            update_order_fields.limit_price = new_short_limit
            update_order_fields.tag = "Update #{0}".format(len(short_order.update_requests) + 1)
            short_order.update(update_order_fields)

    def trailing_stop_orders(self):
        '''TrailingStopOrders work the same way as StopMarketOrders, except
        their stop price is adjusted to a certain amount, keeping it a certain
        fixed distance from/to the market price, depending on the order direction,
        which allows to preserve profits and protecting against losses.
        The stop price can be accessed just as with StopMarketOrders, and
        the trailing amount can be accessed with the OrderTicket.get(OrderField), for example:
        Code:
            current_trailing_amount = order_ticket.get(OrderField.STOP_PRICE)
            trailing_as_percentage = order_ticket.get[bool](OrderField.TRAILING_AS_PERCENTAGE)'''
        if self.time_is(7, 12, 0):
            self.log("Submitting TrailingStopOrder")

            # a long stop is triggered when the price rises above the
            # value so we'll set a long stop .25% above the current bar's

            close = self.securities[self.spy.value].close
            stop_price = close * 1.0025
            new_ticket = self.trailing_stop_order(self.spy, 10, stop_price, trailing_amount=0.0025, trailing_as_percentage=True)
            self.__open_trailing_stop_orders.append(new_ticket)

            # a short stop is triggered when the price falls below the
            # value so we'll set a short stop .25% below the current bar's

            stop_price = close * .9975
            new_ticket = self.trailing_stop_order(self.spy, -10, stop_price, trailing_amount=0.0025, trailing_as_percentage=True)
            self.__open_trailing_stop_orders.append(new_ticket)

        # when we submitted new stop market orders we placed them into this list,
        # so while there's two entries they're still open and need processing
        elif len(self.__open_trailing_stop_orders) == 2:
            long_order = self.__open_trailing_stop_orders[0]
            short_order = self.__open_trailing_stop_orders[1]
            if self.check_pair_orders_for_fills(long_order, short_order):
                self.__open_trailing_stop_orders = []
                return

            # if neither order has filled in the last 5 minutes, bring in the trailing percentage by 0.01%
            if ((self.utc_time - long_order.time).total_seconds() / 60) % 5 != 0:
                return

            long_trailing_percentage = long_order.get(OrderField.TRAILING_AMOUNT)
            new_long_trailing_percentage = max(long_trailing_percentage - 0.0001, 0.0001)
            short_trailing_percentage = short_order.get(OrderField.TRAILING_AMOUNT)
            new_short_trailing_percentage = max(short_trailing_percentage - 0.0001, 0.0001)
            self.log("Updating trailing percentages - Long: {0:.3f} Short: {1:.3f}".format(new_long_trailing_percentage, new_short_trailing_percentage))

            update_order_fields = UpdateOrderFields()
            # we could change the quantity, but need to specify it
            #Quantity =
            update_order_fields.trailing_amount = new_long_trailing_percentage
            update_order_fields.tag = "Update #{0}".format(len(long_order.update_requests) + 1)
            long_order.update(update_order_fields)

            update_order_fields = UpdateOrderFields()
            update_order_fields.trailing_amount = new_short_trailing_percentage
            update_order_fields.tag = "Update #{0}".format(len(short_order.update_requests) + 1)
            short_order.update(update_order_fields)

    def market_on_close_orders(self):
        '''MarketOnCloseOrders are always executed at the next market's closing price.
        The only properties that can be updated are the quantity and order tag properties.'''
        if self.time_is(9, 12, 0):
            self.log("Submitting MarketOnCloseOrder")

            # open a new position or triple our existing position
            qty = self.portfolio[self.spy.value].quantity
            qty = 100 if qty == 0 else 2*qty

            new_ticket = self.market_on_close_order(self.spy, qty)
            self.__open_market_on_close_orders.append(new_ticket)

        if len(self.__open_market_on_close_orders) == 1 and self.time.minute == 59:
            ticket = self.__open_market_on_close_orders[0]
            # check for fills
            if ticket.status == OrderStatus.FILLED:
                self.__open_market_on_close_orders = []
                return

            quantity = ticket.quantity + 1
            self.log("Updating quantity  - New Quantity: {0}".format(quantity))

            # we can update the quantity and tag
            update_order_fields = UpdateOrderFields()
            update_order_fields.quantity = quantity
            update_order_fields.tag = "Update #{0}".format(len(ticket.update_requests) + 1)
            ticket.update(update_order_fields)

        if self.time_is(self.end_date.day, 12 + 3, 45):
            self.log("Submitting MarketOnCloseOrder to liquidate end of algorithm")
            self.market_on_close_order(self.spy, -self.portfolio[self.spy.value].quantity, tag="Liquidate end of algorithm")

    def market_on_open_orders(self):
        '''MarketOnOpenOrders are always executed at the next
        market's opening price. The only properties that can
        be updated are the quantity and order tag properties.'''
        if self.time_is(8, 14 + 2, 0):
            self.log("Submitting MarketOnOpenOrder")

            # its EOD, let's submit a market on open order to short even more!
            new_ticket = self.market_on_open_order(self.spy, 50)
            self.__open_market_on_open_orders.append(new_ticket)

        if len(self.__open_market_on_open_orders) == 1 and self.time.minute == 59:
            ticket = self.__open_market_on_open_orders[0]

            # check for fills
            if ticket.status == OrderStatus.FILLED:
                self.__open_market_on_open_orders = []
                return

            quantity = ticket.quantity + 1
            self.log("Updating quantity  - New Quantity: {0}".format(quantity))

            # we can update the quantity and tag
            update_order_fields = UpdateOrderFields()
            update_order_fields.quantity = quantity
            update_order_fields.tag = "Update #{0}".format(len(ticket.update_requests) + 1)
            ticket.update(update_order_fields)

    def on_order_event(self, order_event):
        order = self.transactions.get_order_by_id(order_event.order_id)
        self.log("{0}: {1}: {2}".format(self.time, order.type, order_event))

        if order_event.quantity == 0:
            raise AssertionError("OrderEvent quantity is Not expected to be 0, it should hold the current order Quantity")

        if order_event.quantity != order.quantity:
            raise AssertionError("OrderEvent quantity should hold the current order Quantity")

        if (type(order) is LimitOrder and order_event.limit_price == 0 or
            type(order) is StopLimitOrder and order_event.limit_price == 0):
            raise AssertionError("OrderEvent LimitPrice is Not expected to be 0 for LimitOrder and StopLimitOrder")

        if type(order) is StopMarketOrder and order_event.stop_price == 0:
            raise AssertionError("OrderEvent StopPrice is Not expected to be 0 for StopMarketOrder")

        # We can access the order ticket from the order event
        if order_event.ticket is None:
            raise AssertionError("OrderEvent Ticket was not set")
        if order_event.order_id != order_event.ticket.order_id:
            raise AssertionError("OrderEvent.ORDER_ID and order_event.ticket.order_id do not match")

    def check_pair_orders_for_fills(self, long_order, short_order):
        if long_order.status == OrderStatus.FILLED:
            self.log("{0}: Cancelling short order, long order is filled.".format(short_order.order_type))
            short_order.cancel("Long filled.")
            return True

        if short_order.status == OrderStatus.FILLED:
            self.log("{0}: Cancelling long order, short order is filled.".format(long_order.order_type))
            long_order.cancel("Short filled")
            return True

        return False

    def time_is(self, day, hour, minute):
        return self.time.day == day and self.time.hour == hour and self.time.minute == minute

    def on_end_of_algorithm(self):
        basic_order_ticket_filter = lambda x: x.symbol == self.spy

        filled_orders = self.transactions.get_orders(lambda x: x.status == OrderStatus.FILLED)
        order_tickets = self.transactions.get_order_tickets(basic_order_ticket_filter)
        open_orders = self.transactions.get_open_orders(lambda x: x.symbol == self.spy)
        open_order_tickets = self.transactions.get_open_order_tickets(basic_order_ticket_filter)
        remaining_open_orders = self.transactions.get_open_orders_remaining_quantity(basic_order_ticket_filter)

        # The type returned by self.transactions.get_orders() is iterable and not a list
        # that's why we use sum() to get the size of the iterable object type
        filled_orders_size = sum(1 for order in filled_orders)
        order_tickets_size = sum(1 for ticket in order_tickets)
        open_order_tickets_size = sum(1 for ticket in open_order_tickets)

        assert(filled_orders_size == 9 and order_tickets_size == 12), "There were expected 9 filled orders and 12 order tickets"
        assert(not (len(open_orders) or open_order_tickets_size)), "No open orders or tickets were expected"
        assert(not remaining_open_orders), "No remaining quantity to be filled from open orders was expected"

        spy_open_orders = self.transactions.get_open_orders(self.spy)
        spy_open_order_tickets = self.transactions.get_open_order_tickets(self.spy)
        spy_open_order_tickets_size = sum(1 for tickets in spy_open_order_tickets)
        spy_open_orders_remaining_quantity = self.transactions.get_open_orders_remaining_quantity(self.spy)

        assert(not (len(spy_open_orders) or spy_open_order_tickets_size)), "No open orders or tickets were expected"
        assert(not spy_open_orders_remaining_quantity), "No remaining quantity to be filled from open orders was expected"

        default_orders = self.transactions.get_orders()
        default_order_tickets = self.transactions.get_order_tickets()
        default_open_orders = self.transactions.get_open_orders()
        default_open_order_tickets = self.transactions.get_open_order_tickets()
        default_open_orders_remaining = self.transactions.get_open_orders_remaining_quantity()

        default_orders_size = sum(1 for order in default_orders)
        default_order_tickets_size = sum(1 for ticket in default_order_tickets)
        default_open_order_tickets_size = sum(1 for ticket in default_open_order_tickets)

        assert(default_orders_size == 12 and default_order_tickets_size == 12), "There were expected 12 orders and 12 order tickets"
        assert(not (len(default_open_orders) or default_open_order_tickets_size)), "No open orders or tickets were expected"
        assert(not default_open_orders_remaining), "No remaining quantity to be filled from open orders was expected"
```


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 test algorithm for scheduled universe selection GH 3890

Output:
```python

from AlgorithmImports import *

class FundamentalCustomSelectionTimeRegressionAlgorithm(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._month_start_selection = 0
        self._month_end_selection = 0
        self._specific_date_selection = 0
        self._symbol = Symbol.create("SPY", SecurityType.EQUITY, Market.USA)

        self.set_start_date(2014, 3, 25)
        self.set_end_date(2014, 5, 10)
        self.universe_settings.resolution = Resolution.DAILY

        # Test use case A
        self.add_universe(self.date_rules.month_start(), self.selection_function__month_start)

        # Test use case B
        other_settings = UniverseSettings(self.universe_settings)
        other_settings.schedule.on(self.date_rules.month_end())

        self.add_universe(FundamentalUniverse.usa(self.selection_function__month_end, other_settings))

        # Test use case C
        self.universe_settings.schedule.on(self.date_rules.on(datetime(2014, 5, 9)))
        self.add_universe(FundamentalUniverse.usa(self.selection_function__specific_date))

    def selection_function__specific_date(self, coarse):
        self._specific_date_selection += 1
        if self.time != datetime(2014, 5, 9):
            raise ValueError("SelectionFunction_SpecificDate unexpected selection: " + str(self.time))
        return [ self._symbol ]

    def selection_function__month_start(self, coarse):
        self._month_start_selection += 1
        if self._month_start_selection == 1:
            if self.time != self.start_date:
                raise ValueError("Month Start Unexpected initial selection: " + str(self.time))
        elif self.time != datetime(2014, 4, 1) and self.time != datetime(2014, 5, 1):
            raise ValueError("Month Start unexpected selection: " + str(self.time))
        return [ self._symbol ]

    def selection_function__month_end(self, coarse):
        self._month_end_selection += 1
        if self._month_end_selection == 1:
            if self.time != self.start_date:
                raise ValueError("Month End unexpected initial selection: " + str(self.time))
        elif self.time != datetime(2014, 3, 31) and self.time != datetime(2014, 4, 30):
            raise ValueError("Month End unexpected selection: " + str(self.time))
        return [ self._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
        '''
        if not self.portfolio.invested:
            self.set_holdings(self._symbol, 1)

    def on_end_of_algorithm(self):
        if self._month_end_selection != 3:
            raise ValueError("Month End unexpected selection count: " + str(self._month_end_selection))
        if self._month_start_selection != 3:
            raise ValueError("Month Start unexpected selection count: " + str(self._month_start_selection))
        if self._specific_date_selection != 1:
            raise ValueError("Specific date unexpected selection count: " + str(self._month_start_selection))
```


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 India Index Algorithm uses framework components to define the algorithm.

Output:
```python

from AlgorithmImports import *

class BasicTemplateIndiaIndexAlgorithm(QCAlgorithm):
    '''Basic template framework algorithm uses framework components to define the algorithm.'''

    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_account_currency("INR") #Set Account Currency
        self.set_start_date(2019, 1, 1)  #Set Start Date
        self.set_end_date(2019, 1, 5)    #Set End Date
        self.set_cash(1000000)          #Set Strategy Cash

        # Use indicator for signal; but it cannot be traded
        self.nifty = self.add_index("NIFTY50", Resolution.MINUTE, Market.INDIA).symbol
        # Trade Index based ETF
        self.nifty_etf = self.add_equity("JUNIORBEES", Resolution.MINUTE, Market.INDIA).symbol

        # Set Order Properties as per the requirements for order placement
        self.default_order_properties = IndiaOrderProperties(Exchange.NSE)

        # Define indicator
        self._ema_slow = self.ema(self.nifty, 80)
        self._ema_fast = self.ema(self.nifty, 200)

        self.debug("numpy test >>> print numpy.pi: " + str(np.pi))

    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 data.bars.contains_key(self.nifty) or not data.bars.contains_key(self.nifty_etf):
            return

        if not self._ema_slow.is_ready:
            return

        if self._ema_fast > self._ema_slow:
            if not self.portfolio.invested:
                self.market_ticket = self.market_order(self.nifty_etf, 1)
        else:
            self.liquidate()

    def on_end_of_algorithm(self):
        if self.portfolio[self.nifty].total_sale_volume > 0:
            raise AssertionError("Index is not tradable.")

```


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 for asserting that tick history that includes multiple tick types (trade, quote) is correctly converted to a pandas
dataframe without raising exceptions. The main exception in this case was a "non-unique multi-index" error due to trades adn quote ticks with
duplicated timestamps.

Output:
```python

from AlgorithmImports import *

class PandasDataFrameFromMultipleTickTypeTickHistoryRegressionAlgorithm(QCAlgorithm):
    def initialize(self):
        self.set_start_date(2013, 10, 8)
        self.set_end_date(2013, 10, 8)

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

        subscriptions = [x for x in self.subscription_manager.subscriptions if x.symbol == spy]
        if len(subscriptions) != 2:
            raise AssertionError(f"Expected 2 subscriptions, but found {len(subscriptions)}")

        history = pd.DataFrame()
        try:
            history = self.history(Tick, spy, timedelta(days=1), Resolution.TICK)
        except Exception as e:
            raise AssertionError(f"History call failed: {e}")

        if history.shape[0] == 0:
            raise AssertionError("SPY tick history is empty")

        if not np.array_equal(history.columns.to_numpy(), ['askprice', 'asksize', 'bidprice', 'bidsize', 'exchange', 'lastprice', 'quantity']):
            raise AssertionError("Unexpected columns in SPY tick history")

        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
: In this example we look at the canonical 15/30 day moving average cross. This algorithm
will go long when the 15 crosses above the 30 and will liquidate when the 15 crosses
back below the 30.

Output:
```python

from AlgorithmImports import *

class MovingAverageCrossAlgorithm(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(2009, 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.add_equity("SPY")

        # create a 15 day exponential moving average
        self.fast = self.ema("SPY", 15, Resolution.DAILY)

        # create a 30 day exponential moving average
        self.slow = self.ema("SPY", 30, Resolution.DAILY)

        self.previous = None

    def on_data(self, data):
        '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
        # a couple things to notice in this method:
        #  1. We never need to 'update' our indicators with the data, the engine takes care of this for us
        #  2. We can use indicators directly in math expressions
        #  3. We can easily plot many indicators at the same time

        # wait for our slow ema to fully initialize
        if not self.slow.is_ready:
            return

        # only once per day
        if self.previous is not None and self.previous.date() == self.time.date():
            return

        # define a small tolerance on our checks to avoid bouncing
        tolerance = 0.00015

        holdings = self.portfolio["SPY"].quantity

        # we only want to go long if we're currently short or flat
        if holdings <= 0:
            # if the fast is greater than the slow, we'll go long
            if self.fast.current.value > self.slow.current.value *(1 + tolerance):
                self.log("BUY  >> {0}".format(self.securities["SPY"].price))
                self.set_holdings("SPY", 1.0)

        # we only want to liquidate if we're currently long
        # if the fast is less than the slow we'll liquidate our long
        if holdings > 0 and self.fast.current.value < self.slow.current.value:
            self.log("SELL >> {0}".format(self.securities["SPY"].price))
            self.liquidate("SPY")

        self.previous = self.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
: Basic template algorithm simply initializes the date range and cash. This is a skeleton
framework you can use for designing an algorithm.

Output:
```python

from AlgorithmImports import *

class BasicTemplateAlgorithm(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,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.MINUTE)
        self.debug("numpy test >>> print numpy.pi: " + str(np.pi))

    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)
```


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) future option expiry for short calls.
We expect 2 orders from the algorithm, which are:

  * Initial entry, sell ES Call Option (expiring OTM)
    - Profit the option premium, since the option was not assigned.

  * Liquidation of ES call OTM contract on the last trade date

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 FutureOptionShortCallOTMExpiryRegressionAlgorithm(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 >= 3400.0 and x.id.option_right == OptionRight.CALL],
                    key=lambda x: x.id.strike_price
                )
            )[0], Resolution.MINUTE).symbol

        self.expected_contract = Symbol.create_option(self.es19m20, Market.CME, OptionStyle.AMERICAN, OptionRight.CALL, 3400.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.scheduled_market_order)

    def scheduled_market_order(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}")

            if 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:
            raise AssertionError(f"Expected no order events for underlying Symbol {security.symbol}")

        if security.symbol == self.expected_contract:
            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"{order_event}")

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

        if order_event.direction == OrderDirection.BUY and option_contract.holdings.quantity != 0:
            raise AssertionError("Expected no options holdings after closing position")

        if order_event.is_assignment:
            raise AssertionError(f"Assignment was not expected for {order_event.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
: Regression algorithm to assert the behavior of <see cref="RsiAlphaModel"/>.

Output:
```python

from AlgorithmImports import *
from BaseFrameworkRegressionAlgorithm import BaseFrameworkRegressionAlgorithm
from Alphas.RsiAlphaModel import RsiAlphaModel

class RsiAlphaModelFrameworkRegressionAlgorithm(BaseFrameworkRegressionAlgorithm):

    def initialize(self):
        super().initialize()
        self.set_alpha(RsiAlphaModel())

    def on_end_of_algorithm(self):
        # We have removed all securities from the universe. The Alpha Model should remove the consolidator
        consolidator_count = sum([s.consolidators.count for s in self.subscription_manager.subscriptions])
        if consolidator_count > 0:
            raise AssertionError(f"The number of consolidators should be zero. Actual: {consolidator_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
: This algorithm showcases some features of the IObjectStore feature.

Output:
```python

from AlgorithmImports import *
from io import StringIO

class ObjectStoreExampleAlgorithm(QCAlgorithm):
    '''This algorithm showcases some features of the IObjectStore feature.
    One use case is to make consecutive backtests run faster by caching the results of
    potentially time consuming operations. In this example, we save the results of a
    history call. This pattern can be equally applied to a machine learning model being
    trained and then saving the model weights in the object store.
    '''
    spy_close_object_store_key = "spy_close"
    spy_close_history = RollingWindow(252)
    spy_close_ema10_history = RollingWindow(252)
    spy_close_ema50_history = RollingWindow(252)

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

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

        self.spy_close = self.identity(self.SPY, Resolution.DAILY)
        self.spy_close_ema10 = IndicatorExtensions.ema(self.spy_close, 10)
        self.spy_close_ema50 = IndicatorExtensions.ema(self.spy_close, 50)

        # track last year of close and EMA10/EMA50
        self.spy_close.updated += lambda _, args: self.spy_close_history.add(args)
        self.spy_close_ema10.updated += lambda _, args: self.spy_close_ema10_history.add(args)
        self.spy_close_ema50.updated += lambda _, args: self.spy_close_ema50_history.add(args)

        if self.object_store.contains_key(self.spy_close_object_store_key):
            # our object store has our historical data saved, read the data
            # and push it through the indicators to warm everything up
            values = self.object_store.read(self.spy_close_object_store_key)
            self.debug(f'{self.spy_close_object_store_key} key exists in object store.')

            history = pd.read_csv(StringIO(values), header=None, index_col=0, squeeze=True)
            history.index = pd.to_datetime(history.index)
            for time, close in history.items():
                self.spy_close.update(time, close)

        else:
            self.debug(f'{self.spy_close_object_store_key} key does not exist in object store. Fetching history...')

            # if our object store doesn't have our data, fetch the history to initialize
            # we're pulling the last year's worth of SPY daily trade bars to fee into our indicators
            history = self.history(self.SPY, timedelta(365), Resolution.DAILY).close.unstack(0).squeeze()

            for time, close in history.items():
                self.spy_close.update(time, close)

            # save our warm up data so next time we don't need to issue the history request
            self.object_store.save(self.spy_close_object_store_key,
                '\n'.join(reversed([f'{x.end_time},{x.value}' for x in self.spy_close_history])))

            # Can also use ObjectStore.save_bytes(key, byte[])
            # and to read  ObjectStore.read_bytes(key) => byte[]

            # we can also get a file path for our data. some ML libraries require model
            # weights to be loaded directly from a file path. The object store can provide
            # a file path for any key by: ObjectStore.get_file_path(key) => string (file path)

    def on_data(self, slice):

        close = self.spy_close
        ema10 = self.spy_close_ema10
        ema50 = self.spy_close_ema50

        if ema10 > close and ema10 > ema50:
            self.set_holdings(self.SPY, 1)

        elif ema10 < close and ema10 < ema50:
            self.set_holdings(self.SPY, -1)

        elif ema10 < ema50 and self.portfolio[self.SPY].is_long:
            self.liquidate(self.SPY)

        elif ema10 > ema50 and self.portfolio[self.SPY].is_short:
            self.liquidate(self.SPY)
```


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 test for consistency of hour data over a reverse split event in US equities.

Output:
```python

from AlgorithmImports import *

class HourSplitRegressionAlgorithm(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2014, 6, 6)
        self.set_end_date(2014, 6, 9)
        self.set_cash(100000)
        self.set_benchmark(lambda x: 0)

        self._symbol = self.add_equity("AAPL", Resolution.HOUR).symbol

    def on_data(self, slice):
        if slice.bars.count == 0: return
        if (not self.portfolio.invested) and self.time.date() == self.end_date.date():
            self.buy(self._symbol, 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
: Regression algorithm to test zeroed benchmark through BrokerageModel override

Output:
```python

from AlgorithmImports import *

class ZeroedBenchmarkRegressionAlgorithm(QCAlgorithm):

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

        # Add Equity
        self.add_equity("SPY", Resolution.HOUR)

        # Use our Test Brokerage Model with zerod default benchmark
        self.set_brokerage_model(TestBrokerageModel())

    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)

class TestBrokerageModel(DefaultBrokerageModel):

    def get_benchmark(self, securities):
        return FuncBenchmark(self.func)

    def func(self, datetime):
        return 0
```


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 sends a list of portfolio targets from algorithm's Portfolio
to Collective2 API every time the ema indicators crosses between themselves.

Output:
```python

from AlgorithmImports import *

class Collective2PortfolioSignalExportDemonstrationAlgorithm(QCAlgorithm):

    def initialize(self):
        ''' 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

        # Symbols accepted by Collective2. Collective2 accepts stock, future, forex and US stock option symbols
        self.add_equity("GOOG")
        self._symbols = [
            Symbol.create("SPY", SecurityType.EQUITY, Market.USA, None, None),
            Symbol.create("EURUSD", SecurityType.FOREX, Market.OANDA, None, None),
            Symbol.create_future("ES", Market.CME, datetime(2023, 12, 15), None),
            Symbol.create_option("GOOG", Market.USA, OptionStyle.AMERICAN, OptionRight.CALL, 130, datetime(2023, 9, 1))
        ]
        for item in self._symbols:
            self.add_security(item)

        self.fast = self.ema("SPY", 10)
        self.slow = self.ema("SPY", 100)

        # Initialize these flags, to check when the ema indicators crosses between themselves
        self.ema_fast_is_not_set = True
        self.ema_fast_was_above = False

        # Collective2 APIv4 KEY: This value is provided by Collective2 in their webpage in your account section (See https://collective2.com/account-info)
        # See API documentation at https://trade.collective2.com/c2-api
        self.collective2_apikey = "YOUR APIV4 KEY"

        # Collective2 System ID: This value is found beside the system's name (strategy's name) on the main system page
        self.collective2_system_id = 0

        # Disable automatic exports as we manually set them
        self.signal_export.automatic_export_time_span = None

        # Set Collective2 signal export provider
        self.signal_export.add_signal_export_provider(Collective2SignalExport(self.collective2_apikey, self.collective2_system_id))

        self.first_call = True

        self.set_warm_up(100)

    def on_data(self, data):
        ''' Reduce the quantity of holdings for one security and increase the holdings to the another
        one when the EMA's indicators crosses between themselves, then send a signal to Collective2 API '''
        if self.is_warming_up: return

        # Place an order as soon as possible to send a signal.
        if self.first_call:
            self.set_holdings("SPY", 0.1)
            self.signal_export.set_target_portfolio_from_portfolio()
            self.first_call = False

        fast = self.fast.current.value
        slow = self.slow.current.value

        # Set the value of flag _ema_fast_was_above, to know when the ema indicators crosses between themselves
        if self.ema_fast_is_not_set == True:
            if fast > slow *1.001:
                self.ema_fast_was_above = True
            else:
                self.ema_fast_was_above = False
            self.ema_fast_is_not_set = False

        # Check whether ema fast and ema slow crosses. If they do, set holdings to SPY
        # or reduce its holdings, and send signals to Collective2 API from your Portfolio
        if fast > slow * 1.001 and (not self.ema_fast_was_above):
            self.set_holdings("SPY", 0.1)
            self.signal_export.set_target_portfolio_from_portfolio()
        elif fast < slow * 0.999 and (self.ema_fast_was_above):
            self.set_holdings("SPY", 0.01)
            self.signal_export.set_target_portfolio_from_portfolio()
```


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 data type bugs in the Consolidate API. Related to GH 4205.

Output:
```python

from AlgorithmImports import *
from CustomDataRegressionAlgorithm import Bitcoin

class ConsolidateRegressionAlgorithm(QCAlgorithm):

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

        SP500 = Symbol.create(Futures.Indices.SP_500_E_MINI, SecurityType.FUTURE, Market.CME)
        symbol = list(self.futures_chain(SP500))[0]
        self._future = self.add_future_contract(symbol)

        tradable_dates_count = len(list(Time.each_tradeable_day_in_time_zone(self._future.exchange.hours,
                                                                             self.start_date,
                                                                             self.end_date,
                                                                             self._future.exchange.time_zone,
                                                                             False)))
        self._expected_consolidation_counts = []

        self.consolidate(symbol, Calendar.MONTHLY, lambda bar: self.update_monthly_consolidator(bar)) # shouldn't consolidate

        self.consolidate(symbol, Calendar.WEEKLY, TickType.TRADE, lambda bar: self.update_weekly_consolidator(bar))

        self.consolidate(symbol, Resolution.DAILY, lambda bar: self.update_trade_bar(bar, 0))
        self._expected_consolidation_counts.append(tradable_dates_count)

        self.consolidate(symbol, Resolution.DAILY, TickType.QUOTE, lambda bar: self.update_quote_bar(bar, 1))
        self._expected_consolidation_counts.append(tradable_dates_count)

        self.consolidate(symbol, timedelta(1), lambda bar: self.update_trade_bar(bar, 2))
        self._expected_consolidation_counts.append(tradable_dates_count - 1)

        self.consolidate(symbol, timedelta(1), TickType.QUOTE, lambda bar: self.update_quote_bar(bar, 3))
        self._expected_consolidation_counts.append(tradable_dates_count - 1)

        # sending None tick type
        self.consolidate(symbol, timedelta(1), None, lambda bar: self.update_trade_bar(bar, 4))
        self._expected_consolidation_counts.append(tradable_dates_count - 1)

        self.consolidate(symbol, Resolution.DAILY, None, lambda bar: self.update_trade_bar(bar, 5))
        self._expected_consolidation_counts.append(tradable_dates_count)

        self._consolidation_counts = [0] * len(self._expected_consolidation_counts)
        self._smas = [SimpleMovingAverage(10) for x in self._consolidation_counts]
        self._last_sma_updates = [datetime.min for x in self._consolidation_counts]
        self._monthly_consolidator_sma = SimpleMovingAverage(10)
        self._monthly_consolidation_count = 0
        self._weekly_consolidator_sma = SimpleMovingAverage(10)
        self._weekly_consolidation_count = 0
        self._last_weekly_sma_update = datetime.min

        # custom data
        self._custom_data_consolidator = 0
        custom_symbol = self.add_data(Bitcoin, "BTC", Resolution.DAILY).symbol
        self.consolidate(custom_symbol, timedelta(1), lambda bar: self.increment_counter(1))

        self._custom_data_consolidator2 = 0
        self.consolidate(custom_symbol, Resolution.DAILY, lambda bar: self.increment_counter(2))

    def increment_counter(self, id):
        if id == 1:
            self._custom_data_consolidator += 1
        if id == 2:
            self._custom_data_consolidator2 += 1

    def update_trade_bar(self, bar, position):
        self._smas[position].update(bar.end_time, bar.volume)
        self._last_sma_updates[position] = bar.end_time
        self._consolidation_counts[position] += 1

    def update_quote_bar(self, bar, position):
        self._smas[position].update(bar.end_time, bar.ask.high)
        self._last_sma_updates[position] = bar.end_time
        self._consolidation_counts[position] += 1

    def update_monthly_consolidator(self, bar):
        self._monthly_consolidator_sma.update(bar.end_time, bar.volume)
        self._monthly_consolidation_count += 1

    def update_weekly_consolidator(self, bar):
        self._weekly_consolidator_sma.update(bar.end_time, bar.volume)
        self._last_weekly_sma_update = bar.end_time
        self._weekly_consolidation_count += 1

    def on_end_of_algorithm(self):
        for i, expected_consolidation_count in enumerate(self._expected_consolidation_counts):
            consolidation_count = self._consolidation_counts[i]
            if consolidation_count != expected_consolidation_count:
                raise ValueError(f"Unexpected consolidation count for index {i}: expected {expected_consolidation_count} but was {consolidation_count}")

        expected_weekly_consolidations = (self.end_date - self.start_date).days // 7
        if self._weekly_consolidation_count != expected_weekly_consolidations:
            raise ValueError(f"Expected {expected_weekly_consolidations} weekly consolidations but found {self._weekly_consolidation_count}")

        if self._custom_data_consolidator == 0:
            raise ValueError("Custom data consolidator did not consolidate any data")

        if self._custom_data_consolidator2 == 0:
            raise ValueError("Custom data consolidator 2 did not consolidate any data")

        for i, sma in enumerate(self._smas):
            if sma.samples != self._expected_consolidation_counts[i]:
                raise AssertionError(f"Expected {self._expected_consolidation_counts[i]} samples in each SMA but found {sma.samples} in SMA in index {i}")

            last_update = self._last_sma_updates[i]
            if sma.current.time != last_update:
                raise AssertionError(f"Expected SMA in index {i} to have been last updated at {last_update} but was {sma.current.time}")

        if self._monthly_consolidation_count != 0 or self._monthly_consolidator_sma.samples != 0:
            raise AssertionError("Expected monthly consolidator to not have consolidated any data")

        if self._weekly_consolidator_sma.samples != expected_weekly_consolidations:
            raise AssertionError(f"Expected {expected_weekly_consolidations} samples in the weekly consolidator SMA but found {self._weekly_consolidator_sma.samples}")

        if self._weekly_consolidator_sma.current.time != self._last_weekly_sma_update:
            raise AssertionError(f"Expected weekly consolidator SMA to have been last updated at {self._last_weekly_sma_update} but was {self._weekly_consolidator_sma.current.time}")

    # on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.
    def on_data(self, data):
        if not self.portfolio.invested and self._future.has_data:
           self.set_holdings(self._future.symbol, 0.5)
```


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
: Demostrates the use of <see cref="VolumeRenkoConsolidator"/> for creating constant volume bar

Output:
```python

from AlgorithmImports import *

class VolumeRenkoConsolidatorAlgorithm(QCAlgorithm):

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

        self._sma = SimpleMovingAverage(10)
        self._tick_consolidated = False

        self._spy = self.add_equity("SPY", Resolution.MINUTE).symbol
        self._tradebar_volume_consolidator = VolumeRenkoConsolidator(1000000)
        self._tradebar_volume_consolidator.data_consolidated += self.on_spy_data_consolidated

        self._ibm = self.add_equity("IBM", Resolution.TICK).symbol
        self._tick_volume_consolidator = VolumeRenkoConsolidator(1000000)
        self._tick_volume_consolidator.data_consolidated += self.on_ibm_data_consolidated

        history = self.history[TradeBar](self._spy, 1000, Resolution.MINUTE)
        for bar in history:
            self._tradebar_volume_consolidator.update(bar)

    def on_spy_data_consolidated(self, sender, bar):
        self._sma.update(bar.end_time, bar.value)
        self.debug(f"SPY {bar.time} to {bar.end_time} :: O:{bar.open} H:{bar.high} L:{bar.low} C:{bar.close} V:{bar.volume}")
        if bar.volume != 1000000:
            raise AssertionError("Volume of consolidated bar does not match set value!")

    def on_ibm_data_consolidated(self, sender, bar):
        self.debug(f"IBM {bar.time} to {bar.end_time} :: O:{bar.open} H:{bar.high} L:{bar.low} C:{bar.close} V:{bar.volume}")
        if bar.volume != 1000000:
            raise AssertionError("Volume of consolidated bar does not match set value!")
        self._tick_consolidated = True

    def on_data(self, slice):
        # Update by TradeBar
        if slice.bars.contains_key(self._spy):
            self._tradebar_volume_consolidator.update(slice.bars[self._spy])

        # Update by Tick
        if slice.ticks.contains_key(self._ibm):
            for tick in slice.ticks[self._ibm]:
                self._tick_volume_consolidator.update(tick)

        if self._sma.is_ready and self._sma.current.value < self.securities[self._spy].price:
            self.set_holdings(self._spy, 1)
        else:
            self.set_holdings(self._spy, 0)

    def on_end_of_algorithm(self):
        if not self._tick_consolidated:
            raise AssertionError("Tick consolidator was never been called")
```


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 option exercise and assignment functionality
We open two positions and go with them into expiration. We expect to see our long position exercised and short position assigned.

Output:
```python

from AlgorithmImports import *

class OptionSplitRegressionAlgorithm(QCAlgorithm):

    def initialize(self):

        # this test opens position in the first day of trading, lives through stock split (7 for 1),
        # and closes adjusted position on the second day

        self.set_cash(1000000)
        self.set_start_date(2014,6,6)
        self.set_end_date(2014,6,9)

        option = self.add_option("AAPL")

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

        self.set_benchmark("AAPL")
        self.contract = None

    def on_data(self, slice):
        if not self.portfolio.invested:
            if self.time.hour > 9 and self.time.minute > 0:
                for kvp in slice.option_chains:
                    chain = kvp.value
                    contracts = filter(lambda x: x.strike == 650 and x.right ==  OptionRight.CALL, chain)
                    sorted_contracts = sorted(contracts, key = lambda x: x.expiry)

                if len(sorted_contracts) > 1:
                    self.contract = sorted_contracts[1]
                    self.buy(self.contract.symbol, 1)

        elif self.time.day > 6 and self.time.hour > 14 and self.time.minute > 0:
            self.liquidate()

        if self.portfolio.invested:
            options_hold = [x for x in self.portfolio.securities if x.value.holdings.absolute_quantity != 0]
            holdings = options_hold[0].value.holdings.absolute_quantity
            if self.time.day == 6 and holdings != 1:
                self.log("Expected position quantity of 1 but was {0}".format(holdings))
            if self.time.day == 9 and holdings != 7:
                self.log("Expected position quantity of 7 but was {0}".format(holdings))

    # 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(365*2))

    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
: Demonstration of how to define a universe using the fundamental data

Output:
```python

from AlgorithmImports import *

class FundamentalRegressionAlgorithm(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2014, 3, 26)
        self.set_end_date(2014, 4, 7)

        self.universe_settings.resolution = Resolution.DAILY

        self._universe = self.add_universe(self.selection_function)

        # before we add any symbol
        self.assert_fundamental_universe_data()

        self.add_equity("SPY")
        self.add_equity("AAPL")

        # Request fundamental data for symbols at current algorithm time
        ibm = Symbol.create("IBM", SecurityType.EQUITY, Market.USA)
        ibm_fundamental = self.fundamentals(ibm)
        if self.time != self.start_date or self.time != ibm_fundamental.end_time:
            raise ValueError(f"Unexpected Fundamental time {ibm_fundamental.end_time}")
        if ibm_fundamental.price == 0:
            raise ValueError(f"Unexpected Fundamental IBM price!")
        nb = Symbol.create("NB", SecurityType.EQUITY, Market.USA)
        fundamentals = self.fundamentals([ nb, ibm ])
        if len(fundamentals) != 2:
            raise ValueError(f"Unexpected Fundamental count {len(fundamentals)}! Expected 2")

        # Request historical fundamental data for symbols
        history = self.history(Fundamental, timedelta(days=2))
        if len(history) != 4:
            raise ValueError(f"Unexpected Fundamental history count {len(history)}! Expected 4")

        for ticker in [ "AAPL", "SPY" ]:
            data = history.loc[ticker]
            if data["value"][0] == 0:
                raise ValueError(f"Unexpected {data} fundamental data")
        if Object.reference_equals(data.earningreports.iloc[0], data.earningreports.iloc[1]):
            raise ValueError(f"Unexpected fundamental data instance duplication")
        if data.earningreports.iloc[0]._time_provider.get_utc_now() == data.earningreports.iloc[1]._time_provider.get_utc_now():
            raise ValueError(f"Unexpected fundamental data instance duplication")

        self.assert_fundamental_universe_data()

        self.changes = None
        self.number_of_symbols_fundamental = 2

    def assert_fundamental_universe_data(self):
        # Case A
        universe_data = self.history(self._universe.data_type, [self._universe.symbol], timedelta(days=2), flatten=True)
        self.assert_fundamental_history(universe_data, "A")

        # Case B (sugar on A)
        universe_data_per_time = self.history(self._universe, timedelta(days=2), flatten=True)
        self.assert_fundamental_history(universe_data_per_time, "B")

        # Case C: Passing through the unvierse type and symbol
        enumerable_of_data_dictionary = self.history[self._universe.data_type]([self._universe.symbol], 100)
        for selection_collection_for_a_day in enumerable_of_data_dictionary:
            self.assert_fundamental_enumerator(selection_collection_for_a_day[self._universe.symbol], "C")

    def assert_fundamental_history(self, df, case_name):
        dates = df.index.get_level_values('time').unique()
        if dates.shape[0] != 2:
            raise ValueError(f"Unexpected Fundamental universe dates count {dates.shape[0]}! Expected 2")

        for date in dates:
            sub_df = df.loc[date]
            if sub_df.shape[0] < 7000:
                raise ValueError(f"Unexpected historical Fundamentals data count {sub_df.shape[0]} case {case_name}! Expected > 7000")

    def assert_fundamental_enumerator(self, enumerable, case_name):
        data_point_count = 0
        for fundamental in enumerable:
            data_point_count += 1
            if type(fundamental) is not Fundamental:
                raise ValueError(f"Unexpected Fundamentals data type {type(fundamental)} case {case_name}! {str(fundamental)}")
        if data_point_count < 7000:
            raise ValueError(f"Unexpected historical Fundamentals data count {data_point_count} case {case_name}! Expected > 7000")

    # return a list of three fixed symbol objects
    def selection_function(self, fundamental):
        # sort descending by daily dollar volume
        sorted_by_dollar_volume = sorted([x for x in fundamental if x.price > 1],
            key=lambda x: x.dollar_volume, reverse=True)

        # sort descending by P/E ratio
        sorted_by_pe_ratio = sorted(sorted_by_dollar_volume, key=lambda x: x.valuation_ratios.pe_ratio, reverse=True)

        # take the top entries from our sorted collection
        return [ x.symbol for x in sorted_by_pe_ratio[:self.number_of_symbols_fundamental] ]

    def on_data(self, data):
        # if we have no changes, do nothing
        if self.changes is None: return

        # liquidate removed securities
        for security in self.changes.removed_securities:
            if security.invested:
                self.liquidate(security.symbol)
                self.debug("Liquidated Stock: " + str(security.symbol.value))

        # we want 50% allocation in each security in our universe
        for security in self.changes.added_securities:
            self.set_holdings(security.symbol, 0.02)

        self.changes = None

    # this event fires whenever we have changes to our universe
    def on_securities_changed(self, changes):
        self.changes = changes
```


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 that we receive the expected data when
we add future option contracts individually using <see cref="AddFutureOptionContract"/>

Output:
```python

from AlgorithmImports import *

class AddFutureOptionContractDataStreamingRegressionAlgorithm(QCAlgorithm):
    def initialize(self):
        self.on_data_reached = False
        self.invested = False
        self.symbols_received = []
        self.expected_symbols_received = []
        self.data_received = {}

        self.set_start_date(2020, 1, 4)
        self.set_end_date(2020, 1, 8)

        self.es20h20 = self.add_future_contract(
            Symbol.create_future(Futures.Indices.SP_500_E_MINI, Market.CME, datetime(2020, 3, 20)),
            Resolution.MINUTE).symbol

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

        # Get option contract lists for 2020/01/05 (timedelta(days=1)) because Lean has local data for that date
        option_chains = list(self.option_chain_provider.get_option_contract_list(self.es20h20, self.time + timedelta(days=1)))
        option_chains += self.option_chain_provider.get_option_contract_list(self.es19m20, self.time + timedelta(days=1))

        for option_contract in option_chains:
            self.expected_symbols_received.append(self.add_future_option_contract(option_contract, Resolution.MINUTE).symbol)

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

        self.on_data_reached = True
        has_option_quote_bars = False

        for qb in data.quote_bars.values():
            if qb.symbol.security_type != SecurityType.FUTURE_OPTION:
                continue

            has_option_quote_bars = True

            self.symbols_received.append(qb.symbol)
            if qb.symbol not in self.data_received:
                self.data_received[qb.symbol] = []

            self.data_received[qb.symbol].append(qb)

        if self.invested or not has_option_quote_bars:
            return

        if data.contains_key(self.es20h20) and data.contains_key(self.es19m20):
            self.set_holdings(self.es20h20, 0.2)
            self.set_holdings(self.es19m20, 0.2)

            self.invested = True

    def on_end_of_algorithm(self):
        self.symbols_received = list(set(self.symbols_received))
        self.expected_symbols_received = list(set(self.expected_symbols_received))

        if not self.on_data_reached:
            raise AssertionError("OnData() was never called.")
        if len(self.symbols_received) != len(self.expected_symbols_received):
            raise AssertionError(f"Expected {len(self.expected_symbols_received)} option contracts Symbols, found {len(self.symbols_received)}")

        missing_symbols = [expected_symbol.value for expected_symbol in self.expected_symbols_received if expected_symbol not in self.symbols_received]
        if any(missing_symbols):
            raise AssertionError(f'Symbols: "{", ".join(missing_symbols)}" were not found in OnData')

        for expected_symbol in self.expected_symbols_received:
            data = self.data_received[expected_symbol]
            for data_point in data:
                data_point.end_time = datetime(1970, 1, 1)

            non_dupe_data_count = len(set(data))
            if non_dupe_data_count < 1000:
                raise AssertionError(f"Received too few data points. Expected >=1000, found {non_dupe_data_count} for {expected_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
: Test algorithm generating insights with custom tags

Output:
```python

from AlgorithmImports import *

from Selection.ManualUniverseSelectionModel import ManualUniverseSelectionModel
from Portfolio.EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel
from Execution.ImmediateExecutionModel import ImmediateExecutionModel

class InsightTagAlphaRegressionAlgorithm(QCAlgorithm):

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

        self.universe_settings.resolution = Resolution.DAILY

        self.spy = Symbol.create("SPY", SecurityType.EQUITY, Market.USA)
        self.fb = Symbol.create("FB", SecurityType.EQUITY, Market.USA)
        self.ibm = Symbol.create("IBM", SecurityType.EQUITY, Market.USA)

        # set algorithm framework models
        self.set_universe_selection(ManualUniverseSelectionModel([self.spy, self.fb, self.ibm]))
        self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
        self.set_execution(ImmediateExecutionModel())

        self.add_alpha(OneTimeAlphaModel(self.spy))
        self.add_alpha(OneTimeAlphaModel(self.fb))
        self.add_alpha(OneTimeAlphaModel(self.ibm))

        self.insights_generated += self.on_insights_generated_verifier

        self._symbols_with_generated_insights = []

    def on_insights_generated_verifier(self, algorithm: IAlgorithm, insights_collection: GeneratedInsightsCollection) -> None:
        for insight in insights_collection.insights:
            if insight.tag != OneTimeAlphaModel.generate_insight_tag(insight.symbol):
                raise AssertionError("Unexpected insight tag was emitted")

            self._symbols_with_generated_insights.append(insight.symbol)

    def on_end_of_algorithm(self) -> None:
        if len(self._symbols_with_generated_insights) != 3:
            raise AssertionError("Unexpected number of symbols with generated insights")

        if not self.spy in self._symbols_with_generated_insights:
            raise AssertionError("SPY symbol was not found in symbols with generated insights")

        if not self.fb in self._symbols_with_generated_insights:
            raise AssertionError("FB symbol was not found in symbols with generated insights")

        if not self.ibm in self._symbols_with_generated_insights:
            raise AssertionError("IBM symbol was not found in symbols with generated insights")

class OneTimeAlphaModel(AlphaModel):
    def __init__(self, symbol):
        self._symbol = symbol
        self.triggered = False

    def update(self, algorithm, data):
        insights = []
        if not self.triggered:
            self.triggered = True
            insights.append(Insight.price(
                self._symbol,
                Resolution.DAILY,
                1,
                InsightDirection.DOWN,
                tag=OneTimeAlphaModel.generate_insight_tag(self._symbol)))
        return insights

    @staticmethod
    def generate_insight_tag(symbol: Symbol) -> str:
        return f"Insight generated for {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
: In this algorithm we demonstrate how to perform some technical analysis as
part of your coarse fundamental universe selection

Output:
```python

from AlgorithmImports import *

class EmaCrossUniverseSelectionAlgorithm(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(2010,1,1)  #Set Start Date
        self.set_end_date(2015,1,1)    #Set End Date
        self.set_cash(100000)           #Set Strategy Cash

        self.universe_settings.resolution = Resolution.DAILY
        self.universe_settings.leverage = 2

        self.coarse_count = 10
        self.averages = { }

        # this add universe method accepts two parameters:
        # - coarse selection function: accepts an IEnumerable<CoarseFundamental> and returns an IEnumerable<Symbol>
        self.add_universe(self.coarse_selection_function)

    # sort the data by daily dollar volume and take the top 'NumberOfSymbols'
    def coarse_selection_function(self, coarse):

        # We are going to use a dictionary to refer the object that will keep the moving averages
        for cf in coarse:
            if cf.symbol not in self.averages:
                self.averages[cf.symbol] = SymbolData(cf.symbol)

            # Updates the SymbolData object with current EOD price
            avg = self.averages[cf.symbol]
            avg.update(cf.end_time, cf.adjusted_price)

        # Filter the values of the dict: we only want up-trending securities
        values = list(filter(lambda x: x.is_uptrend, self.averages.values()))

        # Sorts the values of the dict: we want those with greater difference between the moving averages
        values.sort(key=lambda x: x.scale, reverse=True)

        for x in values[:self.coarse_count]:
            self.log('symbol: ' + str(x.symbol.value) + '  scale: ' + str(x.scale))

        # we need to return only the symbol objects
        return [ x.symbol for x in values[:self.coarse_count] ]

    # this event fires whenever we have changes to our universe
    def on_securities_changed(self, changes):
        # liquidate removed securities
        for security in changes.removed_securities:
            if security.invested:
                self.liquidate(security.symbol)

        # we want 20% allocation in each security in our universe
        for security in changes.added_securities:
            self.set_holdings(security.symbol, 0.1)

class SymbolData(object):
    def __init__(self, symbol):
        self._symbol = symbol
        self.tolerance = 1.01
        self.fast = ExponentialMovingAverage(100)
        self.slow = ExponentialMovingAverage(300)
        self.is_uptrend = False
        self.scale = 0

    def update(self, time, value):
        if self.fast.update(time, value) and self.slow.update(time, value):
            fast = self.fast.current.value
            slow = self.slow.current.value
            self.is_uptrend = fast > slow * self.tolerance

        if self.is_uptrend:
            self.scale = (fast - slow) / ((fast + slow) / 2.0)
```


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 equally weighted portfolio and a maximum sector exposure.

Output:
```python

from AlgorithmImports import *
from Portfolio.EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel
from Alphas.ConstantAlphaModel import ConstantAlphaModel
from Execution.ImmediateExecutionModel import ImmediateExecutionModel
from Risk.MaximumSectorExposureRiskManagementModel import MaximumSectorExposureRiskManagementModel

class SectorExposureRiskFrameworkAlgorithm(QCAlgorithm):
    '''This example algorithm defines its own custom coarse/fine fundamental selection model

    def initialize(self):

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

        self.set_start_date(2014, 3, 25)
        self.set_end_date(2014, 4, 7)
        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(EqualWeightingPortfolioConstructionModel())
        self.set_risk_management(MaximumSectorExposureRiskManagementModel())

    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):
        tickers = ["AAPL", "AIG", "IBM"] if self.time.date() < date(2014, 4, 1) 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
: Tests the mapping of the ETF symbol that has a constituent universe attached to it and ensures
that data is loaded after the mapping event takes place.

Output:
```python

from AlgorithmImports import *

class ETFConstituentUniverseFilterFunctionRegressionAlgorithm(QCAlgorithm):
    def initialize(self):
        self.set_start_date(2011, 2, 1)
        self.set_end_date(2011, 4, 4)
        self.set_cash(100000)

        self.filter_date_constituent_symbol_count = {}
        self.constituent_data_encountered = {}
        self.constituent_symbols = []
        self.mapping_event_occurred = False

        self.universe_settings.resolution = Resolution.HOUR

        self.aapl = Symbol.create("AAPL", SecurityType.EQUITY, Market.USA)
        self.qqq = self.add_equity("QQQ", Resolution.DAILY).symbol

        self.add_universe(self.universe.etf(self.qqq, self.universe_settings, self.filter_etfs))

    def filter_etfs(self, constituents):
        constituent_symbols = [i.symbol for i in constituents]

        if self.aapl not in constituent_symbols:
            raise AssertionError("AAPL not found in QQQ constituents")

        self.filter_date_constituent_symbol_count[self.utc_time.date()] = len(constituent_symbols)
        for symbol in constituent_symbols:
            self.constituent_symbols.append(symbol)

        self.constituent_symbols = list(set(self.constituent_symbols))
        return constituent_symbols

    def on_data(self, data):
        if len(data.symbol_changed_events) != 0:
            for symbol_changed in data.symbol_changed_events.values():
                if symbol_changed.symbol != self.qqq:
                    raise AssertionError(f"Mapped symbol is not QQQ. Instead, found: {symbol_changed.symbol}")
                if symbol_changed.old_symbol != "QQQQ":
                    raise AssertionError(f"Old QQQ Symbol is not QQQQ. Instead, found: {symbol_changed.old_symbol}")
                if symbol_changed.new_symbol != "QQQ":
                    raise AssertionError(f"New QQQ Symbol is not QQQ. Instead, found: {symbol_changed.new_symbol}")

                self.mapping_event_occurred = True

        if self.qqq in data and len([i for i in data.keys()]) == 1:
            return

        if self.utc_time.date() not in self.constituent_data_encountered:
            self.constituent_data_encountered[self.utc_time.date()] = False

        if len([i for i in data.keys() if i in self.constituent_symbols]) != 0:
            self.constituent_data_encountered[self.utc_time.date()] = True

        if not self.portfolio.invested:
            self.set_holdings(self.aapl, 0.5)

    def on_end_of_algorithm(self):
        if len(self.filter_date_constituent_symbol_count) != 2:
            raise AssertionError(f"ETF constituent filtering function was not called 2 times (actual: {len(self.filter_date_constituent_symbol_count)}")

        if not self.mapping_event_occurred:
            raise AssertionError("No mapping/SymbolChangedEvent occurred. Expected for QQQ to be mapped from QQQQ -> QQQ")

        for constituent_date, constituents_count in self.filter_date_constituent_symbol_count.items():
            if constituents_count < 25:
                raise AssertionError(f"Expected 25 or more constituents in filter function on {constituent_date}, found {constituents_count}")

        for constituent_date, constituent_encountered in self.constituent_data_encountered.items():
            if not constituent_encountered:
                raise AssertionError(f"Received data in OnData(...) but it did not contain any constituent data on {constituent_date.strftime('%Y-%m-%d %H:%M:%S.%f')}")
```


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="MaximumUnrealizedProfitPercentPerSecurity"/>.

Output:
```python

from AlgorithmImports import *
from BaseFrameworkRegressionAlgorithm import BaseFrameworkRegressionAlgorithm
from Risk.MaximumUnrealizedProfitPercentPerSecurity import MaximumUnrealizedProfitPercentPerSecurity

class MaximumUnrealizedProfitPercentPerSecurityFrameworkRegressionAlgorithm(BaseFrameworkRegressionAlgorithm):

    def initialize(self):
        super().initialize()
        self.set_universe_selection(ManualUniverseSelectionModel(Symbol.create("AAPL", SecurityType.EQUITY, Market.USA)))

        self.set_risk_management(MaximumUnrealizedProfitPercentPerSecurity(0.004))
```


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) index option expiry for short calls.
We expect 2 orders from the algorithm, which are:

  * Initial entry, sell SPX Call Option (expiring ITM)
  * Option assignment

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 IndexOptionShortCallITMExpiryRegressionAlgorithm(QCAlgorithm):

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

        self.portfolio.set_margin_call_model(MarginCallModel.NULL);

        # avoid getting assigned
        self.set_security_initializer(CompositeSecurityInitializer(self.security_initializer, FuncSecurityInitializer(self.custom_security_initializer)))

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

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

        self.expected_contract = Symbol.create_option(self.spx, Market.USA, OptionStyle.EUROPEAN, OptionRight.CALL, 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:
            self.assert_index_option_order_exercise(order_event, security, self.securities[self.expected_contract])
        elif 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_order_exercise(self, order_event: OrderEvent, index: Security, option_contract: Security):
        if "Assignment" in order_event.message:
            if order_event.fill_price != 3200:
                raise AssertionError("Option was not assigned at expected strike price (3200)")

            if order_event.direction != OrderDirection.SELL or index.holdings.quantity != 0:
                raise AssertionError(f"Expected Qty: 0 index holdings for assigned index option {index.symbol}, found {index.holdings.quantity}")

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

        if order_event.is_assignment and option.holdings.quantity != 0:
            raise AssertionError(f"Holdings were found after option contract was assigned: {option.symbol}")

    ### <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())}")

    def custom_security_initializer(self, security):
        if Extensions.is_option(security.symbol.security_type):
            security.set_option_assignment_model(NullOptionAssignmentModel())
```


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 short calls.
We expect 2 orders from the algorithm, which are:

  * Initial entry, sell SPX Call Option (expiring OTM)
    - Profit the option premium, since the option was not assigned.

  * Liquidation of SPX call OTM contract on the last trade date

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 IndexOptionShortCallOTMExpiryRegressionAlgorithm(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 expiring ITM, 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 >= 4250 and i.id.option_right == OptionRight.CALL 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))[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.CALL, 4250, 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(f"Expected no order events for underlying Symbol {security.symbol}")

        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_contract: Security):
        if order_event.direction == OrderDirection.SELL and option_contract.holdings.quantity != -1:
            raise AssertionError(f"No holdings were created for option contract {option_contract.symbol}")
        if order_event.direction == OrderDirection.BUY and option_contract.holdings.quantity != 0:
            raise AssertionError("Expected no options holdings after closing position")
        if order_event.is_assignment:
            raise AssertionError(f"Assignment was not expected for {order_event.symbol}")

    ### <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
: def initialize(self) -> None:

Output:
```python

from AlgorithmImports import *

class BasicTemplateIndexOptionsAlgorithm(QCAlgorithm):
    def initialize(self) -> None:
        self.set_start_date(2021, 1, 4)
        self.set_end_date(2021, 2, 1)
        self.set_cash(1000000)

        self.spx = self.add_index("SPX", Resolution.MINUTE).symbol
        spx_options = self.add_index_option(self.spx, Resolution.MINUTE)
        spx_options.set_filter(lambda x: x.calls_only())

        self.ema_slow = self.ema(self.spx, 80)
        self.ema_fast = self.ema(self.spx, 200)

    def on_data(self, data: Slice) -> None:
        if self.spx not in data.bars or not self.ema_slow.is_ready:
            return

        for chain in data.option_chains.values():
            for contract in chain.contracts.values():
                if self.portfolio.invested:
                    continue

                if (self.ema_fast > self.ema_slow and contract.right == OptionRight.CALL) or \
                    (self.ema_fast < self.ema_slow and contract.right == OptionRight.PUT):

                    self.liquidate(self.invert_option(contract.symbol))
                    self.market_order(contract.symbol, 1)

    def on_end_of_algorithm(self) -> None:
        if self.portfolio[self.spx].total_sale_volume > 0:
            raise AssertionError("Index is not tradable.")

        if self.portfolio.total_sale_volume == 0:
            raise AssertionError("Trade volume should be greater than zero by the end of this algorithm")

    def invert_option(self, symbol: Symbol) -> Symbol:
        return Symbol.create_option(
            symbol.underlying,
            symbol.id.market,
            symbol.id.option_style,
            OptionRight.PUT if symbol.id.option_right == OptionRight.CALL else OptionRight.CALL,
            symbol.id.strike_price,
            symbol.id.date
        )
```