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 shows how to grab symbols from an external api each day
and load data using the universe selection feature. In this example we
define a custom data type for the NYSE top gainers and then short the
top 2 gainers each day

Output:
```python

from AlgorithmImports import *

class CustomDataUniverseAlgorithm(QCAlgorithm):

    def initialize(self):

        # Data ADDED via universe selection is added with Daily resolution.
        self.universe_settings.resolution = Resolution.DAILY

        self.set_start_date(2015,1,5)
        self.set_end_date(2015,7,1)
        self.set_cash(100000)

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

        # add a custom universe data source (defaults to usa-equity)
        self.add_universe(NyseTopGainers, "universe-nyse-top-gainers", Resolution.DAILY, self.nyse_top_gainers)

    def nyse_top_gainers(self, data):
        return [ x.symbol for x in data if x["TopGainersRank"] <= 2 ]

    def on_data(self, slice):
        pass

    def on_securities_changed(self, changes):
        self._changes = changes

        for security in changes.removed_securities:
            #  liquidate securities that have been removed
            if security.invested:
                self.liquidate(security.symbol)
                self.log("Exit {0} at {1}".format(security.symbol, security.close))

        for security in changes.added_securities:
            # enter short positions on new securities
            if not security.invested and security.close != 0:
                qty = self.calculate_order_quantity(security.symbol, -0.25)
                self.market_on_open_order(security.symbol, qty)
                self.log("Enter {0} at {1}".format(security.symbol, security.close))

class NyseTopGainers(PythonData):
    def __init__(self):
        self.count = 0
        self.last_date = datetime.min

    def get_source(self, config, date, is_live_mode):
        url = "http://www.wsj.com/mdc/public/page/2_3021-gainnyse-gainer.html" if is_live_mode else \
            "https://www.dropbox.com/s/vrn3p38qberw3df/nyse-gainers.csv?dl=1"

        return SubscriptionDataSource(url, SubscriptionTransportMedium.REMOTE_FILE)

    def reader(self, config, line, date, is_live_mode):

        if not is_live_mode:
            # backtest gets data from csv file in dropbox
            if not (line.strip() and line[0].isdigit()): return None
            csv = line.split(',')
            nyse = NyseTopGainers()
            nyse.time = datetime.strptime(csv[0], "%Y%m%d")
            nyse.end_time = nyse.time + timedelta(1)
            nyse.symbol = Symbol.create(csv[1], SecurityType.EQUITY, Market.USA)
            nyse["TopGainersRank"] = int(csv[2])
            return nyse

        if self.last_date != date:
            # reset our counter for the new day
            self.last_date = date
            self.count = 0

        # parse the html into a symbol
        if not line.startswith('<a href=\"/public/quotes/main.html?symbol='):
            # we're only looking for lines that contain the symbols
            return None

        last_close_paren = line.rfind(')')
        last_open_paren = line.rfind('(')
        if last_open_paren == -1 or last_close_paren == -1:
            return None

        symbol_string = line[last_open_paren + 1:last_close_paren]
        nyse = NyseTopGainers()
        nyse.time = date
        nyse.end_time = nyse.time + timedelta(1)
        nyse.symbol = Symbol.create(symbol_string, SecurityType.EQUITY, Market.USA)
        nyse["TopGainersRank"] = self.count
        self.count = self.count + 1
        return nyse
```


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 used for regression tests purposes

Output:
```python

from AlgorithmImports import *

class RegressionAlgorithm(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,8)    #Set End Date
        self.set_cash(10000000)         #Set Strategy Cash
        # Find more symbols here: http://quantconnect.com/data
        self.add_equity("SPY", Resolution.TICK)
        self.add_equity("BAC", Resolution.MINUTE)
        self.add_equity("AIG", Resolution.HOUR)
        self.add_equity("IBM", Resolution.DAILY)

        self.__last_trade_ticks = self.start_date
        self.__last_trade_trade_bars = self.__last_trade_ticks
        self.__trade_every = timedelta(minutes=1)

    def on_data(self, data):
        '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
        if self.time - self.__last_trade_trade_bars < self.__trade_every:
            return
        self.__last_trade_trade_bars = self.time

        for kvp in data.bars:
            bar = kvp.Value
            if bar.is_fill_forward:
                continue

            symbol = kvp.key
            holdings = self.portfolio[symbol]

            if not holdings.invested:
                self.market_order(symbol, 10)
            else:
                self.market_order(symbol, -holdings.quantity)
```


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

Input:
Generate a LEAN Algorithm that can be described like this
: This regression algorithm tests In The Money (ITM) index option expiry for calls.
We test to make sure that index options have greeks enabled, same as equity options.

Output:
```python

from AlgorithmImports import *

class IndexOptionCallITMGreeksExpiryRegressionAlgorithm(QCAlgorithm):
    def initialize(self):
        self.on_data_calls = 0
        self.invested = False

        self.set_start_date(2021, 1, 4)
        self.set_end_date(2021, 1, 31)

        spx = self.add_index("SPX", Resolution.MINUTE)
        spx.volatility_model = StandardDeviationOfReturnsVolatilityModel(60, Resolution.MINUTE, timedelta(minutes=1))
        self.spx = spx.symbol

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

        self.spx_option.price_model = OptionPriceModels.black_scholes()

        self.expected_option_contract = Symbol.create_option(self.spx, Market.USA, OptionStyle.EUROPEAN, OptionRight.CALL, 3200, datetime(2021, 1, 15))
        if self.spx_option.symbol != self.expected_option_contract:
            raise AssertionError(f"Contract {self.expected_option_contract} was not found in the chain")

    def on_data(self, data: Slice):
        # Let the algo warmup, but without using SetWarmup. Otherwise, we get
        # no contracts in the option chain
        if self.invested or self.on_data_calls < 40:
            self.on_data_calls += 1
            return

        self.on_data_calls += 1

        if data.option_chains.count == 0:
            return

        if all([any([c.symbol not in data for c in o.contracts.values()]) for o in data.option_chains.values()]):
            return

        if len(list(list(data.option_chains.values())[0].contracts.values())) == 0:
            raise AssertionError(f"No contracts found in the option {list(data.option_chains.keys())[0]}")

        deltas = [i.greeks.delta for i in self.sort_by_max_volume(data)]
        gammas = [i.greeks.gamma for i in self.sort_by_max_volume(data)] #data.option_chains.values().order_by_descending(y => y.contracts.values().sum(x => x.volume)).first().contracts.values().select(x => x.greeks.gamma).to_list()
        lambda_ = [i.greeks.lambda_ for i in self.sort_by_max_volume(data)] #data.option_chains.values().order_by_descending(y => y.contracts.values().sum(x => x.volume)).first().contracts.values().select(x => x.greeks.lambda).to_list()
        rho = [i.greeks.rho for i in self.sort_by_max_volume(data)] #data.option_chains.values().order_by_descending(y => y.contracts.values().sum(x => x.volume)).first().contracts.values().select(x => x.greeks.rho).to_list()
        theta = [i.greeks.theta for i in self.sort_by_max_volume(data)] #data.option_chains.values().order_by_descending(y => y.contracts.values().sum(x => x.volume)).first().contracts.values().select(x => x.greeks.theta).to_list()
        vega = [i.greeks.vega for i in self.sort_by_max_volume(data)] #data.option_chains.values().order_by_descending(y => y.contracts.values().sum(x => x.volume)).first().contracts.values().select(x => x.greeks.vega).to_list()

        # The commented out test cases all return zero.
        # This is because of failure to evaluate the greeks in the option pricing model, most likely
        # due to us not clearing the default 30 day requirement for the volatility model to start being updated.
        if any([i for i in deltas if i == 0]):
            raise AssertionError("Option contract Delta was equal to zero")

        # Delta is 1, therefore we expect a gamma of 0
        if any([i for i in gammas if i == 0]):
            raise AssertionError("Option contract Gamma was equal to zero")

        if any([i for i in lambda_ if lambda_ == 0]):
            raise AssertionError("Option contract Lambda was equal to zero")

        if any([i for i in rho if i == 0]):
            raise AssertionError("Option contract Rho was equal to zero")

        if any([i for i in theta if i == 0]):
            raise AssertionError("Option contract Theta was equal to zero")

        # The strike is far away from the underlying asset's price, and we're very close to expiry.
        # Zero is an expected value here.
        if any([i for i in vega if vega == 0]):
            raise AggregateException("Option contract Vega was equal to zero")

        if not self.invested:
            self.set_holdings(list(list(data.option_chains.values())[0].contracts.values())[0].symbol, 1)
            self.invested = True

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

        if not self.invested:
            raise AssertionError(f"Never checked greeks, maybe we have no option data?")

    def sort_by_max_volume(self, data: Slice):
        chain = [i for i in sorted(list(data.option_chains.values()), key=lambda x: sum([j.volume for j in x.contracts.values()]), reverse=True)][0]
        return chain.contracts.values()
```


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

Input:
Generate a LEAN Algorithm that can be described like this
: Regression test illustrating how history from custom data sources can be requested. The <see cref="QCAlgorithm.history"/> method used in this
example also allows to specify other parameters than just the resolution, such as the data normalization mode, the data mapping mode, etc.

Output:
```python

from AlgorithmImports import *

class HistoryWithCustomDataSourceRegressionAlgorithm(QCAlgorithm):
    def initialize(self):
        self.set_start_date(2014, 6, 5)
        self.set_end_date(2014, 6, 6)

        self.aapl = self.add_data(CustomData, "AAPL", Resolution.MINUTE).symbol
        self.spy = self.add_data(CustomData, "SPY", Resolution.MINUTE).symbol

    def on_end_of_algorithm(self):
        aapl_history = self.history(CustomData, self.aapl, self.start_date, self.end_date, Resolution.MINUTE,
            fill_forward=False, extended_market_hours=False, data_normalization_mode=DataNormalizationMode.RAW).droplevel(0, axis=0)
        spy_history = self.history(CustomData, self.spy, self.start_date, self.end_date, Resolution.MINUTE,
            fill_forward=False, extended_market_hours=False, data_normalization_mode=DataNormalizationMode.RAW).droplevel(0, axis=0)

        if aapl_history.size == 0 or spy_history.size == 0:
            raise AssertionError("At least one of the history results is empty")

        # Check that both resutls contain the same data, since CustomData fetches APPL data regardless of the symbol
        if not aapl_history.equals(spy_history):
            raise AssertionError("Histories are not equal")

class CustomData(PythonData):
    '''Custom data source for the regression test algorithm, which returns AAPL equity data regardless of the symbol requested.'''

    def get_source(self, config, date, is_live_mode):
        return TradeBar().get_source(
            SubscriptionDataConfig(
                config,
                CustomData,
                # Create a new symbol as equity so we find the existing data files
                # Symbol.create(config.mapped_symbol, SecurityType.EQUITY, config.market)),
                Symbol.create("AAPL", SecurityType.EQUITY, config.market)),
            date,
            is_live_mode)

    def reader(self, config, line, date, is_live_mode):
        trade_bar = TradeBar.parse_equity(config, line, date)
        data = CustomData()
        data.time = trade_bar.time
        data.value = trade_bar.value
        data.close = trade_bar.close
        data.open = trade_bar.open
        data.high = trade_bar.high
        data.low = trade_bar.low
        data.volume = trade_bar.volume

        return data
```


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

Input:
Generate a LEAN Algorithm that can be described like this
: Regression algorithm which tests that a two leg currency conversion happens correctly

Output:
```python

from AlgorithmImports import *

class TwoLegCurrencyConversionRegressionAlgorithm(QCAlgorithm):
    def initialize(self):
        self.set_start_date(2018, 4, 4)
        self.set_end_date(2018, 4, 4)
        self.set_brokerage_model(BrokerageName.GDAX, AccountType.CASH)
        # GDAX doesn't have LTCETH or ETHLTC, but they do have ETHUSD and LTCUSD to form a path between ETH and LTC
        self.set_account_currency("ETH")
        self.set_cash("ETH", 100000)
        self.set_cash("LTC", 100000)
        self.set_cash("USD", 100000)

        self._eth_usd_symbol = self.add_crypto("ETHUSD", Resolution.MINUTE).symbol
        self._ltc_usd_symbol = self.add_crypto("LTCUSD", Resolution.MINUTE).symbol

    def on_data(self, data):
        if not self.portfolio.invested:
            self.market_order(self._ltc_usd_symbol, 1)

    def on_end_of_algorithm(self):
        ltc_cash = self.portfolio.cash_book["LTC"]

        conversion_symbols = [x.symbol for x in ltc_cash.currency_conversion.conversion_rate_securities]

        if len(conversion_symbols) != 2:
            raise ValueError(
                f"Expected two conversion rate securities for LTC to ETH, is {len(conversion_symbols)}")

        if conversion_symbols[0] != self._ltc_usd_symbol:
            raise ValueError(
                f"Expected first conversion rate security from LTC to ETH to be {self._ltc_usd_symbol}, is {conversion_symbols[0]}")

        if conversion_symbols[1] != self._eth_usd_symbol:
            raise ValueError(
                f"Expected second conversion rate security from LTC to ETH to be {self._eth_usd_symbol}, is {conversion_symbols[1]}")

        ltc_usd_value = self.securities[self._ltc_usd_symbol].get_last_data().value
        eth_usd_value = self.securities[self._eth_usd_symbol].get_last_data().value

        expected_conversion_rate = ltc_usd_value / eth_usd_value
        actual_conversion_rate = ltc_cash.conversion_rate

        if actual_conversion_rate != expected_conversion_rate:
            raise ValueError(
                f"Expected conversion rate from LTC to ETH to be {expected_conversion_rate}, is {actual_conversion_rate}")
```


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 verifying OnEndOfDay callbacks are called as expected. See GH issue 2865.

Output:
```python

from AlgorithmImports import *

class OnEndOfDayRegressionAlgorithm(QCAlgorithm):
    '''Test algorithm verifying OnEndOfDay callbacks are called as expected. See GH issue 2865.'''
    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.set_cash(100000)

        self._spy_symbol = Symbol.create("SPY", SecurityType.EQUITY, Market.USA)
        self._bac_symbol = Symbol.create("BAC", SecurityType.EQUITY, Market.USA)
        self._ibm_symbol = Symbol.create("IBM", SecurityType.EQUITY, Market.USA)
        self._on_end_of_day_spy_call_count = 0
        self._on_end_of_day_bac_call_count = 0
        self._on_end_of_day_ibm_call_count = 0

        self.add_universe('my_universe_name', self.selection)

    def selection(self, time):
        if time.day == 8:
            return [self._spy_symbol.value, self._ibm_symbol.value]
        return [self._spy_symbol.value]

    def on_end_of_day(self, symbol):
        '''We expect it to be called on each day after the first selection process
        happens and the algorithm has a security in it
        '''
        if symbol == self._spy_symbol:
            if self._on_end_of_day_spy_call_count == 0:
                # just the first time
                self.set_holdings(self._spy_symbol, 0.5)
                self.add_equity("BAC")
            self._on_end_of_day_spy_call_count += 1
        if symbol == self._bac_symbol:
            if self._on_end_of_day_bac_call_count == 0:
                # just the first time
                self.set_holdings(self._bac_symbol, 0.5)
            self._on_end_of_day_bac_call_count += 1
        if symbol == self._ibm_symbol:
            self._on_end_of_day_ibm_call_count += 1

        self.log("OnEndOfDay() called: " + str(self.utc_time)
                + ". SPY count " + str(self._on_end_of_day_spy_call_count)
                + ". BAC count " + str(self._on_end_of_day_bac_call_count)
                + ". IBM count " + str(self._on_end_of_day_ibm_call_count))

    def on_end_of_algorithm(self):
        '''Assert expected behavior'''
        if self._on_end_of_day_spy_call_count != 5:
            raise ValueError("OnEndOfDay(SPY) unexpected count call " + str(self._on_end_of_day_spy_call_count))
        if self._on_end_of_day_bac_call_count != 4:
            raise ValueError("OnEndOfDay(BAC) unexpected count call " + str(self._on_end_of_day_bac_call_count))
        if self._on_end_of_day_ibm_call_count != 1:
            raise ValueError("OnEndOfDay(IBM) unexpected count call " + str(self._on_end_of_day_ibm_call_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
: Regression algorithm illustrating how to request history data for different data normalization modes.

Output:
```python

from AlgorithmImports import *

class HistoryWithDifferentDataNormalizationModeRegressionAlgorithm(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2013, 10, 7)
        self.set_end_date(2014, 1, 1)
        self.aapl_equity_symbol = self.add_equity("AAPL", Resolution.DAILY).symbol
        self.es_future_symbol = self.add_future(Futures.Indices.SP_500_E_MINI, Resolution.DAILY).symbol

    def on_end_of_algorithm(self):
        equity_data_normalization_modes = [
            DataNormalizationMode.RAW,
            DataNormalizationMode.ADJUSTED,
            DataNormalizationMode.SPLIT_ADJUSTED
        ]
        self.check_history_results_for_data_normalization_modes(self.aapl_equity_symbol, self.start_date, self.end_date, Resolution.DAILY,
            equity_data_normalization_modes)

        future_data_normalization_modes = [
            DataNormalizationMode.RAW,
            DataNormalizationMode.BACKWARDS_RATIO,
            DataNormalizationMode.BACKWARDS_PANAMA_CANAL,
            DataNormalizationMode.FORWARD_PANAMA_CANAL
        ]
        self.check_history_results_for_data_normalization_modes(self.es_future_symbol, self.start_date, self.end_date, Resolution.DAILY,
            future_data_normalization_modes)

    def check_history_results_for_data_normalization_modes(self, symbol, start, end, resolution, data_normalization_modes):
        history_results = [self.history([symbol], start, end, resolution, data_normalization_mode=x) for x in data_normalization_modes]
        history_results = [x.droplevel(0, axis=0) for x in history_results] if len(history_results[0].index.levels) == 3 else history_results
        history_results = [x.loc[symbol].close for x in history_results]

        if any(x.size == 0 or x.size != history_results[0].size for x in history_results):
            raise AssertionError(f"History results for {symbol} have different number of bars")

        # Check that, for each history result, close prices at each time are different for these securities (AAPL and ES)
        for j in range(history_results[0].size):
            close_prices = set(history_results[i][j] for i in range(len(history_results)))
            if len(close_prices) != len(data_normalization_modes):
                raise AssertionError(f"History results for {symbol} have different close prices at the same 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
: Tests delistings for Futures and Futures Options to ensure that they are delisted at the expected times.

Output:
```python

from AlgorithmImports import *

class FuturesAndFutures_optionsExpiryTimeAndLiquidationRegressionAlgorithm(QCAlgorithm):

    def initialize(self):
        self.invested = False
        self.liquidated = 0
        self.delistings_received = 0

        self.expected_expiry_warning_time = datetime(2020, 6, 19)
        self.expected_expiry_delisting_time = datetime(2020, 6, 20)
        self.expected_liquidation_time = datetime(2020, 6, 20)

        self.set_start_date(2020, 1, 5)
        self.set_end_date(2020, 12, 1)
        self.set_cash(100000)

        es = Symbol.create_future(
            "ES",
            Market.CME,
            datetime(2020, 6, 19)
        )

        es_option = Symbol.create_option(
            es,
            Market.CME,
            OptionStyle.AMERICAN,
            OptionRight.PUT,
            3400.0,
            datetime(2020, 6, 19)
        )

        self.es_future = self.add_future_contract(es, Resolution.MINUTE).symbol
        self.es_future_option = self.add_future_option_contract(es_option, Resolution.MINUTE).symbol

    def on_data(self, data: Slice):
        for delisting in data.delistings.values():
            self.delistings_received += 1

            if delisting.type == DelistingType.WARNING and delisting.time != self.expected_expiry_warning_time:
                raise AssertionError(f"Expiry warning with time {delisting.time} but is expected to be {self.expected_expiry_warning_time}")

            if delisting.type == DelistingType.WARNING and delisting.time != datetime(self.time.year, self.time.month, self.time.day):
                raise AssertionError(f"Delisting warning received at an unexpected date: {self.time} - expected {delisting.time}")

            if delisting.type == DelistingType.DELISTED and delisting.time != self.expected_expiry_delisting_time:
                raise AssertionError(f"Delisting occurred at unexpected time: {delisting.time} - expected: {self.expected_expiry_delisting_time}")

            if delisting.type == DelistingType.DELISTED and delisting.time != datetime(self.time.year, self.time.month, self.time.day):
                raise AssertionError(f"Delisting notice received at an unexpected date: {self.time} - expected {delisting.time}")

        if not self.invested and \
            (self.es_future in data.bars or self.es_future in data.quote_bars) and \
            (self.es_future_option in data.bars or self.es_future_option in data.quote_bars):

            self.invested = True

            self.market_order(self.es_future, 1)
            self.market_order(self.es_future_option, 1)

    def on_order_event(self, order_event: OrderEvent):
        if order_event.direction != OrderDirection.SELL or order_event.status != OrderStatus.FILLED:
            return

        # * Future Liquidation
        # * Future Option Exercise
        # * We expect NO Underlying Future Liquidation because we already hold a Long future position so the FOP Put selling leaves us breakeven
        self.liquidated += 1
        if order_event.symbol.security_type == SecurityType.FUTURE_OPTION and self.expected_liquidation_time != self.time:
            raise AssertionError(f"Expected to liquidate option {order_event.symbol} at {self.expected_liquidation_time}, instead liquidated at {self.time}")

        if order_event.symbol.security_type == SecurityType.FUTURE and \
            (self.expected_liquidation_time - timedelta(minutes=1)) != self.time and \
            self.expected_liquidation_time != self.time:

            raise AssertionError(f"Expected to liquidate future {order_event.symbol} at {self.expected_liquidation_time} (+1 minute), instead liquidated at {self.time}")

    def on_end_of_algorithm(self):
        if not self.invested:
            raise AssertionError("Never invested in ES futures and FOPs")

        if self.delistings_received != 4:
            raise AssertionError(f"Expected 4 delisting events received, found: {self.delistings_received}")

        if self.liquidated != 2:
            raise AssertionError(f"Expected 3 liquidation events, found {self.liquidated}")
```


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 a default symbol is created using equity market when scheduling if none found

Output:
```python

from AlgorithmImports import *

class DefaultSchedulingSymbolRegressionAlgorithm(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)

        # implicitly figured usa equity
        self.schedule.on(self.date_rules.tomorrow, self.time_rules.after_market_open("AAPL"), self._implicit_check)

        # picked up from cache
        self.add_index("SPX")
        self.schedule.on(self.date_rules.tomorrow, self.time_rules.before_market_close("SPX", extended_market_close = True), self._explicit_check)

    def _implicit_check(self):
        self._implicitChecked = True
        if self.time.time() != time(9, 30, 0):
            raise RegressionTestException(f"Unexpected time of day {self.time.time()}")

    def _explicit_check(self):
        self._explicitChecked = True
        if self.time.time() != time(16, 15, 0):
            raise RegressionTestException(f"Unexpected time of day {self.time.time()}")

    def on_end_of_algorithm(self):
        if not self._explicitChecked or not self._implicitChecked:
            raise RegressionTestException("Failed to run expected checks!")
```


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

Output:
```python

from AlgorithmImports import *
from BaseFrameworkRegressionAlgorithm import BaseFrameworkRegressionAlgorithm
from Risk.MaximumDrawdownPercentPerSecurity import MaximumDrawdownPercentPerSecurity

class MaximumDrawdownPercentPerSecurityFrameworkRegressionAlgorithm(BaseFrameworkRegressionAlgorithm):

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

        self.set_risk_management(MaximumDrawdownPercentPerSecurity(0.004))

```


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

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

  * Initial entry, buy ES Call Option (expiring ITM)
  * Option exercise, receiving ES future contracts
  * Future contract liquidation, due to impending expiry

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 FutureOptionCallITMExpiryRegressionAlgorithm(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 <= 3200.0 and x.id.option_right == OptionRight.CALL],
                       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.CALL, 3200.0, datetime(2020, 6, 19))
        if self.es_option != self.expected_contract:
            raise AssertionError(f"Contract {self.expected_contract} was not found in the chain")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

Input:
Generate a LEAN Algorithm that can be described like this
: Regression algorithm asserting that universe symbols selection can be done by returning the symbol IDs in the selection function

Output:
```python

from AlgorithmImports import *

class SelectUniverseSymbolsFromIDRegressionAlgorithm(QCAlgorithm):
    '''
    Regression algorithm asserting that universe symbols selection can be done by returning the symbol IDs in the selection function
    '''

    def initialize(self):
        self.set_start_date(2014, 3, 24)
        self.set_end_date(2014, 3, 26)
        self.set_cash(100000)

        self._securities = []
        self.universe_settings.resolution = Resolution.DAILY
        self.add_universe(self.select_symbol)

    def select_symbol(self, fundamental):
        symbols = [x.symbol for x in fundamental]

        if not symbols:
            return []

        self.log(f"Symbols: {', '.join([str(s) for s in symbols])}")
        # Just for testing, but more filtering could be done here as shown below:
        #symbols = [x.symbol for x in fundamental if x.asset_classification.morningstar_sector_code == MorningstarSectorCode.TECHNOLOGY]

        history = self.history(symbols, datetime(1998, 1, 1), self.time, Resolution.DAILY)

        all_time_highs = history['high'].unstack(0).max()
        last_closes = history['close'].unstack(0).iloc[-1]
        security_ids = (last_closes / all_time_highs).sort_values().index[-5:]

        return security_ids

    def on_securities_changed(self, changes):
        self._securities.extend(changes.added_securities)

    def on_end_of_algorithm(self):
        if not self._securities:
            raise AssertionError("No securities were selected")
```


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 asserting that the consolidators are removed from the SubscriptionManager.
This makes sure that we don't lose references to python consolidators when
they are wrapped in a DataConsolidatorPythonWrapper.

Output:
```python

from AlgorithmImports import *

class ManuallyRemovedConsolidatorsAlgorithm(QCAlgorithm):

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

        self.consolidators = []

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

        # Case 1: consolidator registered through a RegisterIndicator() call,
        # which will wrap the consolidator instance in a DataConsolidatorPythonWrapper
        consolidator = self.resolve_consolidator(self.spy, Resolution.MINUTE)
        self.consolidators.append(consolidator)

        indicator_name = self.create_indicator_name(self.spy, "close", Resolution.MINUTE)
        identity = Identity(indicator_name)
        self.indicator = self.register_indicator(self.spy, identity, consolidator)

        # Case 2: consolidator registered directly through the SubscriptionManager
        consolidator = self.resolve_consolidator(self.spy, Resolution.MINUTE)
        self.consolidators.append(consolidator)
        self.subscription_manager.add_consolidator(self.spy, consolidator)

        # Case 3: custom python consolidator not derived from IDataConsolidator
        consolidator = CustomQuoteBarConsolidator(timedelta(hours=1))
        self.consolidators.append(consolidator)
        self.subscription_manager.add_consolidator(self.spy, consolidator)

    def on_end_of_algorithm(self) -> None:
        # Remove the first consolidator

        for i in range(3):
            consolidator = self.consolidators[i]
            self.remove_consolidator(consolidator, expected_consolidator_count=2 - i)

    def remove_consolidator(self, consolidator: IDataConsolidator, expected_consolidator_count: int) -> None:
        self.subscription_manager.remove_consolidator(self.spy, consolidator)

        consolidator_count = sum(s.consolidators.count for s in self.subscription_manager.subscriptions)
        if consolidator_count != expected_consolidator_count:
            raise AssertionError(f"Unexpected number of consolidators after removal. "
                            f"Expected: {expected_consolidator_count}. Actual: {consolidator_count}")

class CustomQuoteBarConsolidator(PythonConsolidator):
    '''A custom quote bar consolidator that inherits from PythonConsolidator and implements
    the IDataConsolidator interface, it must implement all of IDataConsolidator. Reference
    PythonConsolidator.cs and DataConsolidatorPythonWrapper.PY for more information.

    This class shows how to implement a consolidator from scratch in Python, this gives us more
    freedom to determine the behavior of the consolidator but can't leverage any of the built in
    functions of an inherited class.

    For this example we implemented a Quotebar from scratch'''

    def __init__(self, period):

        #IDataConsolidator required vars for all consolidators
        self.consolidated = None        #Most recently consolidated piece of data.
        self.working_data = None         #Data being currently consolidated
        self.input_type = QuoteBar       #The type consumed by this consolidator
        self.output_type = QuoteBar      #The type produced by this consolidator

        #Consolidator Variables
        self.period = period

    def update(self, data):
        '''Updates this consolidator with the specified data'''

        #If we don't have bar yet, create one
        if self.working_data is None:
            self.working_data = QuoteBar(data.time,data.symbol,data.bid,data.last_bid_size,
                data.ask,data.last_ask_size,self.period)

        #Update bar using QuoteBar's update()
        self.working_data.update(data.value, data.bid.close, data.ask.close, 0,
            data.last_bid_size, data.last_ask_size)

    def scan(self, time):
        '''Scans this consolidator to see if it should emit a bar due to time passing'''

        if self.period is not None and self.working_data is not None:
            if time - self.working_data.time >= self.period:

                #Trigger the event handler with a copy of self and the data
                self.on_data_consolidated(self, self.working_data)

                #Set the most recent consolidated piece of data and then clear the working_data
                self.consolidated = self.working_data
                self.working_data = 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
: def initialize(self) -> None:

Output:
```python

from AlgorithmImports import *

from collections import deque
from math import isclose

class CustomIndicatorWithExtensionAlgorithm(QCAlgorithm):
    def initialize(self) -> None:
        self.set_start_date(2013, 10, 9)
        self.set_end_date(2013, 10, 9)

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

        self._sma_values = []
        self._period = 10

        self._sma = self.sma(self._spy, self._period, Resolution.MINUTE)
        self._sma.updated += self.on_sma_updated

        self._custom_sma = CustomSimpleMovingAverage("My SMA", self._period)
        self._ext = IndicatorExtensions.of(self._custom_sma, self._sma)
        self._ext.updated += self.on_indicator_extension_updated

        self._sma_minus_custom = IndicatorExtensions.minus(self._sma, self._custom_sma)
        self._sma_minus_custom.updated += self.on_minus_updated

        self._sma_was_updated = False
        self._custom_sma_was_updated = False
        self._sma_minus_custom_was_updated = False

    def on_sma_updated(self, sender: object, updated: IndicatorDataPoint) -> None:
        self._sma_was_updated = True

        if self._sma.is_ready:
            self._sma_values.append(self._sma.current.value)

    def on_indicator_extension_updated(self, sender: object, updated: IndicatorDataPoint) -> None:
        self._custom_sma_was_updated = True

        sma_last_values = self._sma_values[-self._period:]
        expected = sum(sma_last_values) / len(sma_last_values)

        if not isclose(expected, self._custom_sma.value):
            raise AssertionError(f"Expected the custom SMA to calculate the moving average of the last {self._period} values of the SMA. "
                            f"Current expected: {expected}. Actual {self._custom_sma.value}.")

        self.debug(f"{self._sma.current.value} :: {self._custom_sma.value} :: {updated}")

    def on_minus_updated(self, sender: object, updated: IndicatorDataPoint) -> None:
        self._sma_minus_custom_was_updated = True

        expected = self._sma.current.value - self._custom_sma.value

        if not isclose(expected, self._sma_minus_custom.current.value):
            raise AssertionError(f"Expected the composite minus indicator to calculate the difference between the SMA and custom SMA indicators. "
                            f"Expected: {expected}. Actual {self._sma_minus_custom.current.value}.")

    def on_end_of_algorithm(self) -> None:
        if not (self._sma_was_updated and self._custom_sma_was_updated and self._sma_minus_custom_was_updated):
            raise AssertionError("Expected all indicators to have been updated.")

# Custom indicator
class CustomSimpleMovingAverage(PythonIndicator):
    def __init__(self, name: str, period: int) -> None:
        self.name = name
        self.value = 0
        self.warm_up_period = period
        self._queue = deque(maxlen=period)

    def update(self, input: BaseData) -> bool:
        self._queue.appendleft(input.value)
        count = len(self._queue)
        self.value = sum(self._queue) / count

        return count == self._queue.maxlen
```


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 of custom volatility model

Output:
```python

from AlgorithmImports import *

class CustomVolatilityModelAlgorithm(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2013,10,7)   #Set Start Date
        self.set_end_date(2015,7,15)     #Set End Date
        self.set_cash(100000)           #Set Strategy Cash
        # Find more symbols here: http://quantconnect.com/data
        self.equity = self.add_equity("SPY", Resolution.DAILY)
        self.equity.set_volatility_model(CustomVolatilityModel(10))

    def on_data(self, data):
        if not self.portfolio.invested and self.equity.volatility_model.volatility > 0:
            self.set_holdings("SPY", 1)

# Python implementation of StandardDeviationOfReturnsVolatilityModel
# Computes the annualized sample standard deviation of daily returns as the volatility of the security
# https://github.com/QuantConnect/Lean/blob/master/Common/Securities/Volatility/StandardDeviationOfReturnsVolatilityModel.cs
class CustomVolatilityModel():
    def __init__(self, periods):
        self.last_update = datetime.min
        self.last_price = 0
        self.needs_update = False
        self.period_span = timedelta(1)
        self.window = RollingWindow(periods)

        # Volatility is a mandatory attribute
        self.volatility = 0

    # Updates this model using the new price information in the specified security instance
    # Update is a mandatory method
    def update(self, security, data):
        time_since_last_update = data.end_time - self.last_update
        if time_since_last_update >= self.period_span and data.price > 0:
            if self.last_price > 0:
                self.window.add(float(data.price / self.last_price) - 1.0)
                self.needs_update = self.window.is_ready
            self.last_update = data.end_time
            self.last_price = data.price

        if self.window.count < 2:
            self.volatility = 0
            return

        if self.needs_update:
            self.needs_update = False
            std = np.std([ x for x in self.window ])
            self.volatility = std * np.sqrt(252.0)

    # Returns history requirements for the volatility model expressed in the form of history request
    # GetHistoryRequirements is a mandatory method
    def get_history_requirements(self, security, utc_time):
        # For simplicity's sake, we will not set a history requirement
        return 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
: Demonstration of how to estimate constituents of QC500 index based on the company fundamentals
The algorithm creates a default tradable and liquid universe containing 500 US equities
which are chosen at the first trading day of each month.

Output:
```python

from AlgorithmImports import *

class ConstituentsQC500GeneratorAlgorithm(QCAlgorithm):

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

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

        # Add QC500 Universe
        self.add_universe(self.universe.qc_500)
```


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 illustrating how to get a security's industry-standard identifier from its `Symbol`

Output:
```python

from AlgorithmImports import *

class IndustryStandardSecurityIdentifiersRegressionAlgorithm(QCAlgorithm):

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

        equity = self.add_equity("AAPL").symbol

        cusip = equity.cusip
        composite_figi = equity.composite_figi
        sedol = equity.sedol
        isin = equity.isin
        cik = equity.cik

        self.check_symbol_representation(cusip, "CUSIP")
        self.check_symbol_representation(composite_figi, "Composite FIGI")
        self.check_symbol_representation(sedol, "SEDOL")
        self.check_symbol_representation(isin, "ISIN")
        self.check_symbol_representation(f"{cik}", "CIK")

        # Check Symbol API vs QCAlgorithm API
        self.check_ap_is_symbol_representations(cusip, self.cusip(equity), "CUSIP")
        self.check_ap_is_symbol_representations(composite_figi, self.composite_figi(equity), "Composite FIGI")
        self.check_ap_is_symbol_representations(sedol, self.sedol(equity), "SEDOL")
        self.check_ap_is_symbol_representations(isin, self.isin(equity), "ISIN")
        self.check_ap_is_symbol_representations(f"{cik}", f"{self.cik(equity)}", "CIK")

        self.log(f"\n_aapl CUSIP: {cusip}"
                 f"\n_aapl Composite FIGI: {composite_figi}"
                 f"\n_aapl SEDOL: {sedol}"
                 f"\n_aapl ISIN: {isin}"
                 f"\n_aapl CIK: {cik}")

    def check_symbol_representation(self, symbol: str, standard: str) -> None:
        if not symbol:
            raise AssertionError(f"{standard} symbol representation is null or empty")

    def check_ap_is_symbol_representations(self, symbol_api_symbol: str, algorithm_api_symbol: str, standard: str) -> None:
        if symbol_api_symbol != algorithm_api_symbol:
            raise AssertionError(f"Symbol API {standard} symbol representation ({symbol_api_symbol}) does not match "
                            f"QCAlgorithm API {standard} symbol representation ({algorithm_api_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 algorithm shows how you can handle universe selection in anyway you like,
at any time you like. This algorithm has a list of 10 stocks that it rotates
through every hour.

Output:
```python

from AlgorithmImports import *

class UserDefinedUniverseAlgorithm(QCAlgorithm):

	def initialize(self) -> None:
		self.set_cash(100000)
		self.set_start_date(2015, 1, 1)
		self.set_end_date(2015, 12, 1)
		self._symbols = ["SPY", "GOOG", "IBM", "AAPL", "MSFT", "CSCO", "ADBE", "WMT"]

		self.universe_settings.resolution = Resolution.HOUR
		self.add_universe('my_universe_name', Resolution.HOUR, self.selection)

	def selection(self, time: datetime) -> list[str]:
		index = time.hour % len(self._symbols)
		return [self._symbols[index]]

	def on_securities_changed(self, changes: SecurityChanges) -> None:
		for removed in changes.removed_securities:
			if removed.invested:
				self.liquidate(removed.symbol)

		for added in changes.added_securities:
			self.set_holdings(added.symbol, 1/len(changes.added_securities))
```


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

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

Output:
```python

from AlgorithmImports import *
from BaseFrameworkRegressionAlgorithm import BaseFrameworkRegressionAlgorithm
from Alphas.HistoricalReturnsAlphaModel import HistoricalReturnsAlphaModel

class HistoricalReturnsAlphaModelFrameworkRegressionAlgorithm(BaseFrameworkRegressionAlgorithm):

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

    def on_end_of_algorithm(self):
        expected = 78
        if self.insights.total_count != expected:
            raise AssertionError(f"The total number of insights should be {expected}. Actual: {self.insights.total_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
: Test algorithm using 'QCAlgorithm.add_alpha_model()'

Output:
```python

from AlgorithmImports import *

class AddAlphaModelAlgorithm(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

        self.universe_settings.resolution = Resolution.DAILY

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

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

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

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

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


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 'ConfidenceWeightedPortfolioConstructionModel' and 'ConstantAlphaModel'
generating a constant 'Insight' with a 0.25 confidence

Output:
```python

from AlgorithmImports import *

class ConfidenceWeightedFrameworkAlgorithm(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.'''

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

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

        self.set_start_date(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, 0.25))
        self.set_portfolio_construction(ConfidenceWeightedPortfolioConstructionModel())
        self.set_execution(ImmediateExecutionModel())

    def on_end_of_algorithm(self):
        # holdings value should be 0.25 - to avoid price fluctuation issue we compare with 0.28 and 0.23
        if (self.portfolio.total_holdings_value > self.portfolio.total_portfolio_value * 0.28
            or self.portfolio.total_holdings_value < self.portfolio.total_portfolio_value * 0.23):
            raise ValueError("Unexpected Total Holdings Value: " + str(self.portfolio.total_holdings_value))
```


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

Input:
Generate a LEAN Algorithm that can be described like this
: Custom Consolidator Regression Algorithm shows some examples of how to build custom

Output:
```python

from AlgorithmImports import *

class CustomConsolidatorRegressionAlgorithm(QCAlgorithm):
    '''Custom Consolidator Regression Algorithm shows some examples of how to build custom
    consolidators in Python.'''

    def initialize(self):
        self.set_start_date(2013,10,4)
        self.set_end_date(2013,10,11)
        self.set_cash(100000)
        self.add_equity("SPY", Resolution.MINUTE)

        #Create 5 day QuoteBarConsolidator; set consolidated function; add to subscription manager
        five_day_consolidator = QuoteBarConsolidator(timedelta(days=5))
        five_day_consolidator.data_consolidated += self.on_quote_bar_data_consolidated
        self.subscription_manager.add_consolidator("SPY", five_day_consolidator)

        #Create a 3:10PM custom quote bar consolidator
        timed_consolidator = DailyTimeQuoteBarConsolidator(time(hour=15, minute=10))
        timed_consolidator.data_consolidated += self.on_quote_bar_data_consolidated
        self.subscription_manager.add_consolidator("SPY", timed_consolidator)

        #Create our entirely custom 2 day quote bar consolidator
        self.custom_consolidator = CustomQuoteBarConsolidator(timedelta(days=2))
        self.custom_consolidator.data_consolidated += (self.on_quote_bar_data_consolidated)
        self.subscription_manager.add_consolidator("SPY", self.custom_consolidator)

        #Create an indicator and register a consolidator to it
        self.moving_average = SimpleMovingAverage(5)
        self.custom_consolidator2 = CustomQuoteBarConsolidator(timedelta(hours=1))
        self.register_indicator("SPY", self.moving_average, self.custom_consolidator2)

    def on_quote_bar_data_consolidated(self, sender, bar):
        '''Function assigned to be triggered by consolidators.
        Designed to post debug messages to show how the examples work, including
        which consolidator is posting, as well as its values.

        If using an inherited class and not overwriting OnDataConsolidated
        we expect to see the super C# class as the sender type.

        Using sender.period only works when all consolidators have a Period value.
        '''

        consolidator_info = str(type(sender)) + str(sender.period)

        self.debug("Bar Type: " + consolidator_info)
        self.debug("Bar Range: " + bar.time.ctime() + " - " + bar.end_time.ctime())
        self.debug("Bar value: " + str(bar.close))

    def on_data(self, slice):
        test = slice.get_values()

        if self.custom_consolidator.consolidated and slice.contains_key("SPY"):
            data = slice['SPY']

            if self.moving_average.is_ready:
                if data.value > self.moving_average.current.price:
                    self.set_holdings("SPY", .5)
                else :
                    self.set_holdings("SPY", 0)

class DailyTimeQuoteBarConsolidator(QuoteBarConsolidator):
    '''A custom QuoteBar consolidator that inherits from C# class QuoteBarConsolidator.

    This class shows an example of building on top of an existing consolidator class, it is important
    to note that this class can leverage the functions of QuoteBarConsolidator but its private fields
    (_period, _workingbar, etc.) are separate from this Python. For that reason if we want Scan() to work
    we must overwrite the function with our desired Scan function and trigger OnDataConsolidated().

    For this particular example we implemented the scan method to trigger a consolidated bar
    at close_time everyday'''

    def __init__(self, close_time):
        self.close_time = close_time
        self.working_bar = None

    def update(self, data):
        '''Updates this consolidator with the specified data'''

        #If we don't have bar yet, create one
        if self.working_bar is None:
            self.working_bar = QuoteBar(data.time,data.symbol,data.bid,data.last_bid_size,
                data.ask,data.last_ask_size)

        #Update bar using QuoteBarConsolidator's AggregateBar()
        self.aggregate_bar(self.working_bar, data)

    def scan(self, time):
        '''Scans this consolidator to see if it should emit a bar due yet'''

        if self.working_bar is None:
            return

        #If its our desired bar end time take the steps to
        if time.hour == self.close_time.hour and time.minute == self.close_time.minute:

            #Set end time
            self.working_bar.end_time = time

            #Emit event using QuoteBarConsolidator's OnDataConsolidated()
            self.on_data_consolidated(self.working_bar)

            #Reset the working bar to None
            self.working_bar = None

class CustomQuoteBarConsolidator(PythonConsolidator):
    '''A custom quote bar consolidator that inherits from PythonConsolidator and implements
    the IDataConsolidator interface, it must implement all of IDataConsolidator. Reference
    PythonConsolidator.cs and DataConsolidatorPythonWrapper.PY for more information.

    This class shows how to implement a consolidator from scratch in Python, this gives us more
    freedom to determine the behavior of the consolidator but can't leverage any of the built in
    functions of an inherited class.

    For this example we implemented a Quotebar from scratch'''

    def __init__(self, period):

        #IDataConsolidator required vars for all consolidators
        self.consolidated = None        #Most recently consolidated piece of data.
        self.working_data = None         #Data being currently consolidated
        self.input_type = QuoteBar       #The type consumed by this consolidator
        self.output_type = QuoteBar      #The type produced by this consolidator

        #Consolidator Variables
        self.period = period

    def update(self, data):
        '''Updates this consolidator with the specified data'''

        #If we don't have bar yet, create one
        if self.working_data is None:
            self.working_data = QuoteBar(data.time,data.symbol,data.bid,data.last_bid_size,
                data.ask,data.last_ask_size,self.period)

        #Update bar using QuoteBar's update()
        self.working_data.update(data.value, data.bid.close, data.ask.close, 0,
            data.last_bid_size, data.last_ask_size)

    def scan(self, time):
        '''Scans this consolidator to see if it should emit a bar due to time passing'''

        if self.period is not None and self.working_data is not None:
            if time - self.working_data.time >= self.period:

                #Trigger the event handler with a copy of self and the data
                self.on_data_consolidated(self, self.working_data)

                #Set the most recent consolidated piece of data and then clear the working_data
                self.consolidated = self.working_data
                self.working_data = 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
: Regression algorithm which tests a fine fundamental filtered universe,
related to GH issue 4127

Output:
```python

from AlgorithmImports import *

class FineFundamentalFilteredUniverseRegressionAlgorithm(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, 10, 8)
        self.set_end_date(2014, 10, 13)

        self.universe_settings.resolution = Resolution.DAILY

        symbol = Symbol(SecurityIdentifier.generate_constituent_identifier("constituents-universe-qctest", SecurityType.EQUITY, Market.USA), "constituents-universe-qctest")
        self.add_universe(ConstituentsUniverse(symbol, self.universe_settings), self.fine_selection_function)

    def fine_selection_function(self, fine):
        return [ x.symbol for x in fine if x.company_profile != None and x.company_profile.headquarter_city != None and x.company_profile.headquarter_city.lower() == "cupertino" ]

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

        Arguments:
            data: Slice object keyed by symbol containing the stock data
        '''
        if not self.portfolio.invested:
            if data.keys()[0].value != "AAPL":
                raise ValueError(f"Unexpected symbol was added to the universe: {data.keys()[0]}")
            self.set_holdings(data.keys()[0], 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
: The demonstration algorithm shows some of the most common order methods when working with Crypto assets.

Output:
```python

from AlgorithmImports import *

class BasicTemplateCryptoAlgorithm(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(2018, 4, 4)  #Set Start Date
        self.set_end_date(2018, 4, 4)    #Set End Date

        # Although typically real brokerages as GDAX only support a single account currency,
        # here we add both USD and EUR to demonstrate how to handle non-USD account currencies.
        # Set Strategy Cash (USD)
        self.set_cash(10000)

        # Set Strategy Cash (EUR)
        # EUR/USD conversion rate will be updated dynamically
        self.set_cash("EUR", 10000)

        # Add some coins as initial holdings
        # When connected to a real brokerage, the amount specified in SetCash
        # will be replaced with the amount in your actual account.
        self.set_cash("BTC", 1)
        self.set_cash("ETH", 5)

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

        # You can uncomment the following lines when live trading with GDAX,
        # to ensure limit orders will only be posted to the order book and never executed as a taker (incurring fees).
        # Please note this statement has no effect in backtesting or paper trading.
        # self.default_order_properties = GDAXOrderProperties()
        # self.default_order_properties.post_only = True

        # Find more symbols here: http://quantconnect.com/data
        self.add_crypto("BTCUSD", Resolution.MINUTE)
        self.add_crypto("ETHUSD", Resolution.MINUTE)
        self.add_crypto("BTCEUR", Resolution.MINUTE)
        symbol = self.add_crypto("LTCUSD", Resolution.MINUTE).symbol

        # create two moving averages
        self.fast = self.ema(symbol, 30, Resolution.MINUTE)
        self.slow = self.ema(symbol, 60, Resolution.MINUTE)

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

        Arguments:
            data: Slice object keyed by symbol containing the stock data
        '''

        # Note: all limit orders in this algorithm will be paying taker fees,
        # they shouldn't, but they do (for now) because of this issue:
        # https://github.com/QuantConnect/Lean/issues/1852

        if self.time.hour == 1 and self.time.minute == 0:
            # Sell all ETH holdings with a limit order at 1% above the current price
            limit_price = round(self.securities["ETHUSD"].price * 1.01, 2)
            quantity = self.portfolio.cash_book["ETH"].amount
            self.limit_order("ETHUSD", -quantity, limit_price)

        elif self.time.hour == 2 and self.time.minute == 0:
            # Submit a buy limit order for BTC at 5% below the current price
            usd_total = self.portfolio.cash_book["USD"].amount
            limit_price = round(self.securities["BTCUSD"].price * 0.95, 2)
            # use only half of our total USD
            quantity = usd_total * 0.5 / limit_price
            self.limit_order("BTCUSD", quantity, limit_price)

        elif self.time.hour == 2 and self.time.minute == 1:
            # Get current USD available, subtracting amount reserved for buy open orders
            usd_total = self.portfolio.cash_book["USD"].amount
            usd_reserved = sum(x.quantity * x.limit_price for x
                in [x for x in self.transactions.get_open_orders()
                    if x.direction == OrderDirection.BUY
                        and x.type == OrderType.LIMIT
                        and (x.symbol.value == "BTCUSD" or x.symbol.value == "ETHUSD")])
            usd_available = usd_total - usd_reserved
            self.debug("usd_available: {}".format(usd_available))

            # Submit a marketable buy limit order for ETH at 1% above the current price
            limit_price = round(self.securities["ETHUSD"].price * 1.01, 2)

            # use all of our available USD
            quantity = usd_available / limit_price

            # this order will be rejected (for now) because of this issue:
            # https://github.com/QuantConnect/Lean/issues/1852
            self.limit_order("ETHUSD", quantity, limit_price)

            # use only half of our available USD
            quantity = usd_available * 0.5 / limit_price
            self.limit_order("ETHUSD", quantity, limit_price)

        elif self.time.hour == 11 and self.time.minute == 0:
            # Liquidate our BTC holdings (including the initial holding)
            self.set_holdings("BTCUSD", 0)

        elif self.time.hour == 12 and self.time.minute == 0:
            # Submit a market buy order for 1 BTC using EUR
            self.buy("BTCEUR", 1)

            # Submit a sell limit order at 10% above market price
            limit_price = round(self.securities["BTCEUR"].price * 1.1, 2)
            self.limit_order("BTCEUR", -1, limit_price)

        elif self.time.hour == 13 and self.time.minute == 0:
            # Cancel the limit order if not filled
            self.transactions.cancel_open_orders("BTCEUR")

        elif self.time.hour > 13:
            # To include any initial holdings, we read the LTC amount from the cashbook
            # instead of using Portfolio["LTCUSD"].quantity

            if self.fast > self.slow:
                if self.portfolio.cash_book["LTC"].amount == 0:
                    self.buy("LTCUSD", 10)
            else:
                if self.portfolio.cash_book["LTC"].amount > 0:
                    self.liquidate("LTCUSD")

    def on_order_event(self, order_event):
        self.debug("{} {}".format(self.time, order_event.to_string()))

    def on_end_of_algorithm(self):
        self.log("{} - TotalPortfolioValue: {}".format(self.time, self.portfolio.total_portfolio_value))
        self.log("{} - CashBook: {}".format(self.time, self.portfolio.cash_book))
```


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
: Framework algorithm that uses the PearsonCorrelationPairsTradingAlphaModel.
This model extendes BasePairsTradingAlphaModel and uses Pearson correlation
to rank the pairs trading candidates and use the best candidate to trade.

Output:
```python

from AlgorithmImports import *
from Alphas.PearsonCorrelationPairsTradingAlphaModel import PearsonCorrelationPairsTradingAlphaModel

class PearsonCorrelationPairsTradingAlphaModelFrameworkAlgorithm(QCAlgorithm):
    '''Framework algorithm that uses the PearsonCorrelationPairsTradingAlphaModel.
    This model extendes BasePairsTradingAlphaModel and uses Pearson correlation
    to rank the pairs trading candidates and use the best candidate to trade.'''

    def initialize(self):

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

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

        # Manually add SPY 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.day <= (self.end_date - timedelta(1)).day else []))

        self.set_alpha(PearsonCorrelationPairsTradingAlphaModel(252, Resolution.DAILY))
        self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
        self.set_execution(ImmediateExecutionModel())
        self.set_risk_management(NullRiskManagementModel())

    def on_end_of_algorithm(self) -> None:
        # We have removed all securities from the universe. The Alpha Model should remove the consolidator
        consolidator_count = sum(s.consolidators.count for s in self.subscription_manager.subscriptions)
        if consolidator_count > 0:
            raise AssertionError(f"The number of consolidator should be zero. Actual: {consolidator_count}")
```


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

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

  * Initial entry, sell ES Call Option (expiring ITM)
  * Option assignment, sell 1 contract of the underlying (ES)
  * Future contract expiry, liquidation (buy 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 FutureOptionShortCallITMExpiryRegressionAlgorithm(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 <= 3100.0 and x.id.option_right == OptionRight.CALL],
                    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.CALL, 3100.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 != 3100.0:
                raise AssertionError("Option was not assigned at expected strike price (3100)")

            if order_event.direction != OrderDirection.SELL 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.BUY 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
: This example demonstrates how to add futures with daily resolution.

Output:
```python

from AlgorithmImports import *

class BasicTemplateFuturesDailyAlgorithm(QCAlgorithm):
    def initialize(self):
        self.set_start_date(2013, 10, 8)
        self.set_end_date(2014, 10, 10)
        self.set_cash(1000000)

        resolution = self.get_resolution()
        extended_market_hours = self.get_extended_market_hours()

        # Subscribe and set our expiry filter for the futures chain
        self.future_sp500 = self.add_future(Futures.Indices.SP_500_E_MINI, resolution, extended_market_hours=extended_market_hours)
        self.future_gold = self.add_future(Futures.Metals.GOLD, resolution, extended_market_hours=extended_market_hours)

        # set our expiry filter for this futures chain
        # SetFilter method accepts timedelta objects or integer for days.
        # The following statements yield the same filtering criteria
        self.future_sp500.set_filter(timedelta(0), timedelta(182))
        self.future_gold.set_filter(0, 182)

    def on_data(self,slice):
        if not self.portfolio.invested:
            for chain in slice.future_chains:
                 # Get contracts expiring no earlier than in 90 days
                contracts = list(filter(lambda x: x.expiry > self.time + timedelta(90), chain.value))

                # if there is any contract, trade the front contract
                if len(contracts) == 0: continue
                contract = sorted(contracts, key = lambda x: x.expiry)[0]

                # if found, trade it.
                self.market_order(contract.symbol, 1)
        # Same as above, check for cases like trading on a friday night.
        elif all(x.exchange.hours.is_open(self.time, True) for x in self.securities.values() if x.invested):
            self.liquidate()

    def on_securities_changed(self, changes: SecurityChanges) -> None:
        if len(changes.removed_securities) > 0 and \
            self.portfolio.invested and \
            all(x.exchange.hours.is_open(self.time, True) for x in self.securities.values() if x.invested):
            self.liquidate()

    def get_resolution(self):
        return Resolution.DAILY

    def get_extended_market_hours(self):
        return False
```


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
: Regrssion algorithm to assert we can update indicators that inherit from IndicatorBase<TradeBar> with RenkoBar's

Output:
```python

from AlgorithmImports import *

class IndicatorWithRenkoBarsRegressionAlgorithm(QCAlgorithm):

    def initialize(self) -> None:
        self.set_start_date(2013, 10, 7)
        self.set_end_date(2013, 10, 9)

        self.add_equity("SPY")
        self.add_equity("AIG")

        spy_renko_consolidator = RenkoConsolidator(0.1)
        spy_renko_consolidator.data_consolidated += self.on_spy_data_consolidated

        aig_renko_consolidator = RenkoConsolidator(0.05)
        aig_renko_consolidator.data_consolidated += self.on_aig_data_consolidated

        self.subscription_manager.add_consolidator("SPY", spy_renko_consolidator)
        self.subscription_manager.add_consolidator("AIG", aig_renko_consolidator)

        self._mi = MassIndex("MassIndex", 9, 25)
        self._wasi = WilderAccumulativeSwingIndex("WilderAccumulativeSwingIndex", 8)
        self._wsi = WilderSwingIndex("WilderSwingIndex", 8)
        self._b = Beta("Beta", 3, "AIG", "SPY")
        self._indicators = [self._mi, self._wasi, self._wsi, self._b]

    def on_spy_data_consolidated(self, sender: object, renko_bar: RenkoBar) -> None:
        self._mi.update(renko_bar)
        self._wasi.update(renko_bar)
        self._wsi.update(renko_bar)
        self._b.update(renko_bar)

    def on_aig_data_consolidated(self, sender: object, renko_bar: RenkoBar) -> None:
        self._b.update(renko_bar)

    def on_end_of_algorithm(self) -> None:
        for indicator in self._indicators:
            if not indicator.is_ready:
                raise AssertionError(f"{indicator.name} indicator should be ready")
            elif indicator.current.value == 0:
                raise AssertionError(f"The current value of the {indicator.name} indicator should be different than zero")
```


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_universe_selection(IUniverseSelectionModel)'

Output:
```python

from AlgorithmImports import *

class AddUniverseSelectionModelAlgorithm(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.universe_settings.resolution = Resolution.DAILY

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

        self.set_universe_selection(ManualUniverseSelectionModel([ Symbol.create("SPY", SecurityType.EQUITY, Market.USA) ]))
        self.add_universe_selection(ManualUniverseSelectionModel([ Symbol.create("AAPL", SecurityType.EQUITY, Market.USA) ]))
        self.add_universe_selection(ManualUniverseSelectionModel(
                Symbol.create("SPY", SecurityType.EQUITY, Market.USA), # duplicate will be ignored
                Symbol.create("FB", SecurityType.EQUITY, Market.USA)))

    def on_end_of_algorithm(self):
        if self.universe_manager.count != 3:
            raise ValueError("Unexpected universe count")
        if self.universe_manager.active_securities.count != 3:
            raise ValueError("Unexpected active securities")
```


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

Input:
Generate a LEAN Algorithm that can be described like this
: Example algorithm demonstrating the usage of the RSI indicator
in combination with ETF constituents data to replicate the weighting
of the ETF's assets in our own account.

Output:
```python

from AlgorithmImports import *

class ETFConstituentUniverseRSIAlphaModelAlgorithm(QCAlgorithm):
    ### <summary>
    ### Initialize the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
    ### </summary>
    def initialize(self):
        self.set_start_date(2020, 12, 1)
        self.set_end_date(2021, 1, 31)
        self.set_cash(100000)

        self.set_alpha(ConstituentWeightedRsiAlphaModel())
        self.set_portfolio_construction(InsightWeightingPortfolioConstructionModel())
        self.set_execution(ImmediateExecutionModel())

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

        # We load hourly data for ETF constituents in this algorithm
        self.universe_settings.resolution = Resolution.HOUR
        self.settings.minimum_order_margin_portfolio_percentage = 0.01

        self.add_universe(self.universe.etf(spy, self.universe_settings, self.filter_etf_constituents))

    ### <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):
        return [i.symbol for i in constituents if i.weight is not None and i.weight >= 0.001]

class ConstituentWeightedRsiAlphaModel(AlphaModel):
    def __init__(self, max_trades=None):
        self.rsi_symbol_data = {}

    def update(self, algorithm: QCAlgorithm, data: Slice):
        algo_constituents = []
        for bar_symbol in data.bars.keys():
            if not algorithm.securities[bar_symbol].cache.has_data(ETFConstituentUniverse):
                continue

            constituent_data = algorithm.securities[bar_symbol].cache.get_data(ETFConstituentUniverse)
            algo_constituents.append(constituent_data)

        if len(algo_constituents) == 0 or len(data.bars) == 0:
            # Don't do anything if we have no data we can work with
            return []

        constituents = {i.symbol:i for i in algo_constituents}

        for bar in data.bars.values():
            if bar.symbol not in constituents:
                # Dealing with a manually added equity, which in this case is SPY
                continue

            if bar.symbol not in self.rsi_symbol_data:
                # First time we're initializing the RSI.
                # It won't be ready now, but it will be
                # after 7 data points
                constituent = constituents[bar.symbol]
                self.rsi_symbol_data[bar.symbol] = SymbolData(bar.symbol, algorithm, constituent, 7)

        all_ready = all([sd.rsi.is_ready for sd in self.rsi_symbol_data.values()])
        if not all_ready:
            # We're still warming up the RSI indicators.
            return []

        insights = []

        for symbol, symbol_data in self.rsi_symbol_data.items():
            average_loss = symbol_data.rsi.average_loss.current.value
            average_gain = symbol_data.rsi.average_gain.current.value

            # If we've lost more than gained, then we think it's going to go down more
            direction = InsightDirection.DOWN if average_loss > average_gain else InsightDirection.UP

            # Set the weight of the insight as the weight of the ETF's
            # holding. The InsightWeightingPortfolioConstructionModel
            # will rebalance our portfolio to have the same percentage
            # of holdings in our algorithm that the ETF has.
            insights.append(Insight.price(
                symbol,
                timedelta(days=1),
                direction,
                float(average_loss if direction == InsightDirection.DOWN else average_gain),
                weight=float(symbol_data.constituent.weight)
            ))

        return insights

class SymbolData:
    def __init__(self, symbol, algorithm, constituent, period):
        self.symbol = symbol
        self.constituent = constituent
        self.rsi = algorithm.rsi(symbol, period, MovingAverageType.EXPONENTIAL, Resolution.HOUR)
```


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 using FutureOptions daily resolution

Output:
```python

from AlgorithmImports import *

class FutureOptionDailyRegressionAlgorithm(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2020, 1, 7)
        self.set_end_date(2020, 1, 8)
        resolution = Resolution.DAILY

        # Add our underlying future contract
        self.es = self.add_future_contract(
            Symbol.create_future(
                Futures.Indices.SP_500_E_MINI,
                Market.CME,
                datetime(2020, 3, 20)
            ),
            resolution).symbol

        # Attempt to fetch a specific ITM future option contract
        es_options = [
            self.add_future_option_contract(x, resolution).symbol
            for x in self.option_chain(self.es)
            if x.id.strike_price == 3200 and x.id.option_right == OptionRight.CALL
        ]
        self.es_option = es_options[0]

        # Validate it is the expected contract
        expected_contract = Symbol.create_option(self.es, Market.CME, OptionStyle.AMERICAN, OptionRight.CALL, 3200, datetime(2020, 3, 20))
        if self.es_option != expected_contract:
            raise AssertionError(f"Contract {self.es_option} was not the expected contract {expected_contract}")

        # Schedule a purchase of this contract tomorrow at 10AM when the market is open
        self.schedule.on(self.date_rules.tomorrow, self.time_rules.at(10,0,0), self.schedule_callback_buy)

        # Schedule liquidation at 2pm tomorrow when the market is open
        self.schedule.on(self.date_rules.tomorrow, self.time_rules.at(14,0,0), self.schedule_callback_liquidate)

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

    def on_data(self, slice):
        # Assert we are only getting data at 4PM NY, for ES future market closes at 16pm NY
        if slice.time.hour != 17:
            raise AssertionError(f"Expected data at 5PM each day; instead was {slice.time}")

    def schedule_callback_liquidate(self):
        self.liquidate()

    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
: Test algorithm using 'InsightWeightingPortfolioConstructionModel' and 'ConstantAlphaModel'
generating a constant 'Insight' with a 0.25 weight

Output:
```python

from AlgorithmImports import *

from Selection.ManualUniverseSelectionModel import ManualUniverseSelectionModel
from Alphas.ConstantAlphaModel import ConstantAlphaModel
from Portfolio.InsightWeightingPortfolioConstructionModel import InsightWeightingPortfolioConstructionModel
from Execution.ImmediateExecutionModel import ImmediateExecutionModel

class InsightWeightingFrameworkAlgorithm(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.'''

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

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

        self.set_start_date(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, 0.25))
        self.set_portfolio_construction(InsightWeightingPortfolioConstructionModel())
        self.set_execution(ImmediateExecutionModel())

    def on_end_of_algorithm(self):
        # holdings value should be 0.25 - to avoid price fluctuation issue we compare with 0.28 and 0.23
        if (self.portfolio.total_holdings_value > self.portfolio.total_portfolio_value * 0.28
            or self.portfolio.total_holdings_value < self.portfolio.total_portfolio_value * 0.23):
            raise ValueError("Unexpected Total Holdings Value: " + str(self.portfolio.total_holdings_value))
```