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

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

  * Initial entry, sell ES Put Option (expiring ITM)
  * Option assignment, buy 1 contract of the underlying (ES)
  * Future contract expiry, liquidation (sell 1 ES future)

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 FutureOptionShortPutITMExpiryRegressionAlgorithm(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.PUT],
                    key=lambda x: x.id.strike_price,
                    reverse=True
                )
            )[0], Resolution.MINUTE).symbol

        self.expected_contract = Symbol.create_option(self.es19m20, Market.CME, OptionStyle.AMERICAN, OptionRight.PUT, 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:
            self.assert_future_option_order_exercise(order_event, security, self.securities[self.expected_contract])

        elif 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_order_exercise(self, order_event: OrderEvent, future: Security, option_contract: Security):
        if "Assignment" in order_event.message:
            if order_event.fill_price != 3400.0:
                raise AssertionError("Option was not assigned at expected strike price (3400)")

            if order_event.direction != OrderDirection.BUY or future.holdings.quantity != 1:
                raise AssertionError(f"Expected Qty: 1 futures holdings for assigned future {future.symbol}, found {future.holdings.quantity}")

            return

        if order_event.direction == OrderDirection.SELL and future.holdings.quantity != 0:
            # We buy back the underlying at expiration, so we expect a neutral position then
            raise AssertionError(f"Expected no holdings when liquidating future contract {future.symbol}")

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

    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
: Options Open Interest data regression test.

Output:
```python

from AlgorithmImports import *

class OptionOpenInterestRegressionAlgorithm(QCAlgorithm):

    def initialize(self):
        self.set_cash(1000000)
        self.set_start_date(2014,6,5)
        self.set_end_date(2014,6,6)

        option = self.add_option("TWX")

        # set our strike/expiry filter for this option chain
        option.set_filter(-10, 10, timedelta(0), timedelta(365*2))

        # use the underlying equity as the benchmark
        self.set_benchmark("TWX")

    def on_data(self, slice):
        if not self.portfolio.invested:
            for chain in slice.option_chains:
                for contract in chain.value:
                    if float(contract.symbol.id.strike_price) == 72.5 and \
                       contract.symbol.id.option_right == OptionRight.CALL and \
                       contract.symbol.id.date == datetime(2016, 1, 15):

                        history = self.history(OpenInterest, contract.symbol, timedelta(1))["openinterest"]
                        if len(history.index) == 0 or 0 in history.values:
                            raise ValueError("Regression test failed: open interest history request is empty")

                        security = self.securities[contract.symbol]
                        open_interest_cache = security.cache.get_data(OpenInterest)
                        if open_interest_cache == None:
                            raise ValueError("Regression test failed: current open interest isn't in the security cache")
                        if slice.time.date() == datetime(2014, 6, 5).date() and (contract.open_interest != 50 or security.open_interest != 50):
                            raise ValueError("Regression test failed: current open interest was not correctly loaded and is not equal to 50")
                        if slice.time.date() == datetime(2014, 6, 6).date() and (contract.open_interest != 70 or security.open_interest != 70):
                            raise ValueError("Regression test failed: current open interest was not correctly loaded and is not equal to 70")
                        if slice.time.date() == datetime(2014, 6, 6).date():
                            self.market_order(contract.symbol, 1)
                            self.market_on_close_order(contract.symbol, -1)

                if all(contract.open_interest == 0 for contract in chain.value):
                    raise ValueError("Regression test failed: open interest is zero for all contracts")

    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
: We add an option contract using 'QCAlgorithm.add_option_contract' and place a trade, the underlying
gets deselected from the universe selection but should still be present since we manually added the option contract.
Later we call 'QCAlgorithm.remove_option_contract' and expect both option and underlying to be removed.

Output:
```python

from AlgorithmImports import *

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

        self.set_start_date(2014, 6, 5)
        self.set_end_date(2014, 6, 30)

        self._expiration = datetime(2014, 6, 21)
        self._option = None
        self._traded = False

        self._twx = Symbol.create("TWX", SecurityType.EQUITY, Market.USA)

        self.add_universe("my-daily-universe-name", self.selector)

    def selector(self, time):
        return [ "AAPL" ]

    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 self._option == None:
            chain = self.option_chain(self._twx)
            options = sorted(chain, key=lambda x: x.id.symbol)

            option = next((option
                           for option in options
                           if option.id.date == self._expiration and
                           option.id.option_right == OptionRight.CALL and
                           option.id.option_style == OptionStyle.AMERICAN), None)
            if option != None:
                self._option = self.add_option_contract(option).symbol

        if self._option != None and self.securities[self._option].price != 0 and not self._traded:
            self._traded = True
            self.buy(self._option, 1)

        if self.time > self._expiration and self.securities[self._twx].invested:
                # we liquidate the option exercised position
                self.liquidate(self._twx)
```


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 demonstrating the use of custom data sourced from multiple "files" in the object store

Output:
```python

from AlgorithmImports import *

class CustomDataMultiFileObjectStoreRegressionAlgorithm(QCAlgorithm):
    custom_data = "2017-08-18 01:00:00,5749.5,5852.95,5749.5,5842.2,214402430,8753.33\n2017-08-18 02:00:00,5834.1,5904.35,5822.2,5898.85,144794030,5405.72\n2017-08-18 03:00:00,5885.5,5898.8,5852.3,5857.55,145721790,5163.09\n2017-08-18 04:00:00,5811.95,5815,5760.4,5770.9,160523863,5219.24\n2017-08-18 05:00:00,5794.75,5848.2,5786.05,5836.95,151929179,5429.87\n2017-08-18 06:00:00,5889.95,5900.45,5858.45,5867.9,123586417,4303.93\n2017-08-18 07:00:00,5833.15,5833.85,5775.55,5811.55,127624733,4823.52\n2017-08-18 08:00:00,5834.6,5864.95,5834.6,5859,110427867,4661.55\n2017-08-18 09:00:00,5869.9,5879.35,5802.85,5816.7,117516350,4820.53\n2017-08-18 10:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\n2017-08-18 11:00:00,6000.5,6019,5951.15,6009,127707078,6591.27\n2017-08-18 12:00:00,5991.2,6038.2,5980.95,6030.8,116275729,4641.97\n2017-08-18 13:00:00,5930.8,5966.05,5910.95,5955.25,151162819,5915.8\n2017-08-18 14:00:00,5972.25,5989.8,5926.75,5973.3,191516153,8349.59\n2017-08-18 15:00:00,5984.7,6051.1,5974.55,6038.05,171728134,7774.83\n2017-08-18 16:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\n2017-08-18 17:00:00,6000.5,6019,5951.15,6009,127707078,6591.27\n2017-08-18 18:00:00,5991.2,6038.2,5980.95,6030.8,116275729,4641.97\n2017-08-18 19:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\n2017-08-18 20:00:00,5895,5956.55,5869.5,5921.4,114174694,4961.54\n2017-08-18 21:00:00,5900.05,5972.7,5871.3,5881,118346364,4888.65\n2017-08-18 22:00:00,5907.9,5931.65,5857.4,5878,100130739,4304.75\n2017-08-18 23:00:00,5848.75,5868.05,5780.35,5788.8,180902123,6695.57\n2017-08-19 01:00:00,5771.75,5792.9,5738.6,5760.2,140394424,5894.04\n2017-08-19 02:00:00,5709.35,5729.85,5683.1,5699.1,142041404,5462.45\n2017-08-19 03:00:00,5748.95,5819.4,5739.4,5808.4,124410018,5121.33\n2017-08-19 04:00:00,5820.4,5854.9,5770.25,5850.05,107160887,4560.84\n2017-08-19 05:00:00,5841.9,5863.4,5804.3,5813.6,117541145,4591.91\n2017-08-19 06:00:00,5805.75,5828.4,5777.9,5822.25,115539008,4643.17\n2017-08-19 07:00:00,5754.15,5755,5645.65,5655.9,198400131,7148\n2017-08-19 08:00:00,5639.9,5686.15,5616.85,5667.65,182410583,6697.18\n2017-08-19 09:00:00,5638.05,5640,5566.25,5590.25,193488581,6308.88\n2017-08-19 10:00:00,5606.95,5666.25,5570.25,5609.1,196571543,6792.49\n2017-08-19 11:00:00,5627.95,5635.25,5579.35,5588.7,160095940,5939.3\n2017-08-19 12:00:00,5647.95,5699.35,5630.95,5682.35,239029425,9184.29\n2017-08-19 13:00:00,5749.5,5852.95,5749.5,5842.2,214402430,8753.33\n2017-08-19 14:00:00,5834.1,5904.35,5822.2,5898.85,144794030,5405.72\n2017-08-19 15:00:00,5885.5,5898.8,5852.3,5857.55,145721790,5163.09\n2017-08-19 16:00:00,5811.95,5815,5760.4,5770.9,160523863,5219.24\n2017-08-19 17:00:00,5794.75,5848.2,5786.05,5836.95,151929179,5429.87\n2017-08-19 18:00:00,5889.95,5900.45,5858.45,5867.9,123586417,4303.93\n2017-08-19 19:00:00,5833.15,5833.85,5775.55,5811.55,127624733,4823.52\n2017-08-19 20:00:00,5834.6,5864.95,5834.6,5859,110427867,4661.55\n2017-08-19 21:00:00,5869.9,5879.35,5802.85,5816.7,117516350,4820.53\n2017-08-19 22:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\n2017-08-19 23:00:00,6000.5,6019,5951.15,6009,127707078,6591.27\n2017-08-21 01:00:00,5749.5,5852.95,5749.5,5842.2,214402430,8753.33\n2017-08-21 02:00:00,5834.1,5904.35,5822.2,5898.85,144794030,5405.72\n2017-08-21 03:00:00,5885.5,5898.8,5852.3,5857.55,145721790,5163.09\n2017-08-21 04:00:00,5811.95,5815,5760.4,5770.9,160523863,5219.24\n2017-08-21 05:00:00,5794.75,5848.2,5786.05,5836.95,151929179,5429.87\n2017-08-21 06:00:00,5889.95,5900.45,5858.45,5867.9,123586417,4303.93\n2017-08-21 07:00:00,5833.15,5833.85,5775.55,5811.55,127624733,4823.52\n2017-08-21 08:00:00,5834.6,5864.95,5834.6,5859,110427867,4661.55\n2017-08-21 09:00:00,5869.9,5879.35,5802.85,5816.7,117516350,4820.53\n2017-08-21 10:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\n2017-08-21 11:00:00,6000.5,6019,5951.15,6009,127707078,6591.27\n2017-08-21 12:00:00,5991.2,6038.2,5980.95,6030.8,116275729,4641.97\n2017-08-21 13:00:00,5930.8,5966.05,5910.95,5955.25,151162819,5915.8\n2017-08-21 14:00:00,5972.25,5989.8,5926.75,5973.3,191516153,8349.59\n2017-08-21 15:00:00,5984.7,6051.1,5974.55,6038.05,171728134,7774.83\n2017-08-21 16:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\n2017-08-21 17:00:00,6000.5,6019,5951.15,6009,127707078,6591.27\n2017-08-21 18:00:00,5991.2,6038.2,5980.95,6030.8,116275729,4641.97\n2017-08-21 19:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\n2017-08-21 20:00:00,5895,5956.55,5869.5,5921.4,114174694,4961.54\n2017-08-21 21:00:00,5900.05,5972.7,5871.3,5881,118346364,4888.65\n2017-08-21 22:00:00,5907.9,5931.65,5857.4,5878,100130739,4304.75\n2017-08-21 23:00:00,5848.75,5868.05,5780.35,5788.8,180902123,6695.57"

    def initialize(self):
        self.set_start_date(2017, 8, 18)
        self.set_end_date(2017, 8, 21)
        self.set_cash(100000)

        self.set_benchmark(lambda x: 0)

        self.custom_symbol = self.add_data(ExampleCustomData, "ExampleCustomData", Resolution.HOUR).symbol

        # Saving data here for demonstration and regression testing purposes.
        # In real scenarios, data has to be saved to the object store before the algorithm starts.
        # Note: The data is stored in separate files for each date.
        data = {}
        for line in self.custom_data.split('\n'):
            csv = line.split(',')
            time = datetime.strptime(csv[0], '%Y-%m-%d %H:%M:%S').date()
            if time not in data:
                data[time] = line
            else:
                data[time] += '\n' + line

        for date, date_data in data.items():
            self.object_store.save(self.get_custom_data_key(date), date_data)

        self.received_data = []

    def on_data(self, slice: Slice):
        if slice.contains_key(self.custom_symbol):
            custom_data = slice.get(ExampleCustomData, self.custom_symbol)
            if custom_data.price == 0:
                raise AssertionError("Custom data price was not expected to be zero")

            self.received_data.append(custom_data)

    def on_end_of_algorithm(self):
        if not self.received_data:
            raise AssertionError("Custom data was not fetched")

        custom_security = self.securities[self.custom_symbol]
        if custom_security is None or custom_security.price == 0:
            raise AssertionError("Expected the custom security to be added to the algorithm securities and to have a price that is not zero")

        # Make sure history requests work as expected
        history = self.history(ExampleCustomData, self.custom_symbol, self.start_date, self.end_date, Resolution.HOUR)

        if history.shape[0] != len(self.received_data):
            raise AssertionError("History request returned more or less data than expected")

        for i in range(len(self.received_data)):
            received_data = self.received_data[i]
            if (history.index[i][0] != received_data.symbol or
                history.index[i][1] != received_data.time or
                history[["value"]].values[i][0] != received_data.value or
                history[["open"]].values[i][0] != received_data.open or
                history[["high"]].values[i][0] != received_data.high or
                history[["low"]].values[i][0] != received_data.low or
                history[["close"]].values[i][0] != received_data.close):
                raise AssertionError("History request returned different data than expected")

    @staticmethod
    def get_custom_data_key(date: date) -> str:
        return f"CustomData/ExampleCustomData{date.strftime('%Y%m%d')}"

class ExampleCustomData(PythonData):
    CustomDataKey = ""

    def get_source(self, config, date, is_live):
        return SubscriptionDataSource(CustomDataMultiFileObjectStoreRegressionAlgorithm.get_custom_data_key(date.date()),
                                      SubscriptionTransportMedium.OBJECT_STORE,
                                      FileFormat.CSV)

    def reader(self, config, line, date, is_live):
        data = line.split(',')
        obj_data = ExampleCustomData()
        obj_data.symbol = config.symbol
        obj_data.time = datetime.strptime(data[0], '%Y-%m-%d %H:%M:%S')
        obj_data.value = float(data[4])
        obj_data["Open"] = float(data[1])
        obj_data["High"] = float(data[2])
        obj_data["Low"] = float(data[3])
        obj_data["Close"] = float(data[4])
        return obj_data
```


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

Input:
Generate a LEAN Algorithm that can be described like this
: This algorithm sends a list of current portfolio targets to Numerai API before each trading day
See (https://docs.numer.ai/numerai-signals/signals-overview) for more information
about accepted symbols, signals, etc.

Output:
```python

from AlgorithmImports import *

class NumeraiSignalExportDemonstrationAlgorithm(QCAlgorithm):

    _securities = []

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

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

        self.set_security_initializer(BrokerageModelSecurityInitializer(self.brokerage_model, FuncSecuritySeeder(self.get_last_known_prices)))

        # Add the CRSP US Total Market Index constituents, which represents approximately 100% of the investable US Equity market
        self.etf_symbol = self.add_equity("VTI").symbol
        self.add_universe(self.universe.etf(self.etf_symbol))

        # Create a Scheduled Event to submit signals every trading day at 13:00 UTC
        self.schedule.on(self.date_rules.every_day(self.etf_symbol), self.time_rules.at(13, 0, TimeZones.UTC), self.submit_signals)

        # Set Numerai signal export provider
        # Numerai Public ID: This value is provided by Numerai Signals in their main webpage once you've logged in
        # and created a API key. See (https://signals.numer.ai/account)
        numerai_public_id = ""

        # Numerai Secret ID: This value is provided by Numerai Signals in their main webpage once you've logged in
        # and created a API key. See (https://signals.numer.ai/account)
        numerai_secret_id = ""

        # Numerai Model ID: This value is provided by Numerai Signals in their main webpage once you've logged in
        # and created a model. See (https://signals.numer.ai/models)
        numerai_model_id = ""

        numerai_filename = "" # (Optional) Replace this value with your submission filename

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

        # Set Numerai signal export provider
        self.signal_export.add_signal_export_provider(NumeraiSignalExport(numerai_public_id, numerai_secret_id, numerai_model_id, numerai_filename))

    def submit_signals(self) -> None:
        # Select the subset of ETF constituents we can trade
        symbols = sorted([security.symbol for security in self._securities if security.has_data])
        if len(symbols) == 0:
            return

        # Get historical data
        # close_prices = self.history(symbols, 22, Resolution.DAILY).close.unstack(0)

        # Create portfolio targets
        #  Numerai requires that at least one of the signals have a unique weight
        #  To ensure they are all unique, this demo gives a linear allocation to each symbol (ie. 1/55, 2/55, ..., 10/55)
        denominator = len(symbols) * (len(symbols) + 1) / 2 # sum of 1, 2, ..., len(symbols)
        targets = [PortfolioTarget(symbol, (i+1) / denominator) for i, symbol in enumerate(symbols)]

        # (Optional) Place trades
        self.set_holdings(targets)

        # Send signals to Numerai
        success = self.signal_export.set_target_portfolio(targets)
        if not success:
            self.debug(f"Couldn't send targets at {self.time}")

    def on_securities_changed(self, changes: SecurityChanges) -> None:
        for security in changes.removed_securities:
            if security in self._securities:
                self._securities.remove(security)

        self._securities.extend([security for security in changes.added_securities if security.symbol != self.etf_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
: This example demonstrates how to add options for a given underlying equity security.
It also shows how you can prefilter contracts easily based on strikes and expirations, and how you
can inspect the option chain to pick a specific option contract to trade.

Output:
```python

from AlgorithmImports import *

class BasicTemplateOptionsAlgorithm(QCAlgorithm):
    underlying_ticker = "GOOG"

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

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

        # set our strike/expiry filter for this option chain
        option.set_filter(lambda u: (u.strikes(-2, +2)
                                     # Expiration method accepts TimeSpan objects or integer for days.
                                     # The following statements yield the same filtering criteria
                                     .expiration(0, 180)))
                                     #.expiration(TimeSpan.zero, TimeSpan.from_days(180))))

        # use the underlying equity as the benchmark
        self.set_benchmark(equity.symbol)

    def on_data(self, slice):
        if self.portfolio.invested or not self.is_market_open(self.option_symbol): return

        chain = slice.option_chains.get(self.option_symbol)
        if not chain:
            return

        # we sort the contracts to find at the money (ATM) contract with farthest expiration
        contracts = sorted(sorted(sorted(chain, \
            key = lambda x: abs(chain.underlying.price - x.strike)), \
            key = lambda x: x.expiry, reverse=True), \
            key = lambda x: x.right, reverse=True)

        # if found, trade it
        if len(contracts) == 0: return
        symbol = contracts[0].symbol
        self.market_order(symbol, 1)
        self.market_on_close_order(symbol, -1)

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


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

Input:
Generate a LEAN Algorithm that can be described like this
: Regression algorithm asserting that historical data can be requested with tick resolution without requiring
a tick resolution subscription

Output:
```python

from datetime import timedelta
from AlgorithmImports import *

class TickHistoryRequestWithoutTickSubscriptionRegressionAlgorithm(QCAlgorithm):

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

        # Subscribing SPY and IBM with daily and hour resolution instead of tick resolution
        spy = self.add_equity("SPY", Resolution.DAILY).symbol
        ibm = self.add_equity("IBM", Resolution.HOUR).symbol

        # Requesting history for SPY and IBM (separately) with tick resolution
        spy_history = self.history[Tick](spy, timedelta(days=1), Resolution.TICK)
        if not any(spy_history):
            raise AssertionError("SPY tick history is empty")

        ibm_history = self.history[Tick](ibm, timedelta(days=1), Resolution.TICK)
        if not any(ibm_history):
            raise AssertionError("IBM tick history is empty")

        # Requesting history for SPY and IBM (together) with tick resolution
        spy_ibm_history = self.history[Tick]([spy, ibm], timedelta(days=1), Resolution.TICK)
        if not any(spy_ibm_history):
            raise AssertionError("Compound SPY and IBM tick history is empty")

        self.quit()
```


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

Input:
Generate a LEAN Algorithm that can be described like this
: Basic algorithm demonstrating how to place trailing stop orders.

Output:
```python

from AlgorithmImports import *

class TrailingStopOrderRegressionAlgorithm(QCAlgorithm):
    '''Basic algorithm demonstrating how to place trailing stop orders.'''

    buy_trailing_amount = 2
    sell_trailing_amount = 0.5
    asynchronous_orders = False

    def initialize(self):

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

        self._symbol = self.add_equity("SPY").symbol

        self._buy_order_ticket: OrderTicket = None
        self._sell_order_ticket: OrderTicket = None
        self._previous_slice: Slice = None

    def on_data(self, slice: Slice):
        if not slice.contains_key(self._symbol):
            return

        if self._buy_order_ticket is None:
            self._buy_order_ticket = self.trailing_stop_order(self._symbol, 100, trailing_amount=self.buy_trailing_amount, trailing_as_percentage=False, asynchronous=self.asynchronous_orders)
        elif self._buy_order_ticket.status != OrderStatus.FILLED:
            stop_price = self._buy_order_ticket.get(OrderField.STOP_PRICE)

            # Get the previous bar to compare to the stop price,
            # because stop price update attempt with the current slice data happens after OnData.
            low = self._previous_slice.quote_bars[self._symbol].ask.low if self._previous_slice.quote_bars.contains_key(self._symbol) \
                else self._previous_slice.bars[self._symbol].low

            stop_price_to_market_price_distance = stop_price - low
            if stop_price_to_market_price_distance > self.buy_trailing_amount:
                raise AssertionError(f"StopPrice {stop_price} should be within {self.buy_trailing_amount} of the previous low price {low} at all times.")

        if self._sell_order_ticket is None:
            if self.portfolio.invested:
                self._sell_order_ticket = self.trailing_stop_order(self._symbol, -100, trailing_amount=self.sell_trailing_amount, trailing_as_percentage=False, asynchronous=self.asynchronous_orders)
        elif self._sell_order_ticket.status != OrderStatus.FILLED:
            stop_price = self._sell_order_ticket.get(OrderField.STOP_PRICE)

            # Get the previous bar to compare to the stop price,
            # because stop price update attempt with the current slice data happens after OnData.
            high = self._previous_slice.quote_bars[self._symbol].bid.high if self._previous_slice.quote_bars.contains_key(self._symbol) \
                    else self._previous_slice.bars[self._symbol].high
            stop_price_to_market_price_distance = high - stop_price
            if stop_price_to_market_price_distance > self.sell_trailing_amount:
                raise AssertionError(f"StopPrice {stop_price} should be within {self.sell_trailing_amount} of the previous high price {high} at all times.")

        self._previous_slice = slice

    def on_order_event(self, orderEvent: OrderEvent):
        if orderEvent.status == OrderStatus.FILLED:
            if orderEvent.direction == OrderDirection.BUY:
                stop_price = self._buy_order_ticket.get(OrderField.STOP_PRICE)
                if orderEvent.fill_price < stop_price:
                    raise AssertionError(f"Buy trailing stop order should have filled with price greater than or equal to the stop price {stop_price}. "
                                    f"Fill price: {orderEvent.fill_price}")
            else:
                stop_price = self._sell_order_ticket.get(OrderField.STOP_PRICE)
                if orderEvent.fill_price > stop_price:
                    raise AssertionError(f"Sell trailing stop order should have filled with price less than or equal to the stop price {stop_price}. "
                                    f"Fill price: {orderEvent.fill_price}")

    def on_end_of_algorithm(self):
        for ticket in self.transactions.get_order_tickets():
            if ticket.submit_request.asynchronous != self.asynchronous_orders:
                raise AssertionError("Expected all orders to have the same asynchronous flag as the algorithm.")
```


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

Input:
Generate a LEAN Algorithm that can be described like this
: Regression algorithm asserting the behavior of different callback commands call

Output:
```python

from AlgorithmImports import *

class InvalidCommand():
    variable = 10

class VoidCommand():
    quantity = 0
    target = []
    parameters = {}
    targettime = None

    def run(self, algo: IAlgorithm) -> bool:
        if not self.targettime or self.targettime != algo.time:
            return False
        tag = self.parameters["tag"]
        algo.order(self.target[0], self.get_quantity(), tag=tag)
        return True

    def get_quantity(self):
        return self.quantity

class BoolCommand(Command):
    something_else = {}
    array_test = []
    result = False

    def run(self, algo) -> bool:
        trade_ibm = self.my_custom_method()
        if trade_ibm:
            algo.debug(f"BoolCommand.run: {str(self)}")
            algo.buy("IBM", 1)
        return trade_ibm

    def my_custom_method(self):
        return self.result

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

        self.set_start_date(2013, 10, 7)
        self.set_end_date(2013, 10, 11)

        self.add_equity("SPY")
        self.add_equity("IBM")
        self.add_equity("BAC")

        self.add_command(VoidCommand)
        self.add_command(BoolCommand)

        threw_exception = False
        try:
            self.add_command(InvalidCommand)
        except:
            threw_exception = True
        if not threw_exception:
            raise ValueError('InvalidCommand did not throw!')

        bool_command = BoolCommand()
        bool_command.result = True
        bool_command.something_else = { "Property": 10 }
        bool_command.array_test = [ "SPY", "BTCUSD" ]
        link = self.link(bool_command)
        if "&command%5barray_test%5d%5b0%5d=SPY&command%5barray_test%5d%5b1%5d=BTCUSD&command%5bresult%5d=True&command%5bsomething_else%5d%5bProperty%5d=10&command%5b%24type%5d=BoolCommand" not in link:
            raise ValueError(f'Invalid link was generated! {link}')

        potential_command = VoidCommand()
        potential_command.target = [ "BAC" ]
        potential_command.quantity = 10
        potential_command.parameters = { "tag": "Signal X" }

        command_link = self.link(potential_command)
        if "&command%5btarget%5d%5b0%5d=BAC&command%5bquantity%5d=10&command%5bparameters%5d%5btag%5d=Signal+X&command%5b%24type%5d=VoidCommand" not in command_link:
            raise ValueError(f'Invalid link was generated! {command_link}')
        self.notify.email("email@address", "Trade Command Event", f"Signal X trade\nFollow link to trigger: {command_link}")

        untyped_command_link = self.link({ "symbol": "SPY", "parameters": { "quantity": 10 } })
        if "&command%5bsymbol%5d=SPY&command%5bparameters%5d%5bquantity%5d=10" not in untyped_command_link:
            raise ValueError(f'Invalid link was generated! {untyped_command_link}')
        self.notify.email("email@address", "Untyped Command Event", f"Signal Y trade\nFollow link to trigger: {untyped_command_link}")

        # We need to create a project on QuantConnect to test the broadcast_command method
        # and use the project_id in the broadcast_command call
        self.project_id = 21805137

        # All live deployments receive the broadcasts below
        broadcast_result = self.broadcast_command(potential_command)
        broadcast_result2 = self.broadcast_command({ "symbol": "SPY", "parameters": { "quantity": 10 } })

    def on_command(self, data: object) -> bool:
        self.debug(f"on_command: {str(data)}")
        self.buy(data.symbol, data.parameters["quantity"])
        return True # False, None
```


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

Input:
Generate a LEAN Algorithm that can be described like this
: Algorithm demonstrating custom charting support in QuantConnect.
The entire charting system of quantconnect is adaptable. You can adjust it to draw whatever you'd like.
Charts can be stacked, or overlayed on each other. Series can be candles, lines or scatter plots.
Even the default behaviours of QuantConnect can be overridden.

Output:
```python

from AlgorithmImports import *

class CustomChartingAlgorithm(QCAlgorithm):
    def initialize(self):
        self.set_start_date(2016,1,1)
        self.set_end_date(2017,1,1)
        self.set_cash(100000)

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

        # In your initialize method:
        # Chart - Master Container for the Chart:
        stock_plot = Chart("Trade Plot")
        # On the Trade Plotter Chart we want 3 series: trades and price:
        stock_plot.add_series(Series("Buy", SeriesType.SCATTER, 0))
        stock_plot.add_series(Series("Sell", SeriesType.SCATTER, 0))
        stock_plot.add_series(Series("Price", SeriesType.LINE, 0))
        self.add_chart(stock_plot)

        # On the Average Cross Chart we want 2 series, slow MA and fast MA
        avg_cross = Chart("Average Cross")
        avg_cross.add_series(Series("FastMA", SeriesType.LINE, 0))
        avg_cross.add_series(Series("SlowMA", SeriesType.LINE, 0))
        self.add_chart(avg_cross)

        # There's support for candlestick charts built-in:
        weekly_spy_plot = Chart("Weekly SPY")
        spy_candlesticks = CandlestickSeries("SPY")
        weekly_spy_plot.add_series(spy_candlesticks)
        self.add_chart(weekly_spy_plot)

        self.consolidate(spy, Calendar.WEEKLY, lambda bar: self.plot("Weekly SPY", "SPY", bar))

        self.fast_ma = 0
        self.slow_ma = 0
        self.last_price = 0
        self.resample = datetime.min
        self.resample_period = (self.end_date - self.start_date) / 2000

    def on_data(self, slice):
        if slice["SPY"] is None: return

        self.last_price = slice["SPY"].close
        if self.fast_ma == 0: self.fast_ma = self.last_price
        if self.slow_ma == 0: self.slow_ma = self.last_price
        self.fast_ma = (0.01 * self.last_price) + (0.99 * self.fast_ma)
        self.slow_ma = (0.001 * self.last_price) + (0.999 * self.slow_ma)

        if self.time > self.resample:
            self.resample = self.time  + self.resample_period
            self.plot("Average Cross", "FastMA", self.fast_ma)
            self.plot("Average Cross", "SlowMA", self.slow_ma)

        # On the 5th days when not invested buy:
        if not self.portfolio.invested and self.time.day % 13 == 0:
        	self.order("SPY", (int)(self.portfolio.margin_remaining / self.last_price))
        	self.plot("Trade Plot", "Buy", self.last_price)
        elif self.time.day % 21 == 0 and self.portfolio.invested:
            self.plot("Trade Plot", "Sell", self.last_price)
            self.liquidate()

    def on_end_of_day(self, symbol):
       #Log the end of day prices:
       self.plot("Trade Plot", "Price", self.last_price)
```


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

Output:
```python

from AlgorithmImports import *

class CustomDataTypeHistoryAlgorithm(QCAlgorithm):
    def initialize(self):
        self.set_start_date(2017, 8, 20)
        self.set_end_date(2017, 8, 20)

        self._symbol = self.add_data(CustomDataType, "CustomDataType", Resolution.HOUR).symbol

        history = list(self.history[CustomDataType](self._symbol, 48, Resolution.HOUR))

        if len(history) == 0:
            raise AssertionError("History request returned no data")

        self._assert_history_data(history)

        history2 = list(self.history[CustomDataType]([self._symbol], 48, Resolution.HOUR))

        if len(history2) != len(history):
            raise AssertionError("History requests returned different data")

        self._assert_history_data([y.values()[0] for y in history2])

    def _assert_history_data(self, history:  List[PythonData]) -> None:
        expected_keys = ['open', 'close', 'high', 'low', 'some_property']
        if any(any(not x[key] for key in expected_keys)
               or x["some_property"] != "some property value"
               for x in history):
            raise AssertionError("History request returned data without the expected properties")

class CustomDataType(PythonData):

    def get_source(self, config: SubscriptionDataConfig, date: datetime, is_live: bool) -> SubscriptionDataSource:
        source = "https://www.dl.dropboxusercontent.com/s/d83xvd7mm9fzpk0/path_to_my_csv_data.csv?dl=0"
        return SubscriptionDataSource(source, SubscriptionTransportMedium.REMOTE_FILE)

    def reader(self, config: SubscriptionDataConfig, line: str, date: datetime, is_live: bool) -> BaseData:
        if not (line.strip()):
            return None

        data = line.split(',')
        obj_data = CustomDataType()
        obj_data.symbol = config.symbol

        try:
            obj_data.time = datetime.strptime(data[0], '%Y-%m-%d %H:%M:%S') + timedelta(hours=20)
            obj_data["open"] = float(data[1])
            obj_data["high"] = float(data[2])
            obj_data["low"] = float(data[3])
            obj_data["close"] = float(data[4])
            obj_data.value = obj_data["close"]

            # property for asserting the correct data is fetched
            obj_data["some_property"] = "some property value"
        except ValueError:
            return None

        return obj_data
```


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

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

Output:
```python

from AlgorithmImports import *

class BasicTemplateFillForwardAlgorithm(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,11,30)    #Set End Date
        self.set_cash(100000)           #Set Strategy Cash
        # Find more symbols here: http://quantconnect.com/data
        self.add_security(SecurityType.EQUITY, "ASUR", Resolution.SECOND)

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

        Arguments:
            data: Slice object keyed by symbol containing the stock data
        '''
        if not self.portfolio.invested:
            self.set_holdings("ASUR", 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
: We add an option contract using 'QCAlgorithm.add_option_contract' and place a trade, the underlying
gets deselected from the universe selection but should still be present since we manually added the option contract.
Later we call 'QCAlgorithm.remove_option_contract' and expect both option and underlying to be removed.

Output:
```python

from AlgorithmImports import *

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

        self.set_start_date(2014, 6, 5)
        self.set_end_date(2014, 6, 9)

        self._expiration = datetime(2014, 6, 21)
        self._security_changes = None
        self._option = None
        self._traded = False

        self._twx = Symbol.create("TWX", SecurityType.EQUITY, Market.USA)
        self._aapl = Symbol.create("AAPL", SecurityType.EQUITY, Market.USA)
        self.universe_settings.resolution = Resolution.MINUTE
        self.universe_settings.data_normalization_mode = DataNormalizationMode.RAW

        self.add_universe(self.selector, self.selector)

    def selector(self, fundamental):
        if self.time <= datetime(2014, 6, 5):
            return  [ self._twx ]
        return [ self._aapl ]

    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 self._option != None and self.securities[self._option].price != 0 and not self._traded:
            self._traded = True
            self.buy(self._option, 1)

        if self.time == datetime(2014, 6, 6, 14, 0, 0):
            # liquidate & remove the option
            self.remove_option_contract(self._option)

    def on_securities_changed(self, changes):
        # keep track of all removed and added securities
        if self._security_changes == None:
            self._security_changes = changes
        else:
            self._security_changes += changes

        if any(security.symbol.security_type == SecurityType.OPTION for security in changes.added_securities):
            return

        for addedSecurity in changes.added_securities:
            option_chain = self.option_chain(addedSecurity.symbol)
            options = sorted(option_chain, key=lambda x: x.id.symbol)

            option = next((option
                           for option in options
                           if option.id.date == self._expiration and
                           option.id.option_right == OptionRight.CALL and
                           option.id.option_style == OptionStyle.AMERICAN), None)

            self.add_option_contract(option)

            # just keep the first we got
            if self._option == None:
                self._option = option
```


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

Input:
Generate a LEAN Algorithm that can be described like this
: Example algorithm of how to use RangeConsolidator

Output:
```python

from AlgorithmImports import *

class RangeConsolidatorAlgorithm(QCAlgorithm):
    def get_resolution(self) -> Resolution:
        return Resolution.DAILY

    def get_range(self) -> int:
        return 100

    def initialize(self) -> None:
        self.set_start_and_end_dates()
        self.add_equity("SPY", self.get_resolution())
        range_consolidator = self.create_range_consolidator()
        range_consolidator.data_consolidated += self.on_data_consolidated
        self._first_data_consolidated = None

        self.subscription_manager.add_consolidator("SPY", range_consolidator)

    def set_start_and_end_dates(self) -> None:
        self.set_start_date(2013, 10, 7)
        self.set_end_date(2013, 10, 11)

    def on_end_of_algorithm(self) -> None:
        if not self._first_data_consolidated:
            raise AssertionError("The consolidator should have consolidated at least one RangeBar, but it did not consolidated any one")

    def create_range_consolidator(self) -> RangeConsolidator:
        return RangeConsolidator(self.get_range())

    def on_data_consolidated(self, sender: object, range_bar: RangeBar) -> None:
        if not self._first_data_consolidated:
            self._first_data_consolidated = range_bar

        if round(range_bar.high - range_bar.low, 2) != self.get_range() * 0.01: # The minimum price change for SPY is 0.01, therefore the range size of each bar equals Range * 0.01
            raise AssertionError(f"The difference between the High and Low for all RangeBar's should be {self.get_range() * 0.01}, but for this RangeBar was {round(range_bar.low - range_bar.high, 2)}")
```


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
: Alpha model for ETF constituents, where we generate insights based on the weighting
of the ETF constituent

Output:
```python

from AlgorithmImports import *

constituent_data = []

class ETFConstituentAlphaModel(AlphaModel):
    def on_securities_changed(self, algorithm: QCAlgorithm, changes: SecurityChanges) -> None:
        pass

    ### <summary>
    ### Creates new insights based on constituent data and their weighting
    ### in their respective ETF
    ### </summary>
    def update(self, algorithm: QCAlgorithm, data: Slice) -> list[Insight]:
        global constituent_data
        insights = []

        for constituent in constituent_data:
            if constituent.symbol not in data.bars and \
                constituent.symbol not in data.quote_bars:

                continue

            insight_direction = InsightDirection.UP if constituent.weight is not None and constituent.weight >= 0.01 else InsightDirection.DOWN

            insights.append(Insight(
                algorithm.utc_time,
                constituent.symbol,
                timedelta(days=1),
                InsightType.PRICE,
                insight_direction,
                float(1 * int(insight_direction)),
                1.0,
                weight=float(0 if constituent.weight is None else constituent.weight)
            ))

        return insights

class ETFConstituentPortfolioModel(PortfolioConstructionModel):
    def __init__(self) -> None:
        self.has_added = False

    ### <summary>
    ### Securities changed, detects if we've got new additions to the universe
    ### so that we don't try to trade every loop
    ### </summary>
    def on_securities_changed(self, algorithm: QCAlgorithm, changes: SecurityChanges) -> None:
        self.has_added = len(changes.added_securities) != 0

    ### <summary>
    ### Creates portfolio targets based on the insights provided to us by the alpha model.
    ### Emits portfolio targets setting the quantity to the weight of the constituent
    ### in its respective ETF.
    ### </summary>
    def create_targets(self, algorithm: QCAlgorithm, insights: list[Insight]) -> list[PortfolioTarget]:
        if not self.has_added:
            return []

        final_insights = []
        for insight in insights:
            final_insights.append(PortfolioTarget(insight.symbol, float(0 if insight.weight is None else insight.weight)))
            self.has_added = False

        return final_insights

class ETFConstituentExecutionModel(ExecutionModel):
    ### <summary>
    ### Liquidates if constituents have been removed from the universe
    ### </summary>
    def on_securities_changed(self, algorithm: QCAlgorithm, changes: SecurityChanges) -> None:
        for change in changes.removed_securities:
            algorithm.liquidate(change.symbol)

    ### <summary>
    ### Creates orders for constituents that attempts to add
    ### the weighting of the constituent in our portfolio. The
    ### resulting algorithm portfolio weight might not be equal
    ### to the leverage of the ETF (1x, 2x, 3x, etc.)
    ### </summary>
    def execute(self, algorithm: QCAlgorithm, targets: list[IPortfolioTarget]) -> None:
        for target in targets:
            algorithm.set_holdings(target.symbol, target.quantity)

class ETFConstituentUniverseFrameworkRegressionAlgorithm(QCAlgorithm):
    ### <summary>
    ### Initializes the algorithm, setting up the framework classes and ETF constituent universe settings
    ### </summary>
    def initialize(self) -> None:
        self.set_start_date(2020, 12, 1)
        self.set_end_date(2021, 1, 31)
        self.set_cash(100000)

        self.set_alpha(ETFConstituentAlphaModel())
        self.set_portfolio_construction(ETFConstituentPortfolioModel())
        self.set_execution(ETFConstituentExecutionModel())

        self.universe_settings.resolution = Resolution.HOUR
        universe = self.add_universe(self.universe.etf("SPY", self.universe_settings, self.filter_etf_constituents))

        historical_data = self.history(universe, 1, flatten=True)
        if len(historical_data) < 200:
            raise ValueError(f"Unexpected universe DataCollection count {len(historical_data)}! Expected > 200")

    ### <summary>
    ### Filters ETF constituents
    ### </summary>
    ### <param name="constituents">ETF constituents</param>
    ### <returns>ETF constituent Symbols that we want to include in the algorithm</returns>
    def filter_etf_constituents(self, constituents: list[ETFConstituentUniverse]) -> list[Symbol]:
        global constituent_data

        constituent_data_local = [i for i in constituents if i.weight and i.weight >= 0.001]
        constituent_data = list(constituent_data_local)

        return [i.symbol for i in constituent_data_local]
```


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 verifies automatic option contract assignment behavior.

Output:
```python

from AlgorithmImports import *

class OptionAssignmentRegressionAlgorithm(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2015, 12, 23)
        self.set_end_date(2015, 12, 28)
        self.set_cash(100000)
        self.stock = self.add_equity("GOOG", Resolution.MINUTE)

        contracts = list(self.option_chain(self.stock.symbol))

        self.put_option_symbol = sorted(
            [c for c in contracts if c.id.option_right == OptionRight.PUT and c.id.strike_price == 800],
            key=lambda c: c.id.date
        )[0]

        self.call_option_symbol = sorted(
            [c for c in contracts if c.id.option_right == OptionRight.CALL and c.id.strike_price == 600],
            key=lambda c: c.id.date
        )[0]

        self.put_option = self.add_option_contract(self.put_option_symbol)
        self.call_option = self.add_option_contract(self.call_option_symbol)

    def on_data(self, data):
        if not self.portfolio.invested and self.stock.price != 0 and self.put_option.price != 0 and self.call_option.price != 0:
            #this gets executed on start and after each auto-assignment, finally ending with expiration assignment
            if self.time < self.put_option_symbol.id.date:
                self.market_order(self.put_option_symbol, -1)

            if self.time < self.call_option_symbol.id.date:
                self.market_order(self.call_option_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 for fractional forex pair

Output:
```python

from AlgorithmImports import *

class FractionalQuantityRegressionAlgorithm(QCAlgorithm):

    def initialize(self):

        self.set_start_date(2015, 11, 12)
        self.set_end_date(2016, 4, 1)
        self.set_cash(100000)
        self.set_brokerage_model(BrokerageName.GDAX, AccountType.CASH)

        self.set_time_zone(TimeZones.UTC)

        security = self.add_security(SecurityType.CRYPTO, "BTCUSD", Resolution.DAILY, Market.GDAX, False, 1, True)

        ### The default buying power model for the Crypto security type is now CashBuyingPowerModel.
        ### Since this test algorithm uses leverage we need to set a buying power model with margin.
        security.set_buying_power_model(SecurityMarginModel(3.3))

        con = TradeBarConsolidator(1)
        self.subscription_manager.add_consolidator("BTCUSD", con)
        con.data_consolidated += self.data_consolidated
        self.set_benchmark(security.symbol)

    def data_consolidated(self, sender, bar):
        quantity = math.floor((self.portfolio.cash + self.portfolio.total_fees) / abs(bar.value + 1))
        btc_qnty = float(self.portfolio["BTCUSD"].quantity)

        if not self.portfolio.invested:
            self.order("BTCUSD", quantity)
        elif btc_qnty == quantity:
            self.order("BTCUSD", 0.1)
        elif btc_qnty == quantity + 0.1:
            self.order("BTCUSD", 0.01)
        elif btc_qnty == quantity + 0.11:
            self.order("BTCUSD", -0.02)
        elif btc_qnty == quantity + 0.09:
            # should fail (below minimum order quantity)
            self.order("BTCUSD", 0.00001)
            self.set_holdings("BTCUSD", -2.0)
            self.set_holdings("BTCUSD", 2.0)
            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
: CapmAlphaRankingFrameworkAlgorithm: example of custom scheduled universe selection model
Universe Selection inspired by https://www.quantconnect.com/tutorials/strategy-library/capm-alpha-ranking-strategy-on-dow-30-companies

Output:
```python

from AlgorithmImports import *

class CapmAlphaRankingFrameworkAlgorithm(QCAlgorithm):
    '''CapmAlphaRankingFrameworkAlgorithm: example of custom scheduled universe selection model'''

    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.'''

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

        self.set_start_date(2016, 1, 1)   #Set Start Date
        self.set_end_date(2017, 1, 1)     #Set End Date
        self.set_cash(100000)            #Set Strategy Cash

        # set algorithm framework models
        self.set_universe_selection(CapmAlphaRankingUniverseSelectionModel())
        self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(1), 0.025, None))
        self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
        self.set_execution(ImmediateExecutionModel())
        self.set_risk_management(MaximumDrawdownPercentPerSecurity(0.01))

class CapmAlphaRankingUniverseSelectionModel(UniverseSelectionModel):
    '''This universe selection model picks stocks with the highest alpha: interception of the linear regression against a benchmark.'''

    period = 21
    benchmark = "SPY"

    # Symbols of Dow 30 companies.
    _symbols = [Symbol.create(x, SecurityType.EQUITY, Market.USA)
               for x in ["AAPL", "AXP", "BA", "CAT", "CSCO", "CVX", "DD", "DIS", "GE", "GS",
                         "HD", "IBM", "INTC", "JPM", "KO", "MCD", "MMM", "MRK", "MSFT",
                         "NKE","PFE", "PG", "TRV", "UNH", "UTX", "V", "VZ", "WMT", "XOM"]]

    def create_universes(self, algorithm):

        # Adds the benchmark to the user defined universe
        benchmark = algorithm.add_equity(self.benchmark, Resolution.DAILY)

        # Defines a schedule universe that fires after market open when the month starts
        return [ ScheduledUniverse(
            benchmark.exchange.time_zone,
            algorithm.date_rules.month_start(self.benchmark),
            algorithm.time_rules.after_market_open(self.benchmark),
            lambda datetime: self.select_pair(algorithm, datetime),
            algorithm.universe_settings)]

    def select_pair(self, algorithm, date):
        '''Selects the pair (two stocks) with the highest alpha'''
        dictionary = dict()
        benchmark = self._get_returns(algorithm, self.benchmark)
        ones = np.ones(len(benchmark))

        for symbol in self._symbols:
            prices = self._get_returns(algorithm, symbol)
            if prices is None: continue
            A = np.vstack([prices, ones]).T

            # Calculate the Least-Square fitting to the returns of a given symbol and the benchmark
            ols = np.linalg.lstsq(A, benchmark)[0]
            dictionary[symbol] = ols[1]

        # Returns the top 2 highest alphas
        ordered_dictionary = sorted(dictionary.items(), key= lambda x: x[1], reverse=True)
        return [x[0] for x in ordered_dictionary[:2]]

    def _get_returns(self, algorithm, symbol):

        history = algorithm.history([symbol], self.period, Resolution.DAILY)
        if history.empty: return None

        window = RollingWindow(self.period)
        rate_of_change = RateOfChange(1)

        def roc_updated(s, item):
            window.add(item.value)

        rate_of_change.updated += roc_updated

        history = history.close.reset_index(level=0, drop=True).items()

        for time, value in history:
            rate_of_change.update(time, value)

        return [ x for x in window]
```


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 is for testing a custom Python filter for options
that returns a OptionFilterUniverse.

Output:
```python

from AlgorithmImports import *

class FilterUniverseRegressionAlgorithm(QCAlgorithm):
    underlying_ticker = "GOOG"

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

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

        # Set our custom universe filter
        option.set_filter(self.filter_function)

        # use the underlying equity as the benchmark
        self.set_benchmark(equity.symbol)

    def filter_function(self, universe):
        universe = universe.weeklys_only().strikes(-5, +5).calls_only().expiration(0, 1)
        return universe

    def on_data(self,slice):
        if self.portfolio.invested: return

        for kvp in slice.option_chains:

            if kvp.key != self.option_symbol: continue

            chain = kvp.value
            contracts = [option for option in sorted(chain, key = lambda x:x.strike, reverse = True)]

            if contracts:
                self.market_order(contracts[0].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 validate SecurityCache.Session functionality.
Verifies that daily session bars (Open, High, Low, Close, Volume) are correctly

Output:
```python

from AlgorithmImports import *

class SecuritySessionRegressionAlgorithm(QCAlgorithm):

    def initialize(self):
        self.add_security_initializer(self.initialize_session_tracking)
        self.initialize_security()

        # Check initial session values
        session = self.security.session
        if session is None:
            raise RegressionTestException("Security.Session is none")
        if (session.open != 0
            or session.high != 0
            or session.low != 0
            or session.close != 0
            or session.volume != 0
            or session.open_interest != 0):
            raise RegressionTestException("Session should start with all zero values.")

        self.security_was_removed = False
        self.open = self.close = self.high = self.volume = 0
        self.low = float('inf')
        self.current_date = self.start_date
        self.previous_session_bar = None

        self.schedule.on(
            self.date_rules.every_day(),
            self.time_rules.after_market_close(self.security.symbol, 1),
            self.validate_session_bars
        )

    def initialize_security(self):
        self.set_start_date(2013, 10, 7)
        self.set_end_date(2013, 10, 11)
        self.security = self.add_equity("SPY", Resolution.HOUR)

    def initialize_session_tracking(self, security):
        # activate session tracking
        security.session.size = 3

    def _are_equal(self, value1, value2):
        tolerance = 1e-10
        return abs(value1 - value2) <= tolerance

    def validate_session_bars(self):
        session = self.security.session
        # At this point the data was consolidated (market close)

        # Save previous session bar
        self.previous_session_bar = {
            'date': self.current_date,
            'open': self.open,
            'high': self.high,
            'low': self.low,
            'close': self.close,
            'volume': self.volume
        }

        if self.security_was_removed:
            self.previous_session_bar = None
            self.security_was_removed = False
            return

        # Check current session values
        if (not self._are_equal(session.open, self.open)
            or not self._are_equal(session.high, self.high)
            or not self._are_equal(session.low, self.low)
            or not self._are_equal(session.close, self.close)
            or not self._are_equal(session.volume, self.volume)):
            raise RegressionTestException("Mismatch in current session bar (OHLCV)")

    def is_within_market_hours(self, current_date_time):
        market_open = self.security.exchange.hours.get_next_market_open(current_date_time.date(), False).time()
        market_close = self.security.exchange.hours.get_next_market_close(current_date_time.date(), False).time()
        current_time = current_date_time.time()
        return market_open < current_time <= market_close

    def on_data(self, data):
        if not self.is_within_market_hours(data.time):
            # Skip data outside market hours
            return

        # Accumulate data within regular market hours
        # to later compare against the Session values
        self.accumulate_session_data(data)

    def accumulate_session_data(self, data):
        symbol = self.security.symbol
        if self.current_date.date() == data.time.date():
            # Same trading day
            if self.open == 0:
                self.open = data[symbol].open
            self.high = max(self.high, data[symbol].high)
            self.low = min(self.low, data[symbol].low)
            self.close = data[symbol].close
            self.volume += data[symbol].volume
        else:
            # New trading day

            if self.previous_session_bar is not None:
                session = self.security.session
                if (self.previous_session_bar['open'] != session[1].open
                    or self.previous_session_bar['high'] != session[1].high
                    or self.previous_session_bar['low'] != session[1].low
                    or self.previous_session_bar['close'] != session[1].close
                    or self.previous_session_bar['volume'] != session[1].volume):
                    raise RegressionTestException("Mismatch in previous session bar (OHLCV)")

            # This is the first data point of the new session
            self.open = data[symbol].open
            self.close = data[symbol].close
            self.high = data[symbol].high
            self.low = data[symbol].low
            self.volume = data[symbol].volume
            self.current_date = data.time
```


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

Input:
Generate a LEAN Algorithm that can be described like this
: Regression algorithm asserting that tick history request includes both trade and quote data

Output:
```python

from AlgorithmImports import *

class HistoryTickRegressionAlgorithm(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2013, 10, 12)
        self.set_end_date(2013, 10, 13)

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

        trades_count = 0
        quotes_count = 0
        for point in self.history[Tick](self._symbol, timedelta(days=1), Resolution.TICK):
            if point.tick_type == TickType.TRADE:
                trades_count += 1
            elif point.tick_type == TickType.QUOTE:
                quotes_count += 1

            if trades_count > 0 and quotes_count > 0:
                # We already found at least one tick of each type, we can exit the loop
                break

        if trades_count == 0 or quotes_count == 0:
            raise AssertionError("Expected to find at least one tick of each type (quote and trade)")

        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
: Regression algorithm to assert the behavior of <see cref="EmaCrossAlphaModel"/>.

Output:
```python

from AlgorithmImports import *
from BaseFrameworkRegressionAlgorithm import BaseFrameworkRegressionAlgorithm
from Alphas.EmaCrossAlphaModel import EmaCrossAlphaModel

class EmaCrossAlphaModelFrameworkRegressionAlgorithm(BaseFrameworkRegressionAlgorithm):

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

    def on_end_of_algorithm(self):
        pass
```


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

Input:
Generate a LEAN Algorithm that can be described like this
: Demonstration of how to define a universe using the fundamental data

Output:
```python

from AlgorithmImports import *
from Selection.FundamentalUniverseSelectionModel import FundamentalUniverseSelectionModel

class FundamentalUniverseSelectionRegressionAlgorithm(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.add_equity("SPY")
        self.add_equity("AAPL")

        self.set_universe_selection(FundamentalUniverseSelectionModelTest())

        self.changes = None

    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

class FundamentalUniverseSelectionModelTest(FundamentalUniverseSelectionModel):

    def select(self, algorithm, 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[:2] ]
```


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

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

        self.universe_settings.resolution = Resolution.DAILY

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

        self.set_universe_selection(FundamentalUniverseSelectionModel(self.select))

        self.changes = None
        self.number_of_symbols_fundamental = 10

    # 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

    def select(self, fundamental):
        # sort descending by daily dollar volume
        sorted_by_dollar_volume = sorted([x for x in fundamental if x.has_fundamental_data and 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[:2] ]
```


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 using 'QCAlgorithm.add_risk_management(IRiskManagementModel)'

Output:
```python

from AlgorithmImports import *

class AddRiskManagementAlgorithm(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.universe_settings.resolution = Resolution.MINUTE

        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 = [ Symbol.create("SPY", SecurityType.EQUITY, Market.USA) ]

        # set algorithm framework models
        self.set_universe_selection(ManualUniverseSelectionModel(symbols))
        self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(minutes = 20), 0.025, None))
        self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
        self.set_execution(ImmediateExecutionModel())

        # Both setting methods should work
        risk_model = CompositeRiskManagementModel(MaximumDrawdownPercentPortfolio(0.02))
        risk_model.add_risk_management(MaximumUnrealizedProfitPercentPerSecurity(0.01))

        self.set_risk_management(MaximumDrawdownPercentPortfolio(0.02))
        self.add_risk_management(MaximumUnrealizedProfitPercentPerSecurity(0.01))

```


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 Continuous Futures Template Algorithm with extended market hours

Output:
```python

from AlgorithmImports import *

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

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

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

        self._continuous_contract = self.add_future(Futures.Indices.SP_500_E_MINI,
                                                  data_normalization_mode = DataNormalizationMode.BACKWARDS_RATIO,
                                                  data_mapping_mode = DataMappingMode.LAST_TRADING_DAY,
                                                  contract_depth_offset = 0,
                                                  extended_market_hours = True)

        self._fast = self.sma(self._continuous_contract.symbol, 4, Resolution.DAILY)
        self._slow = self.sma(self._continuous_contract.symbol, 10, Resolution.DAILY)
        self._current_contract = 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.

        Arguments:
            data: Slice object keyed by symbol containing the stock data
        '''
        for changed_event in data.symbol_changed_events.values():
            if changed_event.symbol == self._continuous_contract.symbol:
                self.log(f"SymbolChanged event: {changed_event}")

        if not self.is_market_open(self._continuous_contract.symbol):
            return

        if not self.portfolio.invested:
            if self._fast.current.value > self._slow.current.value:
                self._current_contract = self.securities[self._continuous_contract.mapped]
                self.buy(self._current_contract.symbol, 1)
        elif self._fast.current.value < self._slow.current.value:
            self.liquidate()

        if self._current_contract is not None and self._current_contract.symbol != self._continuous_contract.mapped:
            self.log(f"{Time} - rolling position from {self._current_contract.symbol} to {self._continuous_contract.mapped}")

            current_position_size = self._current_contract.holdings.quantity
            self.liquidate(self._current_contract.symbol)
            self.buy(self._continuous_contract.mapped, current_position_size)
            self._current_contract = self.securities[self._continuous_contract.mapped]

    def on_order_event(self, order_event):
        self.debug("Purchased Stock: {0}".format(order_event.symbol))

    def on_securities_changed(self, changes):
        self.debug(f"{self.time}-{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
: Asserts that algorithms can be universe-only, that is, universe selection is performed even if the ETF security is not explicitly added.
Reproduces https://github.com/QuantConnect/Lean/issues/7473

Output:
```python

from AlgorithmImports import *

class UniverseOnlyRegressionAlgorithm(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2020, 12, 1)
        self.set_end_date(2020, 12, 12)
        self.set_cash(100000)

        self.universe_settings.resolution = Resolution.DAILY

        # Add universe without a security added
        self.add_universe(self.universe.etf("GDVD", self.universe_settings, self.filter_universe))

        self.selection_done = False

    def filter_universe(self, constituents: List[ETFConstituentData]) -> List[Symbol]:
        self.selection_done = True
        return [x.symbol for x in constituents]

    def on_end_of_algorithm(self):
        if not self.selection_done:
            raise AssertionError("Universe selection was not performed")
```


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 demonstrates how to use the OptionUniverseSelectionModel to select options contracts based on specified conditions.
The model is updated daily and selects different options based on the current date.
The algorithm ensures that only valid option contracts are selected for the universe.

Output:
```python

from AlgorithmImports import *

class AddOptionUniverseSelectionModelRegressionAlgorithm(QCAlgorithm):
    def initialize(self):
        self.set_start_date(2014, 6, 5)
        self.set_end_date(2014, 6, 6)
        self.option_count = 0

        self.universe_settings.resolution = Resolution.MINUTE
        self.set_universe_selection(OptionUniverseSelectionModel(
            timedelta(days=1),
            self.select_option_chain_symbols
        ))

    def select_option_chain_symbols(self, utc_time):
        new_york_time = Extensions.convert_from_utc(utc_time, TimeZones.NEW_YORK)
        if new_york_time.date() < datetime(2014, 6, 6).date():
            return [ Symbol.create("TWX", SecurityType.OPTION, Market.USA) ]

        if new_york_time.date() >= datetime(2014, 6, 6).date():
            return [ Symbol.create("AAPL", SecurityType.OPTION, Market.USA) ]

    def on_securities_changed(self, changes):
        if len(changes.added_securities) > 0:
            for security in changes.added_securities:
                symbol = security.symbol.underlying if security.symbol.underlying else security.Symbol
                if symbol.value != "AAPL" and symbol.value != "TWX":
                    raise RegressionTestException(f"Unexpected security {security.Symbol}")

                if security.symbol.security_type == SecurityType.OPTION:
                    self.option_count += 1

    def on_end_of_algorithm(self):
        if len(self.active_securities) == 0:
            raise RegressionTestException("No active securities found. Expected at least one active security")
        if self.option_count == 0:
            raise RegressionTestException("The option count should be greater than 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
: Abstract regression framework algorithm for multiple framework regression tests

Output:
```python

from AlgorithmImports import *

class BaseFrameworkRegressionAlgorithm(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2014, 6, 1)
        self.set_end_date(2014, 6, 30)

        self.universe_settings.resolution = Resolution.HOUR
        self.universe_settings.data_normalization_mode = DataNormalizationMode.RAW

        symbols = [Symbol.create(ticker, SecurityType.EQUITY, Market.USA)
            for ticker in ["AAPL", "AIG", "BAC", "SPY"]]

        # Manually add AAPL and AIG when the algorithm starts
        self.set_universe_selection(ManualUniverseSelectionModel(symbols[:2]))

        # At midnight, add all securities every day except on the last data
        # With this procedure, the Alpha Model will experience multiple universe changes
        self.add_universe_selection(ScheduledUniverseSelectionModel(
            self.date_rules.every_day(), self.time_rules.midnight,
            lambda dt: symbols if dt < self.end_date - timedelta(1) else []))

        self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(31), 0.025, None))
        self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
        self.set_execution(ImmediateExecutionModel())
        self.set_risk_management(NullRiskManagementModel())

    def on_end_of_algorithm(self):
        # The base implementation checks for active insights
        insights_count = len(self.insights.get_insights(lambda insight: insight.is_active(self.utc_time)))
        if insights_count != 0:
            raise AssertionError(f"The number of active insights should be 0. Actual: {insights_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
: Shows how to set a custom benchmark for you algorithms

Output:
```python

from AlgorithmImports import *

class CustomBenchmarkAlgorithm(QCAlgorithm):

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

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

        # Disabling the benchmark / setting to a fixed value
        # self.set_benchmark(lambda x: 0)

        # Set the benchmark to AAPL US Equity
        self.set_benchmark(Symbol.create("AAPL", SecurityType.EQUITY, Market.USA))

    def on_data(self, data):
        '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
        if not self.portfolio.invested:
            self.set_holdings("SPY", 1)
            self.debug("Purchased Stock")

        tuple_result = SymbolCache.try_get_symbol("AAPL", None)
        if tuple_result[0]:
            raise AssertionError("Benchmark Symbol is not expected to be added to the Symbol cache")
```


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

Input:
Generate a LEAN Algorithm that can be described like this
: Regression algorithm asserting the behavior of specifying a null position group allowing us to fill orders which would be invalid if not

Output:
```python

from AlgorithmImports import *

class NullMarginMultipleOrdersRegressionAlgorithm(QCAlgorithm):

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

        # override security position group model
        self.portfolio.set_positions(SecurityPositionGroupModel.NULL)
        # override margin requirements
        self.set_security_initializer(lambda security: security.set_buying_power_model(ConstantBuyingPowerModel(1)))

        equity = self.add_equity("GOOG", leverage=4, fill_forward=True)
        option = self.add_option(equity.symbol, fill_forward=True)
        self._option_symbol = option.symbol

        option.set_filter(lambda u: u.strikes(-2, +2).expiration(0, 180))

    def on_data(self, data: Slice):
        if not self.portfolio.invested:
            if self.is_market_open(self._option_symbol):
                chain = data.option_chains.get(self._option_symbol)
                if chain:
                    call_contracts = [contract for contract in chain if contract.right == OptionRight.CALL]
                    call_contracts.sort(key=lambda x: (x.expiry, 1/ x.strike), reverse=True)

                    option_contract = call_contracts[0]
                    self.market_order(option_contract.symbol.underlying, 1000)
                    self.market_order(option_contract.symbol, -10)

                    if self.portfolio.total_margin_used != 1010:
                        raise ValueError(f"Unexpected margin used {self.portfolio.total_margin_used}")
```


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 using custom buying power model in backtesting.
QuantConnect allows you to model all orders as deeply and accurately as you need.

Output:
```python

from AlgorithmImports import *

class CustomBuyingPowerModelAlgorithm(QCAlgorithm):
    '''Demonstration of using custom buying power model in backtesting.
    QuantConnect allows you to model all orders as deeply and accurately as you need.'''

    def initialize(self):
        self.set_start_date(2013,10,1)   # Set Start Date
        self.set_end_date(2013,10,31)    # Set End Date
        security = self.add_equity("SPY", Resolution.HOUR)
        self.spy = security.symbol

        # set the buying power model
        security.set_buying_power_model(CustomBuyingPowerModel())

    def on_data(self, slice):
        if self.portfolio.invested:
            return

        quantity = self.calculate_order_quantity(self.spy, 1)
        if quantity % 100 != 0:
            raise AssertionError(f'CustomBuyingPowerModel only allow quantity that is multiple of 100 and {quantity} was found')

        # We normally get insufficient buying power model, but the
        # CustomBuyingPowerModel always says that there is sufficient buying power for the orders
        self.market_order(self.spy, quantity * 10)

class CustomBuyingPowerModel(BuyingPowerModel):
    def get_maximum_order_quantity_for_target_buying_power(self, parameters):
        quantity = super().get_maximum_order_quantity_for_target_buying_power(parameters).quantity
        quantity = np.floor(quantity / 100) * 100
        return GetMaximumOrderQuantityResult(quantity)

    def has_sufficient_buying_power_for_order(self, parameters):
        return HasSufficientBuyingPowerForOrderResult(True)

    # Let's always return 0 as the maintenance margin so we avoid margin call orders
    def get_maintenance_margin(self, parameters):
        return MaintenanceMargin(0)

    # Override this as well because the base implementation calls GetMaintenanceMargin (overridden)
    # because in C# it wouldn't resolve the overridden Python method
    def get_reserved_buying_power_for_position(self, parameters):
        return parameters.result_in_account_currency(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
: Demonstration algorithm for the Warm Up feature with basic indicators.

Output:
```python

from AlgorithmImports import *

class WarmupAlgorithm(QCAlgorithm):

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

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

        fast_period = 60
        slow_period = 3600

        self.fast = self.ema("SPY", fast_period)
        self.slow = self.ema("SPY", slow_period)

        self.set_warmup(slow_period)
        self.first = True

    def on_data(self, data):
        '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
        if self.first and not self.is_warming_up:
            self.first = False
            self.log("Fast: {0}".format(self.fast.samples))
            self.log("Slow: {0}".format(self.slow.samples))

        if self.fast.current.value > self.slow.current.value:
            self.set_holdings("SPY", 1)
        else:
            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 test tests for the loading of futures options contracts with a contract month of 2020-03 can live
and be loaded from the same ZIP file that the 2020-04 contract month Future Option contract lives in.

Output:
```python

from AlgorithmImports import *

class FutureOptionMultipleContractsInDifferentContractMonthsWithSameUnderlyingFutureRegressionAlgorithm(QCAlgorithm):

    def initialize(self):
        self.expected_symbols = {
            self._create_option(datetime(2020, 3, 26), OptionRight.CALL, 1650.0): False,
            self._create_option(datetime(2020, 3, 26), OptionRight.PUT, 1540.0): False,
            self._create_option(datetime(2020, 2, 25), OptionRight.CALL, 1600.0): False,
            self._create_option(datetime(2020, 2, 25), OptionRight.PUT, 1545.0): False
        }

        # Required for FOPs to use extended hours, until GH #6491 is addressed
        self.universe_settings.extended_market_hours = True

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

        gold_futures = self.add_future("GC", Resolution.MINUTE, Market.COMEX, extended_market_hours=True)
        gold_futures.SetFilter(0, 365)

        self.add_future_option(gold_futures.Symbol)

    def on_data(self, data: Slice):
        for symbol in data.quote_bars.keys():
            # Check that we are in regular hours, we can place a market order (on extended hours, limit orders should be used)
            if symbol in self.expected_symbols and self.is_in_regular_hours(symbol):
                invested = self.expected_symbols[symbol]
                if not invested:
                    self.market_order(symbol, 1)

                self.expected_symbols[symbol] = True

    def on_end_of_algorithm(self):
        not_encountered = [str(k) for k,v in self.expected_symbols.items() if not v]
        if any(not_encountered):
            raise AssertionError(f"Expected all Symbols encountered and invested in, but the following were not found: {', '.join(not_encountered)}")

        if not self.portfolio.invested:
            raise AssertionError("Expected holdings at the end of algorithm, but none were found.")

    def is_in_regular_hours(self, symbol):
        return self.securities[symbol].exchange.exchange_open

    def _create_option(self, expiry: datetime, option_right: OptionRight, strike_price: float) -> Symbol:
        return Symbol.create_option(
            Symbol.create_future("GC", Market.COMEX, datetime(2020, 4, 28)),
            Market.COMEX,
            OptionStyle.AMERICAN,
            option_right,
            strike_price,
            expiry
        )
```


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 demonstrates how to use the FutureUniverseSelectionModel to select futures contracts for a given underlying asset.
The model is set to update daily, and the algorithm ensures that the selected contracts meet specific criteria.
This also includes a check to ensure that only future contracts are added to the algorithm's universe.

Output:
```python

from AlgorithmImports import *

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

        self.set_universe_selection(FutureUniverseSelectionModel(
            timedelta(days=1),
            lambda time: [ Symbol.create(Futures.Indices.SP_500_E_MINI, SecurityType.FUTURE, Market.CME) ]
        ))

    def on_securities_changed(self, changes):
        if len(changes.added_securities) > 0:
            for security in changes.added_securities:
                if security.symbol.security_type != SecurityType.FUTURE:
                    raise RegressionTestException(f"Expected future security, but found '{security.symbol.security_type}'")
                if security.symbol.id.symbol != "ES":
                    raise RegressionTestException(f"Expected future symbol 'ES', but found '{security.symbol.id.symbol}'")

    def on_end_of_algorithm(self):
        if len(self.active_securities) == 0:
            raise RegressionTestException("No active securities found. Expected at least one active security")
```


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 asserts that futures have data at extended market hours when this is enabled.

Output:
```python

from AlgorithmImports import *

class FutureContractsExtendedMarketHoursRegressionAlgorithm(QCAlgorithm):
    def initialize(self):
        self.set_start_date(2013, 10, 6)
        self.set_end_date(2013, 10, 11)

        es_future_symbol = Symbol.create_future(Futures.Indices.SP_500_E_MINI, Market.CME, datetime(2013, 12, 20))
        self._es = self.add_future_contract(es_future_symbol, Resolution.HOUR, fill_forward=True, extended_market_hours=True)

        gc_future_symbol = Symbol.create_future(Futures.Metals.GOLD, Market.COMEX, datetime(2013, 10, 29))
        self._gc = self.add_future_contract(gc_future_symbol, Resolution.HOUR, fill_forward=True, extended_market_hours=False)

        self._es_ran_on_regular_hours = False
        self._es_ran_on_extended_hours = False
        self._gc_ran_on_regular_hours = False
        self._gc_ran_on_extended_hours = False

    def on_data(self, slice):
        slice_symbols = set(slice.keys())
        slice_symbols.update(slice.bars.keys())
        slice_symbols.update(slice.ticks.keys())
        slice_symbols.update(slice.quote_bars.keys())
        slice_symbols.update([x.canonical for x in slice_symbols])

        es_is_in_regular_hours = self._es.exchange.hours.is_open(self.time, False)
        es_is_in_extended_hours = not es_is_in_regular_hours and self._es.exchange.hours.is_open(self.time, True)
        slice_has_es_data = self._es.symbol in slice_symbols
        self._es_ran_on_regular_hours |= es_is_in_regular_hours and slice_has_es_data
        self._es_ran_on_extended_hours |= es_is_in_extended_hours and slice_has_es_data

        gc_is_in_regular_hours = self._gc.exchange.hours.is_open(self.time, False)
        gc_is_in_extended_hours = not gc_is_in_regular_hours and self._gc.exchange.hours.is_open(self.time, True)
        slice_has_gc_data = self._gc.symbol in slice_symbols
        self._gc_ran_on_regular_hours |= gc_is_in_regular_hours and slice_has_gc_data
        self._gc_ran_on_extended_hours |= gc_is_in_extended_hours and slice_has_gc_data

    def on_end_of_algorithm(self):
        if not self._es_ran_on_regular_hours:
            raise AssertionError(f"Algorithm should have run on regular hours for {self._es.symbol} future, which enabled extended market hours")

        if not self._es_ran_on_extended_hours:
            raise AssertionError(f"Algorithm should have run on extended hours for {self._es.symbol} future, which enabled extended market hours")

        if not self._gc_ran_on_regular_hours:
            raise AssertionError(f"Algorithm should have run on regular hours for {self._gc.symbol} future, which did not enable extended market hours")

        if self._gc_ran_on_extended_hours:
            raise AssertionError(f"Algorithm should have not run on extended hours for {self._gc.symbol} future, which did not enable extended market hours")
```


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

Input:
Generate a LEAN Algorithm that can be described like this
: Regression algorithm asserting 'OnWarmupFinished' is being called

Output:
```python

from AlgorithmImports import *

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

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

        self.add_equity("SPY", Resolution.MINUTE)
        self.set_warmup(timedelta(days = 1))
        self._on_warmup_finished = 0

    def on_warmup_finished(self):
        self._on_warmup_finished += 1

    def on_end_of_algorithm(self):
        if self._on_warmup_finished != 1:
            raise AssertionError(f"Unexpected OnWarmupFinished call count {self._on_warmup_finished}")
```